@multiplayer-app/ai-agent-react 0.1.0-beta.89 → 0.1.0-beta.91
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai-agent-react.cjs.js +2 -2
- package/dist/ai-agent-react.cjs.js.map +1 -1
- package/dist/ai-agent-react.es.js +6 -4
- package/dist/ai-agent-react.es.js.map +1 -1
- package/dist/config/types.d.ts.map +1 -1
- package/dist/runtime/AgentRuntime.d.ts.map +1 -1
- package/package.json +2 -2
- package/dist/components/ChatWindow/MessageList/Message/MessageAttachments.d.ts +0 -7
- package/dist/components/ChatWindow/MessageList/Message/MessageAttachments.d.ts.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const B=require("zod"),N=require("react/jsx-runtime"),V=require("react"),yt=require("@tanstack/react-query"),r5=require("zustand"),_t=require("nanoid"),a5=require("react-dom");function i5(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const te=i5(V),o5=i5(a5);class Gu extends Error{constructor(t,n){super(t),this.statusCode=n,this.name="HttpError"}}const s5=B.z.object({background:B.z.string(),surface:B.z.string(),text:B.z.string(),subtext:B.z.string(),border:B.z.string(),accent:B.z.string(),accentSoft:B.z.string(),warning:B.z.string(),danger:B.z.string(),fontFamily:B.z.string(),radius:B.z.string(),fontSize:B.z.string(),colorMode:B.z.enum(["light","dark"])}),l5=B.z.object({key:B.z.string(),label:B.z.string(),description:B.z.string().optional(),tools:B.z.array(B.z.string()).default([]),defaultModel:B.z.string().optional(),autoConfirmTools:B.z.array(B.z.string()).optional()}),Wu=B.z.object({appId:B.z.string(),workspaceId:B.z.string().optional(),debug:B.z.boolean().optional(),user:B.z.object({id:B.z.string(),displayName:B.z.string().optional(),email:B.z.string().optional(),avatarUrl:B.z.string().optional()}).optional(),contextKeys:B.z.array(l5),transport:B.z.union([B.z.object({mode:B.z.literal("proxy"),baseUrl:B.z.string(),apiKey:B.z.string().optional(),socketPath:B.z.string().optional(),socketNamespace:B.z.string().optional(),timeoutMs:B.z.number().optional(),headers:B.z.record(B.z.string()).optional()}),B.z.object({mode:B.z.literal("direct"),provider:B.z.enum(["openrouter","openai","custom"]),endpoint:B.z.string().optional(),apiKey:B.z.string().optional(),model:B.z.string().optional(),titleGenerationModel:B.z.string().optional(),timeoutMs:B.z.number().optional(),headers:B.z.record(B.z.string()).optional()})]),theme:s5.partial().optional(),tools:B.z.array(B.z.object({name:B.z.string(),label:B.z.string(),description:B.z.string().optional(),icon:B.z.string().optional(),schema:B.z.record(B.z.any()).optional(),confirmation:B.z.enum(["auto","manual"]).optional(),category:B.z.string().optional()})).optional(),models:B.z.array(B.z.object({id:B.z.string(),label:B.z.string(),provider:B.z.string().optional(),reasoning:B.z.enum(["disabled","concise","deep"]).optional(),contexts:B.z.array(B.z.string()).optional()})).optional(),features:B.z.object({reasoning:B.z.boolean().optional(),artifactsPanel:B.z.boolean().optional(),modelSwitching:B.z.boolean().optional(),toolConfiguration:B.z.boolean().optional(),fileAttachments:B.z.boolean().optional(),selectionAttachments:B.z.boolean().optional(),multiAgentControl:B.z.boolean().optional(),sandboxControls:B.z.boolean().optional(),historySidebar:B.z.boolean().optional(),titleGeneration:B.z.enum(["local","llm"]).optional(),pageContextAttachments:B.z.boolean().optional()}).optional(),pageContext:B.z.object({includeUserAgent:B.z.boolean().optional(),includeReferrer:B.z.boolean().optional(),includeViewport:B.z.boolean().optional(),includeTitle:B.z.boolean().optional(),name:B.z.string().optional()}).optional(),defaultContextKey:B.z.string().optional(),messagesPageSize:B.z.number().int().positive().max(200).optional(),translations:B.z.object({newChat:B.z.string().optional(),followUp:B.z.string().optional(),sendMessage:B.z.string().optional(),stopStreaming:B.z.string().optional(),typeMessageToSend:B.z.string().optional(),attachFiles:B.z.string().optional(),attachSelectionToContext:B.z.string().optional(),attachments:B.z.string().optional(),chats:B.z.string().optional(),multiUserChats:B.z.string().optional(),noMultiUserChats:B.z.string().optional(),noChatsYet:B.z.string().optional(),untitledChat:B.z.string().optional(),deleteChat:B.z.string().optional(),showChatHistory:B.z.string().optional(),hideChatHistory:B.z.string().optional(),fetchingChats:B.z.string().optional(),fetchingChatError:B.z.string().optional(),helloThere:B.z.string().optional(),howCanIHelpYou:B.z.string().optional()}).optional()}),Ni={panelTitle:"",newChat:"New chat",followUp:"Follow up...",sendMessage:"Send message",stopStreaming:"Stop streaming",typeMessageToSend:"Type a message to send",attachFiles:"Attach files",attachSelectionToContext:"Attach selected text to context",attachments:"Attachments",chats:"Chats",multiUserChats:"Shared chats",noMultiUserChats:"No shared chats yet.",noChatsYet:"No chats yet.",untitledChat:"Untitled chat",deleteChat:"Delete chat",showChatHistory:"Show chat history",hideChatHistory:"Hide chat history",close:"Close",fetchingChats:"Fetching chats…",fetchingChatError:"Fetching chats failed",helloThere:"Hello there!",howCanIHelpYou:"How can I help you today?",agentSettingsLoading:"Loading agent settings…",agentSettingsError:"Failed to load agent settings.",agentSettingsNoConfigurableTools:"No configurable tools available.",agentSettingsNoToolsForAgent:"No tools configured.",agentSettingsTooltip:"Configure agent tools",formProposalFailed:"Failed to propose form values",formProposalPreparing:"Preparing form fill proposal…",formProposalNone:"No form fields proposed.",formProposalHeaderPrefix:"Proposed values for",formProposalApplied:"Applied",formProposalRejected:"Rejected",formProposalApplyAll:"Apply all",formProposalShowAll:"Show all",formProposalShowLess:"Show less",formProposalApplyFieldPrefix:"Apply"},z7={panelTitle:String,newChat:String,followUp:String,sendMessage:String,stopStreaming:String,typeMessageToSend:String,attachFiles:String,attachSelectionToContext:String,attachments:String,chats:String,multiUserChats:String,noMultiUserChats:String,noChatsYet:String,untitledChat:String,deleteChat:String,showChatHistory:String,hideChatHistory:String,fetchingChats:String,fetchingChatError:String,helloThere:String,howCanIHelpYou:String,close:String,agentSettingsLoading:String,agentSettingsError:String,agentSettingsNoConfigurableTools:String,agentSettingsNoToolsForAgent:String,agentSettingsTooltip:String,formProposalFailed:String,formProposalPreparing:String,formProposalNone:String,formProposalHeaderPrefix:String,formProposalApplied:String,formProposalRejected:String,formProposalApplyAll:String,formProposalShowAll:String,formProposalShowLess:String,formProposalApplyFieldPrefix:String};exports.SortOrder=void 0;(function(e){e.Asc="asc",e.Desc="desc"})(exports.SortOrder||(exports.SortOrder={}));exports.MessageRole=void 0;(function(e){e.System="system",e.User="user",e.Assistant="assistant",e.Tool="tool",e.Reasoning="reasoning",e.Error="error"})(exports.MessageRole||(exports.MessageRole={}));exports.AgentAttachmentType=void 0;(function(e){e.File="file",e.Link="link",e.Artifact="artifact",e.Context="context"})(exports.AgentAttachmentType||(exports.AgentAttachmentType={}));exports.AgentToolCallStatus=void 0;(function(e){e.Pending="pending",e.Running="running",e.Succeeded="succeeded",e.Failed="failed"})(exports.AgentToolCallStatus||(exports.AgentToolCallStatus={}));exports.AgentProcessStatus=void 0;(function(e){e.Queued="queued",e.ApprovalRequired="approvalRequired",e.Running="running",e.Paused="paused",e.Error="error",e.Complete="complete"})(exports.AgentProcessStatus||(exports.AgentProcessStatus={}));exports.StreamChunkType=void 0;(function(e){e.Message="message",e.Reasoning="reasoning",e.Tool="tool",e.Artifact="artifact",e.Error="error",e.Chat="chat"})(exports.StreamChunkType||(exports.StreamChunkType={}));exports.ChatType=void 0;(function(e){e.Chat="chat",e.Agent="agent"})(exports.ChatType||(exports.ChatType={}));exports.AgentStatus=void 0;(function(e){e.Processing="processing",e.Streaming="streaming",e.Finished="finished",e.Aborted="aborted",e.WaitingForUserAction="waitingForUserAction",e.Error="error"})(exports.AgentStatus||(exports.AgentStatus={}));exports.AgentToolType=void 0;(function(e){e.API_TOOL="api_tool",e.WEB_SEARCH="web_search",e.LOCAL_FUNCTION="local_function",e.SUBAGENT="subagent",e.REQUEST_CLARIFICATION="request_clarification"})(exports.AgentToolType||(exports.AgentToolType={}));exports.ActivityOperationName=void 0;(function(e){e.MESSAGE_PROCESSING="messageProcessing",e.AGENT_SELECTION="agentSelection",e.STEP_FINISHED="stepFinished",e.TITLE_GENERATION="titleGeneration",e.SUBAGENT="subagent"})(exports.ActivityOperationName||(exports.ActivityOperationName={}));exports.AgentSessionKind=void 0;(function(e){e.ROOT="ROOT",e.SUBAGENT="SUBAGENT"})(exports.AgentSessionKind||(exports.AgentSessionKind={}));var fi={ChatNew:"chat:new",MessageNew:"message:new",ChatUpdate:"chat:update",ChatSubscribe:"chat:subscribe",ChatUnsubscribe:"chat:unsubscribe"},Ai={Path:"/socket.io",UserRoomPrefix:"user:",DefaultUserId:"guest"},c5=["webSnippet","formSnapshot","formField"],$7=B.z.string().datetime({offset:!0}).or(B.z.string().datetime()),F7=B.z.object({app:B.z.string().min(1).optional(),url:B.z.string().url().optional(),route:B.z.string().min(1).optional(),domPath:B.z.string().min(1).optional()}).strict(),P7=B.z.object({containsPII:B.z.boolean().optional(),redactionsApplied:B.z.array(B.z.string().min(1)).max(50).optional()}).strict(),q7=B.z.union([B.z.object({type:B.z.literal("text"),exact:B.z.string().min(1).max(4e3),prefix:B.z.string().min(1).max(500).optional(),suffix:B.z.string().min(1).max(500).optional(),domPath:B.z.string().min(1).max(2e3).optional(),startOffset:B.z.number().int().min(0).optional(),endOffset:B.z.number().int().min(0).optional()}).strict(),B.z.object({type:B.z.literal("dom"),domPath:B.z.string().min(1).max(2e3)}).strict(),B.z.object({type:B.z.literal("form"),formId:B.z.string().min(1).max(200).optional(),fieldName:B.z.string().min(1).max(200).optional(),domPath:B.z.string().min(1).max(2e3).optional()}).strict()]),Xi=B.z.object({schemaVersion:B.z.literal(1),kind:B.z.string().min(1).max(100),capturedAt:$7,source:F7.optional(),security:P7.optional(),target:q7.optional()}),B7=Xi.extend({kind:B.z.literal("webSnippet"),title:B.z.string().min(1).max(200).optional(),selectedText:B.z.string().min(1).max(4e3)}).strict(),U7=Xi.extend({kind:B.z.literal("formSnapshot"),formId:B.z.string().min(1).max(200).optional(),formName:B.z.string().min(1).max(200).optional(),fields:B.z.array(B.z.object({name:B.z.string().min(1).max(200),label:B.z.string().min(1).max(200).optional(),value:B.z.string().min(0).max(1e3),inputType:B.z.enum(["text","textarea","number","select","radio","checkbox","date","email","tel"]).optional(),options:B.z.array(B.z.object({value:B.z.string().min(0).max(500),label:B.z.string().min(0).max(500)}).strict()).max(200).optional(),domPath:B.z.string().min(1).max(2e3).optional()}).strict()).min(1).max(50)}).strict(),H7=Xi.extend({kind:B.z.literal("formField"),formId:B.z.string().min(1).max(200).optional(),fieldName:B.z.string().min(1).max(200),fieldLabel:B.z.string().min(1).max(200).optional(),value:B.z.string().min(0).max(1e3),inputType:B.z.enum(["text","textarea","number","select","radio","checkbox","date","email","tel"]).optional(),options:B.z.array(B.z.object({value:B.z.string().min(0).max(500),label:B.z.string().min(0).max(500)}).strict()).max(200).optional(),domPath:B.z.string().min(1).max(2e3).optional()}).strict(),j7=Xi.extend({kind:B.z.string().min(1).max(100).refine(function(e){return!c5.includes(e)},"kind must not collide with built-in kinds"),title:B.z.string().min(1).max(200).optional(),summary:B.z.string().min(1).max(4e3).optional(),data:B.z.record(B.z.string().min(1).max(200),B.z.unknown()).optional()}).strict().superRefine(function(e,t){if(e.data){var n=JSON.stringify(e.data);n.length>12e3&&t.addIssue({code:"custom",message:"data is too large (max ~12k JSON chars)",path:["data"]})}}),u5=B.z.union([B7,U7,H7,j7]),Ba=B.z.object({id:B.z.string().min(1),type:B.z.nativeEnum(exports.AgentAttachmentType),name:B.z.string().min(1).max(500),url:B.z.string().url().optional(),mimeType:B.z.string().min(1).max(200).optional(),metadata:B.z.record(B.z.string(),B.z.unknown()).optional()}).strict(),d5=B.z.union([Ba.extend({type:B.z.literal(exports.AgentAttachmentType.Context),metadata:u5}).strict(),Ba.extend({type:B.z.literal(exports.AgentAttachmentType.File),size:B.z.number().int().min(0).optional(),metadata:B.z.object({uploadedAt:B.z.string().optional(),s3Key:B.z.string().optional(),processingStatus:B.z.enum(["pending","processed","failed"]).optional(),size:B.z.number().int().min(0).optional(),lastModified:B.z.number().optional()}).optional()}).strict(),Ba.extend({type:B.z.literal(exports.AgentAttachmentType.Link)}).strict(),Ba.extend({type:B.z.literal(exports.AgentAttachmentType.Artifact)}).strict()]),V7=B.z.object({chatId:B.z.string().optional(),content:B.z.string().min(1),contextKey:B.z.string().min(1),attachments:B.z.array(d5).optional(),metadata:B.z.record(B.z.string(),B.z.unknown()).optional(),model:B.z.string().optional(),temperature:B.z.number().optional(),userId:B.z.string().optional(),participantIds:B.z.array(B.z.string().min(1)).optional(),mentions:B.z.array(B.z.object({type:B.z.enum(["user","agent"]),name:B.z.string().min(1),id:B.z.string().optional()}).strict()).optional()}).strict();new TextEncoder;const G7=new TextDecoder,W7=3;class Or{constructor(t){this.config=t}streamControllers=new Map;socketId;updateConfig(t){if(t.mode!=="proxy")throw new Error("ProxyTransport.updateConfig requires proxy mode configuration");this.config=t}setSocketId(t){this.socketId=t}withHeaders(t,n){const r={...this.config.headers,...t};this.config.apiKey&&(r.Authorization=`Bearer ${this.config.apiKey}`);const a=n?.body!==void 0&&n?.body!==null,i=Object.keys(r).some(o=>o.toLowerCase()==="content-type");return a&&!i&&(r["Content-Type"]="application/json"),r}async formatHttpError(t,n){const r=n.status,a=n.statusText,i=n.headers.get("content-type")??"";let o;try{if(i.includes("application/json")){const l=await n.json();o=typeof l?.message=="string"&&l.message||typeof l?.error=="string"&&l.error||typeof l?.detail=="string"&&l.detail||typeof l?.title=="string"&&l.title||typeof l=="string"&&l||(l?JSON.stringify(l):void 0)}else{const l=(await n.text()).trim();!/<\s*html[\s>]|<\s*body[\s>]/i.test(l)&&l&&(o=l.length>500?l.slice(0,500)+"…":l)}}catch{}const s=`Message sending failed (${r}${a?` ${a}`:""}).`;return{message:o?`${s} ${o}`:`${s} Please try again.`,statusCode:r}}async request(t,n){const r=await fetch(`${this.config.baseUrl}${t}`,{...n,credentials:"include",headers:this.withHeaders(n?.headers,n),signal:n?.signal});if(!r.ok){const{message:i,statusCode:o}=await this.formatHttpError(t,r),s=new Gu(i,o);throw this.config.onError?.(s),s}if(r.status===204)return;if(r.headers.get("content-type")?.includes("application/json")){const i=await r.text();return i?JSON.parse(i):void 0}const a=await r.text();if(a)return JSON.parse(a)}async sendMessage(t){const n={};return this.socketId&&(n["x-socket-id"]=this.socketId),this.request("/chats/send",{method:"POST",headers:n,body:JSON.stringify(t)})}async streamMessage(t,n,r){const a=r?.streamKey??t.chatId??`stream-${Date.now()}-${Math.random().toString(16).slice(2)}`,i=new AbortController,o=setTimeout(()=>i.abort(),this.config.timeoutMs??5*60*1e3);try{const s={Accept:"text/event-stream"};if(this.socketId&&(s["x-socket-id"]=this.socketId),i.signal.aborted)throw new Error("Stream was aborted before fetch started");this.streamControllers.set(a,i);const l=await fetch(`${this.config.baseUrl}/chats/stream`,{method:"POST",signal:i.signal,credentials:"include",body:JSON.stringify(t),headers:this.withHeaders(s,{method:"POST",body:JSON.stringify(t)})});if(!l.ok){const{message:m,statusCode:h}=await this.formatHttpError("/chats/stream",l),g=new Gu(m,h);throw this.config.onError?.(g),g}if(!l.body)throw new Error("Streaming response body missing");const u=l.body.getReader();let d="",p;for(;;){const{value:m,done:h}=await u.read();if(h)break;d+=G7.decode(m,{stream:!0});const g=d.split(`
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const B=require("zod"),N=require("react/jsx-runtime"),V=require("react"),yt=require("@tanstack/react-query"),r5=require("zustand"),_t=require("nanoid"),a5=require("react-dom");function i5(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const te=i5(V),o5=i5(a5);class Gu extends Error{constructor(t,n){super(t),this.statusCode=n,this.name="HttpError"}}const s5=B.z.object({background:B.z.string(),surface:B.z.string(),text:B.z.string(),subtext:B.z.string(),border:B.z.string(),accent:B.z.string(),accentSoft:B.z.string(),warning:B.z.string(),danger:B.z.string(),fontFamily:B.z.string(),radius:B.z.string(),fontSize:B.z.string(),colorMode:B.z.enum(["light","dark"])}),l5=B.z.object({key:B.z.string(),label:B.z.string(),description:B.z.string().optional(),tools:B.z.array(B.z.string()).default([]),defaultModel:B.z.string().optional(),autoConfirmTools:B.z.array(B.z.string()).optional()}),Wu=B.z.object({appId:B.z.string(),workspaceId:B.z.string().optional(),debug:B.z.boolean().optional(),user:B.z.object({id:B.z.string(),displayName:B.z.string().optional(),email:B.z.string().optional(),avatarUrl:B.z.string().optional()}).optional(),contextKeys:B.z.array(l5),transport:B.z.union([B.z.object({mode:B.z.literal("proxy"),baseUrl:B.z.string(),apiKey:B.z.string().optional(),socketPath:B.z.string().optional(),socketNamespace:B.z.string().optional(),timeoutMs:B.z.number().optional(),headers:B.z.record(B.z.string()).optional()}),B.z.object({mode:B.z.literal("direct"),provider:B.z.enum(["openrouter","openai","custom"]),endpoint:B.z.string().optional(),apiKey:B.z.string().optional(),model:B.z.string().optional(),titleGenerationModel:B.z.string().optional(),timeoutMs:B.z.number().optional(),headers:B.z.record(B.z.string()).optional()})]),theme:s5.partial().optional(),tools:B.z.array(B.z.object({name:B.z.string(),label:B.z.string(),description:B.z.string().optional(),icon:B.z.string().optional(),schema:B.z.record(B.z.any()).optional(),confirmation:B.z.enum(["auto","manual"]).optional(),category:B.z.string().optional()})).optional(),models:B.z.array(B.z.object({id:B.z.string(),label:B.z.string(),provider:B.z.string().optional(),reasoning:B.z.enum(["disabled","concise","deep"]).optional(),contexts:B.z.array(B.z.string()).optional()})).optional(),features:B.z.object({reasoning:B.z.boolean().optional(),artifactsPanel:B.z.boolean().optional(),modelSwitching:B.z.boolean().optional(),toolConfiguration:B.z.boolean().optional(),fileAttachments:B.z.boolean().optional(),selectionAttachments:B.z.boolean().optional(),multiAgentControl:B.z.boolean().optional(),sandboxControls:B.z.boolean().optional(),historySidebar:B.z.boolean().optional(),titleGeneration:B.z.enum(["local","llm"]).optional(),pageContextAttachments:B.z.boolean().optional()}).optional(),pageContext:B.z.object({includeUserAgent:B.z.boolean().optional(),includeReferrer:B.z.boolean().optional(),includeViewport:B.z.boolean().optional(),includeTitle:B.z.boolean().optional(),name:B.z.string().optional()}).optional(),defaultContextKey:B.z.string().optional(),messagesPageSize:B.z.number().int().positive().max(200).optional(),translations:B.z.object({newChat:B.z.string().optional(),followUp:B.z.string().optional(),sendMessage:B.z.string().optional(),stopStreaming:B.z.string().optional(),typeMessageToSend:B.z.string().optional(),attachFiles:B.z.string().optional(),attachSelectionToContext:B.z.string().optional(),attachments:B.z.string().optional(),chats:B.z.string().optional(),multiUserChats:B.z.string().optional(),noMultiUserChats:B.z.string().optional(),noChatsYet:B.z.string().optional(),untitledChat:B.z.string().optional(),deleteChat:B.z.string().optional(),showChatHistory:B.z.string().optional(),hideChatHistory:B.z.string().optional(),fetchingChats:B.z.string().optional(),fetchingChatError:B.z.string().optional(),helloThere:B.z.string().optional(),howCanIHelpYou:B.z.string().optional()}).optional()}),Ni={panelTitle:"",newChat:"New chat",followUp:"Follow up...",sendMessage:"Send message",stopStreaming:"Stop streaming",typeMessageToSend:"Type a message to send",attachFiles:"Attach files",attachSelectionToContext:"Attach selected text to context",attachments:"Attachments",chats:"Chats",multiUserChats:"Shared chats",noMultiUserChats:"No shared chats yet.",noChatsYet:"No chats yet.",untitledChat:"Untitled chat",deleteChat:"Delete chat",showChatHistory:"Show chat history",hideChatHistory:"Hide chat history",close:"Close",fetchingChats:"Fetching chats…",fetchingChatError:"Fetching chats failed",helloThere:"Hello there!",howCanIHelpYou:"How can I help you today?",agentSettingsLoading:"Loading agent settings…",agentSettingsError:"Failed to load agent settings.",agentSettingsNoConfigurableTools:"No configurable tools available.",agentSettingsNoToolsForAgent:"No tools configured.",agentSettingsTooltip:"Configure agent tools",formProposalFailed:"Failed to propose form values",formProposalPreparing:"Preparing form fill proposal…",formProposalNone:"No form fields proposed.",formProposalHeaderPrefix:"Proposed values for",formProposalApplied:"Applied",formProposalRejected:"Rejected",formProposalApplyAll:"Apply all",formProposalShowAll:"Show all",formProposalShowLess:"Show less",formProposalApplyFieldPrefix:"Apply"},z7={panelTitle:String,newChat:String,followUp:String,sendMessage:String,stopStreaming:String,typeMessageToSend:String,attachFiles:String,attachSelectionToContext:String,attachments:String,chats:String,multiUserChats:String,noMultiUserChats:String,noChatsYet:String,untitledChat:String,deleteChat:String,showChatHistory:String,hideChatHistory:String,fetchingChats:String,fetchingChatError:String,helloThere:String,howCanIHelpYou:String,close:String,agentSettingsLoading:String,agentSettingsError:String,agentSettingsNoConfigurableTools:String,agentSettingsNoToolsForAgent:String,agentSettingsTooltip:String,formProposalFailed:String,formProposalPreparing:String,formProposalNone:String,formProposalHeaderPrefix:String,formProposalApplied:String,formProposalRejected:String,formProposalApplyAll:String,formProposalShowAll:String,formProposalShowLess:String,formProposalApplyFieldPrefix:String};exports.SortOrder=void 0;(function(e){e.Asc="asc",e.Desc="desc"})(exports.SortOrder||(exports.SortOrder={}));exports.MessageRole=void 0;(function(e){e.System="system",e.User="user",e.Assistant="assistant",e.Tool="tool",e.Reasoning="reasoning",e.Error="error"})(exports.MessageRole||(exports.MessageRole={}));exports.AgentAttachmentType=void 0;(function(e){e.File="file",e.Link="link",e.Artifact="artifact",e.Context="context"})(exports.AgentAttachmentType||(exports.AgentAttachmentType={}));exports.AgentToolCallStatus=void 0;(function(e){e.Pending="pending",e.Running="running",e.Succeeded="succeeded",e.Failed="failed"})(exports.AgentToolCallStatus||(exports.AgentToolCallStatus={}));exports.AgentProcessStatus=void 0;(function(e){e.Queued="queued",e.ApprovalRequired="approvalRequired",e.Running="running",e.Paused="paused",e.Error="error",e.Complete="complete"})(exports.AgentProcessStatus||(exports.AgentProcessStatus={}));exports.StreamChunkType=void 0;(function(e){e.Message="message",e.Reasoning="reasoning",e.Tool="tool",e.Artifact="artifact",e.Error="error",e.Chat="chat"})(exports.StreamChunkType||(exports.StreamChunkType={}));exports.ChatType=void 0;(function(e){e.Chat="chat",e.Agent="agent"})(exports.ChatType||(exports.ChatType={}));exports.AgentStatus=void 0;(function(e){e.Processing="processing",e.Streaming="streaming",e.Finished="finished",e.Aborted="aborted",e.WaitingForUserAction="waitingForUserAction",e.Error="error",e.Timedout="timedout"})(exports.AgentStatus||(exports.AgentStatus={}));exports.AgentToolType=void 0;(function(e){e.API_TOOL="api_tool",e.WEB_SEARCH="web_search",e.LOCAL_FUNCTION="local_function",e.SUBAGENT="subagent",e.REQUEST_CLARIFICATION="request_clarification"})(exports.AgentToolType||(exports.AgentToolType={}));exports.ActivityOperationName=void 0;(function(e){e.MESSAGE_PROCESSING="messageProcessing",e.AGENT_SELECTION="agentSelection",e.STEP_FINISHED="stepFinished",e.TITLE_GENERATION="titleGeneration",e.SUBAGENT="subagent"})(exports.ActivityOperationName||(exports.ActivityOperationName={}));exports.AgentSessionKind=void 0;(function(e){e.ROOT="ROOT",e.SUBAGENT="SUBAGENT"})(exports.AgentSessionKind||(exports.AgentSessionKind={}));var fi={ChatNew:"chat:new",MessageNew:"message:new",ChatUpdate:"chat:update",ChatSubscribe:"chat:subscribe",ChatUnsubscribe:"chat:unsubscribe"},Ai={Path:"/socket.io",UserRoomPrefix:"user:",DefaultUserId:"guest"},c5=["webSnippet","formSnapshot","formField"],$7=B.z.string().datetime({offset:!0}).or(B.z.string().datetime()),F7=B.z.object({app:B.z.string().min(1).optional(),url:B.z.string().url().optional(),route:B.z.string().min(1).optional(),domPath:B.z.string().min(1).optional()}).strict(),P7=B.z.object({containsPII:B.z.boolean().optional(),redactionsApplied:B.z.array(B.z.string().min(1)).max(50).optional()}).strict(),q7=B.z.union([B.z.object({type:B.z.literal("text"),exact:B.z.string().min(1).max(4e3),prefix:B.z.string().min(1).max(500).optional(),suffix:B.z.string().min(1).max(500).optional(),domPath:B.z.string().min(1).max(2e3).optional(),startOffset:B.z.number().int().min(0).optional(),endOffset:B.z.number().int().min(0).optional()}).strict(),B.z.object({type:B.z.literal("dom"),domPath:B.z.string().min(1).max(2e3)}).strict(),B.z.object({type:B.z.literal("form"),formId:B.z.string().min(1).max(200).optional(),fieldName:B.z.string().min(1).max(200).optional(),domPath:B.z.string().min(1).max(2e3).optional()}).strict()]),Xi=B.z.object({schemaVersion:B.z.literal(1),kind:B.z.string().min(1).max(100),capturedAt:$7,source:F7.optional(),security:P7.optional(),target:q7.optional()}),B7=Xi.extend({kind:B.z.literal("webSnippet"),title:B.z.string().min(1).max(200).optional(),selectedText:B.z.string().min(1).max(4e3)}).strict(),U7=Xi.extend({kind:B.z.literal("formSnapshot"),formId:B.z.string().min(1).max(200).optional(),formName:B.z.string().min(1).max(200).optional(),fields:B.z.array(B.z.object({name:B.z.string().min(1).max(200),label:B.z.string().min(1).max(200).optional(),value:B.z.string().min(0).max(1e3),inputType:B.z.enum(["text","textarea","number","select","radio","checkbox","date","email","tel"]).optional(),options:B.z.array(B.z.object({value:B.z.string().min(0).max(500),label:B.z.string().min(0).max(500)}).strict()).max(200).optional(),domPath:B.z.string().min(1).max(2e3).optional()}).strict()).min(1).max(50)}).strict(),H7=Xi.extend({kind:B.z.literal("formField"),formId:B.z.string().min(1).max(200).optional(),fieldName:B.z.string().min(1).max(200),fieldLabel:B.z.string().min(1).max(200).optional(),value:B.z.string().min(0).max(1e3),inputType:B.z.enum(["text","textarea","number","select","radio","checkbox","date","email","tel"]).optional(),options:B.z.array(B.z.object({value:B.z.string().min(0).max(500),label:B.z.string().min(0).max(500)}).strict()).max(200).optional(),domPath:B.z.string().min(1).max(2e3).optional()}).strict(),j7=Xi.extend({kind:B.z.string().min(1).max(100).refine(function(e){return!c5.includes(e)},"kind must not collide with built-in kinds"),title:B.z.string().min(1).max(200).optional(),summary:B.z.string().min(1).max(4e3).optional(),data:B.z.record(B.z.string().min(1).max(200),B.z.unknown()).optional()}).strict().superRefine(function(e,t){if(e.data){var n=JSON.stringify(e.data);n.length>12e3&&t.addIssue({code:"custom",message:"data is too large (max ~12k JSON chars)",path:["data"]})}}),u5=B.z.union([B7,U7,H7,j7]),Ba=B.z.object({id:B.z.string().min(1),type:B.z.nativeEnum(exports.AgentAttachmentType),name:B.z.string().min(1).max(500),url:B.z.string().url().optional(),mimeType:B.z.string().min(1).max(200).optional(),metadata:B.z.record(B.z.string(),B.z.unknown()).optional()}).strict(),d5=B.z.union([Ba.extend({type:B.z.literal(exports.AgentAttachmentType.Context),metadata:u5}).strict(),Ba.extend({type:B.z.literal(exports.AgentAttachmentType.File),size:B.z.number().int().min(0).optional(),metadata:B.z.object({uploadedAt:B.z.string().optional(),s3Key:B.z.string().optional(),processingStatus:B.z.enum(["pending","processed","failed"]).optional(),size:B.z.number().int().min(0).optional(),lastModified:B.z.number().optional()}).optional()}).strict(),Ba.extend({type:B.z.literal(exports.AgentAttachmentType.Link)}).strict(),Ba.extend({type:B.z.literal(exports.AgentAttachmentType.Artifact)}).strict()]),V7=B.z.object({chatId:B.z.string().optional(),content:B.z.string().min(1),contextKey:B.z.string().min(1),attachments:B.z.array(d5).optional(),metadata:B.z.record(B.z.string(),B.z.unknown()).optional(),model:B.z.string().optional(),temperature:B.z.number().optional(),userId:B.z.string().optional(),participantIds:B.z.array(B.z.string().min(1)).optional(),mentions:B.z.array(B.z.object({type:B.z.enum(["user","agent"]),name:B.z.string().min(1),id:B.z.string().optional()}).strict()).optional()}).strict();new TextEncoder;const G7=new TextDecoder,W7=3;class Or{constructor(t){this.config=t}streamControllers=new Map;socketId;updateConfig(t){if(t.mode!=="proxy")throw new Error("ProxyTransport.updateConfig requires proxy mode configuration");this.config=t}setSocketId(t){this.socketId=t}withHeaders(t,n){const r={...this.config.headers,...t};this.config.apiKey&&(r.Authorization=`Bearer ${this.config.apiKey}`);const a=n?.body!==void 0&&n?.body!==null,i=Object.keys(r).some(o=>o.toLowerCase()==="content-type");return a&&!i&&(r["Content-Type"]="application/json"),r}async formatHttpError(t,n){const r=n.status,a=n.statusText,i=n.headers.get("content-type")??"";let o;try{if(i.includes("application/json")){const l=await n.json();o=typeof l?.message=="string"&&l.message||typeof l?.error=="string"&&l.error||typeof l?.detail=="string"&&l.detail||typeof l?.title=="string"&&l.title||typeof l=="string"&&l||(l?JSON.stringify(l):void 0)}else{const l=(await n.text()).trim();!/<\s*html[\s>]|<\s*body[\s>]/i.test(l)&&l&&(o=l.length>500?l.slice(0,500)+"…":l)}}catch{}const s=`Message sending failed (${r}${a?` ${a}`:""}).`;return{message:o?`${s} ${o}`:`${s} Please try again.`,statusCode:r}}async request(t,n){const r=await fetch(`${this.config.baseUrl}${t}`,{...n,credentials:"include",headers:this.withHeaders(n?.headers,n),signal:n?.signal});if(!r.ok){const{message:i,statusCode:o}=await this.formatHttpError(t,r),s=new Gu(i,o);throw this.config.onError?.(s),s}if(r.status===204)return;if(r.headers.get("content-type")?.includes("application/json")){const i=await r.text();return i?JSON.parse(i):void 0}const a=await r.text();if(a)return JSON.parse(a)}async sendMessage(t){const n={};return this.socketId&&(n["x-socket-id"]=this.socketId),this.request("/chats/send",{method:"POST",headers:n,body:JSON.stringify(t)})}async streamMessage(t,n,r){const a=r?.streamKey??t.chatId??`stream-${Date.now()}-${Math.random().toString(16).slice(2)}`,i=new AbortController,o=setTimeout(()=>i.abort(),this.config.timeoutMs??5*60*1e3);try{const s={Accept:"text/event-stream"};if(this.socketId&&(s["x-socket-id"]=this.socketId),i.signal.aborted)throw new Error("Stream was aborted before fetch started");this.streamControllers.set(a,i);const l=await fetch(`${this.config.baseUrl}/chats/stream`,{method:"POST",signal:i.signal,credentials:"include",body:JSON.stringify(t),headers:this.withHeaders(s,{method:"POST",body:JSON.stringify(t)})});if(!l.ok){const{message:m,statusCode:h}=await this.formatHttpError("/chats/stream",l),g=new Gu(m,h);throw this.config.onError?.(g),g}if(!l.body)throw new Error("Streaming response body missing");const u=l.body.getReader();let d="",p;for(;;){const{value:m,done:h}=await u.read();if(h)break;d+=G7.decode(m,{stream:!0});const g=d.split(`
|
|
2
2
|
|
|
3
3
|
`);d=g.pop()??"";for(const f of g){const w=f.trim();if(!w.startsWith("data:"))continue;const v=w.replace(/^data:\s*/,"");if(!v||v==="[DONE]"){n({type:exports.StreamChunkType.Message,done:!0});continue}let k;try{k=JSON.parse(v)}catch(_){console.error("Failed to parse SSE chunk",_);continue}k.message?.chat&&(p=k.message.chat,this.streamControllers.set(p,i)),n(k)}}if(p)try{const m=await this.getMessages(p,{limit:W7});return{id:p,messages:m.messages}}catch(m){console.error("Failed to fetch messages after streaming",m)}}finally{clearTimeout(o);const s=[];for(const[l,u]of this.streamControllers.entries())u===i&&s.push(l);s.forEach(l=>this.streamControllers.delete(l))}}async sendMultiUserMessage(t){const n=t.chatId?`/chats/${encodeURIComponent(t.chatId)}/messages`:"/chats/multi-user/messages";return this.request(n,{method:"POST",body:JSON.stringify(t)})}cancelStream(t){this.cancelHttpStream(t),t&&this.request(`/chats/${t}/abort`,{method:"POST",body:JSON.stringify({})}).catch(n=>{console.error("Failed to call abort API:",n)})}cancelHttpStream(t){if(t){const r=this.streamControllers.get(t);if(r){r.abort();const a=[];for(const[i,o]of this.streamControllers.entries())o===r&&a.push(i);a.forEach(i=>this.streamControllers.delete(i))}return}const n=new Set(this.streamControllers.values());for(const r of n)r.abort();this.streamControllers.clear()}async listChats(t){const n=new URLSearchParams;t?.contextKey&&n.set("contextKey",t.contextKey),t?.skip!=null&&n.set("skip",String(t.skip)),t?.limit&&n.set("limit",String(t.limit)),t?.userId&&n.set("userId",t.userId),t?.multiUser!==void 0&&n.set("multiUser",String(t.multiUser)),t?.sortField&&n.set("sortField",t.sortField),t?.sortOrder&&n.set("sortOrder",t.sortOrder);const r=await this.request(`/chats?${n.toString()}`);return{cursor:r.cursor,data:r.data}}async getChat(t){return await this.request(`/chats/${t}`)}async getMessages(t,n){const r=new URLSearchParams({});return n?.limit!=null&&r.set("limit",String(n.limit)),n?.before&&r.set("before",n.before),this.request(`/chats/${t}/messages?${r.toString()}`)}deleteChat(t){return this.request(`/chats/${t}`,{method:"DELETE"})}listAgents(){return this.request("/agents")}controlAgent(t){return this.request(`/agents/${t.id}/control`,{method:"POST",body:JSON.stringify({action:t.action})})}listArtifacts(t){return this.request(`/chats/${t}/artifacts`)}listActivities(t){const n=new URLSearchParams;return t?.groupId&&n.set("groupId",t.groupId),t?.parentId&&n.set("parentId",t.parentId),t?.sourceType&&n.set("sourceType",t.sourceType),t?.skip!=null&&n.set("skip",String(t.skip)),t?.limit!=null&&n.set("limit",String(t.limit)),t?.sort!=null&&(n.set("sortField",t.sort.field),n.set("sortOrder",t.sort.order)),t?.from&&n.set("from",t.from),t?.to&&n.set("to",t.to),t?.tenant&&n.set("tenant",JSON.stringify(t.tenant)),t?.ownerId&&n.set("ownerId",t.ownerId),this.request(`/activities?${n.toString()}`)}listActivitySourceTypes(t){const n=new URLSearchParams;t?.groupId&&n.set("groupId",t.groupId),t?.parentId&&n.set("parentId",t.parentId),t?.from&&n.set("from",t.from),t?.to&&n.set("to",t.to),t?.tenant&&n.set("tenant",JSON.stringify(t.tenant)),t?.ownerId&&n.set("ownerId",t.ownerId);const r=n.toString();return this.request(r?`/activities/source-types?${r}`:"/activities/source-types")}async getActivity(t){return this.request(`/activities/${t}`)}async getActivitySummary(t){const n=new URLSearchParams;t?.period?.from&&n.set("from",t.period.from instanceof Date?t.period.from.toISOString():t.period.from),t?.period?.to&&n.set("to",t.period.to instanceof Date?t.period.to.toISOString():t.period.to),t?.timeBucket&&n.set("timeBucket",t.timeBucket),t?.model&&n.set("model",t.model),t?.tenant&&n.set("tenant",JSON.stringify(t.tenant)),t?.ownerId&&n.set("ownerId",t.ownerId),t?.groupBy?.length&&n.set("groupBy",t.groupBy.join(","));const r=n.toString();return this.request(r?`/activities/summary?${r}`:"/activities/summary")}async recordToolCallAction(t,n,r){const a={};return r?.excludeSocketId!==!1&&this.socketId&&(a["x-socket-id"]=this.socketId),this.request(`/chats/${t}/actions`,{method:"POST",headers:a,body:JSON.stringify({kind:"toolCall",toolCallId:n.toolCallId,action:n.action,...n.data?{data:n.data}:{},...n.systemMessage?{systemMessage:n.systemMessage}:{}})})}async updateToolCall(t,n){const r={};return n?.excludeSocketId!==!1&&this.socketId&&(r["x-socket-id"]=this.socketId),this.request(`/chats/${t.chatId}/messages/${t.messageId}/tool-calls/${t.toolCallId}`,{method:"PATCH",headers:r,body:JSON.stringify({...t.input!==void 0?{input:t.input}:{},...t.output!==void 0?{output:t.output}:{},...t.status!==void 0?{status:t.status}:{}})})}async generateTitle(t){return`${t.contextKey} request ${new Date().toISOString()}`}async listModels(){return(await this.request("/models")).models}async listAgentConfigurations(t){const n=new URLSearchParams;t&&n.set("contextKey",t);const r=n.toString();return(await this.request(r?`/agents/config?${r}`:"/agents/config")).agents}async upsertAgentPreferences(t,n){return this.request(`/agents/${encodeURIComponent(t)}/preferences`,{method:"POST",body:JSON.stringify(n)})}async upsertAgentPreferencesBatch(t){return this.request("/agents/preferences",{method:"POST",body:JSON.stringify(t)})}}const K7="mp-agents-chats",Y7=4,Bt="chats",Ot="messages";class Z7{db=null;initPromise=null;async init(){if(!this.db)return this.initPromise?this.initPromise:(this.initPromise=new Promise((t,n)=>{const r=indexedDB.open(K7,Y7);r.onerror=()=>n(new Error("Failed to open IndexedDB")),r.onsuccess=()=>{this.db=r.result,t()},r.onupgradeneeded=a=>{const i=a.target.result;a.oldVersion;let o;i.objectStoreNames.contains(Bt)?o=r.transaction.objectStore(Bt):o=i.createObjectStore(Bt,{keyPath:"id"}),o.indexNames.contains("contextKey")||o.createIndex("contextKey","contextKey",{unique:!1}),o.indexNames.contains("updatedAt")||o.createIndex("updatedAt","updatedAt",{unique:!1}),o.indexNames.contains("userId")&&o.deleteIndex("userId"),o.indexNames.contains("tenants.userId")||o.createIndex("tenants.userId","tenants.userId",{unique:!1}),i.objectStoreNames.contains(Ot)||i.createObjectStore(Ot,{keyPath:"chatId"}).createIndex("chatId","chatId",{unique:!0})}}),this.initPromise)}normalizeStoredChat(t){const{messages:n,...r}=t;if(r.tenants?.userId)return r;const a=t.userId??"guest";return{...r,tenants:{...r.tenants??{},userId:a}}}async saveChat(t){if(await this.init(),!this.db)throw new Error("IndexedDB not initialized");const{messages:n,...r}=t;return new Promise((a,i)=>{const l=this.db.transaction([Bt],"readwrite").objectStore(Bt).put(r);l.onsuccess=()=>a(),l.onerror=()=>i(new Error("Failed to save chat"))})}async getChat(t){if(await this.init(),!this.db)throw new Error("IndexedDB not initialized");return new Promise((n,r)=>{const a=this.db.transaction([Bt,Ot],"readwrite"),i=a.objectStore(Bt),o=i.get(t);o.onsuccess=async()=>{const s=o.result;if(!s){n(null);return}if(s.messages&&Array.isArray(s.messages)){const u=s.messages,{messages:d,...p}=s;a.objectStore(Ot).put({chatId:t,messages:u}),i.put(p)}const l=this.normalizeStoredChat(s);i.put(l),n(l)},o.onerror=()=>r(new Error("Failed to get chat"))})}async listChats(t){if(await this.init(),!this.db)throw new Error("IndexedDB not initialized");return new Promise((n,r)=>{const a=this.db.transaction([Bt,Ot],"readwrite"),i=a.objectStore(Bt),o=i.getAll();o.onsuccess=()=>{let s=o.result??[];const l=a.objectStore(Ot);if(s=s.map(u=>{if(u.messages&&Array.isArray(u.messages)){l.put({chatId:u.id,messages:u.messages});const p=this.normalizeStoredChat(u);return i.put(p),p}const d=this.normalizeStoredChat(u);return i.put(d),d}),t?.contextKey&&(s=s.filter(u=>u.contextKey===t.contextKey)),t?.userId){const u=t.userId??"guest";s=s.filter(d=>(d.tenants?.userId??"guest")===u)}t?.multiUser!==void 0&&(s=s.filter(u=>(u.participantIds?.length??0)>1===t.multiUser)),s.sort((u,d)=>u.updatedAt<d.updatedAt?1:-1),n(s)},o.onerror=()=>r(new Error("Failed to list chats"))})}async deleteChat(t){if(await this.init(),!this.db)throw new Error("IndexedDB not initialized");return new Promise((n,r)=>{const a=this.db.transaction([Bt,Ot],"readwrite");a.objectStore(Bt).delete(t),a.objectStore(Ot).delete(t),a.oncomplete=()=>n(),a.onerror=()=>r(new Error("Failed to delete chat"))})}async clearAll(){if(await this.init(),!this.db)throw new Error("IndexedDB not initialized");return new Promise((t,n)=>{const r=this.db.transaction([Bt,Ot],"readwrite");r.objectStore(Bt).clear(),r.objectStore(Ot).clear(),r.oncomplete=()=>t(),r.onerror=()=>n(new Error("Failed to clear"))})}async getMessages(t){return await this.init(),this.db?new Promise((n,r)=>{const o=this.db.transaction([Ot],"readonly").objectStore(Ot).get(t);o.onsuccess=()=>{const s=o.result;n(s?.messages??[])},o.onerror=()=>r(new Error("Failed to get messages"))}):[]}async saveMessages(t,n){if(await this.init(),!this.db)throw new Error("IndexedDB not initialized");return new Promise((r,a)=>{const s=this.db.transaction([Ot],"readwrite").objectStore(Ot).put({chatId:t,messages:n});s.onsuccess=()=>r(),s.onerror=()=>a(new Error("Failed to save messages"))})}async appendMessages(t,n){const r=await this.getMessages(t);r.push(...n),await this.saveMessages(t,r)}}const ft=new Z7,X7=new TextDecoder,Q7=3;class $o{constructor(t){if(this.config=t,t.mode!=="direct")throw new Error("DirectTransport requires direct mode configuration");if(!t.model)throw new Error("DirectTransport requires a model to be specified");if(!t.apiKey)throw new Error("DirectTransport requires an API key. Set VITE_LLM_API_KEY in your .env file");this.initializeStorage().catch(n=>{console.error("Failed to initialize chat storage:",n)})}chats=new Map;chatState=new Map;toolRegistry;streamControllers=new Map;contextKeys;initialized=!1;models;untitledChatText="Untitled chat";updateConfig(t){if(t.mode!=="direct")throw new Error("DirectTransport.updateConfig requires direct mode configuration");if(!t.model)throw new Error("DirectTransport requires a model to be specified");if(!t.apiKey)throw new Error("DirectTransport requires an API key");this.config=t}setContextKeys(t){this.contextKeys=t}async initializeStorage(){if(!this.initialized)try{(await ft.listChats()).forEach(n=>{this.chats.set(n.id,n)}),this.initialized=!0}catch(t){console.error("Failed to load chats from IndexedDB:",t),this.initialized=!0}}generateLocalTitle(t){const r=(t.split(`
|
|
4
4
|
`).map(s=>s.trim()).find(s=>s.length>0)??"").replace(/^(\#{1,6}\s+|\d+\.\s+|[-*+]\s+)/,"").replace(/\s+/g," ").trim();if(!r)return this.untitledChatText;const a=80;if(r.length<=a)return r;const i=r.slice(0,a),o=i.lastIndexOf(" ");return o>a*.6?`${i.slice(0,o)}…`:`${i}…`}setToolRegistry(t){this.toolRegistry=t}setModels(t){this.models=t}setUntitledChatText(t){this.untitledChatText=t}toolsToFunctions(t){if(!this.toolRegistry)return;const n=this.toolRegistry.list();return n.length===0?void 0:(t?n.filter(a=>!0):n).map(a=>this.toolToFunction(a))}toolToFunction(t){return{type:"function",function:{name:t.name,description:t.description||t.label,parameters:this.normalizeSchema(t.schema)}}}normalizeSchema(t){if(!t||typeof t!="object")return{type:"object",properties:{},required:[]};const n=t,r={};if(n.properties&&typeof n.properties=="object")for(const[i,o]of Object.entries(n.properties))r[i]=this.normalizePropertySchema(o);const a=Array.isArray(n.required)&&n.required.every(i=>typeof i=="string")?n.required:[];return{type:"object",properties:r,required:a}}normalizePropertySchema(t){if(!t||typeof t!="object"||Array.isArray(t))return{};const n=t,r=typeof n.type=="string"?n.type:void 0;if(r==="enum"){const a=Array.isArray(n.options)?n.options.filter(s=>typeof s=="string"):[],i={type:"string"};a.length>0&&(i.enum=a);const o=this.extractDescription(n);return o&&(i.description=o),typeof n.default=="string"&&(i.default=n.default),i}if(r==="string"&&("label"in n||"placeholder"in n)){const a={type:"string"},i=this.extractDescription(n);return i&&(a.description=i),typeof n.default=="string"&&(a.default=n.default),a}return n}extractDescription(t){if(typeof t.description=="string")return t.description;if(typeof t.label=="string")return t.label}endpoint(){if(this.config.provider==="openrouter")return this.config.endpoint??"https://openrouter.ai/api/v1/chat/completions";if(this.config.provider==="openai")return this.config.endpoint??"https://api.openai.com/v1/chat/completions";if(!this.config.endpoint)throw new Error("Custom direct transport requires endpoint");return this.config.endpoint}buildHeaders(){const t={"Content-Type":"application/json",...this.config.headers};return this.config.apiKey&&(t.Authorization=`Bearer ${this.config.apiKey}`),t}async clearErrorMessages(t){const n=await ft.getMessages(t);if(!n.length)return;const r=n.filter(a=>a.role!==exports.MessageRole.Error);r.length!==n.length&&await ft.saveMessages(t,r)}async appendErrorMessage(t,n){const r={id:_t.nanoid(),chat:t,content:n,role:exports.MessageRole.Error,createdAt:new Date().toISOString(),reasoning:"",toolCalls:[],attachments:[]};await ft.appendMessages(t,[r])}attachChatToError(t,n,r){const a=t instanceof Error?t:new Error(r);return a.chat||Object.defineProperty(a,"chat",{value:n,configurable:!0,enumerable:!1,writable:!0}),a}async ensureChat(t){if(await this.initializeStorage(),t.chatId&&this.chats.has(t.chatId))return this.chats.get(t.chatId);if(t.chatId)try{const o=await ft.getChat(t.chatId);if(o)return this.chats.set(o.id,o),o}catch(o){console.error("Failed to load chat from IndexedDB:",o)}const n=t.metadata?.title,r=typeof n=="string"&&n.trim().length>0?n:this.generateLocalTitle(t.content),a=t.userId??t.tenants?.userId??"guest",i={id:t.chatId??_t.nanoid(),title:r,type:exports.ChatType.Chat,status:exports.AgentStatus.Processing,contextKey:t.contextKey,tenants:{...t.tenants??{},userId:a},createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};return this.chats.set(i.id,i),await this.persistChat(i),i}async persistChat(t){t.updatedAt=new Date().toISOString(),this.chats.set(t.id,t),ft.saveChat(t).catch(n=>{console.error("Failed to persist chat to IndexedDB:",n)})}toOpenAIMessage(t){return{role:t.role===exports.MessageRole.Reasoning?exports.MessageRole.Assistant:t.role,content:t.content}}async callModel(t,n,r){const a=n??this.config.model;if(!a)throw new Error("Model is required. Either specify in payload or config.");const i={model:a,messages:t.map(d=>this.toOpenAIMessage(d))},o=await fetch(this.endpoint(),{method:"POST",headers:this.buildHeaders(),body:JSON.stringify(i)});if(!o.ok)throw new Error(`The AI provider returned an error (status ${o.status}).`);return(await o.json()).choices?.[0]?.message?.content??""}async generateLlmTitle(t){const n=this.config.model;if(!n)return this.generateLocalTitle(t.content);const r=["You generate very short, human-friendly chat titles.","Rules:","- At most 8 words.","- No quotes, no markdown, no emojis.","- Summarize the main intent of the user message.","","User message:",t.content].join(`
|
|
@@ -8287,7 +8287,7 @@
|
|
|
8287
8287
|
*/const e6e=Object.freeze(Object.defineProperty({__proto__:null,AArrowDown:o_,AArrowUp:l_,ALargeSmall:u_,Accessibility:p_,Activity:m_,AirVent:g_,Airplay:b_,AlarmClock:S_,AlarmClockCheck:v_,AlarmClockMinus:w_,AlarmClockOff:E_,AlarmClockPlus:A_,AlarmSmoke:C_,Album:I_,AlignCenterHorizontal:L_,AlignCenterVertical:z_,AlignEndHorizontal:F_,AlignEndVertical:q_,AlignHorizontalDistributeCenter:U_,AlignHorizontalDistributeEnd:j_,AlignHorizontalDistributeStart:G_,AlignHorizontalJustifyCenter:K_,AlignHorizontalJustifyEnd:Z_,AlignHorizontalJustifyStart:Q_,AlignHorizontalSpaceAround:ew,AlignHorizontalSpaceBetween:aw,AlignStartHorizontal:nw,AlignStartVertical:ow,AlignVerticalDistributeCenter:lw,AlignVerticalDistributeEnd:uw,AlignVerticalDistributeStart:mw,AlignVerticalJustifyCenter:pw,AlignVerticalJustifyEnd:gw,AlignVerticalJustifyStart:bw,AlignVerticalSpaceAround:vw,AlignVerticalSpaceBetween:ww,Ambulance:Ew,Ampersand:Sw,Ampersands:Aw,Amphora:Cw,Anchor:Iw,Angry:Lw,Annoyed:zw,Antenna:Fw,Anvil:qw,Aperture:Uw,AppWindow:Gw,AppWindowMac:jw,Apple:Kw,Archive:ex,ArchiveRestore:Zw,ArchiveX:Qw,Armchair:nx,ArrowBigDown:ox,ArrowBigDownDash:ax,ArrowBigLeft:ux,ArrowBigLeftDash:lx,ArrowBigRight:mx,ArrowBigRightDash:px,ArrowBigUp:bx,ArrowBigUpDash:gx,ArrowDown:jx,ArrowDown01:vx,ArrowDown10:wx,ArrowDownAZ:Ex,ArrowDownFromLine:Sx,ArrowDownLeft:Ax,ArrowDownNarrowWide:Cx,ArrowDownRight:Ix,ArrowDownToDot:Lx,ArrowDownToLine:zx,ArrowDownUp:Fx,ArrowDownWideNarrow:qx,ArrowDownZA:Ux,ArrowLeft:Qx,ArrowLeftFromLine:Gx,ArrowLeftRight:Kx,ArrowLeftToLine:Zx,ArrowRight:o9,ArrowRightFromLine:e9,ArrowRightLeft:n9,ArrowRightToLine:a9,ArrowUp:Dd,ArrowUp01:l9,ArrowUp10:u9,ArrowUpAZ:p9,ArrowUpDown:m9,ArrowUpFromDot:g9,ArrowUpFromLine:b9,ArrowUpLeft:v9,ArrowUpNarrowWide:w9,ArrowUpRight:E9,ArrowUpToLine:S9,ArrowUpWideNarrow:A9,ArrowUpZA:C9,ArrowsUpFromLine:D9,Asterisk:O9,AtSign:$9,Atom:P9,AudioLines:B9,AudioWaveform:H9,Award:V9,Axe:W9,Axis3d:X9,Baby:Y9,Backpack:J9,Badge:DE,BadgeAlert:tE,BadgeCent:rE,BadgeCheck:iE,BadgeDollarSign:sE,BadgeEuro:cE,BadgeIndianRupee:dE,BadgeInfo:hE,BadgeJapaneseYen:fE,BadgeMinus:yE,BadgePercent:kE,BadgePlus:_E,BadgePoundSterling:xE,BadgeQuestionMark:ME,BadgeRussianRuble:NE,BadgeSwissFranc:TE,BadgeTurkishLira:RE,BadgeX:OE,BaggageClaim:$E,Ban:PE,Banana:BE,Bandage:HE,Banknote:JE,BanknoteArrowDown:VE,BanknoteArrowUp:WE,BanknoteX:YE,Barcode:XE,Barrel:tM,Baseline:rM,Bath:iM,Battery:kM,BatteryCharging:cM,BatteryFull:sM,BatteryLow:dM,BatteryMedium:hM,BatteryPlus:fM,BatteryWarning:yM,Beaker:_M,Bean:MM,BeanOff:xM,Bed:RM,BedDouble:NM,BedSingle:TM,Beef:OM,Beer:$M,BeerOff:DM,Bell:XM,BellDot:PM,BellElectric:BM,BellMinus:HM,BellOff:VM,BellPlus:WM,BellRing:YM,BetweenHorizontalEnd:JM,BetweenHorizontalStart:tS,BetweenVerticalEnd:rS,BetweenVerticalStart:iS,BicepsFlexed:sS,Bike:cS,Binary:dS,Binoculars:hS,Biohazard:fS,Bird:yS,Birdhouse:kS,Bitcoin:_S,Blend:xS,Blinds:MS,Blocks:NS,Bluetooth:DS,BluetoothConnected:TS,BluetoothOff:RS,BluetoothSearching:OS,Bold:$S,Bolt:PS,Bomb:BS,Bone:HS,Book:PN,BookA:VS,BookAlert:WS,BookAudio:YS,BookCheck:XS,BookCopy:JS,BookDashed:rN,BookDown:tN,BookHeadphones:iN,BookHeart:sN,BookImage:cN,BookKey:dN,BookLock:hN,BookMarked:fN,BookMinus:yN,BookOpen:_N,BookOpenCheck:kN,BookOpenText:xN,BookPlus:MN,BookText:NN,BookType:TN,BookUp:ON,BookUp2:RN,BookUser:DN,BookX:$N,Bookmark:YN,BookmarkCheck:BN,BookmarkMinus:HN,BookmarkPlus:VN,BookmarkX:WN,BoomBox:XN,Bot:rA,BotMessageSquare:JN,BotOff:tA,BottleWine:sA,BowArrow:iA,Box:cA,Boxes:dA,Braces:hA,Brackets:fA,Brain:xA,BrainCircuit:yA,BrainCog:kA,BrickWall:NA,BrickWallFire:_A,BrickWallShield:MA,Briefcase:$A,BriefcaseBusiness:TA,BriefcaseConveyorBelt:RA,BriefcaseMedical:OA,BringToFront:DA,Brush:BA,BrushCleaning:PA,Bubbles:HA,Bug:YA,BugOff:VA,BugPlay:WA,Building:JA,Building2:XA,Bus:rT,BusFront:tT,Cable:sT,CableCar:iT,Cake:dT,CakeSlice:cT,Calculator:hT,Calendar:tC,Calendar1:fT,CalendarArrowDown:yT,CalendarArrowUp:kT,CalendarCheck:xT,CalendarCheck2:_T,CalendarClock:NT,CalendarCog:MT,CalendarDays:TT,CalendarFold:RT,CalendarHeart:OT,CalendarMinus:$T,CalendarMinus2:DT,CalendarOff:PT,CalendarPlus:HT,CalendarPlus2:BT,CalendarRange:VT,CalendarSearch:WT,CalendarSync:YT,CalendarX:JT,CalendarX2:XT,Calendars:rC,Camera:sC,CameraOff:iC,Candy:hC,CandyCane:cC,CandyOff:dC,Cannabis:fC,Captions:kC,CaptionsOff:yC,Car:MC,CarFront:_C,CarTaxiFront:xC,Caravan:NC,CardSim:TC,Carrot:RC,CaseLower:OC,CaseSensitive:DC,CaseUpper:$C,CassetteTape:PC,Cast:BC,Castle:HC,Cat:VC,Cctv:WC,ChartArea:YC,ChartBar:iR,ChartBarBig:XC,ChartBarDecreasing:JC,ChartBarIncreasing:tR,ChartBarStacked:rR,ChartCandlestick:sR,ChartColumn:yR,ChartColumnBig:cR,ChartColumnDecreasing:dR,ChartColumnIncreasing:hR,ChartColumnStacked:fR,ChartGantt:kR,ChartLine:_R,ChartNetwork:xR,ChartNoAxesColumn:TR,ChartNoAxesColumnDecreasing:MR,ChartNoAxesColumnIncreasing:NR,ChartNoAxesCombined:OR,ChartNoAxesGantt:RR,ChartPie:DR,ChartScatter:$R,ChartSpline:PR,Check:VR,CheckCheck:BR,CheckLine:HR,ChefHat:WR,Cherry:YR,ChessBishop:XR,ChessKing:JR,ChessKnight:rI,ChessPawn:tI,ChessQueen:iI,ChessRook:sI,ChevronDown:zd,ChevronFirst:uI,ChevronLast:pI,ChevronLeft:gI,ChevronRight:mI,ChevronUp:h5,ChevronsDown:_I,ChevronsDownUp:kI,ChevronsLeft:NI,ChevronsLeftRight:MI,ChevronsLeftRightEllipsis:xI,ChevronsRight:RI,ChevronsRightLeft:TI,ChevronsUp:DI,ChevronsUpDown:OI,Chromium:$I,Church:BI,Cigarette:HI,CigaretteOff:PI,Circle:ML,CircleAlert:VI,CircleArrowDown:WI,CircleArrowLeft:YI,CircleArrowOutDownLeft:XI,CircleArrowOutDownRight:JI,CircleArrowOutUpLeft:tO,CircleArrowOutUpRight:rO,CircleArrowRight:iO,CircleArrowUp:sO,CircleCheck:dO,CircleCheckBig:cO,CircleChevronDown:hO,CircleChevronLeft:fO,CircleChevronRight:yO,CircleChevronUp:kO,CircleDashed:_O,CircleDivide:xO,CircleDollarSign:MO,CircleDot:TO,CircleDotDashed:NO,CircleEllipsis:RO,CircleEqual:OO,CircleFadingArrowUp:DO,CircleFadingPlus:$O,CircleGauge:PO,CircleMinus:BO,CircleOff:HO,CircleParking:WO,CircleParkingOff:VO,CirclePause:YO,CirclePercent:XO,CirclePlay:JO,CirclePlus:tL,CirclePoundSterling:rL,CirclePower:iL,CircleQuestionMark:sL,CircleSlash:dL,CircleSlash2:cL,CircleSmall:hL,CircleStar:fL,CircleStop:yL,CircleUser:_L,CircleUserRound:kL,CircleX:xL,CircuitBoard:NL,Citrus:TL,Clapperboard:RL,Clipboard:tD,ClipboardCheck:OL,ClipboardClock:DL,ClipboardCopy:$L,ClipboardList:PL,ClipboardMinus:BL,ClipboardPaste:HL,ClipboardPen:WL,ClipboardPenLine:VL,ClipboardPlus:YL,ClipboardType:XL,ClipboardX:JL,Clock:PD,Clock1:rD,Clock10:iD,Clock11:sD,Clock12:cD,Clock2:dD,Clock3:hD,Clock4:fD,Clock5:yD,Clock6:kD,Clock7:_D,Clock8:xD,Clock9:MD,ClockAlert:ND,ClockArrowDown:TD,ClockArrowUp:RD,ClockCheck:OD,ClockFading:DD,ClockPlus:$D,ClosedCaption:BD,Cloud:xz,CloudAlert:HD,CloudCheck:WD,CloudCog:VD,CloudDownload:YD,CloudDrizzle:XD,CloudFog:JD,CloudHail:tz,CloudLightning:rz,CloudMoon:sz,CloudMoonRain:iz,CloudOff:cz,CloudRain:hz,CloudRainWind:dz,CloudSnow:fz,CloudSun:kz,CloudSunRain:yz,CloudUpload:_z,Cloudy:Mz,Clover:Nz,Club:Tz,Code:Oz,CodeXml:Rz,Codepen:Dz,Codesandbox:$z,Coffee:Pz,Cog:Hz,Coins:Bz,Columns2:Vz,Columns3:Yz,Columns3Cog:Wz,Columns4:Xz,Combine:Jz,Command:t$,Compass:r$,Component:i$,Computer:s$,ConciergeBell:c$,Cone:d$,Construction:h$,Contact:y$,ContactRound:f$,Container:k$,Contrast:_$,Cookie:x$,CookingPot:M$,Copy:$$,CopyCheck:N$,CopyMinus:T$,CopyPlus:R$,CopySlash:O$,CopyX:D$,Copyleft:P$,Copyright:B$,CornerDownLeft:H$,CornerDownRight:V$,CornerLeftDown:W$,CornerLeftUp:Y$,CornerRightDown:X$,CornerRightUp:J$,CornerUpLeft:tF,CornerUpRight:rF,Cpu:iF,CreativeCommons:sF,CreditCard:cF,Croissant:dF,Crop:hF,Cross:fF,Crosshair:yF,Crown:kF,Cuboid:_F,CupSoda:xF,Currency:MF,Cylinder:NF,Dam:TF,Database:DF,DatabaseBackup:RF,DatabaseZap:OF,DecimalsArrowLeft:$F,DecimalsArrowRight:PF,Delete:BF,Dessert:HF,Diameter:VF,Diamond:JF,DiamondMinus:WF,DiamondPercent:YF,DiamondPlus:XF,Dice1:tP,Dice2:rP,Dice3:iP,Dice4:sP,Dice5:cP,Dice6:dP,Dices:hP,Diff:fP,Disc:xP,Disc2:yP,Disc3:kP,DiscAlbum:_P,Divide:MP,Dna:TP,DnaOff:NP,Dock:RP,Dog:OP,DollarSign:DP,Donut:$P,DoorClosed:BP,DoorClosedLocked:PP,DoorOpen:HP,Dot:VP,Download:WP,DraftingCompass:YP,Drama:XP,Dribbble:JP,Drill:tq,Drone:rq,Droplet:sq,DropletOff:iq,Droplets:cq,Drum:dq,Drumstick:fq,Dumbbell:hq,Ear:kq,EarOff:yq,Earth:xq,EarthLock:_q,Eclipse:Nq,Egg:Rq,EggFried:Mq,EggOff:Tq,Ellipsis:Dq,EllipsisVertical:Oq,Equal:Bq,EqualApproximately:$q,EqualNot:Pq,Eraser:Hq,EthernetPort:Vq,Euro:Wq,EvCharger:Yq,Expand:Jq,ExternalLink:Xq,Eye:sB,EyeClosed:tB,EyeOff:rB,Facebook:iB,Factory:cB,Fan:dB,FastForward:hB,Feather:yB,Fence:fB,FerrisWheel:kB,Figma:_B,File:wH,FileArchive:xB,FileAxis3d:MB,FileBadge:NB,FileBox:TB,FileBraces:OB,FileBracesCorner:RB,FileChartColumn:$B,FileChartColumnIncreasing:DB,FileChartLine:PB,FileChartPie:BB,FileCheck:VB,FileCheckCorner:HB,FileClock:YB,FileCode:XB,FileCodeCorner:WB,FileCog:JB,FileDiff:tU,FileDigit:rU,FileDown:iU,FileExclamationPoint:sU,FileHeadphone:cU,FileHeart:dU,FileImage:hU,FileInput:fU,FileKey:yU,FileLock:kU,FileMinus:xU,FileMinusCorner:_U,FileMusic:MU,FileOutput:NU,FilePen:RU,FilePenLine:TU,FilePlay:OU,FilePlus:$U,FilePlusCorner:DU,FileQuestionMark:PU,FileScan:BU,FileSearch:VU,FileSearchCorner:HU,FileSignal:YU,FileSliders:WU,FileSpreadsheet:JU,FileStack:XU,FileSymlink:tH,FileTerminal:aH,FileText:m5,FileType:lH,FileTypeCorner:oH,FileUp:uH,FileUser:pH,FileVideoCamera:mH,FileVolume:gH,FileX:vH,FileXCorner:bH,Files:EH,Film:SH,FingerprintPattern:AH,FireExtinguisher:CH,Fish:zH,FishOff:IH,FishSymbol:LH,Flag:jH,FlagOff:FH,FlagTriangleLeft:qH,FlagTriangleRight:UH,Flame:ZH,FlameKindling:GH,Flashlight:QH,FlashlightOff:KH,FlaskConical:nj,FlaskConicalOff:ej,FlaskRound:aj,FlipHorizontal:lj,FlipHorizontal2:oj,FlipVertical:pj,FlipVertical2:uj,Flower:gj,Flower2:mj,Focus:bj,FoldHorizontal:vj,FoldVertical:wj,Folder:AV,FolderArchive:Ej,FolderCheck:Sj,FolderClock:Aj,FolderClosed:Ij,FolderCode:Cj,FolderCog:Lj,FolderDot:zj,FolderDown:Fj,FolderGit:Uj,FolderGit2:qj,FolderHeart:jj,FolderInput:Gj,FolderKanban:Kj,FolderKey:Zj,FolderLock:Qj,FolderMinus:eV,FolderOpen:nV,FolderOpenDot:aV,FolderOutput:oV,FolderPen:lV,FolderPlus:uV,FolderRoot:pV,FolderSearch:gV,FolderSearch2:mV,FolderSymlink:bV,FolderSync:vV,FolderTree:wV,FolderUp:EV,FolderX:SV,Folders:CV,Footprints:IV,Forklift:LV,Form:f5,Forward:$V,Frame:PV,Framer:BV,Frown:HV,Fuel:VV,Fullscreen:WV,Funnel:JV,FunnelPlus:XV,FunnelX:YV,GalleryHorizontal:tG,GalleryHorizontalEnd:rG,GalleryThumbnails:iG,GalleryVertical:cG,GalleryVerticalEnd:sG,Gamepad:fG,Gamepad2:dG,GamepadDirectional:hG,Gauge:yG,Gavel:kG,Gem:_G,GeorgianLari:xG,Ghost:MG,Gift:TG,GitBranch:OG,GitBranchMinus:NG,GitBranchPlus:RG,GitCommitHorizontal:DG,GitCommitVertical:$G,GitCompare:BG,GitCompareArrows:PG,GitFork:HG,GitGraph:VG,GitMerge:WG,GitPullRequest:iW,GitPullRequestArrow:YG,GitPullRequestClosed:XG,GitPullRequestCreate:JG,GitPullRequestCreateArrow:tW,GitPullRequestDraft:rW,Github:cW,Gitlab:sW,GlassWater:hW,Glasses:dW,Globe:$d,GlobeLock:fW,Goal:bW,Gpu:vW,GraduationCap:wW,Grape:EW,Grid2x2:IW,Grid2x2Check:SW,Grid2x2Plus:AW,Grid2x2X:CW,Grid3x2:LW,Grid3x3:zW,Grip:UW,GripHorizontal:FW,GripVertical:qW,Group:jW,Guitar:GW,Ham:KW,Hamburger:ZW,Hammer:QW,Hand:pK,HandCoins:nK,HandFist:eK,HandGrab:aK,HandHeart:oK,HandHelping:lK,HandMetal:mK,HandPlatter:uK,Handbag:bK,Handshake:gK,HardDrive:EK,HardDriveDownload:vK,HardDriveUpload:wK,HardHat:SK,Hash:AK,HatGlasses:CK,Haze:IK,HdmiPort:LK,Heading:KK,Heading1:zK,Heading2:FK,Heading3:UK,Heading4:qK,Heading5:jK,Heading6:GK,HeadphoneOff:ZK,Headphones:QK,Headset:eY,Heart:mY,HeartCrack:nY,HeartHandshake:aY,HeartMinus:oY,HeartOff:lY,HeartPlus:uY,HeartPulse:pY,Heater:gY,Helicopter:bY,Hexagon:vY,Highlighter:wY,History:EY,Hop:AY,HopOff:SY,Hospital:CY,Hotel:IY,Hourglass:LY,House:jY,HouseHeart:zY,HousePlug:FY,HousePlus:qY,HouseWifi:UY,IceCreamBowl:GY,IceCreamCone:KY,IdCard:QY,IdCardLanyard:ZY,Image:mZ,ImageDown:eZ,ImageMinus:nZ,ImageOff:aZ,ImagePlay:oZ,ImagePlus:lZ,ImageUp:uZ,ImageUpscale:pZ,Images:gZ,Import:bZ,Inbox:vZ,IndianRupee:wZ,Infinity:EZ,Info:SZ,InspectionPanel:AZ,Instagram:CZ,Italic:IZ,IterationCcw:LZ,IterationCw:zZ,JapaneseYen:FZ,Joystick:qZ,Kanban:UZ,Kayak:jZ,Key:ZZ,KeyRound:GZ,KeySquare:KZ,Keyboard:nX,KeyboardMusic:QZ,KeyboardOff:eX,Lamp:mX,LampCeiling:aX,LampDesk:oX,LampFloor:lX,LampWallDown:uX,LampWallUp:pX,LandPlot:gX,Landmark:bX,Languages:vX,Laptop:SX,LaptopMinimal:EX,LaptopMinimalCheck:wX,Lasso:CX,LassoSelect:AX,Laugh:IX,Layers:zX,Layers2:LX,LayoutDashboard:FX,LayoutGrid:qX,LayoutList:UX,LayoutPanelLeft:jX,LayoutPanelTop:GX,LayoutTemplate:KX,Leaf:ZX,LeafyGreen:QX,Lectern:eQ,Library:aQ,LibraryBig:nQ,LifeBuoy:oQ,Ligature:lQ,Lightbulb:uQ,LightbulbOff:pQ,LineSquiggle:mQ,Link:kQ,Link2:g5,Link2Off:gQ,Linkedin:_Q,List:cJ,ListCheck:MQ,ListChecks:xQ,ListChevronsDownUp:TQ,ListChevronsUpDown:NQ,ListCollapse:RQ,ListEnd:OQ,ListFilter:$Q,ListFilterPlus:DQ,ListIndentDecrease:PQ,ListIndentIncrease:BQ,ListMinus:VQ,ListMusic:HQ,ListOrdered:WQ,ListPlus:YQ,ListRestart:XQ,ListStart:JQ,ListTodo:tJ,ListTree:rJ,ListVideo:iJ,ListX:sJ,Loader:fJ,LoaderCircle:dJ,LoaderPinwheel:hJ,Locate:kJ,LocateFixed:yJ,LocateOff:_J,Lock:TJ,LockKeyhole:NJ,LockKeyholeOpen:xJ,LockOpen:MJ,LogIn:RJ,LogOut:OJ,Logs:DJ,Lollipop:$J,Luggage:PJ,Magnet:BJ,Mail:iee,MailCheck:HJ,MailMinus:VJ,MailOpen:WJ,MailPlus:YJ,MailQuestionMark:XJ,MailSearch:JJ,MailWarning:tee,MailX:ree,Mailbox:see,Mails:cee,Map:Bee,MapMinus:dee,MapPin:$ee,MapPinCheck:fee,MapPinCheckInside:hee,MapPinHouse:yee,MapPinMinus:_ee,MapPinMinusInside:kee,MapPinOff:xee,MapPinPen:Mee,MapPinPlus:Nee,MapPinPlusInside:Tee,MapPinX:Oee,MapPinXInside:Ree,MapPinned:Pee,MapPlus:Dee,Mars:Vee,MarsStroke:Hee,Martini:Wee,Maximize:Xee,Maximize2:Yee,Medal:Jee,Megaphone:rte,MegaphoneOff:tte,Meh:ite,MemoryStick:ste,Menu:cte,Merge:dte,MessageCircle:Ote,MessageCircleCode:hte,MessageCircleDashed:fte,MessageCircleHeart:yte,MessageCircleMore:kte,MessageCircleOff:_te,MessageCirclePlus:xte,MessageCircleQuestionMark:Mte,MessageCircleReply:Nte,MessageCircleWarning:Tte,MessageCircleX:Rte,MessageSquare:dne,MessageSquareCode:Dte,MessageSquareDashed:$te,MessageSquareDiff:Pte,MessageSquareDot:Bte,MessageSquareHeart:Hte,MessageSquareLock:Vte,MessageSquareMore:Wte,MessageSquareOff:Yte,MessageSquarePlus:Xte,MessageSquareQuote:Jte,MessageSquareReply:tne,MessageSquareShare:rne,MessageSquareText:ine,MessageSquareWarning:sne,MessageSquareX:cne,MessagesSquare:hne,Mic:kne,MicOff:fne,MicVocal:yne,Microchip:_ne,Microscope:xne,Microwave:Mne,Milestone:Nne,Milk:Tne,MilkOff:Rne,Minimize:Dne,Minimize2:One,Minus:$ne,Monitor:cre,MonitorCheck:Pne,MonitorCloud:Bne,MonitorCog:Hne,MonitorDot:Vne,MonitorDown:Wne,MonitorOff:Yne,MonitorPause:Jne,MonitorPlay:Xne,MonitorSmartphone:tre,MonitorSpeaker:rre,MonitorStop:ire,MonitorUp:sre,MonitorX:dre,Moon:yre,MoonStar:hre,Motorbike:fre,Mountain:_re,MountainSnow:kre,Mouse:Dre,MouseOff:xre,MousePointer:Ore,MousePointer2:Nre,MousePointer2Off:Mre,MousePointerBan:Tre,MousePointerClick:Rre,Move:cae,Move3d:$re,MoveDiagonal:Bre,MoveDiagonal2:Pre,MoveDown:Wre,MoveDownLeft:Hre,MoveDownRight:Vre,MoveHorizontal:Xre,MoveLeft:Yre,MoveRight:Jre,MoveUp:iae,MoveUpLeft:tae,MoveUpRight:rae,MoveVertical:sae,Music:fae,Music2:dae,Music3:hae,Music4:yae,Navigation:Mae,Navigation2:kae,Navigation2Off:_ae,NavigationOff:xae,Network:Nae,Newspaper:Tae,Nfc:Rae,NonBinary:Oae,Notebook:Bae,NotebookPen:Dae,NotebookTabs:$ae,NotebookText:Pae,NotepadText:Vae,NotepadTextDashed:Hae,Nut:Yae,NutOff:Wae,Octagon:iie,OctagonAlert:Xae,OctagonMinus:Jae,OctagonPause:tie,OctagonX:rie,Omega:cie,Option:sie,Orbit:die,Origami:hie,Package:Nie,Package2:fie,PackageCheck:yie,PackageMinus:kie,PackageOpen:_ie,PackagePlus:xie,PackageSearch:Mie,PackageX:Tie,PaintBucket:Rie,PaintRoller:Oie,Paintbrush:$ie,PaintbrushVertical:Die,Palette:Pie,Panda:Bie,PanelBottom:Yie,PanelBottomClose:Hie,PanelBottomDashed:Vie,PanelBottomOpen:Wie,PanelLeft:ioe,PanelLeftClose:toe,PanelLeftDashed:Xie,PanelLeftOpen:Jie,PanelLeftRightDashed:roe,PanelRight:hoe,PanelRightClose:coe,PanelRightDashed:soe,PanelRightOpen:doe,PanelTop:xoe,PanelTopBottomDashed:foe,PanelTopClose:yoe,PanelTopDashed:koe,PanelTopOpen:_oe,PanelsLeftBottom:Moe,PanelsRightBottom:Noe,PanelsTopLeft:Toe,Paperclip:Qi,Parentheses:Ioe,ParkingMeter:Loe,PartyPopper:zoe,Pause:Foe,PawPrint:qoe,PcCase:Uoe,Pen:Zoe,PenLine:joe,PenOff:Goe,PenTool:Koe,Pencil:ase,PencilLine:Qoe,PencilOff:ese,PencilRuler:nse,Pentagon:ose,Percent:lse,PersonStanding:use,PhilippinePeso:pse,Phone:Sse,PhoneCall:mse,PhoneForwarded:gse,PhoneIncoming:bse,PhoneMissed:vse,PhoneOff:wse,PhoneOutgoing:Ese,Pi:Ase,Piano:Cse,Pickaxe:Ise,PictureInPicture:zse,PictureInPicture2:Lse,PiggyBank:Fse,Pilcrow:jse,PilcrowLeft:qse,PilcrowRight:Use,Pill:Kse,PillBottle:Gse,Pin:ele,PinOff:Zse,Pipette:Qse,Pizza:nle,Plane:lle,PlaneLanding:ale,PlaneTakeoff:ole,Play:ule,Plug:gle,Plug2:mle,PlugZap:ple,Plus:ble,Pocket:wle,PocketKnife:vle,Podcast:Ele,Pointer:Ale,PointerOff:Sle,Popcorn:Cle,Popsicle:Ile,PoundSterling:Lle,Power:Fle,PowerOff:zle,Presentation:qle,Printer:jle,PrinterCheck:Ule,Projector:Gle,Proportions:Kle,Puzzle:Zle,Pyramid:Qle,QrCode:ece,Quote:nce,Rabbit:ace,Radar:oce,Radiation:lce,Radical:uce,Radio:gce,RadioReceiver:pce,RadioTower:mce,Radius:bce,RailSymbol:vce,Rainbow:wce,Rat:Ece,Ratio:Sce,Receipt:Gce,ReceiptCent:Ace,ReceiptEuro:Cce,ReceiptIndianRupee:Ice,ReceiptJapaneseYen:Lce,ReceiptPoundSterling:zce,ReceiptRussianRuble:Fce,ReceiptSwissFranc:qce,ReceiptText:Uce,ReceiptTurkishLira:jce,RectangleCircle:Kce,RectangleEllipsis:Zce,RectangleGoggles:Qce,RectangleHorizontal:e1e,RectangleVertical:n1e,Recycle:a1e,Redo:u1e,Redo2:o1e,RedoDot:l1e,RefreshCcw:m1e,RefreshCcwDot:p1e,RefreshCw:b1e,RefreshCwOff:g1e,Refrigerator:v1e,Regex:w1e,RemoveFormatting:E1e,Repeat:C1e,Repeat1:S1e,Repeat2:A1e,Replace:L1e,ReplaceAll:I1e,Reply:q1e,ReplyAll:z1e,Rewind:F1e,Ribbon:U1e,Rocket:j1e,RockingChair:G1e,RollerCoaster:K1e,Rose:Z1e,Rotate3d:Q1e,RotateCcw:a0e,RotateCcwKey:e0e,RotateCcwSquare:n0e,RotateCw:l0e,RotateCwSquare:o0e,Route:g0e,RouteOff:u0e,Router:p0e,Rows2:m0e,Rows3:b0e,Rows4:v0e,Rss:w0e,Ruler:S0e,RulerDimensionLine:E0e,RussianRuble:A0e,Sailboat:C0e,Salad:I0e,Sandwich:L0e,Satellite:F0e,SatelliteDish:z0e,SaudiRiyal:q0e,Save:G0e,SaveAll:U0e,SaveOff:j0e,Scale:Q0e,Scale3d:K0e,Scaling:Z0e,Scan:fue,ScanBarcode:eue,ScanEye:nue,ScanFace:aue,ScanHeart:oue,ScanLine:lue,ScanQrCode:uue,ScanSearch:pue,ScanText:Fd,School:yue,Scissors:_ue,ScissorsLineDashed:kue,ScreenShare:Mue,ScreenShareOff:xue,Scroll:Tue,ScrollText:Nue,Search:Pue,SearchCheck:Rue,SearchCode:Oue,SearchSlash:Due,SearchX:$ue,Section:Bue,Send:Wue,SendHorizontal:Hue,SendToBack:Vue,SeparatorHorizontal:Yue,SeparatorVertical:Xue,Server:ide,ServerCog:Jue,ServerCrash:tde,ServerOff:rde,Settings:lde,Settings2:y5,Shapes:ude,Share:mde,Share2:pde,Sheet:gde,Shell:bde,Shield:Ude,ShieldAlert:vde,ShieldBan:wde,ShieldCheck:Ede,ShieldEllipsis:Sde,ShieldHalf:Ade,ShieldMinus:Cde,ShieldOff:Ide,ShieldPlus:Lde,ShieldQuestionMark:zde,ShieldUser:qde,ShieldX:Fde,Ship:Gde,ShipWheel:jde,Shirt:Kde,ShoppingBag:Zde,ShoppingBasket:Qde,ShoppingCart:npe,Shovel:epe,ShowerHead:ape,Shredder:ope,Shrimp:lpe,Shrink:upe,Shrub:ppe,Shuffle:mpe,Sigma:gpe,Signal:Epe,SignalHigh:bpe,SignalLow:vpe,SignalMedium:wpe,SignalZero:Ape,Signature:Spe,Signpost:Lpe,SignpostBig:Cpe,Siren:Ipe,SkipBack:zpe,SkipForward:Fpe,Skull:qpe,Slack:Upe,Slash:jpe,Slice:Gpe,SlidersHorizontal:Kpe,SlidersVertical:Zpe,Smartphone:nhe,SmartphoneCharging:Qpe,SmartphoneNfc:ehe,Smile:ohe,SmilePlus:ahe,Snail:lhe,Snowflake:uhe,SoapDispenserDroplet:phe,Sofa:mhe,SolarPanel:ghe,Soup:bhe,Space:vhe,Spade:whe,Sparkle:Ehe,Sparkles:b5,Speaker:Nhe,Speech:The,SpellCheck:Ohe,SpellCheck2:Rhe,Spline:$he,SplinePointer:Dhe,Split:Phe,Spool:Bhe,Spotlight:Hhe,SprayCan:Vhe,Sprout:Whe,Square:k5,SquareActivity:Yhe,SquareArrowDown:t2e,SquareArrowDownLeft:Xhe,SquareArrowDownRight:Jhe,SquareArrowLeft:r2e,SquareArrowOutDownLeft:i2e,SquareArrowOutDownRight:s2e,SquareArrowOutUpLeft:c2e,SquareArrowOutUpRight:d2e,SquareArrowRight:h2e,SquareArrowUp:k2e,SquareArrowUpLeft:f2e,SquareArrowUpRight:y2e,SquareAsterisk:_2e,SquareBottomDashedScissors:M2e,SquareChartGantt:x2e,SquareCheck:N2e,SquareCheckBig:T2e,SquareChevronDown:O2e,SquareChevronLeft:R2e,SquareChevronRight:D2e,SquareChevronUp:$2e,SquareCode:P2e,SquareDashed:X2e,SquareDashedBottom:H2e,SquareDashedBottomCode:B2e,SquareDashedKanban:V2e,SquareDashedMousePointer:W2e,SquareDashedTopSolid:Y2e,SquareDivide:J2e,SquareDot:tme,SquareEqual:rme,SquareFunction:ime,SquareKanban:sme,SquareLibrary:cme,SquareM:dme,SquareMenu:hme,SquareMinus:fme,SquareMousePointer:yme,SquareParking:_me,SquareParkingOff:kme,SquarePause:xme,SquarePen:Mme,SquarePercent:Nme,SquarePi:Tme,SquarePilcrow:Rme,SquarePlay:$me,SquarePlus:Ome,SquarePower:Dme,SquareRadical:Pme,SquareRoundCorner:Bme,SquareScissors:Hme,SquareSigma:Vme,SquareSlash:Wme,SquareSplitHorizontal:Yme,SquareSplitVertical:Xme,SquareSquare:tfe,SquareStack:Jme,SquareStar:ife,SquareStop:rfe,SquareTerminal:sfe,SquareUser:dfe,SquareUserRound:cfe,SquareX:hfe,SquaresExclude:gfe,SquaresIntersect:bfe,SquaresSubtract:vfe,SquaresUnite:wfe,Squircle:Sfe,SquircleDashed:Efe,Squirrel:Afe,Stamp:Cfe,Star:zfe,StarHalf:Ife,StarOff:Lfe,StepBack:Ffe,StepForward:qfe,Stethoscope:Ufe,Sticker:jfe,StickyNote:Gfe,Store:Kfe,StretchHorizontal:Zfe,StretchVertical:Qfe,Strikethrough:ege,Subscript:nge,Sun:pge,SunDim:age,SunMedium:oge,SunMoon:lge,SunSnow:uge,Sunrise:mge,Sunset:gge,Superscript:bge,SwatchBook:vge,SwissFranc:wge,SwitchCamera:Ege,Sword:Sge,Swords:Age,Syringe:Cge,Table:Gge,Table2:Lge,TableCellsMerge:Ige,TableCellsSplit:zge,TableColumnsSplit:Fge,TableOfContents:qge,TableProperties:Uge,TableRowsSplit:jge,Tablet:Zge,TabletSmartphone:Kge,Tablets:Qge,Tag:eye,Tags:nye,Tally1:aye,Tally2:oye,Tally3:lye,Tally4:uye,Tally5:pye,Tangent:mye,Target:gye,Telescope:bye,Tent:wye,TentTree:vye,Terminal:Sye,TestTube:Aye,TestTubeDiagonal:Eye,TestTubes:Cye,TextAlignCenter:Iye,TextAlignEnd:Lye,TextAlignJustify:zye,TextAlignStart:Fye,TextCursor:Uye,TextCursorInput:qye,TextInitial:jye,TextQuote:Gye,TextSearch:Kye,TextSelect:Zye,TextWrap:e4e,Theater:Qye,Thermometer:o4e,ThermometerSnowflake:n4e,ThermometerSun:a4e,ThumbsDown:l4e,ThumbsUp:u4e,Ticket:E4e,TicketCheck:m4e,TicketMinus:p4e,TicketPercent:g4e,TicketPlus:b4e,TicketSlash:v4e,TicketX:w4e,Tickets:S4e,TicketsPlane:A4e,Timer:L4e,TimerOff:C4e,TimerReset:I4e,ToggleLeft:z4e,ToggleRight:F4e,Toilet:q4e,ToolCase:U4e,Tornado:j4e,Torus:G4e,Touchpad:Z4e,TouchpadOff:K4e,TowerControl:Q4e,ToyBrick:ebe,Tractor:nbe,TrafficCone:obe,TrainFront:lbe,TrainFrontTunnel:abe,TrainTrack:ube,TramFront:mbe,Transgender:pbe,Trash:ybe,Trash2:v5,TreeDeciduous:kbe,TreePalm:xbe,TreePine:_be,Trees:Mbe,Trello:Tbe,TrendingDown:Nbe,TrendingUp:Obe,TrendingUpDown:Rbe,Triangle:Bbe,TriangleAlert:Dbe,TriangleDashed:$be,TriangleRight:Pbe,Trophy:Hbe,Truck:Wbe,TruckElectric:Vbe,TurkishLira:Ybe,Turntable:Jbe,Turtle:Xbe,Tv:ike,TvMinimal:rke,TvMinimalPlay:tke,Twitch:ske,Twitter:cke,Type:hke,TypeOutline:dke,Umbrella:yke,UmbrellaOff:fke,Underline:kke,Undo:xke,Undo2:Mke,UndoDot:_ke,UnfoldHorizontal:Nke,UnfoldVertical:Tke,Ungroup:Rke,University:Dke,Unlink:$ke,Unlink2:Oke,Unplug:Pke,Upload:Bke,Usb:Hke,User:M5e,UserCheck:Vke,UserCog:Wke,UserLock:Yke,UserMinus:Xke,UserPen:Jke,UserPlus:t5e,UserRound:y5e,UserRoundCheck:r5e,UserRoundCog:i5e,UserRoundMinus:s5e,UserRoundPen:c5e,UserRoundPlus:d5e,UserRoundSearch:f5e,UserRoundX:h5e,UserSearch:k5e,UserStar:_5e,UserX:x5e,Users:R5e,UsersRound:N5e,Utensils:O5e,UtensilsCrossed:T5e,UtilityPole:D5e,Variable:$5e,Vault:P5e,VectorSquare:B5e,Vegan:H5e,VenetianMask:V5e,Venus:Y5e,VenusAndMars:W5e,Vibrate:J5e,VibrateOff:X5e,Video:r3e,VideoOff:t3e,Videotape:i3e,View:s3e,Voicemail:c3e,Volleyball:d3e,Volume:_3e,Volume1:h3e,Volume2:f3e,VolumeOff:y3e,VolumeX:k3e,Vote:x3e,Wallet:T3e,WalletCards:M3e,WalletMinimal:N3e,Wallpaper:R3e,Wand:O3e,WandSparkles:D3e,Warehouse:$3e,WashingMachine:P3e,Watch:B3e,Waves:Y3e,WavesArrowDown:H3e,WavesArrowUp:V3e,WavesLadder:W3e,Waypoints:X3e,Webcam:J3e,Webhook:rve,WebhookOff:tve,Weight:ive,Wheat:cve,WheatOff:sve,WholeWord:dve,Wifi:Tve,WifiCog:hve,WifiHigh:fve,WifiLow:yve,WifiOff:kve,WifiPen:_ve,WifiSync:xve,WifiZero:Mve,Wind:Rve,WindArrowDown:Nve,Wine:Ove,WineOff:Dve,Workflow:$ve,Worm:Pve,Wrench:Bve,X:Vve,Youtube:Hve,Zap:Xve,ZapOff:Wve,ZoomIn:Yve,ZoomOut:Jve},Symbol.toStringTag,{value:"Module"})),Pd="mp:formApplyRequested",t6e=e=>{if(!e)return;if(e instanceof Date)return Number.isFinite(e.getTime())?e:void 0;const t=new Date(e);return Number.isFinite(t.getTime())?t:void 0},n6e=(e,t)=>{const n=e.getTime()-t.getTime(),r=Math.round(n/1e3),a=Math.abs(r),i=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"});if(a<45)return i.format(r,"second");const o=Math.round(r/60);if(Math.abs(o)<45)return i.format(o,"minute");const s=Math.round(o/60);if(Math.abs(s)<22)return i.format(s,"hour");const l=Math.round(s/24);if(Math.abs(l)<26)return i.format(l,"day");const u=Math.round(l/30);if(Math.abs(u)<11)return i.format(u,"month");const d=Math.round(l/365);return i.format(d,"year")},r6e=({date:e,refreshMs:t=3e4,emptyText:n=""})=>{const r=V.useMemo(()=>t6e(e),[e]),[a,i]=V.useState(()=>new Date);return V.useEffect(()=>{if(!r)return;const o=window.setInterval(()=>i(new Date),t);return()=>window.clearInterval(o)},[r,t]),r?N.jsx(N.Fragment,{children:n6e(r,a)}):n?N.jsx(N.Fragment,{children:n}):null};function Ji(){return typeof window<"u"}function Ur(e){return qd(e)?(e.nodeName||"").toLowerCase():"#document"}function $t(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function xn(e){var t;return(t=(qd(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function qd(e){return Ji()?e instanceof Node||e instanceof $t(e).Node:!1}function Je(e){return Ji()?e instanceof Element||e instanceof $t(e).Element:!1}function xt(e){return Ji()?e instanceof HTMLElement||e instanceof $t(e).HTMLElement:!1}function Ku(e){return!Ji()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof $t(e).ShadowRoot}const a6e=new Set(["inline","contents"]);function Sa(e){const{overflow:t,overflowX:n,overflowY:r,display:a}=an(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!a6e.has(a)}const i6e=new Set(["table","td","th"]);function o6e(e){return i6e.has(Ur(e))}const s6e=[":popover-open",":modal"];function eo(e){return s6e.some(t=>{try{return e.matches(t)}catch{return!1}})}const l6e=["transform","translate","scale","rotate","perspective"],c6e=["transform","translate","scale","rotate","perspective","filter"],u6e=["paint","layout","strict","content"];function Bd(e){const t=to(),n=Je(e)?an(e):e;return l6e.some(r=>n[r]?n[r]!=="none":!1)||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||c6e.some(r=>(n.willChange||"").includes(r))||u6e.some(r=>(n.contain||"").includes(r))}function d6e(e){let t=$n(e);for(;xt(t)&&!Ln(t);){if(Bd(t))return t;if(eo(t))return null;t=$n(t)}return null}function to(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const p6e=new Set(["html","body","#document"]);function Ln(e){return p6e.has(Ur(e))}function an(e){return $t(e).getComputedStyle(e)}function no(e){return Je(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function $n(e){if(Ur(e)==="html")return e;const t=e.assignedSlot||e.parentNode||Ku(e)&&e.host||xn(e);return Ku(t)?t.host:t}function _5(e){const t=$n(e);return Ln(t)?e.ownerDocument?e.ownerDocument.body:e.body:xt(t)&&Sa(t)?t:_5(t)}function Xn(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const a=_5(e),i=a===((r=e.ownerDocument)==null?void 0:r.body),o=$t(a);if(i){const s=Yu(o);return t.concat(o,o.visualViewport||[],Sa(a)?a:[],s&&n?Xn(s):[])}return t.concat(a,Xn(a,[],n))}function Yu(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}const Ti=Math.min,pr=Math.max,Ci=Math.round,Lr=Math.floor,vn=e=>({x:e,y:e}),h6e={left:"right",right:"left",bottom:"top",top:"bottom"},m6e={start:"end",end:"start"};function Oh(e,t,n){return pr(e,Ti(t,n))}function ro(e,t){return typeof e=="function"?e(t):e}function mr(e){return e.split("-")[0]}function ao(e){return e.split("-")[1]}function w5(e){return e==="x"?"y":"x"}function x5(e){return e==="y"?"height":"width"}const f6e=new Set(["top","bottom"]);function Kn(e){return f6e.has(mr(e))?"y":"x"}function E5(e){return w5(Kn(e))}function g6e(e,t,n){n===void 0&&(n=!1);const r=ao(e),a=E5(e),i=x5(a);let o=a==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(o=Ri(o)),[o,Ri(o)]}function y6e(e){const t=Ri(e);return[Zu(e),t,Zu(t)]}function Zu(e){return e.replace(/start|end/g,t=>m6e[t])}const Lh=["left","right"],Dh=["right","left"],b6e=["top","bottom"],k6e=["bottom","top"];function v6e(e,t,n){switch(e){case"top":case"bottom":return n?t?Dh:Lh:t?Lh:Dh;case"left":case"right":return t?b6e:k6e;default:return[]}}function _6e(e,t,n,r){const a=ao(e);let i=v6e(mr(e),n==="start",r);return a&&(i=i.map(o=>o+"-"+a),t&&(i=i.concat(i.map(Zu)))),i}function Ri(e){return e.replace(/left|right|bottom|top/g,t=>h6e[t])}function w6e(e){return{top:0,right:0,bottom:0,left:0,...e}}function x6e(e){return typeof e!="number"?w6e(e):{top:e,right:e,bottom:e,left:e}}function Ii(e){const{x:t,y:n,width:r,height:a}=e;return{width:r,height:a,top:n,left:t,right:t+r,bottom:n+a,x:t,y:n}}/*!
|
|
8288
8288
|
* tabbable 6.3.0
|
|
8289
8289
|
* @license MIT, https://github.com/focus-trap/tabbable/blob/master/LICENSE
|
|
8290
|
-
*/var E6e=["input:not([inert])","select:not([inert])","textarea:not([inert])","a[href]:not([inert])","button:not([inert])","[tabindex]:not(slot):not([inert])","audio[controls]:not([inert])","video[controls]:not([inert])",'[contenteditable]:not([contenteditable="false"]):not([inert])',"details>summary:first-of-type:not([inert])","details:not([inert])"],Xu=E6e.join(","),M5=typeof Element>"u",pa=M5?function(){}:Element.prototype.matches||Element.prototype.msMatchesSelector||Element.prototype.webkitMatchesSelector,Oi=!M5&&Element.prototype.getRootNode?function(e){var t;return e==null||(t=e.getRootNode)===null||t===void 0?void 0:t.call(e)}:function(e){return e?.ownerDocument},ha=function(t,n){var r;n===void 0&&(n=!0);var a=t==null||(r=t.getAttribute)===null||r===void 0?void 0:r.call(t,"inert"),i=a===""||a==="true",o=i||n&&t&&ha(t.parentNode);return o},M6e=function(t){var n,r=t==null||(n=t.getAttribute)===null||n===void 0?void 0:n.call(t,"contenteditable");return r===""||r==="true"},S6e=function(t,n,r){if(ha(t))return[];var a=Array.prototype.slice.apply(t.querySelectorAll(Xu));return n&&pa.call(t,Xu)&&a.unshift(t),a=a.filter(r),a},Qu=function(t,n,r){for(var a=[],i=Array.from(t);i.length;){var o=i.shift();if(!ha(o,!1))if(o.tagName==="SLOT"){var s=o.assignedElements(),l=s.length?s:o.children,u=Qu(l,!0,r);r.flatten?a.push.apply(a,u):a.push({scopeParent:o,candidates:u})}else{var d=pa.call(o,Xu);d&&r.filter(o)&&(n||!t.includes(o))&&a.push(o);var p=o.shadowRoot||typeof r.getShadowRoot=="function"&&r.getShadowRoot(o),m=!ha(p,!1)&&(!r.shadowRootFilter||r.shadowRootFilter(o));if(p&&m){var h=Qu(p===!0?o.children:p.children,!0,r);r.flatten?a.push.apply(a,h):a.push({scopeParent:o,candidates:h})}else i.unshift.apply(i,o.children)}}return a},S5=function(t){return!isNaN(parseInt(t.getAttribute("tabindex"),10))},N5=function(t){if(!t)throw new Error("No node provided");return t.tabIndex<0&&(/^(AUDIO|VIDEO|DETAILS)$/.test(t.tagName)||M6e(t))&&!S5(t)?0:t.tabIndex},N6e=function(t,n){var r=N5(t);return r<0&&n&&!S5(t)?0:r},A6e=function(t,n){return t.tabIndex===n.tabIndex?t.documentOrder-n.documentOrder:t.tabIndex-n.tabIndex},A5=function(t){return t.tagName==="INPUT"},T6e=function(t){return A5(t)&&t.type==="hidden"},C6e=function(t){var n=t.tagName==="DETAILS"&&Array.prototype.slice.apply(t.children).some(function(r){return r.tagName==="SUMMARY"});return n},R6e=function(t,n){for(var r=0;r<t.length;r++)if(t[r].checked&&t[r].form===n)return t[r]},I6e=function(t){if(!t.name)return!0;var n=t.form||Oi(t),r=function(s){return n.querySelectorAll('input[type="radio"][name="'+s+'"]')},a;if(typeof window<"u"&&typeof window.CSS<"u"&&typeof window.CSS.escape=="function")a=r(window.CSS.escape(t.name));else try{a=r(t.name)}catch(o){return console.error("Looks like you have a radio button with a name attribute containing invalid CSS selector characters and need the CSS.escape polyfill: %s",o.message),!1}var i=R6e(a,t.form);return!i||i===t},O6e=function(t){return A5(t)&&t.type==="radio"},L6e=function(t){return O6e(t)&&!I6e(t)},D6e=function(t){var n,r=t&&Oi(t),a=(n=r)===null||n===void 0?void 0:n.host,i=!1;if(r&&r!==t){var o,s,l;for(i=!!((o=a)!==null&&o!==void 0&&(s=o.ownerDocument)!==null&&s!==void 0&&s.contains(a)||t!=null&&(l=t.ownerDocument)!==null&&l!==void 0&&l.contains(t));!i&&a;){var u,d,p;r=Oi(a),a=(u=r)===null||u===void 0?void 0:u.host,i=!!((d=a)!==null&&d!==void 0&&(p=d.ownerDocument)!==null&&p!==void 0&&p.contains(a))}}return i},zh=function(t){var n=t.getBoundingClientRect(),r=n.width,a=n.height;return r===0&&a===0},z6e=function(t,n){var r=n.displayCheck,a=n.getShadowRoot;if(r==="full-native"&&"checkVisibility"in t){var i=t.checkVisibility({checkOpacity:!1,opacityProperty:!1,contentVisibilityAuto:!0,visibilityProperty:!0,checkVisibilityCSS:!0});return!i}if(getComputedStyle(t).visibility==="hidden")return!0;var o=pa.call(t,"details>summary:first-of-type"),s=o?t.parentElement:t;if(pa.call(s,"details:not([open]) *"))return!0;if(!r||r==="full"||r==="full-native"||r==="legacy-full"){if(typeof a=="function"){for(var l=t;t;){var u=t.parentElement,d=Oi(t);if(u&&!u.shadowRoot&&a(u)===!0)return zh(t);t.assignedSlot?t=t.assignedSlot:!u&&d!==t.ownerDocument?t=d.host:t=u}t=l}if(D6e(t))return!t.getClientRects().length;if(r!=="legacy-full")return!0}else if(r==="non-zero-area")return zh(t);return!1},$6e=function(t){if(/^(INPUT|BUTTON|SELECT|TEXTAREA)$/.test(t.tagName))for(var n=t.parentElement;n;){if(n.tagName==="FIELDSET"&&n.disabled){for(var r=0;r<n.children.length;r++){var a=n.children.item(r);if(a.tagName==="LEGEND")return pa.call(n,"fieldset[disabled] *")?!0:!a.contains(t)}return!0}n=n.parentElement}return!1},F6e=function(t,n){return!(n.disabled||ha(n)||T6e(n)||z6e(n,t)||C6e(n)||$6e(n))},$h=function(t,n){return!(L6e(n)||N5(n)<0||!F6e(t,n))},P6e=function(t){var n=parseInt(t.getAttribute("tabindex"),10);return!!(isNaN(n)||n>=0)},T5=function(t){var n=[],r=[];return t.forEach(function(a,i){var o=!!a.scopeParent,s=o?a.scopeParent:a,l=N6e(s,o),u=o?T5(a.candidates):s;l===0?o?n.push.apply(n,u):n.push(s):r.push({documentOrder:i,tabIndex:l,item:a,isScope:o,content:u})}),r.sort(A6e).reduce(function(a,i){return i.isScope?a.push.apply(a,i.content):a.push(i.content),a},[]).concat(n)},C5=function(t,n){n=n||{};var r;return n.getShadowRoot?r=Qu([t],n.includeContainer,{filter:$h.bind(null,n),flatten:!1,getShadowRoot:n.getShadowRoot,shadowRootFilter:P6e}):r=S6e(t,n.includeContainer,$h.bind(null,n)),T5(r)};function R5(){const e=navigator.userAgentData;return e!=null&&e.platform?e.platform:navigator.platform}function I5(){const e=navigator.userAgentData;return e&&Array.isArray(e.brands)?e.brands.map(t=>{let{brand:n,version:r}=t;return n+"/"+r}).join(" "):navigator.userAgent}function O5(){return/apple/i.test(navigator.vendor)}function Ju(){const e=/android/i;return e.test(R5())||e.test(I5())}function q6e(){return R5().toLowerCase().startsWith("mac")&&!navigator.maxTouchPoints}function L5(){return I5().includes("jsdom/")}const Fh="data-floating-ui-focusable",B6e="input:not([type='hidden']):not([disabled]),[contenteditable]:not([contenteditable='false']),textarea:not([disabled])",Fo="ArrowLeft",Po="ArrowRight",U6e="ArrowUp",H6e="ArrowDown";function ma(e){let t=e.activeElement;for(;((n=t)==null||(n=n.shadowRoot)==null?void 0:n.activeElement)!=null;){var n;t=t.shadowRoot.activeElement}return t}function fr(e,t){if(!e||!t)return!1;const n=t.getRootNode==null?void 0:t.getRootNode();if(e.contains(t))return!0;if(n&&Ku(n)){let r=t;for(;r;){if(e===r)return!0;r=r.parentNode||r.host}}return!1}function Ar(e){return"composedPath"in e?e.composedPath()[0]:e.target}function qo(e,t){if(t==null)return!1;if("composedPath"in e)return e.composedPath().includes(t);const n=e;return n.target!=null&&t.contains(n.target)}function j6e(e){return e.matches("html,body")}function dn(e){return e?.ownerDocument||document}function Ud(e){return xt(e)&&e.matches(B6e)}function V6e(e){return e?e.getAttribute("role")==="combobox"&&Ud(e):!1}function G6e(e){if(!e||L5())return!0;try{return e.matches(":focus-visible")}catch{return!0}}function D5(e){return e?e.hasAttribute(Fh)?e:e.querySelector("["+Fh+"]")||e:null}function oa(e,t,n){return n===void 0&&(n=!0),e.filter(a=>{var i;return a.parentId===t&&(!n||((i=a.context)==null?void 0:i.open))}).flatMap(a=>[a,...oa(e,a.id,n)])}function W6e(e,t){let n,r=-1;function a(i,o){o>r&&(n=i,r=o),oa(e,i).forEach(l=>{a(l.id,o+1)})}return a(t,0),e.find(i=>i.id===n)}function Xt(e){e.preventDefault(),e.stopPropagation()}function K6e(e){return"nativeEvent"in e}function Y6e(e){return e.mozInputSource===0&&e.isTrusted?!0:Ju()&&e.pointerType?e.type==="click"&&e.buttons===1:e.detail===0&&!e.pointerType}function Z6e(e){return L5()?!1:!Ju()&&e.width===0&&e.height===0||Ju()&&e.width===1&&e.height===1&&e.pressure===0&&e.detail===0&&e.pointerType==="mouse"||e.width<1&&e.height<1&&e.pressure===0&&e.detail===0&&e.pointerType==="touch"}function fa(e,t){const n=["mouse","pen"];return t||n.push("",void 0),n.includes(e)}var X6e=typeof document<"u",Q6e=function(){},gt=X6e?V.useLayoutEffect:Q6e;const J6e={...te};function Rn(e){const t=te.useRef(e);return gt(()=>{t.current=e}),t}const e8e=J6e.useInsertionEffect,t8e=e8e||(e=>e());function Vt(e){const t=te.useRef(()=>{if(process.env.NODE_ENV!=="production")throw new Error("Cannot call an event handler while rendering.")});return t8e(()=>{t.current=e}),te.useCallback(function(){for(var n=arguments.length,r=new Array(n),a=0;a<n;a++)r[a]=arguments[a];return t.current==null?void 0:t.current(...r)},[])}function Ua(e,t,n){return Math.floor(e/t)!==n}function sa(e,t){return t<0||t>=e.current.length}function Bo(e,t){return kt(e,{disabledIndices:t})}function Ph(e,t){return kt(e,{decrement:!0,startingIndex:e.current.length,disabledIndices:t})}function kt(e,t){let{startingIndex:n=-1,decrement:r=!1,disabledIndices:a,amount:i=1}=t===void 0?{}:t,o=n;do o+=r?-i:i;while(o>=0&&o<=e.current.length-1&&gi(e,o,a));return o}function n8e(e,t){let{event:n,orientation:r,loop:a,rtl:i,cols:o,disabledIndices:s,minIndex:l,maxIndex:u,prevIndex:d,stopEvent:p=!1}=t,m=d;if(n.key===U6e){if(p&&Xt(n),d===-1)m=u;else if(m=kt(e,{startingIndex:m,amount:o,decrement:!0,disabledIndices:s}),a&&(d-o<l||m<0)){const h=d%o,g=u%o,f=u-(g-h);g===h?m=u:m=g>h?f:f-o}sa(e,m)&&(m=d)}if(n.key===H6e&&(p&&Xt(n),d===-1?m=l:(m=kt(e,{startingIndex:d,amount:o,disabledIndices:s}),a&&d+o>u&&(m=kt(e,{startingIndex:d%o-o,amount:o,disabledIndices:s}))),sa(e,m)&&(m=d)),r==="both"){const h=Lr(d/o);n.key===(i?Fo:Po)&&(p&&Xt(n),d%o!==o-1?(m=kt(e,{startingIndex:d,disabledIndices:s}),a&&Ua(m,o,h)&&(m=kt(e,{startingIndex:d-d%o-1,disabledIndices:s}))):a&&(m=kt(e,{startingIndex:d-d%o-1,disabledIndices:s})),Ua(m,o,h)&&(m=d)),n.key===(i?Po:Fo)&&(p&&Xt(n),d%o!==0?(m=kt(e,{startingIndex:d,decrement:!0,disabledIndices:s}),a&&Ua(m,o,h)&&(m=kt(e,{startingIndex:d+(o-d%o),decrement:!0,disabledIndices:s}))):a&&(m=kt(e,{startingIndex:d+(o-d%o),decrement:!0,disabledIndices:s})),Ua(m,o,h)&&(m=d));const g=Lr(u/o)===h;sa(e,m)&&(a&&g?m=n.key===(i?Po:Fo)?u:kt(e,{startingIndex:d-d%o-1,disabledIndices:s}):m=d)}return m}function r8e(e,t,n){const r=[];let a=0;return e.forEach((i,o)=>{let{width:s,height:l}=i;if(s>t&&process.env.NODE_ENV!=="production")throw new Error("[Floating UI]: Invalid grid - item width at index "+o+" is greater than grid columns");let u=!1;for(n&&(a=0);!u;){const d=[];for(let p=0;p<s;p++)for(let m=0;m<l;m++)d.push(a+p+m*t);a%t+s<=t&&d.every(p=>r[p]==null)?(d.forEach(p=>{r[p]=o}),u=!0):a++}}),[...r]}function a8e(e,t,n,r,a){if(e===-1)return-1;const i=n.indexOf(e),o=t[e];switch(a){case"tl":return i;case"tr":return o?i+o.width-1:i;case"bl":return o?i+(o.height-1)*r:i;case"br":return n.lastIndexOf(e)}}function i8e(e,t){return t.flatMap((n,r)=>e.includes(n)?[r]:[])}function gi(e,t,n){if(typeof n=="function")return n(t);if(n)return n.includes(t);const r=e.current[t];return r==null||r.hasAttribute("disabled")||r.getAttribute("aria-disabled")==="true"}const z5=()=>({getShadowRoot:!0,displayCheck:typeof ResizeObserver=="function"&&ResizeObserver.toString().includes("[native code]")?"full":"none"});function $5(e,t){const n=C5(e,z5()),r=n.length;if(r===0)return;const a=ma(dn(e)),i=n.indexOf(a),o=i===-1?t===1?0:r-1:i+t;return n[o]}function o8e(e){return $5(dn(e).body,1)||e}function s8e(e){return $5(dn(e).body,-1)||e}function Uo(e,t){const n=t||e.currentTarget,r=e.relatedTarget;return!r||!fr(n,r)}function l8e(e){C5(e,z5()).forEach(n=>{n.dataset.tabindex=n.getAttribute("tabindex")||"",n.setAttribute("tabindex","-1")})}function qh(e){e.querySelectorAll("[data-tabindex]").forEach(n=>{const r=n.dataset.tabindex;delete n.dataset.tabindex,r?n.setAttribute("tabindex",r):n.removeAttribute("tabindex")})}function Bh(e,t,n){let{reference:r,floating:a}=e;const i=Kn(t),o=E5(t),s=x5(o),l=mr(t),u=i==="y",d=r.x+r.width/2-a.width/2,p=r.y+r.height/2-a.height/2,m=r[s]/2-a[s]/2;let h;switch(l){case"top":h={x:d,y:r.y-a.height};break;case"bottom":h={x:d,y:r.y+r.height};break;case"right":h={x:r.x+r.width,y:p};break;case"left":h={x:r.x-a.width,y:p};break;default:h={x:r.x,y:r.y}}switch(ao(t)){case"start":h[o]-=m*(n&&u?-1:1);break;case"end":h[o]+=m*(n&&u?-1:1);break}return h}const c8e=async(e,t,n)=>{const{placement:r="bottom",strategy:a="absolute",middleware:i=[],platform:o}=n,s=i.filter(Boolean),l=await(o.isRTL==null?void 0:o.isRTL(t));let u=await o.getElementRects({reference:e,floating:t,strategy:a}),{x:d,y:p}=Bh(u,r,l),m=r,h={},g=0;for(let f=0;f<s.length;f++){const{name:w,fn:v}=s[f],{x:k,y:_,data:E,reset:S}=await v({x:d,y:p,initialPlacement:r,placement:m,strategy:a,middlewareData:h,rects:u,platform:o,elements:{reference:e,floating:t}});d=k??d,p=_??p,h={...h,[w]:{...h[w],...E}},S&&g<=50&&(g++,typeof S=="object"&&(S.placement&&(m=S.placement),S.rects&&(u=S.rects===!0?await o.getElementRects({reference:e,floating:t,strategy:a}):S.rects),{x:d,y:p}=Bh(u,m,l)),f=-1)}return{x:d,y:p,placement:m,strategy:a,middlewareData:h}};async function F5(e,t){var n;t===void 0&&(t={});const{x:r,y:a,platform:i,rects:o,elements:s,strategy:l}=e,{boundary:u="clippingAncestors",rootBoundary:d="viewport",elementContext:p="floating",altBoundary:m=!1,padding:h=0}=ro(t,e),g=x6e(h),w=s[m?p==="floating"?"reference":"floating":p],v=Ii(await i.getClippingRect({element:(n=await(i.isElement==null?void 0:i.isElement(w)))==null||n?w:w.contextElement||await(i.getDocumentElement==null?void 0:i.getDocumentElement(s.floating)),boundary:u,rootBoundary:d,strategy:l})),k=p==="floating"?{x:r,y:a,width:o.floating.width,height:o.floating.height}:o.reference,_=await(i.getOffsetParent==null?void 0:i.getOffsetParent(s.floating)),E=await(i.isElement==null?void 0:i.isElement(_))?await(i.getScale==null?void 0:i.getScale(_))||{x:1,y:1}:{x:1,y:1},S=Ii(i.convertOffsetParentRelativeRectToViewportRelativeRect?await i.convertOffsetParentRelativeRectToViewportRelativeRect({elements:s,rect:k,offsetParent:_,strategy:l}):k);return{top:(v.top-S.top+g.top)/E.y,bottom:(S.bottom-v.bottom+g.bottom)/E.y,left:(v.left-S.left+g.left)/E.x,right:(S.right-v.right+g.right)/E.x}}const u8e=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:a,middlewareData:i,rects:o,initialPlacement:s,platform:l,elements:u}=t,{mainAxis:d=!0,crossAxis:p=!0,fallbackPlacements:m,fallbackStrategy:h="bestFit",fallbackAxisSideDirection:g="none",flipAlignment:f=!0,...w}=ro(e,t);if((n=i.arrow)!=null&&n.alignmentOffset)return{};const v=mr(a),k=Kn(s),_=mr(s)===s,E=await(l.isRTL==null?void 0:l.isRTL(u.floating)),S=m||(_||!f?[Ri(s)]:y6e(s)),x=g!=="none";!m&&x&&S.push(..._6e(s,f,g,E));const D=[s,...S],P=await F5(t,w),C=[];let L=((r=i.flip)==null?void 0:r.overflows)||[];if(d&&C.push(P[v]),p){const K=g6e(a,o,E);C.push(P[K[0]],P[K[1]])}if(L=[...L,{placement:a,overflows:C}],!C.every(K=>K<=0)){var G,X;const K=(((G=i.flip)==null?void 0:G.index)||0)+1,R=D[K];if(R&&(!(p==="alignment"?k!==Kn(R):!1)||L.every(z=>Kn(z.placement)===k?z.overflows[0]>0:!0)))return{data:{index:K,overflows:L},reset:{placement:R}};let U=(X=L.filter(H=>H.overflows[0]<=0).sort((H,z)=>H.overflows[1]-z.overflows[1])[0])==null?void 0:X.placement;if(!U)switch(h){case"bestFit":{var J;const H=(J=L.filter(z=>{if(x){const j=Kn(z.placement);return j===k||j==="y"}return!0}).map(z=>[z.placement,z.overflows.filter(j=>j>0).reduce((j,A)=>j+A,0)]).sort((z,j)=>z[1]-j[1])[0])==null?void 0:J[0];H&&(U=H);break}case"initialPlacement":U=s;break}if(a!==U)return{reset:{placement:U}}}return{}}}},d8e=new Set(["left","top"]);async function p8e(e,t){const{placement:n,platform:r,elements:a}=e,i=await(r.isRTL==null?void 0:r.isRTL(a.floating)),o=mr(n),s=ao(n),l=Kn(n)==="y",u=d8e.has(o)?-1:1,d=i&&l?-1:1,p=ro(t,e);let{mainAxis:m,crossAxis:h,alignmentAxis:g}=typeof p=="number"?{mainAxis:p,crossAxis:0,alignmentAxis:null}:{mainAxis:p.mainAxis||0,crossAxis:p.crossAxis||0,alignmentAxis:p.alignmentAxis};return s&&typeof g=="number"&&(h=s==="end"?g*-1:g),l?{x:h*d,y:m*u}:{x:m*u,y:h*d}}const h8e=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:a,y:i,placement:o,middlewareData:s}=t,l=await p8e(t,e);return o===((n=s.offset)==null?void 0:n.placement)&&(r=s.arrow)!=null&&r.alignmentOffset?{}:{x:a+l.x,y:i+l.y,data:{...l,placement:o}}}}},m8e=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:a}=t,{mainAxis:i=!0,crossAxis:o=!1,limiter:s={fn:w=>{let{x:v,y:k}=w;return{x:v,y:k}}},...l}=ro(e,t),u={x:n,y:r},d=await F5(t,l),p=Kn(mr(a)),m=w5(p);let h=u[m],g=u[p];if(i){const w=m==="y"?"top":"left",v=m==="y"?"bottom":"right",k=h+d[w],_=h-d[v];h=Oh(k,h,_)}if(o){const w=p==="y"?"top":"left",v=p==="y"?"bottom":"right",k=g+d[w],_=g-d[v];g=Oh(k,g,_)}const f=s.fn({...t,[m]:h,[p]:g});return{...f,data:{x:f.x-n,y:f.y-r,enabled:{[m]:i,[p]:o}}}}}};function P5(e){const t=an(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const a=xt(e),i=a?e.offsetWidth:n,o=a?e.offsetHeight:r,s=Ci(n)!==i||Ci(r)!==o;return s&&(n=i,r=o),{width:n,height:r,$:s}}function Hd(e){return Je(e)?e:e.contextElement}function zr(e){const t=Hd(e);if(!xt(t))return vn(1);const n=t.getBoundingClientRect(),{width:r,height:a,$:i}=P5(t);let o=(i?Ci(n.width):n.width)/r,s=(i?Ci(n.height):n.height)/a;return(!o||!Number.isFinite(o))&&(o=1),(!s||!Number.isFinite(s))&&(s=1),{x:o,y:s}}const f8e=vn(0);function q5(e){const t=$t(e);return!to()||!t.visualViewport?f8e:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function g8e(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==$t(e)?!1:t}function gr(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const a=e.getBoundingClientRect(),i=Hd(e);let o=vn(1);t&&(r?Je(r)&&(o=zr(r)):o=zr(e));const s=g8e(i,n,r)?q5(i):vn(0);let l=(a.left+s.x)/o.x,u=(a.top+s.y)/o.y,d=a.width/o.x,p=a.height/o.y;if(i){const m=$t(i),h=r&&Je(r)?$t(r):r;let g=m,f=Yu(g);for(;f&&r&&h!==g;){const w=zr(f),v=f.getBoundingClientRect(),k=an(f),_=v.left+(f.clientLeft+parseFloat(k.paddingLeft))*w.x,E=v.top+(f.clientTop+parseFloat(k.paddingTop))*w.y;l*=w.x,u*=w.y,d*=w.x,p*=w.y,l+=_,u+=E,g=$t(f),f=Yu(g)}}return Ii({width:d,height:p,x:l,y:u})}function io(e,t){const n=no(e).scrollLeft;return t?t.left+n:gr(xn(e)).left+n}function B5(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-io(e,n),a=n.top+t.scrollTop;return{x:r,y:a}}function y8e(e){let{elements:t,rect:n,offsetParent:r,strategy:a}=e;const i=a==="fixed",o=xn(r),s=t?eo(t.floating):!1;if(r===o||s&&i)return n;let l={scrollLeft:0,scrollTop:0},u=vn(1);const d=vn(0),p=xt(r);if((p||!p&&!i)&&((Ur(r)!=="body"||Sa(o))&&(l=no(r)),xt(r))){const h=gr(r);u=zr(r),d.x=h.x+r.clientLeft,d.y=h.y+r.clientTop}const m=o&&!p&&!i?B5(o,l):vn(0);return{width:n.width*u.x,height:n.height*u.y,x:n.x*u.x-l.scrollLeft*u.x+d.x+m.x,y:n.y*u.y-l.scrollTop*u.y+d.y+m.y}}function b8e(e){return Array.from(e.getClientRects())}function k8e(e){const t=xn(e),n=no(e),r=e.ownerDocument.body,a=pr(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),i=pr(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let o=-n.scrollLeft+io(e);const s=-n.scrollTop;return an(r).direction==="rtl"&&(o+=pr(t.clientWidth,r.clientWidth)-a),{width:a,height:i,x:o,y:s}}const Uh=25;function v8e(e,t){const n=$t(e),r=xn(e),a=n.visualViewport;let i=r.clientWidth,o=r.clientHeight,s=0,l=0;if(a){i=a.width,o=a.height;const d=to();(!d||d&&t==="fixed")&&(s=a.offsetLeft,l=a.offsetTop)}const u=io(r);if(u<=0){const d=r.ownerDocument,p=d.body,m=getComputedStyle(p),h=d.compatMode==="CSS1Compat"&&parseFloat(m.marginLeft)+parseFloat(m.marginRight)||0,g=Math.abs(r.clientWidth-p.clientWidth-h);g<=Uh&&(i-=g)}else u<=Uh&&(i+=u);return{width:i,height:o,x:s,y:l}}const _8e=new Set(["absolute","fixed"]);function w8e(e,t){const n=gr(e,!0,t==="fixed"),r=n.top+e.clientTop,a=n.left+e.clientLeft,i=xt(e)?zr(e):vn(1),o=e.clientWidth*i.x,s=e.clientHeight*i.y,l=a*i.x,u=r*i.y;return{width:o,height:s,x:l,y:u}}function Hh(e,t,n){let r;if(t==="viewport")r=v8e(e,n);else if(t==="document")r=k8e(xn(e));else if(Je(t))r=w8e(t,n);else{const a=q5(e);r={x:t.x-a.x,y:t.y-a.y,width:t.width,height:t.height}}return Ii(r)}function U5(e,t){const n=$n(e);return n===t||!Je(n)||Ln(n)?!1:an(n).position==="fixed"||U5(n,t)}function x8e(e,t){const n=t.get(e);if(n)return n;let r=Xn(e,[],!1).filter(s=>Je(s)&&Ur(s)!=="body"),a=null;const i=an(e).position==="fixed";let o=i?$n(e):e;for(;Je(o)&&!Ln(o);){const s=an(o),l=Bd(o);!l&&s.position==="fixed"&&(a=null),(i?!l&&!a:!l&&s.position==="static"&&!!a&&_8e.has(a.position)||Sa(o)&&!l&&U5(e,o))?r=r.filter(d=>d!==o):a=s,o=$n(o)}return t.set(e,r),r}function E8e(e){let{element:t,boundary:n,rootBoundary:r,strategy:a}=e;const o=[...n==="clippingAncestors"?eo(t)?[]:x8e(t,this._c):[].concat(n),r],s=o[0],l=o.reduce((u,d)=>{const p=Hh(t,d,a);return u.top=pr(p.top,u.top),u.right=Ti(p.right,u.right),u.bottom=Ti(p.bottom,u.bottom),u.left=pr(p.left,u.left),u},Hh(t,s,a));return{width:l.right-l.left,height:l.bottom-l.top,x:l.left,y:l.top}}function M8e(e){const{width:t,height:n}=P5(e);return{width:t,height:n}}function S8e(e,t,n){const r=xt(t),a=xn(t),i=n==="fixed",o=gr(e,!0,i,t);let s={scrollLeft:0,scrollTop:0};const l=vn(0);function u(){l.x=io(a)}if(r||!r&&!i)if((Ur(t)!=="body"||Sa(a))&&(s=no(t)),r){const h=gr(t,!0,i,t);l.x=h.x+t.clientLeft,l.y=h.y+t.clientTop}else a&&u();i&&!r&&a&&u();const d=a&&!r&&!i?B5(a,s):vn(0),p=o.left+s.scrollLeft-l.x-d.x,m=o.top+s.scrollTop-l.y-d.y;return{x:p,y:m,width:o.width,height:o.height}}function Ho(e){return an(e).position==="static"}function jh(e,t){if(!xt(e)||an(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return xn(e)===n&&(n=n.ownerDocument.body),n}function H5(e,t){const n=$t(e);if(eo(e))return n;if(!xt(e)){let a=$n(e);for(;a&&!Ln(a);){if(Je(a)&&!Ho(a))return a;a=$n(a)}return n}let r=jh(e,t);for(;r&&o6e(r)&&Ho(r);)r=jh(r,t);return r&&Ln(r)&&Ho(r)&&!Bd(r)?n:r||d6e(e)||n}const N8e=async function(e){const t=this.getOffsetParent||H5,n=this.getDimensions,r=await n(e.floating);return{reference:S8e(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function A8e(e){return an(e).direction==="rtl"}const T8e={convertOffsetParentRelativeRectToViewportRelativeRect:y8e,getDocumentElement:xn,getClippingRect:E8e,getOffsetParent:H5,getElementRects:N8e,getClientRects:b8e,getDimensions:M8e,getScale:zr,isElement:Je,isRTL:A8e};function j5(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function C8e(e,t){let n=null,r;const a=xn(e);function i(){var s;clearTimeout(r),(s=n)==null||s.disconnect(),n=null}function o(s,l){s===void 0&&(s=!1),l===void 0&&(l=1),i();const u=e.getBoundingClientRect(),{left:d,top:p,width:m,height:h}=u;if(s||t(),!m||!h)return;const g=Lr(p),f=Lr(a.clientWidth-(d+m)),w=Lr(a.clientHeight-(p+h)),v=Lr(d),_={rootMargin:-g+"px "+-f+"px "+-w+"px "+-v+"px",threshold:pr(0,Ti(1,l))||1};let E=!0;function S(x){const D=x[0].intersectionRatio;if(D!==l){if(!E)return o();D?o(!1,D):r=setTimeout(()=>{o(!1,1e-7)},1e3)}D===1&&!j5(u,e.getBoundingClientRect())&&o(),E=!1}try{n=new IntersectionObserver(S,{..._,root:a.ownerDocument})}catch{n=new IntersectionObserver(S,_)}n.observe(e)}return o(!0),i}function jd(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:a=!0,ancestorResize:i=!0,elementResize:o=typeof ResizeObserver=="function",layoutShift:s=typeof IntersectionObserver=="function",animationFrame:l=!1}=r,u=Hd(e),d=a||i?[...u?Xn(u):[],...Xn(t)]:[];d.forEach(v=>{a&&v.addEventListener("scroll",n,{passive:!0}),i&&v.addEventListener("resize",n)});const p=u&&s?C8e(u,n):null;let m=-1,h=null;o&&(h=new ResizeObserver(v=>{let[k]=v;k&&k.target===u&&h&&(h.unobserve(t),cancelAnimationFrame(m),m=requestAnimationFrame(()=>{var _;(_=h)==null||_.observe(t)})),n()}),u&&!l&&h.observe(u),h.observe(t));let g,f=l?gr(e):null;l&&w();function w(){const v=gr(e);f&&!j5(f,v)&&n(),f=v,g=requestAnimationFrame(w)}return n(),()=>{var v;d.forEach(k=>{a&&k.removeEventListener("scroll",n),i&&k.removeEventListener("resize",n)}),p?.(),(v=h)==null||v.disconnect(),h=null,l&&cancelAnimationFrame(g)}}const R8e=h8e,I8e=m8e,O8e=u8e,L8e=(e,t,n)=>{const r=new Map,a={platform:T8e,...n},i={...a.platform,_c:r};return c8e(e,t,{...a,platform:i})};var D8e=typeof document<"u",z8e=function(){},yi=D8e?V.useLayoutEffect:z8e;function Li(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,a;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!Li(e[r],t[r]))return!1;return!0}if(a=Object.keys(e),n=a.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,a[r]))return!1;for(r=n;r--!==0;){const i=a[r];if(!(i==="_owner"&&e.$$typeof)&&!Li(e[i],t[i]))return!1}return!0}return e!==e&&t!==t}function V5(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function Vh(e,t){const n=V5(e);return Math.round(t*n)/n}function jo(e){const t=te.useRef(e);return yi(()=>{t.current=e}),t}function $8e(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:a,elements:{reference:i,floating:o}={},transform:s=!0,whileElementsMounted:l,open:u}=e,[d,p]=te.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[m,h]=te.useState(r);Li(m,r)||h(r);const[g,f]=te.useState(null),[w,v]=te.useState(null),k=te.useCallback(z=>{z!==x.current&&(x.current=z,f(z))},[]),_=te.useCallback(z=>{z!==D.current&&(D.current=z,v(z))},[]),E=i||g,S=o||w,x=te.useRef(null),D=te.useRef(null),P=te.useRef(d),C=l!=null,L=jo(l),G=jo(a),X=jo(u),J=te.useCallback(()=>{if(!x.current||!D.current)return;const z={placement:t,strategy:n,middleware:m};G.current&&(z.platform=G.current),L8e(x.current,D.current,z).then(j=>{const A={...j,isPositioned:X.current!==!1};K.current&&!Li(P.current,A)&&(P.current=A,o5.flushSync(()=>{p(A)}))})},[m,t,n,G,X]);yi(()=>{u===!1&&P.current.isPositioned&&(P.current.isPositioned=!1,p(z=>({...z,isPositioned:!1})))},[u]);const K=te.useRef(!1);yi(()=>(K.current=!0,()=>{K.current=!1}),[]),yi(()=>{if(E&&(x.current=E),S&&(D.current=S),E&&S){if(L.current)return L.current(E,S,J);J()}},[E,S,J,L,C]);const R=te.useMemo(()=>({reference:x,floating:D,setReference:k,setFloating:_}),[k,_]),U=te.useMemo(()=>({reference:E,floating:S}),[E,S]),H=te.useMemo(()=>{const z={position:n,left:0,top:0};if(!U.floating)return z;const j=Vh(U.floating,d.x),A=Vh(U.floating,d.y);return s?{...z,transform:"translate("+j+"px, "+A+"px)",...V5(U.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:j,top:A}},[n,s,U.floating,d.x,d.y]);return te.useMemo(()=>({...d,update:J,refs:R,elements:U,floatingStyles:H}),[d,J,R,U,H])}const Vd=(e,t)=>({...R8e(e),options:[e,t]}),Gd=(e,t)=>({...I8e(e),options:[e,t]}),Wd=(e,t)=>({...O8e(e),options:[e,t]}),F8e="data-floating-ui-focusable",Gh="active",Wh="selected",Na="ArrowLeft",Aa="ArrowRight",G5="ArrowUp",oo="ArrowDown",P8e={...te};let Kh=!1,q8e=0;const Yh=()=>"floating-ui-"+Math.random().toString(36).slice(2,6)+q8e++;function B8e(){const[e,t]=te.useState(()=>Kh?Yh():void 0);return gt(()=>{e==null&&t(Yh())},[]),te.useEffect(()=>{Kh=!0},[]),e}const U8e=P8e.useId,Kd=U8e||B8e;let ga;process.env.NODE_ENV!=="production"&&(ga=new Set);function Vo(){for(var e,t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];const a="Floating UI: "+n.join(" ");if(!((e=ga)!=null&&e.has(a))){var i;(i=ga)==null||i.add(a),console.warn(a)}}function H8e(){for(var e,t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];const a="Floating UI: "+n.join(" ");if(!((e=ga)!=null&&e.has(a))){var i;(i=ga)==null||i.add(a),console.error(a)}}function j8e(){const e=new Map;return{emit(t,n){var r;(r=e.get(t))==null||r.forEach(a=>a(n))},on(t,n){e.has(t)||e.set(t,new Set),e.get(t).add(n)},off(t,n){var r;(r=e.get(t))==null||r.delete(n)}}}const V8e=te.createContext(null),G8e=te.createContext(null),so=()=>{var e;return((e=te.useContext(V8e))==null?void 0:e.id)||null},lo=()=>te.useContext(G8e);function Ta(e){return"data-floating-ui-"+e}function Zt(e){e.current!==-1&&(clearTimeout(e.current),e.current=-1)}const Zh=Ta("safe-polygon");function Go(e,t,n){if(n&&!fa(n))return 0;if(typeof e=="number")return e;if(typeof e=="function"){const r=e();return typeof r=="number"?r:r?.[t]}return e?.[t]}function Wo(e){return typeof e=="function"?e():e}function W8e(e,t){t===void 0&&(t={});const{open:n,onOpenChange:r,dataRef:a,events:i,elements:o}=e,{enabled:s=!0,delay:l=0,handleClose:u=null,mouseOnly:d=!1,restMs:p=0,move:m=!0}=t,h=lo(),g=so(),f=Rn(u),w=Rn(l),v=Rn(n),k=Rn(p),_=te.useRef(),E=te.useRef(-1),S=te.useRef(),x=te.useRef(-1),D=te.useRef(!0),P=te.useRef(!1),C=te.useRef(()=>{}),L=te.useRef(!1),G=Vt(()=>{var H;const z=(H=a.current.openEvent)==null?void 0:H.type;return z?.includes("mouse")&&z!=="mousedown"});te.useEffect(()=>{if(!s)return;function H(z){let{open:j}=z;j||(Zt(E),Zt(x),D.current=!0,L.current=!1)}return i.on("openchange",H),()=>{i.off("openchange",H)}},[s,i]),te.useEffect(()=>{if(!s||!f.current||!n)return;function H(j){G()&&r(!1,j,"hover")}const z=dn(o.floating).documentElement;return z.addEventListener("mouseleave",H),()=>{z.removeEventListener("mouseleave",H)}},[o.floating,n,r,s,f,G]);const X=te.useCallback(function(H,z,j){z===void 0&&(z=!0),j===void 0&&(j="hover");const A=Go(w.current,"close",_.current);A&&!S.current?(Zt(E),E.current=window.setTimeout(()=>r(!1,H,j),A)):z&&(Zt(E),r(!1,H,j))},[w,r]),J=Vt(()=>{C.current(),S.current=void 0}),K=Vt(()=>{if(P.current){const H=dn(o.floating).body;H.style.pointerEvents="",H.removeAttribute(Zh),P.current=!1}}),R=Vt(()=>a.current.openEvent?["click","mousedown"].includes(a.current.openEvent.type):!1);te.useEffect(()=>{if(!s)return;function H(ee){if(Zt(E),D.current=!1,d&&!fa(_.current)||Wo(k.current)>0&&!Go(w.current,"open"))return;const O=Go(w.current,"open",_.current);O?E.current=window.setTimeout(()=>{v.current||r(!0,ee,"hover")},O):n||r(!0,ee,"hover")}function z(ee){if(R()){K();return}C.current();const O=dn(o.floating);if(Zt(x),L.current=!1,f.current&&a.current.floatingContext){n||Zt(E),S.current=f.current({...a.current.floatingContext,tree:h,x:ee.clientX,y:ee.clientY,onClose(){K(),J(),R()||X(ee,!0,"safe-polygon")}});const fe=S.current;O.addEventListener("mousemove",fe),C.current=()=>{O.removeEventListener("mousemove",fe)};return}(_.current==="touch"?!fr(o.floating,ee.relatedTarget):!0)&&X(ee)}function j(ee){R()||a.current.floatingContext&&(f.current==null||f.current({...a.current.floatingContext,tree:h,x:ee.clientX,y:ee.clientY,onClose(){K(),J(),R()||X(ee)}})(ee))}function A(){Zt(E)}function Y(ee){R()||X(ee,!1)}if(Je(o.domReference)){const ee=o.domReference,O=o.floating;return n&&ee.addEventListener("mouseleave",j),m&&ee.addEventListener("mousemove",H,{once:!0}),ee.addEventListener("mouseenter",H),ee.addEventListener("mouseleave",z),O&&(O.addEventListener("mouseleave",j),O.addEventListener("mouseenter",A),O.addEventListener("mouseleave",Y)),()=>{n&&ee.removeEventListener("mouseleave",j),m&&ee.removeEventListener("mousemove",H),ee.removeEventListener("mouseenter",H),ee.removeEventListener("mouseleave",z),O&&(O.removeEventListener("mouseleave",j),O.removeEventListener("mouseenter",A),O.removeEventListener("mouseleave",Y))}}},[o,s,e,d,m,X,J,K,r,n,v,h,w,f,a,R,k]),gt(()=>{var H;if(s&&n&&(H=f.current)!=null&&(H=H.__options)!=null&&H.blockPointerEvents&&G()){P.current=!0;const j=o.floating;if(Je(o.domReference)&&j){var z;const A=dn(o.floating).body;A.setAttribute(Zh,"");const Y=o.domReference,ee=h==null||(z=h.nodesRef.current.find(O=>O.id===g))==null||(z=z.context)==null?void 0:z.elements.floating;return ee&&(ee.style.pointerEvents=""),A.style.pointerEvents="none",Y.style.pointerEvents="auto",j.style.pointerEvents="auto",()=>{A.style.pointerEvents="",Y.style.pointerEvents="",j.style.pointerEvents=""}}}},[s,n,g,o,h,f,G]),gt(()=>{n||(_.current=void 0,L.current=!1,J(),K())},[n,J,K]),te.useEffect(()=>()=>{J(),Zt(E),Zt(x),K()},[s,o.domReference,J,K]);const U=te.useMemo(()=>{function H(z){_.current=z.pointerType}return{onPointerDown:H,onPointerEnter:H,onMouseMove(z){const{nativeEvent:j}=z;function A(){!D.current&&!v.current&&r(!0,j,"hover")}d&&!fa(_.current)||n||Wo(k.current)===0||L.current&&z.movementX**2+z.movementY**2<2||(Zt(x),_.current==="touch"?A():(L.current=!0,x.current=window.setTimeout(A,Wo(k.current))))}}},[d,r,n,v,k]);return te.useMemo(()=>s?{reference:U}:{},[s,U])}let Xh=0;function K8e(e,t){t===void 0&&(t={});const{preventScroll:n=!1,cancelPrevious:r=!0,sync:a=!1}=t;r&&cancelAnimationFrame(Xh);const i=()=>e?.focus({preventScroll:n});a?i():Xh=requestAnimationFrame(i)}const W5={border:0,clip:"rect(0 0 0 0)",height:"1px",margin:"-1px",overflow:"hidden",padding:0,position:"fixed",whiteSpace:"nowrap",width:"1px",top:0,left:0},Qh=te.forwardRef(function(t,n){const[r,a]=te.useState();gt(()=>{O5()&&a("button")},[]);const i={ref:n,tabIndex:0,role:r,"aria-hidden":r?void 0:!0,[Ta("focus-guard")]:"",style:W5};return N.jsx("span",{...t,...i})}),K5=te.createContext(null),Jh=Ta("portal");function Y8e(e){e===void 0&&(e={});const{id:t,root:n}=e,r=Kd(),a=X8e(),[i,o]=te.useState(null),s=te.useRef(null);return gt(()=>()=>{i?.remove(),queueMicrotask(()=>{s.current=null})},[i]),gt(()=>{if(!r||s.current)return;const l=t?document.getElementById(t):null;if(!l)return;const u=document.createElement("div");u.id=r,u.setAttribute(Jh,""),l.appendChild(u),s.current=u,o(u)},[t,r]),gt(()=>{if(n===null||!r||s.current)return;let l=n||a?.portalNode;l&&!qd(l)&&(l=l.current),l=l||document.body;let u=null;t&&(u=document.createElement("div"),u.id=t,l.appendChild(u));const d=document.createElement("div");d.id=r,d.setAttribute(Jh,""),l=u||l,l.appendChild(d),s.current=d,o(d)},[t,n,r,a]),i}function Z8e(e){const{children:t,id:n,root:r,preserveTabOrder:a=!0}=e,i=Y8e({id:n,root:r}),[o,s]=te.useState(null),l=te.useRef(null),u=te.useRef(null),d=te.useRef(null),p=te.useRef(null),m=o?.modal,h=o?.open,g=!!o&&!o.modal&&o.open&&a&&!!(r||i);return te.useEffect(()=>{if(!i||!a||m)return;function f(w){i&&Uo(w)&&(w.type==="focusin"?qh:l8e)(i)}return i.addEventListener("focusin",f,!0),i.addEventListener("focusout",f,!0),()=>{i.removeEventListener("focusin",f,!0),i.removeEventListener("focusout",f,!0)}},[i,a,m]),te.useEffect(()=>{i&&(h||qh(i))},[h,i]),N.jsxs(K5.Provider,{value:te.useMemo(()=>({preserveTabOrder:a,beforeOutsideRef:l,afterOutsideRef:u,beforeInsideRef:d,afterInsideRef:p,portalNode:i,setFocusManagerState:s}),[a,i]),children:[g&&i&&N.jsx(Qh,{"data-type":"outside",ref:l,onFocus:f=>{if(Uo(f,i)){var w;(w=d.current)==null||w.focus()}else{const v=o?o.domReference:null,k=s8e(v);k?.focus()}}}),g&&i&&N.jsx("span",{"aria-owns":i.id,style:W5}),i&&o5.createPortal(t,i),g&&i&&N.jsx(Qh,{"data-type":"outside",ref:u,onFocus:f=>{if(Uo(f,i)){var w;(w=p.current)==null||w.focus()}else{const v=o?o.domReference:null,k=o8e(v);k?.focus(),o?.closeOnFocusOut&&o?.onOpenChange(!1,f.nativeEvent,"focus-out")}}})]})}const X8e=()=>te.useContext(K5);function e2(e){return xt(e.target)&&e.target.tagName==="BUTTON"}function Q8e(e){return xt(e.target)&&e.target.tagName==="A"}function t2(e){return Ud(e)}function Y5(e,t){t===void 0&&(t={});const{open:n,onOpenChange:r,dataRef:a,elements:{domReference:i}}=e,{enabled:o=!0,event:s="click",toggle:l=!0,ignoreMouse:u=!1,keyboardHandlers:d=!0,stickIfOpen:p=!0}=t,m=te.useRef(),h=te.useRef(!1),g=te.useMemo(()=>({onPointerDown(f){m.current=f.pointerType},onMouseDown(f){const w=m.current;f.button===0&&s!=="click"&&(fa(w,!0)&&u||(n&&l&&(!(a.current.openEvent&&p)||a.current.openEvent.type==="mousedown")?r(!1,f.nativeEvent,"click"):(f.preventDefault(),r(!0,f.nativeEvent,"click"))))},onClick(f){const w=m.current;if(s==="mousedown"&&m.current){m.current=void 0;return}fa(w,!0)&&u||(n&&l&&(!(a.current.openEvent&&p)||a.current.openEvent.type==="click")?r(!1,f.nativeEvent,"click"):r(!0,f.nativeEvent,"click"))},onKeyDown(f){m.current=void 0,!(f.defaultPrevented||!d||e2(f))&&(f.key===" "&&!t2(i)&&(f.preventDefault(),h.current=!0),!Q8e(f)&&f.key==="Enter"&&r(!(n&&l),f.nativeEvent,"click"))},onKeyUp(f){f.defaultPrevented||!d||e2(f)||t2(i)||f.key===" "&&h.current&&(h.current=!1,r(!(n&&l),f.nativeEvent,"click"))}}),[a,i,s,u,d,r,n,p,l]);return te.useMemo(()=>o?{reference:g}:{},[o,g])}const J8e={pointerdown:"onPointerDown",mousedown:"onMouseDown",click:"onClick"},e7e={pointerdown:"onPointerDownCapture",mousedown:"onMouseDownCapture",click:"onClickCapture"},n2=e=>{var t,n;return{escapeKey:typeof e=="boolean"?e:(t=e?.escapeKey)!=null?t:!1,outsidePress:typeof e=="boolean"?e:(n=e?.outsidePress)!=null?n:!0}};function Yd(e,t){t===void 0&&(t={});const{open:n,onOpenChange:r,elements:a,dataRef:i}=e,{enabled:o=!0,escapeKey:s=!0,outsidePress:l=!0,outsidePressEvent:u="pointerdown",referencePress:d=!1,referencePressEvent:p="pointerdown",ancestorScroll:m=!1,bubbles:h,capture:g}=t,f=lo(),w=Vt(typeof l=="function"?l:()=>!1),v=typeof l=="function"?w:l,k=te.useRef(!1),{escapeKey:_,outsidePress:E}=n2(h),{escapeKey:S,outsidePress:x}=n2(g),D=te.useRef(!1),P=Vt(K=>{var R;if(!n||!o||!s||K.key!=="Escape"||D.current)return;const U=(R=i.current.floatingContext)==null?void 0:R.nodeId,H=f?oa(f.nodesRef.current,U):[];if(!_&&(K.stopPropagation(),H.length>0)){let z=!0;if(H.forEach(j=>{var A;if((A=j.context)!=null&&A.open&&!j.context.dataRef.current.__escapeKeyBubbles){z=!1;return}}),!z)return}r(!1,K6e(K)?K.nativeEvent:K,"escape-key")}),C=Vt(K=>{var R;const U=()=>{var H;P(K),(H=Ar(K))==null||H.removeEventListener("keydown",U)};(R=Ar(K))==null||R.addEventListener("keydown",U)}),L=Vt(K=>{var R;const U=i.current.insideReactTree;i.current.insideReactTree=!1;const H=k.current;if(k.current=!1,u==="click"&&H||U||typeof v=="function"&&!v(K))return;const z=Ar(K),j="["+Ta("inert")+"]",A=dn(a.floating).querySelectorAll(j);let Y=Je(z)?z:null;for(;Y&&!Ln(Y);){const fe=$n(Y);if(Ln(fe)||!Je(fe))break;Y=fe}if(A.length&&Je(z)&&!j6e(z)&&!fr(z,a.floating)&&Array.from(A).every(fe=>!fr(Y,fe)))return;if(xt(z)&&J){const fe=Ln(z),ke=an(z),Ce=/auto|scroll/,Fe=fe||Ce.test(ke.overflowX),tt=fe||Ce.test(ke.overflowY),Ve=Fe&&z.clientWidth>0&&z.scrollWidth>z.clientWidth,ae=tt&&z.clientHeight>0&&z.scrollHeight>z.clientHeight,Se=ke.direction==="rtl",Be=ae&&(Se?K.offsetX<=z.offsetWidth-z.clientWidth:K.offsetX>z.clientWidth),We=Ve&&K.offsetY>z.clientHeight;if(Be||We)return}const ee=(R=i.current.floatingContext)==null?void 0:R.nodeId,O=f&&oa(f.nodesRef.current,ee).some(fe=>{var ke;return qo(K,(ke=fe.context)==null?void 0:ke.elements.floating)});if(qo(K,a.floating)||qo(K,a.domReference)||O)return;const le=f?oa(f.nodesRef.current,ee):[];if(le.length>0){let fe=!0;if(le.forEach(ke=>{var Ce;if((Ce=ke.context)!=null&&Ce.open&&!ke.context.dataRef.current.__outsidePressBubbles){fe=!1;return}}),!fe)return}r(!1,K,"outside-press")}),G=Vt(K=>{var R;const U=()=>{var H;L(K),(H=Ar(K))==null||H.removeEventListener(u,U)};(R=Ar(K))==null||R.addEventListener(u,U)});te.useEffect(()=>{if(!n||!o)return;i.current.__escapeKeyBubbles=_,i.current.__outsidePressBubbles=E;let K=-1;function R(A){r(!1,A,"ancestor-scroll")}function U(){window.clearTimeout(K),D.current=!0}function H(){K=window.setTimeout(()=>{D.current=!1},to()?5:0)}const z=dn(a.floating);s&&(z.addEventListener("keydown",S?C:P,S),z.addEventListener("compositionstart",U),z.addEventListener("compositionend",H)),v&&z.addEventListener(u,x?G:L,x);let j=[];return m&&(Je(a.domReference)&&(j=Xn(a.domReference)),Je(a.floating)&&(j=j.concat(Xn(a.floating))),!Je(a.reference)&&a.reference&&a.reference.contextElement&&(j=j.concat(Xn(a.reference.contextElement)))),j=j.filter(A=>{var Y;return A!==((Y=z.defaultView)==null?void 0:Y.visualViewport)}),j.forEach(A=>{A.addEventListener("scroll",R,{passive:!0})}),()=>{s&&(z.removeEventListener("keydown",S?C:P,S),z.removeEventListener("compositionstart",U),z.removeEventListener("compositionend",H)),v&&z.removeEventListener(u,x?G:L,x),j.forEach(A=>{A.removeEventListener("scroll",R)}),window.clearTimeout(K)}},[i,a,s,v,u,n,r,m,o,_,E,P,S,C,L,x,G]),te.useEffect(()=>{i.current.insideReactTree=!1},[i,v,u]);const X=te.useMemo(()=>({onKeyDown:P,...d&&{[J8e[p]]:K=>{r(!1,K.nativeEvent,"reference-press")},...p!=="click"&&{onClick(K){r(!1,K.nativeEvent,"reference-press")}}}}),[P,r,d,p]),J=te.useMemo(()=>({onKeyDown:P,onMouseDown(){k.current=!0},onMouseUp(){k.current=!0},[e7e[u]]:()=>{i.current.insideReactTree=!0}}),[P,u,i]);return te.useMemo(()=>o?{reference:X,floating:J}:{},[o,X,J])}function t7e(e){const{open:t=!1,onOpenChange:n,elements:r}=e,a=Kd(),i=te.useRef({}),[o]=te.useState(()=>j8e()),s=so()!=null;if(process.env.NODE_ENV!=="production"){const h=r.reference;h&&!Je(h)&&H8e("Cannot pass a virtual element to the `elements.reference` option,","as it must be a real DOM element. Use `refs.setPositionReference()`","instead.")}const[l,u]=te.useState(r.reference),d=Vt((h,g,f)=>{i.current.openEvent=h?g:void 0,o.emit("openchange",{open:h,event:g,reason:f,nested:s}),n?.(h,g,f)}),p=te.useMemo(()=>({setPositionReference:u}),[]),m=te.useMemo(()=>({reference:l||r.reference||null,floating:r.floating||null,domReference:r.reference}),[l,r.reference,r.floating]);return te.useMemo(()=>({dataRef:i,open:t,onOpenChange:d,elements:m,events:o,floatingId:a,refs:p}),[t,d,m,o,a,p])}function Zd(e){e===void 0&&(e={});const{nodeId:t}=e,n=t7e({...e,elements:{reference:null,floating:null,...e.elements}}),r=e.rootContext||n,a=r.elements,[i,o]=te.useState(null),[s,l]=te.useState(null),d=a?.domReference||i,p=te.useRef(null),m=lo();gt(()=>{d&&(p.current=d)},[d]);const h=$8e({...e,elements:{...a,...s&&{reference:s}}}),g=te.useCallback(_=>{const E=Je(_)?{getBoundingClientRect:()=>_.getBoundingClientRect(),getClientRects:()=>_.getClientRects(),contextElement:_}:_;l(E),h.refs.setReference(E)},[h.refs]),f=te.useCallback(_=>{(Je(_)||_===null)&&(p.current=_,o(_)),(Je(h.refs.reference.current)||h.refs.reference.current===null||_!==null&&!Je(_))&&h.refs.setReference(_)},[h.refs]),w=te.useMemo(()=>({...h.refs,setReference:f,setPositionReference:g,domReference:p}),[h.refs,f,g]),v=te.useMemo(()=>({...h.elements,domReference:d}),[h.elements,d]),k=te.useMemo(()=>({...h,...r,refs:w,elements:v,nodeId:t}),[h,w,v,t,r]);return gt(()=>{r.dataRef.current.floatingContext=k;const _=m?.nodesRef.current.find(E=>E.id===t);_&&(_.context=k)}),te.useMemo(()=>({...h,context:k,refs:w,elements:v}),[h,w,v,k])}function Ko(){return q6e()&&O5()}function n7e(e,t){t===void 0&&(t={});const{open:n,onOpenChange:r,events:a,dataRef:i,elements:o}=e,{enabled:s=!0,visibleOnly:l=!0}=t,u=te.useRef(!1),d=te.useRef(-1),p=te.useRef(!0);te.useEffect(()=>{if(!s)return;const h=$t(o.domReference);function g(){!n&&xt(o.domReference)&&o.domReference===ma(dn(o.domReference))&&(u.current=!0)}function f(){p.current=!0}function w(){p.current=!1}return h.addEventListener("blur",g),Ko()&&(h.addEventListener("keydown",f,!0),h.addEventListener("pointerdown",w,!0)),()=>{h.removeEventListener("blur",g),Ko()&&(h.removeEventListener("keydown",f,!0),h.removeEventListener("pointerdown",w,!0))}},[o.domReference,n,s]),te.useEffect(()=>{if(!s)return;function h(g){let{reason:f}=g;(f==="reference-press"||f==="escape-key")&&(u.current=!0)}return a.on("openchange",h),()=>{a.off("openchange",h)}},[a,s]),te.useEffect(()=>()=>{Zt(d)},[]);const m=te.useMemo(()=>({onMouseLeave(){u.current=!1},onFocus(h){if(u.current)return;const g=Ar(h.nativeEvent);if(l&&Je(g)){if(Ko()&&!h.relatedTarget){if(!p.current&&!Ud(g))return}else if(!G6e(g))return}r(!0,h.nativeEvent,"focus")},onBlur(h){u.current=!1;const g=h.relatedTarget,f=h.nativeEvent,w=Je(g)&&g.hasAttribute(Ta("focus-guard"))&&g.getAttribute("data-type")==="outside";d.current=window.setTimeout(()=>{var v;const k=ma(o.domReference?o.domReference.ownerDocument:document);!g&&k===o.domReference||fr((v=i.current.floatingContext)==null?void 0:v.refs.floating.current,k)||fr(o.domReference,k)||w||r(!1,f,"focus")})}}),[i,o.domReference,r,l]);return te.useMemo(()=>s?{reference:m}:{},[s,m])}function Yo(e,t,n){const r=new Map,a=n==="item";let i=e;if(a&&e){const{[Gh]:o,[Wh]:s,...l}=e;i=l}return{...n==="floating"&&{tabIndex:-1,[F8e]:""},...i,...t.map(o=>{const s=o?o[n]:null;return typeof s=="function"?e?s(e):null:s}).concat(e).reduce((o,s)=>(s&&Object.entries(s).forEach(l=>{let[u,d]=l;if(!(a&&[Gh,Wh].includes(u)))if(u.indexOf("on")===0){if(r.has(u)||r.set(u,[]),typeof d=="function"){var p;(p=r.get(u))==null||p.push(d),o[u]=function(){for(var m,h=arguments.length,g=new Array(h),f=0;f<h;f++)g[f]=arguments[f];return(m=r.get(u))==null?void 0:m.map(w=>w(...g)).find(w=>w!==void 0)}}}else o[u]=d}),o),{})}}function Xd(e){e===void 0&&(e=[]);const t=e.map(s=>s?.reference),n=e.map(s=>s?.floating),r=e.map(s=>s?.item),a=te.useCallback(s=>Yo(s,e,"reference"),t),i=te.useCallback(s=>Yo(s,e,"floating"),n),o=te.useCallback(s=>Yo(s,e,"item"),r);return te.useMemo(()=>({getReferenceProps:a,getFloatingProps:i,getItemProps:o}),[a,i,o])}const r7e="Escape";function co(e,t,n){switch(e){case"vertical":return t;case"horizontal":return n;default:return t||n}}function Ha(e,t){return co(t,e===G5||e===oo,e===Na||e===Aa)}function Zo(e,t,n){return co(t,e===oo,n?e===Na:e===Aa)||e==="Enter"||e===" "||e===""}function r2(e,t,n){return co(t,n?e===Na:e===Aa,e===oo)}function a2(e,t,n,r){const a=n?e===Aa:e===Na,i=e===G5;return t==="both"||t==="horizontal"&&r&&r>1?e===r7e:co(t,a,i)}function a7e(e,t){const{open:n,onOpenChange:r,elements:a,floatingId:i}=e,{listRef:o,activeIndex:s,onNavigate:l=()=>{},enabled:u=!0,selectedIndex:d=null,allowEscape:p=!1,loop:m=!1,nested:h=!1,rtl:g=!1,virtual:f=!1,focusItemOnOpen:w="auto",focusItemOnHover:v=!0,openOnArrowKeyDown:k=!0,disabledIndices:_=void 0,orientation:E="vertical",parentOrientation:S,cols:x=1,scrollItemIntoView:D=!0,virtualItemRef:P,itemSizes:C,dense:L=!1}=t;process.env.NODE_ENV!=="production"&&(p&&(m||Vo("`useListNavigation` looping must be enabled to allow escaping."),f||Vo("`useListNavigation` must be virtual to allow escaping.")),E==="vertical"&&x>1&&Vo("In grid list navigation mode (`cols` > 1), the `orientation` should",'be either "horizontal" or "both".'));const G=D5(a.floating),X=Rn(G),J=so(),K=lo();gt(()=>{e.dataRef.current.orientation=E},[e,E]);const R=Vt(()=>{l(z.current===-1?null:z.current)}),U=V6e(a.domReference),H=te.useRef(w),z=te.useRef(d??-1),j=te.useRef(null),A=te.useRef(!0),Y=te.useRef(R),ee=te.useRef(!!a.floating),O=te.useRef(n),le=te.useRef(!1),fe=te.useRef(!1),ke=Rn(_),Ce=Rn(n),Fe=Rn(D),tt=Rn(d),[Ve,ae]=te.useState(),[Se,Be]=te.useState(),We=Vt(()=>{function ce(q){if(f){var Z;(Z=q.id)!=null&&Z.endsWith("-fui-option")&&(q.id=i+"-"+Math.random().toString(16).slice(2,10)),ae(q.id),K?.events.emit("virtualfocus",q),P&&(P.current=q)}else K8e(q,{sync:le.current,preventScroll:!0})}const Me=o.current[z.current],ye=fe.current;Me&&ce(Me),(le.current?q=>q():requestAnimationFrame)(()=>{const q=o.current[z.current]||Me;if(!q)return;Me||ce(q);const Z=Fe.current;Z&&ve&&(ye||!A.current)&&(q.scrollIntoView==null||q.scrollIntoView(typeof Z=="boolean"?{block:"nearest",inline:"nearest"}:Z))})});gt(()=>{u&&(n&&a.floating?H.current&&d!=null&&(fe.current=!0,z.current=d,R()):ee.current&&(z.current=-1,Y.current()))},[u,n,a.floating,d,R]),gt(()=>{if(u&&n&&a.floating)if(s==null){if(le.current=!1,tt.current!=null)return;if(ee.current&&(z.current=-1,We()),(!O.current||!ee.current)&&H.current&&(j.current!=null||H.current===!0&&j.current==null)){let ce=0;const Me=()=>{o.current[0]==null?(ce<2&&(ce?requestAnimationFrame:queueMicrotask)(Me),ce++):(z.current=j.current==null||Zo(j.current,E,g)||h?Bo(o,ke.current):Ph(o,ke.current),j.current=null,R())};Me()}}else sa(o,s)||(z.current=s,We(),fe.current=!1)},[u,n,a.floating,s,tt,h,o,E,g,R,We,ke]),gt(()=>{var ce;if(!u||a.floating||!K||f||!ee.current)return;const Me=K.nodesRef.current,ye=(ce=Me.find(Z=>Z.id===J))==null||(ce=ce.context)==null?void 0:ce.elements.floating,Pe=ma(dn(a.floating)),q=Me.some(Z=>Z.context&&fr(Z.context.elements.floating,Pe));ye&&!q&&A.current&&ye.focus({preventScroll:!0})},[u,a.floating,K,J,f]),gt(()=>{if(!u||!K||!f||J)return;function ce(Me){Be(Me.id),P&&(P.current=Me)}return K.events.on("virtualfocus",ce),()=>{K.events.off("virtualfocus",ce)}},[u,K,f,J,P]),gt(()=>{Y.current=R,O.current=n,ee.current=!!a.floating}),gt(()=>{n||(j.current=null,H.current=w)},[n,w]);const Ae=s!=null,ve=te.useMemo(()=>{function ce(ye){if(!Ce.current)return;const Pe=o.current.indexOf(ye);Pe!==-1&&z.current!==Pe&&(z.current=Pe,R())}return{onFocus(ye){let{currentTarget:Pe}=ye;le.current=!0,ce(Pe)},onClick:ye=>{let{currentTarget:Pe}=ye;return Pe.focus({preventScroll:!0})},onMouseMove(ye){let{currentTarget:Pe}=ye;le.current=!0,fe.current=!1,v&&ce(Pe)},onPointerLeave(ye){let{pointerType:Pe}=ye;if(!(!A.current||Pe==="touch")&&(le.current=!0,!!v&&(z.current=-1,R(),!f))){var q;(q=X.current)==null||q.focus({preventScroll:!0})}}}},[Ce,X,v,o,R,f]),Ge=te.useCallback(()=>{var ce;return S??(K==null||(ce=K.nodesRef.current.find(Me=>Me.id===J))==null||(ce=ce.context)==null||(ce=ce.dataRef)==null?void 0:ce.current.orientation)},[J,K,S]),de=Vt(ce=>{if(A.current=!1,le.current=!0,ce.which===229||!Ce.current&&ce.currentTarget===X.current)return;if(h&&a2(ce.key,E,g,x)){Ha(ce.key,Ge())||Xt(ce),r(!1,ce.nativeEvent,"list-navigation"),xt(a.domReference)&&(f?K?.events.emit("virtualfocus",a.domReference):a.domReference.focus());return}const Me=z.current,ye=Bo(o,_),Pe=Ph(o,_);if(U||(ce.key==="Home"&&(Xt(ce),z.current=ye,R()),ce.key==="End"&&(Xt(ce),z.current=Pe,R())),x>1){const q=C||Array.from({length:o.current.length},()=>({width:1,height:1})),Z=r8e(q,x,L),ne=Z.findIndex(Le=>Le!=null&&!gi(o,Le,_)),pe=Z.reduce((Le,mt,bt)=>mt!=null&&!gi(o,mt,_)?bt:Le,-1),Ee=Z[n8e({current:Z.map(Le=>Le!=null?o.current[Le]:null)},{event:ce,orientation:E,loop:m,rtl:g,cols:x,disabledIndices:i8e([...(typeof _!="function"?_:null)||o.current.map((Le,mt)=>gi(o,mt,_)?mt:void 0),void 0],Z),minIndex:ne,maxIndex:pe,prevIndex:a8e(z.current>Pe?ye:z.current,q,Z,x,ce.key===oo?"bl":ce.key===(g?Na:Aa)?"tr":"tl"),stopEvent:!0})];if(Ee!=null&&(z.current=Ee,R()),E==="both")return}if(Ha(ce.key,E)){if(Xt(ce),n&&!f&&ma(ce.currentTarget.ownerDocument)===ce.currentTarget){z.current=Zo(ce.key,E,g)?ye:Pe,R();return}Zo(ce.key,E,g)?m?z.current=Me>=Pe?p&&Me!==o.current.length?-1:ye:kt(o,{startingIndex:Me,disabledIndices:_}):z.current=Math.min(Pe,kt(o,{startingIndex:Me,disabledIndices:_})):m?z.current=Me<=ye?p&&Me!==-1?o.current.length:Pe:kt(o,{startingIndex:Me,decrement:!0,disabledIndices:_}):z.current=Math.max(ye,kt(o,{startingIndex:Me,decrement:!0,disabledIndices:_})),sa(o,z.current)&&(z.current=-1),R()}}),Ze=te.useMemo(()=>f&&n&&Ae&&{"aria-activedescendant":Se||Ve},[f,n,Ae,Se,Ve]),Ke=te.useMemo(()=>({"aria-orientation":E==="both"?void 0:E,...U?{}:Ze,onKeyDown:de,onPointerMove(){A.current=!0}}),[Ze,de,E,U]),He=te.useMemo(()=>{function ce(ye){w==="auto"&&Y6e(ye.nativeEvent)&&(H.current=!0)}function Me(ye){H.current=w,w==="auto"&&Z6e(ye.nativeEvent)&&(H.current=!0)}return{...Ze,onKeyDown(ye){A.current=!1;const Pe=ye.key.startsWith("Arrow"),q=["Home","End"].includes(ye.key),Z=Pe||q,ne=r2(ye.key,E,g),pe=a2(ye.key,E,g,x),Ee=r2(ye.key,Ge(),g),Le=Ha(ye.key,E),mt=(h?Ee:Le)||ye.key==="Enter"||ye.key.trim()==="";if(f&&n){const ht=K?.nodesRef.current.find(It=>It.parentId==null),Mt=K&&ht?W6e(K.nodesRef.current,ht.id):null;if(Z&&Mt&&P){const It=new KeyboardEvent("keydown",{key:ye.key,bubbles:!0});if(ne||pe){var bt,Hn;const D7=((bt=Mt.context)==null?void 0:bt.elements.domReference)===ye.currentTarget,Ch=pe&&!D7?(Hn=Mt.context)==null?void 0:Hn.elements.domReference:ne?o.current.find(Rh=>Rh?.id===Ve):null;Ch&&(Xt(ye),Ch.dispatchEvent(It),Be(void 0))}if((Le||q)&&Mt.context&&Mt.context.open&&Mt.parentId&&ye.currentTarget!==Mt.context.elements.domReference){var jn;Xt(ye),(jn=Mt.context.elements.domReference)==null||jn.dispatchEvent(It);return}}return de(ye)}if(!(!n&&!k&&Pe)){if(mt){const ht=Ha(ye.key,Ge());j.current=h&&ht?null:ye.key}if(h){Ee&&(Xt(ye),n?(z.current=Bo(o,ke.current),R()):r(!0,ye.nativeEvent,"list-navigation"));return}Le&&(d!=null&&(z.current=d),Xt(ye),!n&&k?r(!0,ye.nativeEvent,"list-navigation"):de(ye),n&&R())}},onFocus(){n&&!f&&(z.current=-1,R())},onPointerDown:Me,onPointerEnter:Me,onMouseDown:ce,onClick:ce}},[Ve,Ze,x,de,ke,w,o,h,R,r,n,k,E,Ge,g,d,K,f,P]);return te.useMemo(()=>u?{reference:He,floating:Ke,item:ve}:{},[u,He,Ke,ve])}const i7e=new Map([["select","listbox"],["combobox","listbox"],["label",!1]]);function Qd(e,t){var n,r;t===void 0&&(t={});const{open:a,elements:i,floatingId:o}=e,{enabled:s=!0,role:l="dialog"}=t,u=Kd(),d=((n=i.domReference)==null?void 0:n.id)||u,p=te.useMemo(()=>{var k;return((k=D5(i.floating))==null?void 0:k.id)||o},[i.floating,o]),m=(r=i7e.get(l))!=null?r:l,g=so()!=null,f=te.useMemo(()=>m==="tooltip"||l==="label"?{["aria-"+(l==="label"?"labelledby":"describedby")]:a?p:void 0}:{"aria-expanded":a?"true":"false","aria-haspopup":m==="alertdialog"?"dialog":m,"aria-controls":a?p:void 0,...m==="listbox"&&{role:"combobox"},...m==="menu"&&{id:d},...m==="menu"&&g&&{role:"menuitem"},...l==="select"&&{"aria-autocomplete":"none"},...l==="combobox"&&{"aria-autocomplete":"list"}},[m,p,g,a,d,l]),w=te.useMemo(()=>{const k={id:p,...m&&{role:m}};return m==="tooltip"||l==="label"?k:{...k,...m==="menu"&&{"aria-labelledby":d}}},[m,p,d,l]),v=te.useCallback(k=>{let{active:_,selected:E}=k;const S={role:"option",..._&&{id:p+"-fui-option"}};switch(l){case"select":case"combobox":return{...S,"aria-selected":E}}return{}},[p,l]);return te.useMemo(()=>s?{reference:f,floating:w,item:v}:{},[s,f,w,v])}const bn=({content:e,children:t,placement:n="top",delay:r=300,disabled:a=!1,className:i=""})=>{const[o,s]=V.useState(!1),{refs:l,floatingStyles:u,context:d,isPositioned:p}=Zd({open:o,onOpenChange:s,placement:n,strategy:"absolute",whileElementsMounted:jd,middleware:[Vd(8),Wd(),Gd({padding:8})]}),m=W8e(d,{delay:{open:r,close:0},enabled:!a}),h=n7e(d,{enabled:!a}),g=Yd(d,{enabled:!0,outsidePress:!0,outsidePressEvent:"mousedown",referencePress:!0,referencePressEvent:"mousedown",escapeKey:!0,ancestorScroll:!0}),f=Qd(d,{role:"tooltip"}),{getReferenceProps:w,getFloatingProps:v}=Xd([m,h,g,f]);return V.useEffect(()=>{if(!o||a)return;const k=()=>{s(!1)};return window.addEventListener("scroll",k,!0),document.addEventListener("scroll",k,!0),()=>{window.removeEventListener("scroll",k,!0),document.removeEventListener("scroll",k,!0)}},[o,a]),a||!e?N.jsx(N.Fragment,{children:t}):N.jsxs(N.Fragment,{children:[N.jsx("span",{ref:l.setReference,...w(),children:t}),o&&N.jsx(Z8e,{children:N.jsx("div",{ref:l.setFloating,style:{...u,opacity:p?1:0,pointerEvents:"none",transition:p?"opacity 0.15s ease-out":"none"},className:`mp-agent-tooltip ${i}`.trim(),...v(),children:e})})]})},nn=({icon:e,size:t="md",iconSize:n,type:r="button",className:a="",tooltip:i,tooltipPlacement:o,...s})=>{const l=e6e[e],u=n??(t==="sm"?14:20),d=N.jsx("button",{type:r,className:`mp-agent-icon-button mp-agent-icon-button-${t} ${a}`.trim(),...s,children:l&&N.jsx(l,{size:u})});return i?N.jsx(bn,{content:i,placement:o,children:d}):d},Jd=({text:e})=>{const[t,n]=V.useState(!1),r=async()=>{try{await navigator.clipboard.writeText(e),n(!0),setTimeout(()=>n(!1),2e3)}catch(a){console.error("Failed to copy:",a)}};return N.jsx(bn,{content:"Copy to clipboard",children:N.jsx(nn,{icon:t?"Check":"Copy",onClick:r,"aria-label":"Copy message",size:"sm"})})},Wt=()=>{const e=$e();return{...Ni,...e.config.translations??{}}},i2=300,Z5=V.memo(({field:e,isExpanded:t,canApply:n,onToggleExpand:r,onApply:a})=>{const i=Wt(),o=e.value.length>i2,s=o&&!t?`${e.value.slice(0,i2)}...`:e.value,l=V.useCallback(()=>{r(e.name)},[e.name,r]),u=V.useCallback(()=>{a(e)},[e,a]);return N.jsxs("div",{className:"mp-agent-form-proposal-row",children:[N.jsxs("div",{className:"mp-agent-form-proposal-main",children:[N.jsx("div",{className:"mp-agent-form-proposal-label",children:e.label||e.name}),N.jsx("div",{className:"mp-agent-form-proposal-value-container",children:N.jsxs("div",{className:"mp-agent-form-proposal-value",children:[s,o&&N.jsx("button",{type:"button",onClick:l,className:"mp-agent-form-proposal-show-all",children:t?i.formProposalShowLess:i.formProposalShowAll})]})})]}),N.jsxs("div",{className:"mp-agent-form-proposal-actions-row",children:[N.jsx(nn,{icon:"Check",onClick:u,tooltip:`${i.formProposalApplyFieldPrefix} ${e.label||e.name}`,size:"sm"}),N.jsx(Jd,{text:e.value})]})]})});Z5.displayName="FormFieldRow";const Ca=30*1e3,Ra=5*60*1e3,X5=20,Ht={all:["mp-agents","activities"],lists:()=>[...Ht.all,"list"],list:e=>[...Ht.lists(),e],infinites:()=>[...Ht.all,"infinite"],infinite:e=>[...Ht.infinites(),e],sourceTypes:e=>[...Ht.all,"sourceTypes",e],detail:e=>[...Ht.all,"detail",e],summary:e=>[...Ht.all,"summary",e]},o7e=e=>e?.pages.flatMap(t=>t.data)??[],Q5=(e,t,n)=>{const r=e.from instanceof Date?e.from.toISOString():e.from,a=e.to instanceof Date?e.to.toISOString():e.to;return{...e.groupId&&{groupId:e.groupId},...e.parentId&&{parentId:e.parentId},...e.sourceType&&{sourceType:e.sourceType},...e.sortField&&e.sortOrder&&{sort:{field:e.sortField,order:e.sortOrder}},...r&&{from:r},...a&&{to:a},...e.tenant&&{tenant:e.tenant},...e.ownerId&&{ownerId:e.ownerId},skip:t,limit:n}},J5=e=>({data:[],cursor:{total:0,skip:0,limit:e}}),s7e=e=>{const t=$e(),{groupId:n,parentId:r,sourceType:a,enabled:i=!0,sortOrder:o=exports.SortOrder.Desc,sortField:s="createdAt",pageSize:l=X5,from:u,to:d,tenant:p,ownerId:m}=e??{};return yt.useInfiniteQuery({queryKey:Ht.infinite({groupId:n,parentId:r,sourceType:a,sortField:s,sortOrder:o,pageSize:l,from:u,to:d,tenant:p,ownerId:m}),queryFn:async({pageParam:h})=>t.transport.listActivities?t.transport.listActivities(Q5({groupId:n,parentId:r,sourceType:a,sortField:s,sortOrder:o,from:u,to:d,tenant:p,ownerId:m},h,l)):J5(l),initialPageParam:0,getNextPageParam:h=>{const g=(h.cursor.skip??0)+h.data.length;return g<h.cursor.total?g:void 0},enabled:i&&!!t.transport.listActivities,staleTime:Ca,gcTime:Ra})},l7e=e=>{const t=$e(),{groupId:n,parentId:r,sourceType:a,page:i,enabled:o=!0,sortOrder:s=exports.SortOrder.Desc,sortField:l="createdAt",pageSize:u=X5,from:d,to:p,tenant:m,ownerId:h}=e,g=(i-1)*u,f=yt.useQuery({queryKey:Ht.list({groupId:n,parentId:r,sourceType:a,sortField:l,sortOrder:s,pageSize:u,page:i,from:d,to:p,tenant:m,ownerId:h}),queryFn:async()=>t.transport.listActivities?t.transport.listActivities(Q5({groupId:n,parentId:r,sourceType:a,sortField:l,sortOrder:s,from:d,to:p,tenant:m,ownerId:h},g,u)):J5(u),enabled:o&&!!t.transport.listActivities&&i>=1,staleTime:Ca,gcTime:Ra}),w=f.data?.cursor.total??0,v=Math.max(1,Math.ceil(w/u));return{...f,page:i,pageSize:u,totalPages:v,total:w,hasNextPage:i<v,hasPreviousPage:i>1}},c7e=e=>{const t=$e();return yt.useQuery({queryKey:Ht.detail(e),queryFn:async()=>!e||!t.transport.getActivity?null:t.transport.getActivity(e),enabled:!!e&&!!t.transport.getActivity,staleTime:Ca,gcTime:Ra})},u7e=e=>{const t=$e(),{enabled:n=!0,...r}=e??{};return yt.useQuery({queryKey:Ht.summary(r),queryFn:async()=>t.transport.getActivitySummary?t.transport.getActivitySummary(r):[],enabled:n&&!!t.transport.getActivitySummary,staleTime:Ca,gcTime:Ra})},d7e=e=>{const t=$e(),{enabled:n=!0,groupId:r,parentId:a,from:i,to:o,tenant:s,ownerId:l}=e??{},u=i instanceof Date?i.toISOString():i,d=o instanceof Date?o.toISOString():o;return yt.useQuery({queryKey:Ht.sourceTypes({groupId:r,parentId:a,from:u,to:d,tenant:s,ownerId:l}),queryFn:async()=>t.transport.listActivitySourceTypes?t.transport.listActivitySourceTypes({...r&&{groupId:r},...a&&{parentId:a},...u&&{from:u},...d&&{to:d},...s&&{tenant:s},...l&&{ownerId:l}}):[],enabled:n&&!!t.transport.listActivitySourceTypes,staleTime:Ca,gcTime:Ra})},o2="mp-agents-guest-user-id";function Hr(){if(typeof window>"u")return`${Ai.DefaultUserId}-${_t.nanoid()}`;const e=localStorage.getItem(o2);if(e)return e;const t=`${Ai.DefaultUserId}-${_t.nanoid()}`;return localStorage.setItem(o2,t),t}const e3=30*1e3,t3=5*60*1e3,uo=20,In={all:["mp-agents","chats"],lists:()=>[...In.all,"list"],list:e=>[...In.lists(),e],infinites:()=>[...In.all,"infinite"],infinite:e=>[...In.infinites(),e],detail:e=>[...In.all,"detail",e]},n3=e=>e?.pages.flatMap(t=>t.data)??[],ep=e=>{const t=$e(),n=t.config.user?.id??Hr(),r=t.config.appId,{pageSize:a=uo,sortOrder:i="desc",sortField:o="updatedAt",multiUser:s,enabled:l=!0}=e??{};return yt.useInfiniteQuery({queryKey:In.infinite({userId:n,appId:r,sortField:o,sortOrder:i,pageSize:a,multiUser:s}),queryFn:async({pageParam:u})=>await t.transport.listChats({userId:n,skip:u,limit:a,multiUser:s,sortOrder:i,sortField:o}),initialPageParam:0,getNextPageParam:u=>{const{cursor:d,data:p}=u,m=(d.skip??0)+p.length;return m<d.total?m:void 0},enabled:l&&!!n,staleTime:e3,gcTime:t3})},r3=ep,p7e=e=>{const t=$e(),n=t.config.user?.id??Hr(),r=t.config.appId,{page:a,pageSize:i=uo,sortOrder:o="desc",sortField:s="updatedAt",multiUser:l,enabled:u=!0}=e,d=(a-1)*i,p=yt.useQuery({queryKey:In.list({userId:n,appId:r,sortField:s,sortOrder:o,pageSize:i,page:a,multiUser:l}),queryFn:async()=>t.transport.listChats({userId:n,skip:d,limit:i,multiUser:l,sortOrder:o,sortField:s}),enabled:u&&!!n&&a>=1,staleTime:e3,gcTime:t3}),m=p.data?.cursor.total??0,h=Math.max(1,Math.ceil(m/i));return{...p,page:a,pageSize:i,totalPages:h,total:m,hasNextPage:a<h,hasPreviousPage:a>1}},tp=e=>{const t=r3(e),n=be(r=>r.hydrateChats);return V.useEffect(()=>{if(t.data?.pages){const r=t.data.pages.flatMap(a=>a.data);n(r)}},[t.data,n]),t},h7e=(e={},t=[])=>{const{threshold:n=50,scrollOnMount:r=!0,observeMutations:a=!0}=e,i=V.useRef(null),o=V.useRef(null),[s,l]=V.useState(!0),u=V.useRef(!1),d=V.useRef(!1),p=V.useRef(),m=V.useCallback(()=>{const f=i.current;if(!f)return!1;const{scrollTop:w,scrollHeight:v,clientHeight:k}=f;return v-w-k<=n},[n]),h=V.useCallback(()=>{const f=i.current,w=o.current;!f||!w||w.scrollIntoView({behavior:"auto",block:"end"})},[]),g=V.useCallback(()=>{const f=m();l(f),f&&(u.current=!1)},[m]);return V.useEffect(()=>{const f=i.current;if(!f)return;let w=f.scrollTop,v;const k=()=>{const _=f.scrollTop;if(!d.current){const E=_<w,S=_>w;(E||S&&!m())&&(u.current=!0)}w=_,g(),v&&clearTimeout(v),v=window.setTimeout(()=>{d.current=!1},150)};return f.addEventListener("scroll",k,{passive:!0}),()=>{f.removeEventListener("scroll",k),v&&clearTimeout(v)}},[m,g]),V.useEffect(()=>{if(!a)return;const f=i.current;if(!f)return;const w=new MutationObserver(()=>{!u.current&&s&&(p.current&&cancelAnimationFrame(p.current),p.current=requestAnimationFrame(()=>{d.current=!0,h(),setTimeout(()=>{d.current=!1},50)})),g()});return w.observe(f,{childList:!0,subtree:!0,characterData:!0,attributes:!1}),()=>{w.disconnect(),p.current&&cancelAnimationFrame(p.current)}},[s,a,h,g]),V.useEffect(()=>{t.length!==0&&!u.current&&s&&(p.current&&cancelAnimationFrame(p.current),p.current=requestAnimationFrame(()=>{d.current=!0,h(),setTimeout(()=>{d.current=!1},50)}))},[...t]),V.useEffect(()=>{if(r&&i.current){const f=window.setTimeout(()=>{d.current=!0,h(),setTimeout(()=>{d.current=!1},50)},100);return()=>{clearTimeout(f)}}},[r,h]),{containerRef:i,sentinelRef:o,isNearBottom:s,scrollToBottom:h,checkIsNearBottom:m}},a3=()=>{const e=$e();return yt.useQuery({queryKey:["mp-agents","models"],queryFn:async()=>e.transport.listModels?await e.transport.listModels():[],staleTime:5*60*1e3,refetchOnWindowFocus:!1})},ja=e=>e.type===exports.AgentAttachmentType.Context&&e?.metadata?.kind==="pageContext";var vt=(e=>(e.Idle="idle",e.Sending="sending",e.Streaming="streaming",e))(vt||{});const Di=e=>e===exports.AgentStatus.Streaming||e===exports.AgentStatus.Processing||e===exports.AgentStatus.WaitingForUserAction?"streaming":"idle",i3=()=>({messages:[],reasoning:[],artifacts:[],pendingAssistant:void 0,messageQueue:[],composerDraft:{value:"",attachments:[]},composerError:void 0,pageContextDismissed:!1,status:"idle"}),ze=(e,t)=>e.chatState[t]??i3(),m7e=e=>r5.create()((t,n)=>({contextKey:e,activeChatId:void 0,draftChatKey:`draft-${_t.nanoid()}`,chats:{},chatState:{},isChatHistoryOpen:!1,composer:{temperature:.4},setContextKey:r=>t({contextKey:r}),setActiveChat:r=>{t(a=>{let i=a.contextKey,o;if(r){const u=a.chats[r];u?.contextKey&&(i=u.contextKey),o=u?.model}const s=a.activeChatId!==r;return{activeChatId:r,contextKey:i,composer:r&&s?{...a.composer,model:o}:a.composer}})},upsertChat:r=>t(a=>{const i=a.chats[r.id],s=a.activeChatId===r.id&&(!i||i.model!==r.model);return{chats:{...a.chats,[r.id]:r},...s?{composer:{...a.composer,model:r.model}}:{}}}),upsertChatState:(r,a)=>t(i=>{const o=ze(i,r),s=typeof a=="function"?a(o):a,l={...o,...s};return{chatState:{...i.chatState,[r]:l}}}),hydrateChats:r=>t(a=>{const i={};r.forEach(u=>{i[u.id]=u});const o=a.activeChatId??r[0]?.id;o&&!i[o]&&a.chats[o]&&(i[o]=a.chats[o]);const l=o?i[o]:void 0;return{chats:i,activeChatId:o,composer:{...a.composer,model:l?.model}}}),removeChat:r=>t(a=>{if(!a.chats[r])return a;const{[r]:i,...o}=a.chats,{[r]:s,...l}=a.chatState,u=a.activeChatId===r;return{chats:o,chatState:l,...u?{activeChatId:void 0}:{}}}),pushReasoning:(r,a)=>t(i=>{const o=ze(i,r);return{chatState:{...i.chatState,[r]:{...o,reasoning:[...o.reasoning,a]}}}}),setArtifacts:(r,a)=>t(i=>{const o=ze(i,r);return{chatState:{...i.chatState,[r]:{...o,artifacts:a}}}}),setComposerOptions:r=>t(a=>({composer:{...a.composer,...r}})),setComposerDraft:(r,a)=>t(i=>{const o=ze(i,r);return{chatState:{...i.chatState,[r]:{...o,composerDraft:{value:a.value??"",attachments:a.attachments??[]}}}}}),setComposerValue:(r,a)=>t(i=>{const o=ze(i,r);return{chatState:{...i.chatState,[r]:{...o,composerDraft:{...o.composerDraft,value:a}}}}}),addComposerAttachments:(r,a)=>t(i=>{const o=ze(i,r),s=o.composerDraft.attachments??[];if(!a||a.length===0)return i;const l=s.find(ja),u=a.find(ja);if(u){const m=a.filter(v=>!ja(v)),h=s.filter(v=>!ja(v)),f=[l?{...u,id:l.id}:u,...m,...h],w=new Map;for(const v of f)w.set(v.id,v);return{chatState:{...i.chatState,[r]:{...o,composerDraft:{...o.composerDraft,attachments:Array.from(w.values())}}}}}const d=[...a,...s],p=new Map;for(const m of d)p.set(m.id,m);return{chatState:{...i.chatState,[r]:{...o,composerDraft:{...o.composerDraft,attachments:Array.from(p.values())}}}}}),removeComposerAttachment:(r,a)=>t(i=>{const o=ze(i,r);return{chatState:{...i.chatState,[r]:{...o,composerDraft:{...o.composerDraft,attachments:o.composerDraft.attachments.filter(s=>s.id!==a)}}}}}),clearComposerDraft:r=>t(a=>{const i=ze(a,r);return{chatState:{...a.chatState,[r]:{...i,composerDraft:{value:"",attachments:[]}}}}}),setComposerError:(r,a)=>t(i=>{const o=ze(i,r);return{chatState:{...i.chatState,[r]:{...o,composerError:a}}}}),setPageContextDismissed:(r,a)=>t(i=>{const o=ze(i,r);return{chatState:{...i.chatState,[r]:{...o,pageContextDismissed:a}}}}),setChatStatus:(r,a)=>t(i=>{const o=ze(i,r);return{chatState:{...i.chatState,[r]:{...o,status:a}}}}),setPendingAssistant:(r,a)=>t(i=>{const o=ze(i,r);return{chatState:{...i.chatState,[r]:{...o,pendingAssistant:a}}}}),commitPendingAssistant:r=>t(a=>{const i=ze(a,r),o=i.pendingAssistant;if(!o)return a;if(!a.chats[r])return{chatState:{...a.chatState,[r]:{...i,pendingAssistant:void 0}}};const u=typeof o.content=="string"&&o.content.trim().length>0?(()=>{if(i.messages[i.messages.length-1]?.id===o.id)return i.messages;const p={...o,chat:r};return[...i.messages,p]})():i.messages;return{chatState:{...a.chatState,[r]:{...i,messages:u,pendingAssistant:void 0}}}}),enqueueQueuedMessage:(r,a,i)=>t(o=>{const s=ze(o,r),l={id:_t.nanoid(),content:a,...i&&i.length>0?{attachments:i}:{},createdAt:new Date().toISOString()};return{chatState:{...o.chatState,[r]:{...s,messageQueue:[...s.messageQueue,l]}}}}),removeQueuedMessage:(r,a)=>t(i=>{const o=ze(i,r);if(o.messageQueue.length===0)return i;const s=o.messageQueue.filter(l=>l.id!==a);return{chatState:{...i.chatState,[r]:{...o,messageQueue:s}}}}),moveChatKeyState:(r,a)=>t(i=>{if(r===a)return i;const o=ze(i,r),s=ze(i,a);if(!(o.messageQueue.length>0||!!o.pendingAssistant||o.status!=="idle"||o.composerDraft.value.length>0||o.composerDraft.attachments.length>0||!!o.composerError))return i;const u=o.composerDraft.value.length>0||o.composerDraft.attachments.length>0,d=s.composerDraft.value.length>0||s.composerDraft.attachments.length>0,p={messages:s.messages,reasoning:s.reasoning,artifacts:s.artifacts,pendingAssistant:o.pendingAssistant??s.pendingAssistant,messageQueue:[...s.messageQueue,...o.messageQueue],composerDraft:u&&!d?o.composerDraft:s.composerDraft,composerError:o.composerError??s.composerError,pageContextDismissed:i.chatState[a]?s.pageContextDismissed:o.pageContextDismissed,status:o.status??s.status};return{chatState:{...i.chatState,[a]:p,[r]:i3()}}}),appendSystemMessage:(r,a)=>t(i=>{const o=ze(i,r),s={id:_t.nanoid(),chat:r,content:a,role:exports.MessageRole.System,createdAt:new Date().toISOString()};return{chatState:{...i.chatState,[r]:{...o,messages:[...o.messages,s]}}}}),upsertToolCall:(r,a)=>t(i=>{const o=ze(i,r),s=[...o.messages],l=s.findIndex(u=>u.role===exports.MessageRole.Tool&&u.toolCalls?.some(d=>d.id===a.id));if(l>=0){const u=s[l],d=(u.toolCalls??[]).map(p=>p.id===a.id?a:p);s[l]={...u,toolCalls:d}}else s.push({id:`tool-${a.id}`,content:"",chat:r,toolCalls:[a],role:exports.MessageRole.Tool,createdAt:new Date().toISOString()});return{chatState:{...i.chatState,[r]:{...o,messages:s}}}}),setChatHistoryOpen:r=>t({isChatHistoryOpen:r}),toggleChatHistory:()=>t(r=>({isChatHistoryOpen:!r.isChatHistoryOpen})),setChatMessages:(r,a)=>t(i=>{const o=ze(i,r),s=o.messages??[],l=typeof a=="function"?a(s):a;return{chatState:{...i.chatState,[r]:{...o,messages:l}}}}),appendMessagesToChat:(r,a)=>t(i=>{const o=ze(i,r);if(a.length===0)return i;const s=new Set(a.map(d=>d.id)),u=[...o.messages.filter(d=>!s.has(d.id)),...a].sort((d,p)=>d.createdAt.localeCompare(p.createdAt));return{chatState:{...i.chatState,[r]:{...o,messages:u}}}})})),o3=()=>{const e=be(s=>s.activeChatId??s.draftChatKey),t=be(s=>ze(s,e).composerDraft),n=be(s=>s.setComposerValue),r=be(s=>s.setComposerDraft),a=be(s=>s.clearComposerDraft),i=be(s=>s.addComposerAttachments),o=be(s=>s.removeComposerAttachment);return{chatKey:e,draft:t,setValue:s=>n(e,s),setDraft:s=>r(e,s),clearDraft:()=>a(e),addAttachments:s=>i(e,s),removeAttachment:s=>o(e,s)}},s3=e=>{const t=$e();return yt.useQuery({queryKey:["mp-agents","configurations",e??"all"],queryFn:async()=>t.transport.listAgentConfigurations?t.transport.listAgentConfigurations(e):[],staleTime:6e4,refetchOnWindowFocus:!1})},f7e=(e,t=[])=>{const n=$e(),r=V.useRef(e),a=V.useCallback(e,t);r.current=a;const i=V.useCallback(o=>r.current(o),[]);V.useEffect(()=>n.registerPageContextProvider(i),[n,i])},l3=e=>{const t=$e();return V.useCallback(r=>{t.events.dispatchEvent(new CustomEvent(e,{detail:r}))},[t,e])},c3=(e,t,n=[],r)=>{const a=$e(),i=V.useRef(t),o=V.useCallback(t,n);i.current=o;const s=V.useCallback(u=>{i.current(u)},[]),l=typeof r=="boolean"?r:r?.capture;V.useEffect(()=>(a.events.addEventListener(e,s,r),()=>{a.events.removeEventListener(e,s,l)}),[a,e,s,l])},g7e=({formId:e,onApply:t,enabled:n=!0})=>{c3(Pd,r=>{n&&r.detail.formId===e&&t(r.detail)},[n,e,t])},y7e=["mp-agents","configurations"],u3=()=>{const e=$e(),t=yt.useQueryClient(),n=()=>t.invalidateQueries({queryKey:y7e}),r=yt.useMutation({mutationFn:async({agentName:i,input:o})=>{if(!e.transport.upsertAgentPreferences)throw new Error("upsertAgentPreferences is not supported by this transport");return e.transport.upsertAgentPreferences(i,o)},onSuccess:n}),a=yt.useMutation({mutationFn:async i=>{if(!e.transport.upsertAgentPreferencesBatch)throw new Error("upsertAgentPreferencesBatch is not supported by this transport");return e.transport.upsertAgentPreferencesBatch(i)},onSuccess:n});return{upsertSingle:r,upsertBatch:a}},d3=()=>{const e=$e(),t=be(s=>s.activeChatId),n=be(s=>s.upsertChat),r=be(s=>s.setActiveChat),a=be(s=>s.setChatStatus),i=!!t,o=yt.useQuery({queryKey:["mp-agents","chat",t],queryFn:()=>e.transport.getChat(t),enabled:i,staleTime:6e4,retry:!1});return V.useEffect(()=>{o.data&&(n(o.data),a(o.data.id,Di(o.data.status)))},[o.data,n,a]),V.useEffect(()=>{o.isError&&t&&r(void 0)},[o.isError,t,r]),o},p3=20,np=e=>{const t=$e(),n=t.config.messagesPageSize??p3,r=be(o=>o.setChatMessages),a=be(o=>!!(e&&o.chats[e])),i=yt.useInfiniteQuery({queryKey:["mp-agents","messages",e,n],queryFn:async({pageParam:o})=>{if(!e||!t.transport.getMessages)throw new Error("No chat or transport");return await t.transport.getMessages(e,{limit:n,...o?{before:o}:{}})},initialPageParam:void 0,getNextPageParam:o=>o.hasMore&&o.messages.length>0?o.messages[0]?.id:void 0,enabled:!!e&&!!t.transport.getMessages&&a,retry:!1});return V.useEffect(()=>{if(!e||!i.data?.pages)return;const s=i.data.pages.slice().reverse().flatMap(u=>u.messages),l=new Set(s.map(u=>u.id));r(e,u=>{const d=u.filter(p=>!l.has(p.id));return[...s,...d]})},[e,i.data,r]),i},rp=()=>{const e=$e(),t=e.config.user?.id??Hr(),n=be(u=>u.activeChatId),r=be(u=>u.removeChat),a=be(u=>u.setActiveChat),[i,o]=V.useState(new Set),s=V.useCallback(async u=>{o(d=>new Set(d).add(u));try{await e.transport.deleteChat(u),r(u),n===u&&a(void 0),e.queryClient.invalidateQueries({queryKey:["mp-agents","chats",t]})}finally{o(d=>{const p=new Set(d);return p.delete(u),p})}},[n,r,e.queryClient,e.transport,a,t]),l=V.useCallback(u=>i.has(u),[i]);return{deleteChat:s,isDeleting:l}},b7e=e=>{if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);if(typeof e=="object")try{return JSON.stringify(e)}catch{return String(e)}return String(e)},k7e=e=>{const t=e.output??e.input??{},n=Array.isArray(t.fields)?t.fields.map(r=>({name:typeof r?.name=="string"?r.name:"",label:typeof r?.label=="string"?r.label:void 0,value:b7e(r?.value),inputType:typeof r?.inputType=="string"?r.inputType:void 0,options:Array.isArray(r?.options)?r.options:void 0})).filter(r=>r.name.length>0):[];return{formId:typeof t.formId=="string"?t.formId:void 0,formName:typeof t.formName=="string"?t.formName:void 0,fields:n,notes:typeof t.notes=="string"?t.notes:void 0}},h3=({call:e,chatId:t,applyAllButtonText:n,showStatus:r=!0})=>{const a=$e(),i=l3(Pd),o=Wt(),s=V.useMemo(()=>k7e(e),[e]),[l,u]=V.useState(new Set),d=V.useMemo(()=>{const x=(e.output??{})?._mp?.lastAction,D=typeof x?.action=="string"?x.action:void 0,P=typeof x?.at=="string"?x.at:void 0;return{action:D,at:P}},[e.output]),p=V.useMemo(()=>d.action==="apply",[d.action]),m=V.useMemo(()=>d.action==="reject",[d.action]),h=V.useMemo(()=>e.status===exports.AgentToolCallStatus.Succeeded&&!!s.formId&&s.fields.length>0&&!p,[e.status,s.formId,s.fields.length,p]);V.useMemo(()=>e.status===exports.AgentToolCallStatus.Succeeded&&!!s.formId&&s.fields.length>0&&!p&&!m,[e.status,s.formId,s.fields.length,p,m]);const g=V.useCallback(async E=>{s.formId&&a.transport.recordToolCallAction&&await a.transport.recordToolCallAction(t,{toolCallId:e.id,action:E.action,data:{formId:s.formId,formName:s.formName,fields:E.fields},systemMessage:E.action==="apply"?`Applied ${E.fields.length} field(s) to ${s.formName??s.formId}.`:`Rejected ${s.formName??s.formId} suggestion.`},{excludeSocketId:!1})},[s.formId,s.formName,t,e.id,a.transport]),f=V.useCallback(async E=>{if(s.formId){i({fields:E,chatId:t,toolCallId:e.id,formId:s.formId,...s.formName?{formName:s.formName}:{}});try{await g({action:"apply",fields:E})}catch{return}}},[s.formId,s.formName,t,e.id,i,g]);V.useCallback(async()=>{if(s.formId)try{await g({action:"reject",fields:s.fields})}catch{return}},[s.formId,s.fields,g]);const w=V.useCallback(E=>{u(S=>{if(S.has(E)){if(S.size===1)return new Set;const x=new Set(S);return x.delete(E),x}else{const x=new Set(S);return x.add(E),x}})},[]),v=V.useCallback(E=>{f([E])},[f]),k=V.useCallback(()=>{f(s.fields)},[f,s.fields]),_=s.formName?`${o.formProposalHeaderPrefix} ${s.formName}`:`${o.formProposalHeaderPrefix} ${s.formId}`;return e.status===exports.AgentToolCallStatus.Failed&&e.error?N.jsx("div",{className:"mp-agent-tool-body",children:N.jsx("div",{className:"mp-agent-tool-simple-message",children:o.formProposalFailed})}):e.status!==exports.AgentToolCallStatus.Succeeded?N.jsx("div",{className:"mp-agent-tool-simple-message",children:o.formProposalPreparing}):!s.formId||s.fields.length===0?N.jsx("div",{className:"mp-agent-tool-simple-message",children:o.formProposalNone}):N.jsxs("div",{className:"mp-agent-tool-body",children:[N.jsx("div",{className:"mp-agent-tool-simple-message",children:_}),s.notes?N.jsx("div",{className:"mp-agent-tool-simple-message",children:s.notes}):null,N.jsx("div",{className:"mp-agent-form-proposal-fields",children:s.fields.map(E=>N.jsx(Z5,{field:E,isExpanded:l.has(E.name),canApply:h,onToggleExpand:w,onApply:v},E.name))}),N.jsxs("div",{className:"mp-agent-form-proposal-actions",children:[r&&(p||m)&&N.jsxs("div",{className:"mp-agent-form-proposal-status",children:[N.jsx("span",{className:`mp-agent-form-proposal-badge ${p?"is-applied":"is-rejected"}`,children:p?o.formProposalApplied:o.formProposalRejected}),d.at?N.jsx("span",{className:"mp-agent-form-proposal-status-time",children:N.jsx(r6e,{date:d.at})}):null]}),N.jsxs("button",{type:"button",onClick:k,className:"mp-agent-form-proposal-apply-all",children:[N.jsx(b5,{size:14})," ",n||o.formProposalApplyAll]})]})]})},po=e=>{const{id:t,name:n,url:r,capturedAt:a,source:i,security:o,target:s,kind:l,...u}=e,d=r??i?.url,p=i||d?{...i??{},...d?{url:d}:{}}:void 0,m=l==="webSnippet"||l==="formSnapshot"||l==="formField"?!0:void 0,h=o||(m!==void 0?{containsPII:m,redactionsApplied:[]}:void 0),g=typeof n=="string"&&n.trim().length?n.trim():l==="webSnippet"?u?.title?`Selection: ${String(u.title)}`:"Selection":l==="formField"?"Form field":l==="formSnapshot"?"Form snapshot":"Context";return{id:t??_t.nanoid(),type:exports.AgentAttachmentType.Context,name:g,...d?{url:d}:{},metadata:{schemaVersion:1,kind:l,capturedAt:a??new Date().toISOString(),...p?{source:p}:{},...h?{security:h}:{},...s?{target:s}:{},...u}}},v7e=e=>{try{const t=new URL(e),n=`${t.searchParams.toString()} ${t.hash}`.toLowerCase();return/(token|key|auth|session|code|password|secret|email)/.test(n)}catch{return/(token|key|auth|session|code|password|secret|email)/.test(e.toLowerCase())}},m3=(e={})=>{if(typeof window>"u")return;const t=e.url??window.location?.href;if(!t)return;const n=e.includeTitle!==!1,r=e.includeReferrer!==!1,a=e.includeViewport!==!1,i=e.includeUserAgent===!0,o=n&&typeof document<"u"?document.title:void 0,s=r&&typeof document<"u"?document.referrer:void 0;let l;try{l=new URL(t)}catch{}const u={url:t,...l?{origin:l.origin,pathname:l.pathname,search:l.search,hash:l.hash}:{},...n&&o?{title:o}:{},...r&&s?{referrer:s}:{},...i&&typeof navigator<"u"?{userAgent:navigator.userAgent}:{},...typeof navigator<"u"&&navigator.language?{language:navigator.language}:{},...typeof Intl<"u"?{timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,locale:Intl.DateTimeFormat().resolvedOptions().locale}:{},...a&&typeof window<"u"?{viewport:{width:window.innerWidth,height:window.innerHeight,devicePixelRatio:window.devicePixelRatio}}:{},...e.extra?e.extra:{}},d=v7e(t)?!0:void 0;return po({kind:"pageContext",name:e.name??"Page context",url:t,title:o,data:u,summary:l?`${l.pathname}${l.search}${l.hash}`:void 0,source:{app:"browser",url:t,route:l?`${l.pathname}${l.search}${l.hash}`:void 0},...d?{security:{containsPII:!0,redactionsApplied:[]}}:{}})},f3=()=>{if(typeof window>"u"||typeof document>"u")return;const e=window.getSelection?.();if(!e||e.rangeCount===0)return;const t=e.getRangeAt(0),n=e.toString().trim();if(!n)return;const r=(t.commonAncestorContainer.nodeType===Node.ELEMENT_NODE?t.commonAncestorContainer:t.commonAncestorContainer.parentElement)??void 0,a=r?_7e(r):void 0,i=r?.textContent??"",o=i.indexOf(n),s=o>=0?o:void 0,l=o>=0?o+n.length:void 0,u=o>=0?i.slice(Math.max(0,o-80),o).trim():void 0,d=o>=0?i.slice(o+n.length,o+n.length+80).trim():void 0;return{selectedText:n,target:{type:"text",exact:n,...u?{prefix:u}:{},...d?{suffix:d}:{},...a?{domPath:a}:{},...s!==void 0?{startOffset:s}:{},...l!==void 0?{endOffset:l}:{}}}},_7e=e=>{if(e.id)return`#${s2(e.id)}`;const t=[];let n=e;for(;n&&n.nodeType===1&&t.length<6;){const r=n.tagName.toLowerCase();if(n.id){t.unshift(`#${s2(n.id)}`);break}const a=n.parentElement;if(!a){t.unshift(r);break}const o=Array.from(a.children).filter(s=>s.tagName===n.tagName).indexOf(n)+1;t.unshift(`${r}:nth-of-type(${o})`),n=a}return t.join(" > ")},s2=e=>e.replace(/[^a-zA-Z0-9_-]/g,"\\$&");class g3{constructor(t){this.rawConfig=t,this.events=new EventTarget;const n=Wu.parse(t);this.config={...n,toolRenderers:t.toolRenderers,composerAttachmentActions:t.composerAttachmentActions,tools:t.tools,pageContext:t.pageContext?{...n.pageContext,...t.pageContext}:n.pageContext,translations:t.translations?{...Ni,...t.translations}:Ni,transport:t.transport.onError?{...n.transport,onError:t.transport.onError}:n.transport},this.transport=this.createTransport(this.config.transport),this.tools=new J7(this.config.tools),this.tools.bindInvoke(this.invokeTool.bind(this)),this.configureTransportAfterCreate(this.transport),Object.entries(t.toolRenderers??{}).forEach(([r,a])=>{a&&this.toolRendererMap.set(r,a)}),this.toolRendererMap.has("propose_form_values")||this.toolRendererMap.set("propose_form_values",h3),this.queryClient=new yt.QueryClient({defaultOptions:{queries:{staleTime:3e4,refetchOnWindowFocus:!1}}})}config;transport;tools;queryClient;events;socketClient=null;toolRendererMap=new Map;storeRef;pageContextProviders=new Set;createTransport(t){return t.mode==="proxy"?new Or(t):new $o(t)}configureTransportAfterCreate(t){this.config.transport.mode==="direct"&&t instanceof $o&&(t.setToolRegistry(this.tools),t.setContextKeys(this.config.contextKeys.map(n=>({key:n.key,tools:n.tools}))),this.config.models&&t.setModels(this.config.models),t.setUntitledChatText(this.config.translations.untitledChat))}updateTransportConfig(t){const n=Wu.parse({...this.rawConfig,transport:t}),r=this.config.transport,a=this.transport;this.rawConfig={...this.rawConfig,transport:t},this.config.transport=t.onError?{...n.transport,onError:t.onError}:n.transport;const i=this.config.transport.mode;if(r.mode!==i){a.cancelStream?.(),this.transport=this.createTransport(this.config.transport),this.configureTransportAfterCreate(this.transport),this.events.dispatchEvent(new CustomEvent("runtime:transport-config-changed",{detail:{previous:r,next:this.config.transport}}));return}i==="proxy"&&a instanceof Or?a.updateConfig(this.config.transport):i==="direct"&&a instanceof $o?(a.updateConfig(this.config.transport),this.configureTransportAfterCreate(a)):(a.cancelStream?.(),this.transport=this.createTransport(this.config.transport),this.configureTransportAfterCreate(this.transport)),this.events.dispatchEvent(new CustomEvent("runtime:transport-config-changed",{detail:{previous:r,next:this.config.transport}}))}setTransportHeaders(t){const n=this.config.transport;this.updateTransportConfig({...n,headers:t})}mergeTransportHeaders(t){const n=this.config.transport;this.updateTransportConfig({...n,headers:{...n.headers??{},...t}})}removeTransportHeaders(t){const n=this.config.transport;if(!n.headers||t.length===0)return;const r={...n.headers};for(const a of t)delete r[a];this.updateTransportConfig({...n,headers:Object.keys(r).length?r:void 0})}get defaultContextKey(){return this.config.defaultContextKey??this.config.contextKeys[0]?.key}get store(){if(!this.storeRef)throw new Error("AgentRuntime store has not been attached yet");return this.storeRef}attachStore(t){this.storeRef=t}get socket(){return this.socketClient}setSocketClient(t){this.socketClient!==t&&(this.socketClient=t,this.events.dispatchEvent(new CustomEvent("runtime:socket-changed",{detail:{socket:t}})))}registerTool(t){this.tools.register(t)}registerToolRenderer(t,n){this.toolRendererMap.set(t,n)}registerPageContextProvider(t){return this.pageContextProviders.add(t),()=>{this.pageContextProviders.delete(t)}}getPageContextInput(){if(typeof window>"u")return{};const t=window.location?.href;let n;if(t)try{const a=new URL(t);n=`${a.pathname}${a.search}${a.hash}`}catch{}const r=typeof document<"u"?document.title:void 0;return{url:t,route:n,title:r}}getPageContextData(t){const n=t??this.getPageContextInput(),r={};let a=!1;const i=this.config.pageContext?.getData;if(i)try{const o=i(n);o&&typeof o=="object"&&(Object.assign(r,o),a=!0)}catch{}for(const o of this.pageContextProviders)try{const s=o(n);s&&typeof s=="object"&&(Object.assign(r,s),a=!0)}catch{}return a?r:void 0}buildPageContextAttachment(){const t=this.config.pageContext,n=this.getPageContextData();return m3({...t?.includeUserAgent!==void 0?{includeUserAgent:t.includeUserAgent}:{},...t?.includeReferrer!==void 0?{includeReferrer:t.includeReferrer}:{},...t?.includeViewport!==void 0?{includeViewport:t.includeViewport}:{},...t?.includeTitle!==void 0?{includeTitle:t.includeTitle}:{},...t?.name?{name:t.name}:{},...n?{extra:n}:{}})}getToolRenderer(t){return this.toolRendererMap.get(t.name)}ensureStore(t){if(!this.storeRef)throw new Error(`Cannot ${t} before AgentRuntime is mounted`);return this.storeRef}resolveChatId(t){const r=this.ensureStore("invoke tools").getState(),a=t?.chatId??r.activeChatId;if(!a||!r.chats[a])throw new Error("Tool invocation requires an active chat. Select or create a chat first.");return a}buildToolContext(t){const n=this.ensureStore("create tool context");return{chatId:t,agentId:this.config.appId,workspaceId:this.config.workspaceId,appendSystemMessage:r=>{n.getState().appendSystemMessage(t,r)}}}writeToolCall(t,n){this.ensureStore("write tool call").getState().upsertToolCall(t,{...n})}async invokeTool(t,n={},r){const a=this.resolveChatId(r),i={id:_t.nanoid(),name:t,input:n,status:exports.AgentToolCallStatus.Running};this.writeToolCall(a,i);const o=this.buildToolContext(a);try{const s=await this.tools.execute(t,n,o,i);return this.writeToolCall(a,s),s}catch(s){const l={...i,status:exports.AgentToolCallStatus.Failed,error:s instanceof Error?s.message:"Unknown tool error"};throw this.writeToolCall(a,l),s}}}const w7e={background:"#050505",surface:"#0f0f11",text:"#f7f7f7",subtext:"#8f9baa",border:"#1f2229",accent:"#6c63ff",accentSoft:"rgba(108, 99, 255, 0.14)",warning:"#ffb347",danger:"#ff5f56",fontFamily:'Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',radius:"12px",fontSize:"14px",colorMode:"light"},y3=e=>({...w7e,...e}),b3=V.createContext(y3()),x7e=e=>({"--mp-agents-bg":e.background,"--mp-agents-surface":e.surface,"--mp-agents-text":e.text,"--mp-agents-subtext":e.subtext,"--mp-agents-border":e.border,"--mp-agents-accent":e.accent,"--mp-agents-accent-soft":e.accentSoft,"--mp-agents-warning":e.warning,"--mp-agents-danger":e.danger,"--mp-agents-radius":e.radius,"--mp-agents-font-size":e.fontSize}),k3=({value:e,children:t})=>{const n=V.useMemo(()=>y3(e),[e]);return N.jsxs(b3.Provider,{value:n,children:[N.jsx("style",{children:`:root {
|
|
8290
|
+
*/var E6e=["input:not([inert])","select:not([inert])","textarea:not([inert])","a[href]:not([inert])","button:not([inert])","[tabindex]:not(slot):not([inert])","audio[controls]:not([inert])","video[controls]:not([inert])",'[contenteditable]:not([contenteditable="false"]):not([inert])',"details>summary:first-of-type:not([inert])","details:not([inert])"],Xu=E6e.join(","),M5=typeof Element>"u",pa=M5?function(){}:Element.prototype.matches||Element.prototype.msMatchesSelector||Element.prototype.webkitMatchesSelector,Oi=!M5&&Element.prototype.getRootNode?function(e){var t;return e==null||(t=e.getRootNode)===null||t===void 0?void 0:t.call(e)}:function(e){return e?.ownerDocument},ha=function(t,n){var r;n===void 0&&(n=!0);var a=t==null||(r=t.getAttribute)===null||r===void 0?void 0:r.call(t,"inert"),i=a===""||a==="true",o=i||n&&t&&ha(t.parentNode);return o},M6e=function(t){var n,r=t==null||(n=t.getAttribute)===null||n===void 0?void 0:n.call(t,"contenteditable");return r===""||r==="true"},S6e=function(t,n,r){if(ha(t))return[];var a=Array.prototype.slice.apply(t.querySelectorAll(Xu));return n&&pa.call(t,Xu)&&a.unshift(t),a=a.filter(r),a},Qu=function(t,n,r){for(var a=[],i=Array.from(t);i.length;){var o=i.shift();if(!ha(o,!1))if(o.tagName==="SLOT"){var s=o.assignedElements(),l=s.length?s:o.children,u=Qu(l,!0,r);r.flatten?a.push.apply(a,u):a.push({scopeParent:o,candidates:u})}else{var d=pa.call(o,Xu);d&&r.filter(o)&&(n||!t.includes(o))&&a.push(o);var p=o.shadowRoot||typeof r.getShadowRoot=="function"&&r.getShadowRoot(o),m=!ha(p,!1)&&(!r.shadowRootFilter||r.shadowRootFilter(o));if(p&&m){var h=Qu(p===!0?o.children:p.children,!0,r);r.flatten?a.push.apply(a,h):a.push({scopeParent:o,candidates:h})}else i.unshift.apply(i,o.children)}}return a},S5=function(t){return!isNaN(parseInt(t.getAttribute("tabindex"),10))},N5=function(t){if(!t)throw new Error("No node provided");return t.tabIndex<0&&(/^(AUDIO|VIDEO|DETAILS)$/.test(t.tagName)||M6e(t))&&!S5(t)?0:t.tabIndex},N6e=function(t,n){var r=N5(t);return r<0&&n&&!S5(t)?0:r},A6e=function(t,n){return t.tabIndex===n.tabIndex?t.documentOrder-n.documentOrder:t.tabIndex-n.tabIndex},A5=function(t){return t.tagName==="INPUT"},T6e=function(t){return A5(t)&&t.type==="hidden"},C6e=function(t){var n=t.tagName==="DETAILS"&&Array.prototype.slice.apply(t.children).some(function(r){return r.tagName==="SUMMARY"});return n},R6e=function(t,n){for(var r=0;r<t.length;r++)if(t[r].checked&&t[r].form===n)return t[r]},I6e=function(t){if(!t.name)return!0;var n=t.form||Oi(t),r=function(s){return n.querySelectorAll('input[type="radio"][name="'+s+'"]')},a;if(typeof window<"u"&&typeof window.CSS<"u"&&typeof window.CSS.escape=="function")a=r(window.CSS.escape(t.name));else try{a=r(t.name)}catch(o){return console.error("Looks like you have a radio button with a name attribute containing invalid CSS selector characters and need the CSS.escape polyfill: %s",o.message),!1}var i=R6e(a,t.form);return!i||i===t},O6e=function(t){return A5(t)&&t.type==="radio"},L6e=function(t){return O6e(t)&&!I6e(t)},D6e=function(t){var n,r=t&&Oi(t),a=(n=r)===null||n===void 0?void 0:n.host,i=!1;if(r&&r!==t){var o,s,l;for(i=!!((o=a)!==null&&o!==void 0&&(s=o.ownerDocument)!==null&&s!==void 0&&s.contains(a)||t!=null&&(l=t.ownerDocument)!==null&&l!==void 0&&l.contains(t));!i&&a;){var u,d,p;r=Oi(a),a=(u=r)===null||u===void 0?void 0:u.host,i=!!((d=a)!==null&&d!==void 0&&(p=d.ownerDocument)!==null&&p!==void 0&&p.contains(a))}}return i},zh=function(t){var n=t.getBoundingClientRect(),r=n.width,a=n.height;return r===0&&a===0},z6e=function(t,n){var r=n.displayCheck,a=n.getShadowRoot;if(r==="full-native"&&"checkVisibility"in t){var i=t.checkVisibility({checkOpacity:!1,opacityProperty:!1,contentVisibilityAuto:!0,visibilityProperty:!0,checkVisibilityCSS:!0});return!i}if(getComputedStyle(t).visibility==="hidden")return!0;var o=pa.call(t,"details>summary:first-of-type"),s=o?t.parentElement:t;if(pa.call(s,"details:not([open]) *"))return!0;if(!r||r==="full"||r==="full-native"||r==="legacy-full"){if(typeof a=="function"){for(var l=t;t;){var u=t.parentElement,d=Oi(t);if(u&&!u.shadowRoot&&a(u)===!0)return zh(t);t.assignedSlot?t=t.assignedSlot:!u&&d!==t.ownerDocument?t=d.host:t=u}t=l}if(D6e(t))return!t.getClientRects().length;if(r!=="legacy-full")return!0}else if(r==="non-zero-area")return zh(t);return!1},$6e=function(t){if(/^(INPUT|BUTTON|SELECT|TEXTAREA)$/.test(t.tagName))for(var n=t.parentElement;n;){if(n.tagName==="FIELDSET"&&n.disabled){for(var r=0;r<n.children.length;r++){var a=n.children.item(r);if(a.tagName==="LEGEND")return pa.call(n,"fieldset[disabled] *")?!0:!a.contains(t)}return!0}n=n.parentElement}return!1},F6e=function(t,n){return!(n.disabled||ha(n)||T6e(n)||z6e(n,t)||C6e(n)||$6e(n))},$h=function(t,n){return!(L6e(n)||N5(n)<0||!F6e(t,n))},P6e=function(t){var n=parseInt(t.getAttribute("tabindex"),10);return!!(isNaN(n)||n>=0)},T5=function(t){var n=[],r=[];return t.forEach(function(a,i){var o=!!a.scopeParent,s=o?a.scopeParent:a,l=N6e(s,o),u=o?T5(a.candidates):s;l===0?o?n.push.apply(n,u):n.push(s):r.push({documentOrder:i,tabIndex:l,item:a,isScope:o,content:u})}),r.sort(A6e).reduce(function(a,i){return i.isScope?a.push.apply(a,i.content):a.push(i.content),a},[]).concat(n)},C5=function(t,n){n=n||{};var r;return n.getShadowRoot?r=Qu([t],n.includeContainer,{filter:$h.bind(null,n),flatten:!1,getShadowRoot:n.getShadowRoot,shadowRootFilter:P6e}):r=S6e(t,n.includeContainer,$h.bind(null,n)),T5(r)};function R5(){const e=navigator.userAgentData;return e!=null&&e.platform?e.platform:navigator.platform}function I5(){const e=navigator.userAgentData;return e&&Array.isArray(e.brands)?e.brands.map(t=>{let{brand:n,version:r}=t;return n+"/"+r}).join(" "):navigator.userAgent}function O5(){return/apple/i.test(navigator.vendor)}function Ju(){const e=/android/i;return e.test(R5())||e.test(I5())}function q6e(){return R5().toLowerCase().startsWith("mac")&&!navigator.maxTouchPoints}function L5(){return I5().includes("jsdom/")}const Fh="data-floating-ui-focusable",B6e="input:not([type='hidden']):not([disabled]),[contenteditable]:not([contenteditable='false']),textarea:not([disabled])",Fo="ArrowLeft",Po="ArrowRight",U6e="ArrowUp",H6e="ArrowDown";function ma(e){let t=e.activeElement;for(;((n=t)==null||(n=n.shadowRoot)==null?void 0:n.activeElement)!=null;){var n;t=t.shadowRoot.activeElement}return t}function fr(e,t){if(!e||!t)return!1;const n=t.getRootNode==null?void 0:t.getRootNode();if(e.contains(t))return!0;if(n&&Ku(n)){let r=t;for(;r;){if(e===r)return!0;r=r.parentNode||r.host}}return!1}function Ar(e){return"composedPath"in e?e.composedPath()[0]:e.target}function qo(e,t){if(t==null)return!1;if("composedPath"in e)return e.composedPath().includes(t);const n=e;return n.target!=null&&t.contains(n.target)}function j6e(e){return e.matches("html,body")}function dn(e){return e?.ownerDocument||document}function Ud(e){return xt(e)&&e.matches(B6e)}function V6e(e){return e?e.getAttribute("role")==="combobox"&&Ud(e):!1}function G6e(e){if(!e||L5())return!0;try{return e.matches(":focus-visible")}catch{return!0}}function D5(e){return e?e.hasAttribute(Fh)?e:e.querySelector("["+Fh+"]")||e:null}function oa(e,t,n){return n===void 0&&(n=!0),e.filter(a=>{var i;return a.parentId===t&&(!n||((i=a.context)==null?void 0:i.open))}).flatMap(a=>[a,...oa(e,a.id,n)])}function W6e(e,t){let n,r=-1;function a(i,o){o>r&&(n=i,r=o),oa(e,i).forEach(l=>{a(l.id,o+1)})}return a(t,0),e.find(i=>i.id===n)}function Xt(e){e.preventDefault(),e.stopPropagation()}function K6e(e){return"nativeEvent"in e}function Y6e(e){return e.mozInputSource===0&&e.isTrusted?!0:Ju()&&e.pointerType?e.type==="click"&&e.buttons===1:e.detail===0&&!e.pointerType}function Z6e(e){return L5()?!1:!Ju()&&e.width===0&&e.height===0||Ju()&&e.width===1&&e.height===1&&e.pressure===0&&e.detail===0&&e.pointerType==="mouse"||e.width<1&&e.height<1&&e.pressure===0&&e.detail===0&&e.pointerType==="touch"}function fa(e,t){const n=["mouse","pen"];return t||n.push("",void 0),n.includes(e)}var X6e=typeof document<"u",Q6e=function(){},gt=X6e?V.useLayoutEffect:Q6e;const J6e={...te};function Rn(e){const t=te.useRef(e);return gt(()=>{t.current=e}),t}const e8e=J6e.useInsertionEffect,t8e=e8e||(e=>e());function Vt(e){const t=te.useRef(()=>{if(process.env.NODE_ENV!=="production")throw new Error("Cannot call an event handler while rendering.")});return t8e(()=>{t.current=e}),te.useCallback(function(){for(var n=arguments.length,r=new Array(n),a=0;a<n;a++)r[a]=arguments[a];return t.current==null?void 0:t.current(...r)},[])}function Ua(e,t,n){return Math.floor(e/t)!==n}function sa(e,t){return t<0||t>=e.current.length}function Bo(e,t){return kt(e,{disabledIndices:t})}function Ph(e,t){return kt(e,{decrement:!0,startingIndex:e.current.length,disabledIndices:t})}function kt(e,t){let{startingIndex:n=-1,decrement:r=!1,disabledIndices:a,amount:i=1}=t===void 0?{}:t,o=n;do o+=r?-i:i;while(o>=0&&o<=e.current.length-1&&gi(e,o,a));return o}function n8e(e,t){let{event:n,orientation:r,loop:a,rtl:i,cols:o,disabledIndices:s,minIndex:l,maxIndex:u,prevIndex:d,stopEvent:p=!1}=t,m=d;if(n.key===U6e){if(p&&Xt(n),d===-1)m=u;else if(m=kt(e,{startingIndex:m,amount:o,decrement:!0,disabledIndices:s}),a&&(d-o<l||m<0)){const h=d%o,g=u%o,f=u-(g-h);g===h?m=u:m=g>h?f:f-o}sa(e,m)&&(m=d)}if(n.key===H6e&&(p&&Xt(n),d===-1?m=l:(m=kt(e,{startingIndex:d,amount:o,disabledIndices:s}),a&&d+o>u&&(m=kt(e,{startingIndex:d%o-o,amount:o,disabledIndices:s}))),sa(e,m)&&(m=d)),r==="both"){const h=Lr(d/o);n.key===(i?Fo:Po)&&(p&&Xt(n),d%o!==o-1?(m=kt(e,{startingIndex:d,disabledIndices:s}),a&&Ua(m,o,h)&&(m=kt(e,{startingIndex:d-d%o-1,disabledIndices:s}))):a&&(m=kt(e,{startingIndex:d-d%o-1,disabledIndices:s})),Ua(m,o,h)&&(m=d)),n.key===(i?Po:Fo)&&(p&&Xt(n),d%o!==0?(m=kt(e,{startingIndex:d,decrement:!0,disabledIndices:s}),a&&Ua(m,o,h)&&(m=kt(e,{startingIndex:d+(o-d%o),decrement:!0,disabledIndices:s}))):a&&(m=kt(e,{startingIndex:d+(o-d%o),decrement:!0,disabledIndices:s})),Ua(m,o,h)&&(m=d));const g=Lr(u/o)===h;sa(e,m)&&(a&&g?m=n.key===(i?Po:Fo)?u:kt(e,{startingIndex:d-d%o-1,disabledIndices:s}):m=d)}return m}function r8e(e,t,n){const r=[];let a=0;return e.forEach((i,o)=>{let{width:s,height:l}=i;if(s>t&&process.env.NODE_ENV!=="production")throw new Error("[Floating UI]: Invalid grid - item width at index "+o+" is greater than grid columns");let u=!1;for(n&&(a=0);!u;){const d=[];for(let p=0;p<s;p++)for(let m=0;m<l;m++)d.push(a+p+m*t);a%t+s<=t&&d.every(p=>r[p]==null)?(d.forEach(p=>{r[p]=o}),u=!0):a++}}),[...r]}function a8e(e,t,n,r,a){if(e===-1)return-1;const i=n.indexOf(e),o=t[e];switch(a){case"tl":return i;case"tr":return o?i+o.width-1:i;case"bl":return o?i+(o.height-1)*r:i;case"br":return n.lastIndexOf(e)}}function i8e(e,t){return t.flatMap((n,r)=>e.includes(n)?[r]:[])}function gi(e,t,n){if(typeof n=="function")return n(t);if(n)return n.includes(t);const r=e.current[t];return r==null||r.hasAttribute("disabled")||r.getAttribute("aria-disabled")==="true"}const z5=()=>({getShadowRoot:!0,displayCheck:typeof ResizeObserver=="function"&&ResizeObserver.toString().includes("[native code]")?"full":"none"});function $5(e,t){const n=C5(e,z5()),r=n.length;if(r===0)return;const a=ma(dn(e)),i=n.indexOf(a),o=i===-1?t===1?0:r-1:i+t;return n[o]}function o8e(e){return $5(dn(e).body,1)||e}function s8e(e){return $5(dn(e).body,-1)||e}function Uo(e,t){const n=t||e.currentTarget,r=e.relatedTarget;return!r||!fr(n,r)}function l8e(e){C5(e,z5()).forEach(n=>{n.dataset.tabindex=n.getAttribute("tabindex")||"",n.setAttribute("tabindex","-1")})}function qh(e){e.querySelectorAll("[data-tabindex]").forEach(n=>{const r=n.dataset.tabindex;delete n.dataset.tabindex,r?n.setAttribute("tabindex",r):n.removeAttribute("tabindex")})}function Bh(e,t,n){let{reference:r,floating:a}=e;const i=Kn(t),o=E5(t),s=x5(o),l=mr(t),u=i==="y",d=r.x+r.width/2-a.width/2,p=r.y+r.height/2-a.height/2,m=r[s]/2-a[s]/2;let h;switch(l){case"top":h={x:d,y:r.y-a.height};break;case"bottom":h={x:d,y:r.y+r.height};break;case"right":h={x:r.x+r.width,y:p};break;case"left":h={x:r.x-a.width,y:p};break;default:h={x:r.x,y:r.y}}switch(ao(t)){case"start":h[o]-=m*(n&&u?-1:1);break;case"end":h[o]+=m*(n&&u?-1:1);break}return h}const c8e=async(e,t,n)=>{const{placement:r="bottom",strategy:a="absolute",middleware:i=[],platform:o}=n,s=i.filter(Boolean),l=await(o.isRTL==null?void 0:o.isRTL(t));let u=await o.getElementRects({reference:e,floating:t,strategy:a}),{x:d,y:p}=Bh(u,r,l),m=r,h={},g=0;for(let f=0;f<s.length;f++){const{name:w,fn:v}=s[f],{x:k,y:_,data:E,reset:S}=await v({x:d,y:p,initialPlacement:r,placement:m,strategy:a,middlewareData:h,rects:u,platform:o,elements:{reference:e,floating:t}});d=k??d,p=_??p,h={...h,[w]:{...h[w],...E}},S&&g<=50&&(g++,typeof S=="object"&&(S.placement&&(m=S.placement),S.rects&&(u=S.rects===!0?await o.getElementRects({reference:e,floating:t,strategy:a}):S.rects),{x:d,y:p}=Bh(u,m,l)),f=-1)}return{x:d,y:p,placement:m,strategy:a,middlewareData:h}};async function F5(e,t){var n;t===void 0&&(t={});const{x:r,y:a,platform:i,rects:o,elements:s,strategy:l}=e,{boundary:u="clippingAncestors",rootBoundary:d="viewport",elementContext:p="floating",altBoundary:m=!1,padding:h=0}=ro(t,e),g=x6e(h),w=s[m?p==="floating"?"reference":"floating":p],v=Ii(await i.getClippingRect({element:(n=await(i.isElement==null?void 0:i.isElement(w)))==null||n?w:w.contextElement||await(i.getDocumentElement==null?void 0:i.getDocumentElement(s.floating)),boundary:u,rootBoundary:d,strategy:l})),k=p==="floating"?{x:r,y:a,width:o.floating.width,height:o.floating.height}:o.reference,_=await(i.getOffsetParent==null?void 0:i.getOffsetParent(s.floating)),E=await(i.isElement==null?void 0:i.isElement(_))?await(i.getScale==null?void 0:i.getScale(_))||{x:1,y:1}:{x:1,y:1},S=Ii(i.convertOffsetParentRelativeRectToViewportRelativeRect?await i.convertOffsetParentRelativeRectToViewportRelativeRect({elements:s,rect:k,offsetParent:_,strategy:l}):k);return{top:(v.top-S.top+g.top)/E.y,bottom:(S.bottom-v.bottom+g.bottom)/E.y,left:(v.left-S.left+g.left)/E.x,right:(S.right-v.right+g.right)/E.x}}const u8e=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:a,middlewareData:i,rects:o,initialPlacement:s,platform:l,elements:u}=t,{mainAxis:d=!0,crossAxis:p=!0,fallbackPlacements:m,fallbackStrategy:h="bestFit",fallbackAxisSideDirection:g="none",flipAlignment:f=!0,...w}=ro(e,t);if((n=i.arrow)!=null&&n.alignmentOffset)return{};const v=mr(a),k=Kn(s),_=mr(s)===s,E=await(l.isRTL==null?void 0:l.isRTL(u.floating)),S=m||(_||!f?[Ri(s)]:y6e(s)),x=g!=="none";!m&&x&&S.push(..._6e(s,f,g,E));const D=[s,...S],P=await F5(t,w),C=[];let L=((r=i.flip)==null?void 0:r.overflows)||[];if(d&&C.push(P[v]),p){const K=g6e(a,o,E);C.push(P[K[0]],P[K[1]])}if(L=[...L,{placement:a,overflows:C}],!C.every(K=>K<=0)){var G,X;const K=(((G=i.flip)==null?void 0:G.index)||0)+1,R=D[K];if(R&&(!(p==="alignment"?k!==Kn(R):!1)||L.every(z=>Kn(z.placement)===k?z.overflows[0]>0:!0)))return{data:{index:K,overflows:L},reset:{placement:R}};let U=(X=L.filter(H=>H.overflows[0]<=0).sort((H,z)=>H.overflows[1]-z.overflows[1])[0])==null?void 0:X.placement;if(!U)switch(h){case"bestFit":{var J;const H=(J=L.filter(z=>{if(x){const j=Kn(z.placement);return j===k||j==="y"}return!0}).map(z=>[z.placement,z.overflows.filter(j=>j>0).reduce((j,A)=>j+A,0)]).sort((z,j)=>z[1]-j[1])[0])==null?void 0:J[0];H&&(U=H);break}case"initialPlacement":U=s;break}if(a!==U)return{reset:{placement:U}}}return{}}}},d8e=new Set(["left","top"]);async function p8e(e,t){const{placement:n,platform:r,elements:a}=e,i=await(r.isRTL==null?void 0:r.isRTL(a.floating)),o=mr(n),s=ao(n),l=Kn(n)==="y",u=d8e.has(o)?-1:1,d=i&&l?-1:1,p=ro(t,e);let{mainAxis:m,crossAxis:h,alignmentAxis:g}=typeof p=="number"?{mainAxis:p,crossAxis:0,alignmentAxis:null}:{mainAxis:p.mainAxis||0,crossAxis:p.crossAxis||0,alignmentAxis:p.alignmentAxis};return s&&typeof g=="number"&&(h=s==="end"?g*-1:g),l?{x:h*d,y:m*u}:{x:m*u,y:h*d}}const h8e=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:a,y:i,placement:o,middlewareData:s}=t,l=await p8e(t,e);return o===((n=s.offset)==null?void 0:n.placement)&&(r=s.arrow)!=null&&r.alignmentOffset?{}:{x:a+l.x,y:i+l.y,data:{...l,placement:o}}}}},m8e=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:a}=t,{mainAxis:i=!0,crossAxis:o=!1,limiter:s={fn:w=>{let{x:v,y:k}=w;return{x:v,y:k}}},...l}=ro(e,t),u={x:n,y:r},d=await F5(t,l),p=Kn(mr(a)),m=w5(p);let h=u[m],g=u[p];if(i){const w=m==="y"?"top":"left",v=m==="y"?"bottom":"right",k=h+d[w],_=h-d[v];h=Oh(k,h,_)}if(o){const w=p==="y"?"top":"left",v=p==="y"?"bottom":"right",k=g+d[w],_=g-d[v];g=Oh(k,g,_)}const f=s.fn({...t,[m]:h,[p]:g});return{...f,data:{x:f.x-n,y:f.y-r,enabled:{[m]:i,[p]:o}}}}}};function P5(e){const t=an(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const a=xt(e),i=a?e.offsetWidth:n,o=a?e.offsetHeight:r,s=Ci(n)!==i||Ci(r)!==o;return s&&(n=i,r=o),{width:n,height:r,$:s}}function Hd(e){return Je(e)?e:e.contextElement}function zr(e){const t=Hd(e);if(!xt(t))return vn(1);const n=t.getBoundingClientRect(),{width:r,height:a,$:i}=P5(t);let o=(i?Ci(n.width):n.width)/r,s=(i?Ci(n.height):n.height)/a;return(!o||!Number.isFinite(o))&&(o=1),(!s||!Number.isFinite(s))&&(s=1),{x:o,y:s}}const f8e=vn(0);function q5(e){const t=$t(e);return!to()||!t.visualViewport?f8e:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function g8e(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==$t(e)?!1:t}function gr(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const a=e.getBoundingClientRect(),i=Hd(e);let o=vn(1);t&&(r?Je(r)&&(o=zr(r)):o=zr(e));const s=g8e(i,n,r)?q5(i):vn(0);let l=(a.left+s.x)/o.x,u=(a.top+s.y)/o.y,d=a.width/o.x,p=a.height/o.y;if(i){const m=$t(i),h=r&&Je(r)?$t(r):r;let g=m,f=Yu(g);for(;f&&r&&h!==g;){const w=zr(f),v=f.getBoundingClientRect(),k=an(f),_=v.left+(f.clientLeft+parseFloat(k.paddingLeft))*w.x,E=v.top+(f.clientTop+parseFloat(k.paddingTop))*w.y;l*=w.x,u*=w.y,d*=w.x,p*=w.y,l+=_,u+=E,g=$t(f),f=Yu(g)}}return Ii({width:d,height:p,x:l,y:u})}function io(e,t){const n=no(e).scrollLeft;return t?t.left+n:gr(xn(e)).left+n}function B5(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-io(e,n),a=n.top+t.scrollTop;return{x:r,y:a}}function y8e(e){let{elements:t,rect:n,offsetParent:r,strategy:a}=e;const i=a==="fixed",o=xn(r),s=t?eo(t.floating):!1;if(r===o||s&&i)return n;let l={scrollLeft:0,scrollTop:0},u=vn(1);const d=vn(0),p=xt(r);if((p||!p&&!i)&&((Ur(r)!=="body"||Sa(o))&&(l=no(r)),xt(r))){const h=gr(r);u=zr(r),d.x=h.x+r.clientLeft,d.y=h.y+r.clientTop}const m=o&&!p&&!i?B5(o,l):vn(0);return{width:n.width*u.x,height:n.height*u.y,x:n.x*u.x-l.scrollLeft*u.x+d.x+m.x,y:n.y*u.y-l.scrollTop*u.y+d.y+m.y}}function b8e(e){return Array.from(e.getClientRects())}function k8e(e){const t=xn(e),n=no(e),r=e.ownerDocument.body,a=pr(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),i=pr(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let o=-n.scrollLeft+io(e);const s=-n.scrollTop;return an(r).direction==="rtl"&&(o+=pr(t.clientWidth,r.clientWidth)-a),{width:a,height:i,x:o,y:s}}const Uh=25;function v8e(e,t){const n=$t(e),r=xn(e),a=n.visualViewport;let i=r.clientWidth,o=r.clientHeight,s=0,l=0;if(a){i=a.width,o=a.height;const d=to();(!d||d&&t==="fixed")&&(s=a.offsetLeft,l=a.offsetTop)}const u=io(r);if(u<=0){const d=r.ownerDocument,p=d.body,m=getComputedStyle(p),h=d.compatMode==="CSS1Compat"&&parseFloat(m.marginLeft)+parseFloat(m.marginRight)||0,g=Math.abs(r.clientWidth-p.clientWidth-h);g<=Uh&&(i-=g)}else u<=Uh&&(i+=u);return{width:i,height:o,x:s,y:l}}const _8e=new Set(["absolute","fixed"]);function w8e(e,t){const n=gr(e,!0,t==="fixed"),r=n.top+e.clientTop,a=n.left+e.clientLeft,i=xt(e)?zr(e):vn(1),o=e.clientWidth*i.x,s=e.clientHeight*i.y,l=a*i.x,u=r*i.y;return{width:o,height:s,x:l,y:u}}function Hh(e,t,n){let r;if(t==="viewport")r=v8e(e,n);else if(t==="document")r=k8e(xn(e));else if(Je(t))r=w8e(t,n);else{const a=q5(e);r={x:t.x-a.x,y:t.y-a.y,width:t.width,height:t.height}}return Ii(r)}function U5(e,t){const n=$n(e);return n===t||!Je(n)||Ln(n)?!1:an(n).position==="fixed"||U5(n,t)}function x8e(e,t){const n=t.get(e);if(n)return n;let r=Xn(e,[],!1).filter(s=>Je(s)&&Ur(s)!=="body"),a=null;const i=an(e).position==="fixed";let o=i?$n(e):e;for(;Je(o)&&!Ln(o);){const s=an(o),l=Bd(o);!l&&s.position==="fixed"&&(a=null),(i?!l&&!a:!l&&s.position==="static"&&!!a&&_8e.has(a.position)||Sa(o)&&!l&&U5(e,o))?r=r.filter(d=>d!==o):a=s,o=$n(o)}return t.set(e,r),r}function E8e(e){let{element:t,boundary:n,rootBoundary:r,strategy:a}=e;const o=[...n==="clippingAncestors"?eo(t)?[]:x8e(t,this._c):[].concat(n),r],s=o[0],l=o.reduce((u,d)=>{const p=Hh(t,d,a);return u.top=pr(p.top,u.top),u.right=Ti(p.right,u.right),u.bottom=Ti(p.bottom,u.bottom),u.left=pr(p.left,u.left),u},Hh(t,s,a));return{width:l.right-l.left,height:l.bottom-l.top,x:l.left,y:l.top}}function M8e(e){const{width:t,height:n}=P5(e);return{width:t,height:n}}function S8e(e,t,n){const r=xt(t),a=xn(t),i=n==="fixed",o=gr(e,!0,i,t);let s={scrollLeft:0,scrollTop:0};const l=vn(0);function u(){l.x=io(a)}if(r||!r&&!i)if((Ur(t)!=="body"||Sa(a))&&(s=no(t)),r){const h=gr(t,!0,i,t);l.x=h.x+t.clientLeft,l.y=h.y+t.clientTop}else a&&u();i&&!r&&a&&u();const d=a&&!r&&!i?B5(a,s):vn(0),p=o.left+s.scrollLeft-l.x-d.x,m=o.top+s.scrollTop-l.y-d.y;return{x:p,y:m,width:o.width,height:o.height}}function Ho(e){return an(e).position==="static"}function jh(e,t){if(!xt(e)||an(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return xn(e)===n&&(n=n.ownerDocument.body),n}function H5(e,t){const n=$t(e);if(eo(e))return n;if(!xt(e)){let a=$n(e);for(;a&&!Ln(a);){if(Je(a)&&!Ho(a))return a;a=$n(a)}return n}let r=jh(e,t);for(;r&&o6e(r)&&Ho(r);)r=jh(r,t);return r&&Ln(r)&&Ho(r)&&!Bd(r)?n:r||d6e(e)||n}const N8e=async function(e){const t=this.getOffsetParent||H5,n=this.getDimensions,r=await n(e.floating);return{reference:S8e(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function A8e(e){return an(e).direction==="rtl"}const T8e={convertOffsetParentRelativeRectToViewportRelativeRect:y8e,getDocumentElement:xn,getClippingRect:E8e,getOffsetParent:H5,getElementRects:N8e,getClientRects:b8e,getDimensions:M8e,getScale:zr,isElement:Je,isRTL:A8e};function j5(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function C8e(e,t){let n=null,r;const a=xn(e);function i(){var s;clearTimeout(r),(s=n)==null||s.disconnect(),n=null}function o(s,l){s===void 0&&(s=!1),l===void 0&&(l=1),i();const u=e.getBoundingClientRect(),{left:d,top:p,width:m,height:h}=u;if(s||t(),!m||!h)return;const g=Lr(p),f=Lr(a.clientWidth-(d+m)),w=Lr(a.clientHeight-(p+h)),v=Lr(d),_={rootMargin:-g+"px "+-f+"px "+-w+"px "+-v+"px",threshold:pr(0,Ti(1,l))||1};let E=!0;function S(x){const D=x[0].intersectionRatio;if(D!==l){if(!E)return o();D?o(!1,D):r=setTimeout(()=>{o(!1,1e-7)},1e3)}D===1&&!j5(u,e.getBoundingClientRect())&&o(),E=!1}try{n=new IntersectionObserver(S,{..._,root:a.ownerDocument})}catch{n=new IntersectionObserver(S,_)}n.observe(e)}return o(!0),i}function jd(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:a=!0,ancestorResize:i=!0,elementResize:o=typeof ResizeObserver=="function",layoutShift:s=typeof IntersectionObserver=="function",animationFrame:l=!1}=r,u=Hd(e),d=a||i?[...u?Xn(u):[],...Xn(t)]:[];d.forEach(v=>{a&&v.addEventListener("scroll",n,{passive:!0}),i&&v.addEventListener("resize",n)});const p=u&&s?C8e(u,n):null;let m=-1,h=null;o&&(h=new ResizeObserver(v=>{let[k]=v;k&&k.target===u&&h&&(h.unobserve(t),cancelAnimationFrame(m),m=requestAnimationFrame(()=>{var _;(_=h)==null||_.observe(t)})),n()}),u&&!l&&h.observe(u),h.observe(t));let g,f=l?gr(e):null;l&&w();function w(){const v=gr(e);f&&!j5(f,v)&&n(),f=v,g=requestAnimationFrame(w)}return n(),()=>{var v;d.forEach(k=>{a&&k.removeEventListener("scroll",n),i&&k.removeEventListener("resize",n)}),p?.(),(v=h)==null||v.disconnect(),h=null,l&&cancelAnimationFrame(g)}}const R8e=h8e,I8e=m8e,O8e=u8e,L8e=(e,t,n)=>{const r=new Map,a={platform:T8e,...n},i={...a.platform,_c:r};return c8e(e,t,{...a,platform:i})};var D8e=typeof document<"u",z8e=function(){},yi=D8e?V.useLayoutEffect:z8e;function Li(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,a;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!Li(e[r],t[r]))return!1;return!0}if(a=Object.keys(e),n=a.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,a[r]))return!1;for(r=n;r--!==0;){const i=a[r];if(!(i==="_owner"&&e.$$typeof)&&!Li(e[i],t[i]))return!1}return!0}return e!==e&&t!==t}function V5(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function Vh(e,t){const n=V5(e);return Math.round(t*n)/n}function jo(e){const t=te.useRef(e);return yi(()=>{t.current=e}),t}function $8e(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:a,elements:{reference:i,floating:o}={},transform:s=!0,whileElementsMounted:l,open:u}=e,[d,p]=te.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[m,h]=te.useState(r);Li(m,r)||h(r);const[g,f]=te.useState(null),[w,v]=te.useState(null),k=te.useCallback(z=>{z!==x.current&&(x.current=z,f(z))},[]),_=te.useCallback(z=>{z!==D.current&&(D.current=z,v(z))},[]),E=i||g,S=o||w,x=te.useRef(null),D=te.useRef(null),P=te.useRef(d),C=l!=null,L=jo(l),G=jo(a),X=jo(u),J=te.useCallback(()=>{if(!x.current||!D.current)return;const z={placement:t,strategy:n,middleware:m};G.current&&(z.platform=G.current),L8e(x.current,D.current,z).then(j=>{const A={...j,isPositioned:X.current!==!1};K.current&&!Li(P.current,A)&&(P.current=A,o5.flushSync(()=>{p(A)}))})},[m,t,n,G,X]);yi(()=>{u===!1&&P.current.isPositioned&&(P.current.isPositioned=!1,p(z=>({...z,isPositioned:!1})))},[u]);const K=te.useRef(!1);yi(()=>(K.current=!0,()=>{K.current=!1}),[]),yi(()=>{if(E&&(x.current=E),S&&(D.current=S),E&&S){if(L.current)return L.current(E,S,J);J()}},[E,S,J,L,C]);const R=te.useMemo(()=>({reference:x,floating:D,setReference:k,setFloating:_}),[k,_]),U=te.useMemo(()=>({reference:E,floating:S}),[E,S]),H=te.useMemo(()=>{const z={position:n,left:0,top:0};if(!U.floating)return z;const j=Vh(U.floating,d.x),A=Vh(U.floating,d.y);return s?{...z,transform:"translate("+j+"px, "+A+"px)",...V5(U.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:j,top:A}},[n,s,U.floating,d.x,d.y]);return te.useMemo(()=>({...d,update:J,refs:R,elements:U,floatingStyles:H}),[d,J,R,U,H])}const Vd=(e,t)=>({...R8e(e),options:[e,t]}),Gd=(e,t)=>({...I8e(e),options:[e,t]}),Wd=(e,t)=>({...O8e(e),options:[e,t]}),F8e="data-floating-ui-focusable",Gh="active",Wh="selected",Na="ArrowLeft",Aa="ArrowRight",G5="ArrowUp",oo="ArrowDown",P8e={...te};let Kh=!1,q8e=0;const Yh=()=>"floating-ui-"+Math.random().toString(36).slice(2,6)+q8e++;function B8e(){const[e,t]=te.useState(()=>Kh?Yh():void 0);return gt(()=>{e==null&&t(Yh())},[]),te.useEffect(()=>{Kh=!0},[]),e}const U8e=P8e.useId,Kd=U8e||B8e;let ga;process.env.NODE_ENV!=="production"&&(ga=new Set);function Vo(){for(var e,t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];const a="Floating UI: "+n.join(" ");if(!((e=ga)!=null&&e.has(a))){var i;(i=ga)==null||i.add(a),console.warn(a)}}function H8e(){for(var e,t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];const a="Floating UI: "+n.join(" ");if(!((e=ga)!=null&&e.has(a))){var i;(i=ga)==null||i.add(a),console.error(a)}}function j8e(){const e=new Map;return{emit(t,n){var r;(r=e.get(t))==null||r.forEach(a=>a(n))},on(t,n){e.has(t)||e.set(t,new Set),e.get(t).add(n)},off(t,n){var r;(r=e.get(t))==null||r.delete(n)}}}const V8e=te.createContext(null),G8e=te.createContext(null),so=()=>{var e;return((e=te.useContext(V8e))==null?void 0:e.id)||null},lo=()=>te.useContext(G8e);function Ta(e){return"data-floating-ui-"+e}function Zt(e){e.current!==-1&&(clearTimeout(e.current),e.current=-1)}const Zh=Ta("safe-polygon");function Go(e,t,n){if(n&&!fa(n))return 0;if(typeof e=="number")return e;if(typeof e=="function"){const r=e();return typeof r=="number"?r:r?.[t]}return e?.[t]}function Wo(e){return typeof e=="function"?e():e}function W8e(e,t){t===void 0&&(t={});const{open:n,onOpenChange:r,dataRef:a,events:i,elements:o}=e,{enabled:s=!0,delay:l=0,handleClose:u=null,mouseOnly:d=!1,restMs:p=0,move:m=!0}=t,h=lo(),g=so(),f=Rn(u),w=Rn(l),v=Rn(n),k=Rn(p),_=te.useRef(),E=te.useRef(-1),S=te.useRef(),x=te.useRef(-1),D=te.useRef(!0),P=te.useRef(!1),C=te.useRef(()=>{}),L=te.useRef(!1),G=Vt(()=>{var H;const z=(H=a.current.openEvent)==null?void 0:H.type;return z?.includes("mouse")&&z!=="mousedown"});te.useEffect(()=>{if(!s)return;function H(z){let{open:j}=z;j||(Zt(E),Zt(x),D.current=!0,L.current=!1)}return i.on("openchange",H),()=>{i.off("openchange",H)}},[s,i]),te.useEffect(()=>{if(!s||!f.current||!n)return;function H(j){G()&&r(!1,j,"hover")}const z=dn(o.floating).documentElement;return z.addEventListener("mouseleave",H),()=>{z.removeEventListener("mouseleave",H)}},[o.floating,n,r,s,f,G]);const X=te.useCallback(function(H,z,j){z===void 0&&(z=!0),j===void 0&&(j="hover");const A=Go(w.current,"close",_.current);A&&!S.current?(Zt(E),E.current=window.setTimeout(()=>r(!1,H,j),A)):z&&(Zt(E),r(!1,H,j))},[w,r]),J=Vt(()=>{C.current(),S.current=void 0}),K=Vt(()=>{if(P.current){const H=dn(o.floating).body;H.style.pointerEvents="",H.removeAttribute(Zh),P.current=!1}}),R=Vt(()=>a.current.openEvent?["click","mousedown"].includes(a.current.openEvent.type):!1);te.useEffect(()=>{if(!s)return;function H(ee){if(Zt(E),D.current=!1,d&&!fa(_.current)||Wo(k.current)>0&&!Go(w.current,"open"))return;const O=Go(w.current,"open",_.current);O?E.current=window.setTimeout(()=>{v.current||r(!0,ee,"hover")},O):n||r(!0,ee,"hover")}function z(ee){if(R()){K();return}C.current();const O=dn(o.floating);if(Zt(x),L.current=!1,f.current&&a.current.floatingContext){n||Zt(E),S.current=f.current({...a.current.floatingContext,tree:h,x:ee.clientX,y:ee.clientY,onClose(){K(),J(),R()||X(ee,!0,"safe-polygon")}});const fe=S.current;O.addEventListener("mousemove",fe),C.current=()=>{O.removeEventListener("mousemove",fe)};return}(_.current==="touch"?!fr(o.floating,ee.relatedTarget):!0)&&X(ee)}function j(ee){R()||a.current.floatingContext&&(f.current==null||f.current({...a.current.floatingContext,tree:h,x:ee.clientX,y:ee.clientY,onClose(){K(),J(),R()||X(ee)}})(ee))}function A(){Zt(E)}function Y(ee){R()||X(ee,!1)}if(Je(o.domReference)){const ee=o.domReference,O=o.floating;return n&&ee.addEventListener("mouseleave",j),m&&ee.addEventListener("mousemove",H,{once:!0}),ee.addEventListener("mouseenter",H),ee.addEventListener("mouseleave",z),O&&(O.addEventListener("mouseleave",j),O.addEventListener("mouseenter",A),O.addEventListener("mouseleave",Y)),()=>{n&&ee.removeEventListener("mouseleave",j),m&&ee.removeEventListener("mousemove",H),ee.removeEventListener("mouseenter",H),ee.removeEventListener("mouseleave",z),O&&(O.removeEventListener("mouseleave",j),O.removeEventListener("mouseenter",A),O.removeEventListener("mouseleave",Y))}}},[o,s,e,d,m,X,J,K,r,n,v,h,w,f,a,R,k]),gt(()=>{var H;if(s&&n&&(H=f.current)!=null&&(H=H.__options)!=null&&H.blockPointerEvents&&G()){P.current=!0;const j=o.floating;if(Je(o.domReference)&&j){var z;const A=dn(o.floating).body;A.setAttribute(Zh,"");const Y=o.domReference,ee=h==null||(z=h.nodesRef.current.find(O=>O.id===g))==null||(z=z.context)==null?void 0:z.elements.floating;return ee&&(ee.style.pointerEvents=""),A.style.pointerEvents="none",Y.style.pointerEvents="auto",j.style.pointerEvents="auto",()=>{A.style.pointerEvents="",Y.style.pointerEvents="",j.style.pointerEvents=""}}}},[s,n,g,o,h,f,G]),gt(()=>{n||(_.current=void 0,L.current=!1,J(),K())},[n,J,K]),te.useEffect(()=>()=>{J(),Zt(E),Zt(x),K()},[s,o.domReference,J,K]);const U=te.useMemo(()=>{function H(z){_.current=z.pointerType}return{onPointerDown:H,onPointerEnter:H,onMouseMove(z){const{nativeEvent:j}=z;function A(){!D.current&&!v.current&&r(!0,j,"hover")}d&&!fa(_.current)||n||Wo(k.current)===0||L.current&&z.movementX**2+z.movementY**2<2||(Zt(x),_.current==="touch"?A():(L.current=!0,x.current=window.setTimeout(A,Wo(k.current))))}}},[d,r,n,v,k]);return te.useMemo(()=>s?{reference:U}:{},[s,U])}let Xh=0;function K8e(e,t){t===void 0&&(t={});const{preventScroll:n=!1,cancelPrevious:r=!0,sync:a=!1}=t;r&&cancelAnimationFrame(Xh);const i=()=>e?.focus({preventScroll:n});a?i():Xh=requestAnimationFrame(i)}const W5={border:0,clip:"rect(0 0 0 0)",height:"1px",margin:"-1px",overflow:"hidden",padding:0,position:"fixed",whiteSpace:"nowrap",width:"1px",top:0,left:0},Qh=te.forwardRef(function(t,n){const[r,a]=te.useState();gt(()=>{O5()&&a("button")},[]);const i={ref:n,tabIndex:0,role:r,"aria-hidden":r?void 0:!0,[Ta("focus-guard")]:"",style:W5};return N.jsx("span",{...t,...i})}),K5=te.createContext(null),Jh=Ta("portal");function Y8e(e){e===void 0&&(e={});const{id:t,root:n}=e,r=Kd(),a=X8e(),[i,o]=te.useState(null),s=te.useRef(null);return gt(()=>()=>{i?.remove(),queueMicrotask(()=>{s.current=null})},[i]),gt(()=>{if(!r||s.current)return;const l=t?document.getElementById(t):null;if(!l)return;const u=document.createElement("div");u.id=r,u.setAttribute(Jh,""),l.appendChild(u),s.current=u,o(u)},[t,r]),gt(()=>{if(n===null||!r||s.current)return;let l=n||a?.portalNode;l&&!qd(l)&&(l=l.current),l=l||document.body;let u=null;t&&(u=document.createElement("div"),u.id=t,l.appendChild(u));const d=document.createElement("div");d.id=r,d.setAttribute(Jh,""),l=u||l,l.appendChild(d),s.current=d,o(d)},[t,n,r,a]),i}function Z8e(e){const{children:t,id:n,root:r,preserveTabOrder:a=!0}=e,i=Y8e({id:n,root:r}),[o,s]=te.useState(null),l=te.useRef(null),u=te.useRef(null),d=te.useRef(null),p=te.useRef(null),m=o?.modal,h=o?.open,g=!!o&&!o.modal&&o.open&&a&&!!(r||i);return te.useEffect(()=>{if(!i||!a||m)return;function f(w){i&&Uo(w)&&(w.type==="focusin"?qh:l8e)(i)}return i.addEventListener("focusin",f,!0),i.addEventListener("focusout",f,!0),()=>{i.removeEventListener("focusin",f,!0),i.removeEventListener("focusout",f,!0)}},[i,a,m]),te.useEffect(()=>{i&&(h||qh(i))},[h,i]),N.jsxs(K5.Provider,{value:te.useMemo(()=>({preserveTabOrder:a,beforeOutsideRef:l,afterOutsideRef:u,beforeInsideRef:d,afterInsideRef:p,portalNode:i,setFocusManagerState:s}),[a,i]),children:[g&&i&&N.jsx(Qh,{"data-type":"outside",ref:l,onFocus:f=>{if(Uo(f,i)){var w;(w=d.current)==null||w.focus()}else{const v=o?o.domReference:null,k=s8e(v);k?.focus()}}}),g&&i&&N.jsx("span",{"aria-owns":i.id,style:W5}),i&&o5.createPortal(t,i),g&&i&&N.jsx(Qh,{"data-type":"outside",ref:u,onFocus:f=>{if(Uo(f,i)){var w;(w=p.current)==null||w.focus()}else{const v=o?o.domReference:null,k=o8e(v);k?.focus(),o?.closeOnFocusOut&&o?.onOpenChange(!1,f.nativeEvent,"focus-out")}}})]})}const X8e=()=>te.useContext(K5);function e2(e){return xt(e.target)&&e.target.tagName==="BUTTON"}function Q8e(e){return xt(e.target)&&e.target.tagName==="A"}function t2(e){return Ud(e)}function Y5(e,t){t===void 0&&(t={});const{open:n,onOpenChange:r,dataRef:a,elements:{domReference:i}}=e,{enabled:o=!0,event:s="click",toggle:l=!0,ignoreMouse:u=!1,keyboardHandlers:d=!0,stickIfOpen:p=!0}=t,m=te.useRef(),h=te.useRef(!1),g=te.useMemo(()=>({onPointerDown(f){m.current=f.pointerType},onMouseDown(f){const w=m.current;f.button===0&&s!=="click"&&(fa(w,!0)&&u||(n&&l&&(!(a.current.openEvent&&p)||a.current.openEvent.type==="mousedown")?r(!1,f.nativeEvent,"click"):(f.preventDefault(),r(!0,f.nativeEvent,"click"))))},onClick(f){const w=m.current;if(s==="mousedown"&&m.current){m.current=void 0;return}fa(w,!0)&&u||(n&&l&&(!(a.current.openEvent&&p)||a.current.openEvent.type==="click")?r(!1,f.nativeEvent,"click"):r(!0,f.nativeEvent,"click"))},onKeyDown(f){m.current=void 0,!(f.defaultPrevented||!d||e2(f))&&(f.key===" "&&!t2(i)&&(f.preventDefault(),h.current=!0),!Q8e(f)&&f.key==="Enter"&&r(!(n&&l),f.nativeEvent,"click"))},onKeyUp(f){f.defaultPrevented||!d||e2(f)||t2(i)||f.key===" "&&h.current&&(h.current=!1,r(!(n&&l),f.nativeEvent,"click"))}}),[a,i,s,u,d,r,n,p,l]);return te.useMemo(()=>o?{reference:g}:{},[o,g])}const J8e={pointerdown:"onPointerDown",mousedown:"onMouseDown",click:"onClick"},e7e={pointerdown:"onPointerDownCapture",mousedown:"onMouseDownCapture",click:"onClickCapture"},n2=e=>{var t,n;return{escapeKey:typeof e=="boolean"?e:(t=e?.escapeKey)!=null?t:!1,outsidePress:typeof e=="boolean"?e:(n=e?.outsidePress)!=null?n:!0}};function Yd(e,t){t===void 0&&(t={});const{open:n,onOpenChange:r,elements:a,dataRef:i}=e,{enabled:o=!0,escapeKey:s=!0,outsidePress:l=!0,outsidePressEvent:u="pointerdown",referencePress:d=!1,referencePressEvent:p="pointerdown",ancestorScroll:m=!1,bubbles:h,capture:g}=t,f=lo(),w=Vt(typeof l=="function"?l:()=>!1),v=typeof l=="function"?w:l,k=te.useRef(!1),{escapeKey:_,outsidePress:E}=n2(h),{escapeKey:S,outsidePress:x}=n2(g),D=te.useRef(!1),P=Vt(K=>{var R;if(!n||!o||!s||K.key!=="Escape"||D.current)return;const U=(R=i.current.floatingContext)==null?void 0:R.nodeId,H=f?oa(f.nodesRef.current,U):[];if(!_&&(K.stopPropagation(),H.length>0)){let z=!0;if(H.forEach(j=>{var A;if((A=j.context)!=null&&A.open&&!j.context.dataRef.current.__escapeKeyBubbles){z=!1;return}}),!z)return}r(!1,K6e(K)?K.nativeEvent:K,"escape-key")}),C=Vt(K=>{var R;const U=()=>{var H;P(K),(H=Ar(K))==null||H.removeEventListener("keydown",U)};(R=Ar(K))==null||R.addEventListener("keydown",U)}),L=Vt(K=>{var R;const U=i.current.insideReactTree;i.current.insideReactTree=!1;const H=k.current;if(k.current=!1,u==="click"&&H||U||typeof v=="function"&&!v(K))return;const z=Ar(K),j="["+Ta("inert")+"]",A=dn(a.floating).querySelectorAll(j);let Y=Je(z)?z:null;for(;Y&&!Ln(Y);){const fe=$n(Y);if(Ln(fe)||!Je(fe))break;Y=fe}if(A.length&&Je(z)&&!j6e(z)&&!fr(z,a.floating)&&Array.from(A).every(fe=>!fr(Y,fe)))return;if(xt(z)&&J){const fe=Ln(z),ke=an(z),Ce=/auto|scroll/,Fe=fe||Ce.test(ke.overflowX),tt=fe||Ce.test(ke.overflowY),Ve=Fe&&z.clientWidth>0&&z.scrollWidth>z.clientWidth,ae=tt&&z.clientHeight>0&&z.scrollHeight>z.clientHeight,Se=ke.direction==="rtl",Be=ae&&(Se?K.offsetX<=z.offsetWidth-z.clientWidth:K.offsetX>z.clientWidth),We=Ve&&K.offsetY>z.clientHeight;if(Be||We)return}const ee=(R=i.current.floatingContext)==null?void 0:R.nodeId,O=f&&oa(f.nodesRef.current,ee).some(fe=>{var ke;return qo(K,(ke=fe.context)==null?void 0:ke.elements.floating)});if(qo(K,a.floating)||qo(K,a.domReference)||O)return;const le=f?oa(f.nodesRef.current,ee):[];if(le.length>0){let fe=!0;if(le.forEach(ke=>{var Ce;if((Ce=ke.context)!=null&&Ce.open&&!ke.context.dataRef.current.__outsidePressBubbles){fe=!1;return}}),!fe)return}r(!1,K,"outside-press")}),G=Vt(K=>{var R;const U=()=>{var H;L(K),(H=Ar(K))==null||H.removeEventListener(u,U)};(R=Ar(K))==null||R.addEventListener(u,U)});te.useEffect(()=>{if(!n||!o)return;i.current.__escapeKeyBubbles=_,i.current.__outsidePressBubbles=E;let K=-1;function R(A){r(!1,A,"ancestor-scroll")}function U(){window.clearTimeout(K),D.current=!0}function H(){K=window.setTimeout(()=>{D.current=!1},to()?5:0)}const z=dn(a.floating);s&&(z.addEventListener("keydown",S?C:P,S),z.addEventListener("compositionstart",U),z.addEventListener("compositionend",H)),v&&z.addEventListener(u,x?G:L,x);let j=[];return m&&(Je(a.domReference)&&(j=Xn(a.domReference)),Je(a.floating)&&(j=j.concat(Xn(a.floating))),!Je(a.reference)&&a.reference&&a.reference.contextElement&&(j=j.concat(Xn(a.reference.contextElement)))),j=j.filter(A=>{var Y;return A!==((Y=z.defaultView)==null?void 0:Y.visualViewport)}),j.forEach(A=>{A.addEventListener("scroll",R,{passive:!0})}),()=>{s&&(z.removeEventListener("keydown",S?C:P,S),z.removeEventListener("compositionstart",U),z.removeEventListener("compositionend",H)),v&&z.removeEventListener(u,x?G:L,x),j.forEach(A=>{A.removeEventListener("scroll",R)}),window.clearTimeout(K)}},[i,a,s,v,u,n,r,m,o,_,E,P,S,C,L,x,G]),te.useEffect(()=>{i.current.insideReactTree=!1},[i,v,u]);const X=te.useMemo(()=>({onKeyDown:P,...d&&{[J8e[p]]:K=>{r(!1,K.nativeEvent,"reference-press")},...p!=="click"&&{onClick(K){r(!1,K.nativeEvent,"reference-press")}}}}),[P,r,d,p]),J=te.useMemo(()=>({onKeyDown:P,onMouseDown(){k.current=!0},onMouseUp(){k.current=!0},[e7e[u]]:()=>{i.current.insideReactTree=!0}}),[P,u,i]);return te.useMemo(()=>o?{reference:X,floating:J}:{},[o,X,J])}function t7e(e){const{open:t=!1,onOpenChange:n,elements:r}=e,a=Kd(),i=te.useRef({}),[o]=te.useState(()=>j8e()),s=so()!=null;if(process.env.NODE_ENV!=="production"){const h=r.reference;h&&!Je(h)&&H8e("Cannot pass a virtual element to the `elements.reference` option,","as it must be a real DOM element. Use `refs.setPositionReference()`","instead.")}const[l,u]=te.useState(r.reference),d=Vt((h,g,f)=>{i.current.openEvent=h?g:void 0,o.emit("openchange",{open:h,event:g,reason:f,nested:s}),n?.(h,g,f)}),p=te.useMemo(()=>({setPositionReference:u}),[]),m=te.useMemo(()=>({reference:l||r.reference||null,floating:r.floating||null,domReference:r.reference}),[l,r.reference,r.floating]);return te.useMemo(()=>({dataRef:i,open:t,onOpenChange:d,elements:m,events:o,floatingId:a,refs:p}),[t,d,m,o,a,p])}function Zd(e){e===void 0&&(e={});const{nodeId:t}=e,n=t7e({...e,elements:{reference:null,floating:null,...e.elements}}),r=e.rootContext||n,a=r.elements,[i,o]=te.useState(null),[s,l]=te.useState(null),d=a?.domReference||i,p=te.useRef(null),m=lo();gt(()=>{d&&(p.current=d)},[d]);const h=$8e({...e,elements:{...a,...s&&{reference:s}}}),g=te.useCallback(_=>{const E=Je(_)?{getBoundingClientRect:()=>_.getBoundingClientRect(),getClientRects:()=>_.getClientRects(),contextElement:_}:_;l(E),h.refs.setReference(E)},[h.refs]),f=te.useCallback(_=>{(Je(_)||_===null)&&(p.current=_,o(_)),(Je(h.refs.reference.current)||h.refs.reference.current===null||_!==null&&!Je(_))&&h.refs.setReference(_)},[h.refs]),w=te.useMemo(()=>({...h.refs,setReference:f,setPositionReference:g,domReference:p}),[h.refs,f,g]),v=te.useMemo(()=>({...h.elements,domReference:d}),[h.elements,d]),k=te.useMemo(()=>({...h,...r,refs:w,elements:v,nodeId:t}),[h,w,v,t,r]);return gt(()=>{r.dataRef.current.floatingContext=k;const _=m?.nodesRef.current.find(E=>E.id===t);_&&(_.context=k)}),te.useMemo(()=>({...h,context:k,refs:w,elements:v}),[h,w,v,k])}function Ko(){return q6e()&&O5()}function n7e(e,t){t===void 0&&(t={});const{open:n,onOpenChange:r,events:a,dataRef:i,elements:o}=e,{enabled:s=!0,visibleOnly:l=!0}=t,u=te.useRef(!1),d=te.useRef(-1),p=te.useRef(!0);te.useEffect(()=>{if(!s)return;const h=$t(o.domReference);function g(){!n&&xt(o.domReference)&&o.domReference===ma(dn(o.domReference))&&(u.current=!0)}function f(){p.current=!0}function w(){p.current=!1}return h.addEventListener("blur",g),Ko()&&(h.addEventListener("keydown",f,!0),h.addEventListener("pointerdown",w,!0)),()=>{h.removeEventListener("blur",g),Ko()&&(h.removeEventListener("keydown",f,!0),h.removeEventListener("pointerdown",w,!0))}},[o.domReference,n,s]),te.useEffect(()=>{if(!s)return;function h(g){let{reason:f}=g;(f==="reference-press"||f==="escape-key")&&(u.current=!0)}return a.on("openchange",h),()=>{a.off("openchange",h)}},[a,s]),te.useEffect(()=>()=>{Zt(d)},[]);const m=te.useMemo(()=>({onMouseLeave(){u.current=!1},onFocus(h){if(u.current)return;const g=Ar(h.nativeEvent);if(l&&Je(g)){if(Ko()&&!h.relatedTarget){if(!p.current&&!Ud(g))return}else if(!G6e(g))return}r(!0,h.nativeEvent,"focus")},onBlur(h){u.current=!1;const g=h.relatedTarget,f=h.nativeEvent,w=Je(g)&&g.hasAttribute(Ta("focus-guard"))&&g.getAttribute("data-type")==="outside";d.current=window.setTimeout(()=>{var v;const k=ma(o.domReference?o.domReference.ownerDocument:document);!g&&k===o.domReference||fr((v=i.current.floatingContext)==null?void 0:v.refs.floating.current,k)||fr(o.domReference,k)||w||r(!1,f,"focus")})}}),[i,o.domReference,r,l]);return te.useMemo(()=>s?{reference:m}:{},[s,m])}function Yo(e,t,n){const r=new Map,a=n==="item";let i=e;if(a&&e){const{[Gh]:o,[Wh]:s,...l}=e;i=l}return{...n==="floating"&&{tabIndex:-1,[F8e]:""},...i,...t.map(o=>{const s=o?o[n]:null;return typeof s=="function"?e?s(e):null:s}).concat(e).reduce((o,s)=>(s&&Object.entries(s).forEach(l=>{let[u,d]=l;if(!(a&&[Gh,Wh].includes(u)))if(u.indexOf("on")===0){if(r.has(u)||r.set(u,[]),typeof d=="function"){var p;(p=r.get(u))==null||p.push(d),o[u]=function(){for(var m,h=arguments.length,g=new Array(h),f=0;f<h;f++)g[f]=arguments[f];return(m=r.get(u))==null?void 0:m.map(w=>w(...g)).find(w=>w!==void 0)}}}else o[u]=d}),o),{})}}function Xd(e){e===void 0&&(e=[]);const t=e.map(s=>s?.reference),n=e.map(s=>s?.floating),r=e.map(s=>s?.item),a=te.useCallback(s=>Yo(s,e,"reference"),t),i=te.useCallback(s=>Yo(s,e,"floating"),n),o=te.useCallback(s=>Yo(s,e,"item"),r);return te.useMemo(()=>({getReferenceProps:a,getFloatingProps:i,getItemProps:o}),[a,i,o])}const r7e="Escape";function co(e,t,n){switch(e){case"vertical":return t;case"horizontal":return n;default:return t||n}}function Ha(e,t){return co(t,e===G5||e===oo,e===Na||e===Aa)}function Zo(e,t,n){return co(t,e===oo,n?e===Na:e===Aa)||e==="Enter"||e===" "||e===""}function r2(e,t,n){return co(t,n?e===Na:e===Aa,e===oo)}function a2(e,t,n,r){const a=n?e===Aa:e===Na,i=e===G5;return t==="both"||t==="horizontal"&&r&&r>1?e===r7e:co(t,a,i)}function a7e(e,t){const{open:n,onOpenChange:r,elements:a,floatingId:i}=e,{listRef:o,activeIndex:s,onNavigate:l=()=>{},enabled:u=!0,selectedIndex:d=null,allowEscape:p=!1,loop:m=!1,nested:h=!1,rtl:g=!1,virtual:f=!1,focusItemOnOpen:w="auto",focusItemOnHover:v=!0,openOnArrowKeyDown:k=!0,disabledIndices:_=void 0,orientation:E="vertical",parentOrientation:S,cols:x=1,scrollItemIntoView:D=!0,virtualItemRef:P,itemSizes:C,dense:L=!1}=t;process.env.NODE_ENV!=="production"&&(p&&(m||Vo("`useListNavigation` looping must be enabled to allow escaping."),f||Vo("`useListNavigation` must be virtual to allow escaping.")),E==="vertical"&&x>1&&Vo("In grid list navigation mode (`cols` > 1), the `orientation` should",'be either "horizontal" or "both".'));const G=D5(a.floating),X=Rn(G),J=so(),K=lo();gt(()=>{e.dataRef.current.orientation=E},[e,E]);const R=Vt(()=>{l(z.current===-1?null:z.current)}),U=V6e(a.domReference),H=te.useRef(w),z=te.useRef(d??-1),j=te.useRef(null),A=te.useRef(!0),Y=te.useRef(R),ee=te.useRef(!!a.floating),O=te.useRef(n),le=te.useRef(!1),fe=te.useRef(!1),ke=Rn(_),Ce=Rn(n),Fe=Rn(D),tt=Rn(d),[Ve,ae]=te.useState(),[Se,Be]=te.useState(),We=Vt(()=>{function ce(q){if(f){var Z;(Z=q.id)!=null&&Z.endsWith("-fui-option")&&(q.id=i+"-"+Math.random().toString(16).slice(2,10)),ae(q.id),K?.events.emit("virtualfocus",q),P&&(P.current=q)}else K8e(q,{sync:le.current,preventScroll:!0})}const Me=o.current[z.current],ye=fe.current;Me&&ce(Me),(le.current?q=>q():requestAnimationFrame)(()=>{const q=o.current[z.current]||Me;if(!q)return;Me||ce(q);const Z=Fe.current;Z&&ve&&(ye||!A.current)&&(q.scrollIntoView==null||q.scrollIntoView(typeof Z=="boolean"?{block:"nearest",inline:"nearest"}:Z))})});gt(()=>{u&&(n&&a.floating?H.current&&d!=null&&(fe.current=!0,z.current=d,R()):ee.current&&(z.current=-1,Y.current()))},[u,n,a.floating,d,R]),gt(()=>{if(u&&n&&a.floating)if(s==null){if(le.current=!1,tt.current!=null)return;if(ee.current&&(z.current=-1,We()),(!O.current||!ee.current)&&H.current&&(j.current!=null||H.current===!0&&j.current==null)){let ce=0;const Me=()=>{o.current[0]==null?(ce<2&&(ce?requestAnimationFrame:queueMicrotask)(Me),ce++):(z.current=j.current==null||Zo(j.current,E,g)||h?Bo(o,ke.current):Ph(o,ke.current),j.current=null,R())};Me()}}else sa(o,s)||(z.current=s,We(),fe.current=!1)},[u,n,a.floating,s,tt,h,o,E,g,R,We,ke]),gt(()=>{var ce;if(!u||a.floating||!K||f||!ee.current)return;const Me=K.nodesRef.current,ye=(ce=Me.find(Z=>Z.id===J))==null||(ce=ce.context)==null?void 0:ce.elements.floating,Pe=ma(dn(a.floating)),q=Me.some(Z=>Z.context&&fr(Z.context.elements.floating,Pe));ye&&!q&&A.current&&ye.focus({preventScroll:!0})},[u,a.floating,K,J,f]),gt(()=>{if(!u||!K||!f||J)return;function ce(Me){Be(Me.id),P&&(P.current=Me)}return K.events.on("virtualfocus",ce),()=>{K.events.off("virtualfocus",ce)}},[u,K,f,J,P]),gt(()=>{Y.current=R,O.current=n,ee.current=!!a.floating}),gt(()=>{n||(j.current=null,H.current=w)},[n,w]);const Ae=s!=null,ve=te.useMemo(()=>{function ce(ye){if(!Ce.current)return;const Pe=o.current.indexOf(ye);Pe!==-1&&z.current!==Pe&&(z.current=Pe,R())}return{onFocus(ye){let{currentTarget:Pe}=ye;le.current=!0,ce(Pe)},onClick:ye=>{let{currentTarget:Pe}=ye;return Pe.focus({preventScroll:!0})},onMouseMove(ye){let{currentTarget:Pe}=ye;le.current=!0,fe.current=!1,v&&ce(Pe)},onPointerLeave(ye){let{pointerType:Pe}=ye;if(!(!A.current||Pe==="touch")&&(le.current=!0,!!v&&(z.current=-1,R(),!f))){var q;(q=X.current)==null||q.focus({preventScroll:!0})}}}},[Ce,X,v,o,R,f]),Ge=te.useCallback(()=>{var ce;return S??(K==null||(ce=K.nodesRef.current.find(Me=>Me.id===J))==null||(ce=ce.context)==null||(ce=ce.dataRef)==null?void 0:ce.current.orientation)},[J,K,S]),de=Vt(ce=>{if(A.current=!1,le.current=!0,ce.which===229||!Ce.current&&ce.currentTarget===X.current)return;if(h&&a2(ce.key,E,g,x)){Ha(ce.key,Ge())||Xt(ce),r(!1,ce.nativeEvent,"list-navigation"),xt(a.domReference)&&(f?K?.events.emit("virtualfocus",a.domReference):a.domReference.focus());return}const Me=z.current,ye=Bo(o,_),Pe=Ph(o,_);if(U||(ce.key==="Home"&&(Xt(ce),z.current=ye,R()),ce.key==="End"&&(Xt(ce),z.current=Pe,R())),x>1){const q=C||Array.from({length:o.current.length},()=>({width:1,height:1})),Z=r8e(q,x,L),ne=Z.findIndex(Le=>Le!=null&&!gi(o,Le,_)),pe=Z.reduce((Le,mt,bt)=>mt!=null&&!gi(o,mt,_)?bt:Le,-1),Ee=Z[n8e({current:Z.map(Le=>Le!=null?o.current[Le]:null)},{event:ce,orientation:E,loop:m,rtl:g,cols:x,disabledIndices:i8e([...(typeof _!="function"?_:null)||o.current.map((Le,mt)=>gi(o,mt,_)?mt:void 0),void 0],Z),minIndex:ne,maxIndex:pe,prevIndex:a8e(z.current>Pe?ye:z.current,q,Z,x,ce.key===oo?"bl":ce.key===(g?Na:Aa)?"tr":"tl"),stopEvent:!0})];if(Ee!=null&&(z.current=Ee,R()),E==="both")return}if(Ha(ce.key,E)){if(Xt(ce),n&&!f&&ma(ce.currentTarget.ownerDocument)===ce.currentTarget){z.current=Zo(ce.key,E,g)?ye:Pe,R();return}Zo(ce.key,E,g)?m?z.current=Me>=Pe?p&&Me!==o.current.length?-1:ye:kt(o,{startingIndex:Me,disabledIndices:_}):z.current=Math.min(Pe,kt(o,{startingIndex:Me,disabledIndices:_})):m?z.current=Me<=ye?p&&Me!==-1?o.current.length:Pe:kt(o,{startingIndex:Me,decrement:!0,disabledIndices:_}):z.current=Math.max(ye,kt(o,{startingIndex:Me,decrement:!0,disabledIndices:_})),sa(o,z.current)&&(z.current=-1),R()}}),Ze=te.useMemo(()=>f&&n&&Ae&&{"aria-activedescendant":Se||Ve},[f,n,Ae,Se,Ve]),Ke=te.useMemo(()=>({"aria-orientation":E==="both"?void 0:E,...U?{}:Ze,onKeyDown:de,onPointerMove(){A.current=!0}}),[Ze,de,E,U]),He=te.useMemo(()=>{function ce(ye){w==="auto"&&Y6e(ye.nativeEvent)&&(H.current=!0)}function Me(ye){H.current=w,w==="auto"&&Z6e(ye.nativeEvent)&&(H.current=!0)}return{...Ze,onKeyDown(ye){A.current=!1;const Pe=ye.key.startsWith("Arrow"),q=["Home","End"].includes(ye.key),Z=Pe||q,ne=r2(ye.key,E,g),pe=a2(ye.key,E,g,x),Ee=r2(ye.key,Ge(),g),Le=Ha(ye.key,E),mt=(h?Ee:Le)||ye.key==="Enter"||ye.key.trim()==="";if(f&&n){const ht=K?.nodesRef.current.find(It=>It.parentId==null),Mt=K&&ht?W6e(K.nodesRef.current,ht.id):null;if(Z&&Mt&&P){const It=new KeyboardEvent("keydown",{key:ye.key,bubbles:!0});if(ne||pe){var bt,Hn;const D7=((bt=Mt.context)==null?void 0:bt.elements.domReference)===ye.currentTarget,Ch=pe&&!D7?(Hn=Mt.context)==null?void 0:Hn.elements.domReference:ne?o.current.find(Rh=>Rh?.id===Ve):null;Ch&&(Xt(ye),Ch.dispatchEvent(It),Be(void 0))}if((Le||q)&&Mt.context&&Mt.context.open&&Mt.parentId&&ye.currentTarget!==Mt.context.elements.domReference){var jn;Xt(ye),(jn=Mt.context.elements.domReference)==null||jn.dispatchEvent(It);return}}return de(ye)}if(!(!n&&!k&&Pe)){if(mt){const ht=Ha(ye.key,Ge());j.current=h&&ht?null:ye.key}if(h){Ee&&(Xt(ye),n?(z.current=Bo(o,ke.current),R()):r(!0,ye.nativeEvent,"list-navigation"));return}Le&&(d!=null&&(z.current=d),Xt(ye),!n&&k?r(!0,ye.nativeEvent,"list-navigation"):de(ye),n&&R())}},onFocus(){n&&!f&&(z.current=-1,R())},onPointerDown:Me,onPointerEnter:Me,onMouseDown:ce,onClick:ce}},[Ve,Ze,x,de,ke,w,o,h,R,r,n,k,E,Ge,g,d,K,f,P]);return te.useMemo(()=>u?{reference:He,floating:Ke,item:ve}:{},[u,He,Ke,ve])}const i7e=new Map([["select","listbox"],["combobox","listbox"],["label",!1]]);function Qd(e,t){var n,r;t===void 0&&(t={});const{open:a,elements:i,floatingId:o}=e,{enabled:s=!0,role:l="dialog"}=t,u=Kd(),d=((n=i.domReference)==null?void 0:n.id)||u,p=te.useMemo(()=>{var k;return((k=D5(i.floating))==null?void 0:k.id)||o},[i.floating,o]),m=(r=i7e.get(l))!=null?r:l,g=so()!=null,f=te.useMemo(()=>m==="tooltip"||l==="label"?{["aria-"+(l==="label"?"labelledby":"describedby")]:a?p:void 0}:{"aria-expanded":a?"true":"false","aria-haspopup":m==="alertdialog"?"dialog":m,"aria-controls":a?p:void 0,...m==="listbox"&&{role:"combobox"},...m==="menu"&&{id:d},...m==="menu"&&g&&{role:"menuitem"},...l==="select"&&{"aria-autocomplete":"none"},...l==="combobox"&&{"aria-autocomplete":"list"}},[m,p,g,a,d,l]),w=te.useMemo(()=>{const k={id:p,...m&&{role:m}};return m==="tooltip"||l==="label"?k:{...k,...m==="menu"&&{"aria-labelledby":d}}},[m,p,d,l]),v=te.useCallback(k=>{let{active:_,selected:E}=k;const S={role:"option",..._&&{id:p+"-fui-option"}};switch(l){case"select":case"combobox":return{...S,"aria-selected":E}}return{}},[p,l]);return te.useMemo(()=>s?{reference:f,floating:w,item:v}:{},[s,f,w,v])}const bn=({content:e,children:t,placement:n="top",delay:r=300,disabled:a=!1,className:i=""})=>{const[o,s]=V.useState(!1),{refs:l,floatingStyles:u,context:d,isPositioned:p}=Zd({open:o,onOpenChange:s,placement:n,strategy:"absolute",whileElementsMounted:jd,middleware:[Vd(8),Wd(),Gd({padding:8})]}),m=W8e(d,{delay:{open:r,close:0},enabled:!a}),h=n7e(d,{enabled:!a}),g=Yd(d,{enabled:!0,outsidePress:!0,outsidePressEvent:"mousedown",referencePress:!0,referencePressEvent:"mousedown",escapeKey:!0,ancestorScroll:!0}),f=Qd(d,{role:"tooltip"}),{getReferenceProps:w,getFloatingProps:v}=Xd([m,h,g,f]);return V.useEffect(()=>{if(!o||a)return;const k=()=>{s(!1)};return window.addEventListener("scroll",k,!0),document.addEventListener("scroll",k,!0),()=>{window.removeEventListener("scroll",k,!0),document.removeEventListener("scroll",k,!0)}},[o,a]),a||!e?N.jsx(N.Fragment,{children:t}):N.jsxs(N.Fragment,{children:[N.jsx("span",{ref:l.setReference,...w(),children:t}),o&&N.jsx(Z8e,{children:N.jsx("div",{ref:l.setFloating,style:{...u,opacity:p?1:0,pointerEvents:"none",transition:p?"opacity 0.15s ease-out":"none"},className:`mp-agent-tooltip ${i}`.trim(),...v(),children:e})})]})},nn=({icon:e,size:t="md",iconSize:n,type:r="button",className:a="",tooltip:i,tooltipPlacement:o,...s})=>{const l=e6e[e],u=n??(t==="sm"?14:20),d=N.jsx("button",{type:r,className:`mp-agent-icon-button mp-agent-icon-button-${t} ${a}`.trim(),...s,children:l&&N.jsx(l,{size:u})});return i?N.jsx(bn,{content:i,placement:o,children:d}):d},Jd=({text:e})=>{const[t,n]=V.useState(!1),r=async()=>{try{await navigator.clipboard.writeText(e),n(!0),setTimeout(()=>n(!1),2e3)}catch(a){console.error("Failed to copy:",a)}};return N.jsx(bn,{content:"Copy to clipboard",children:N.jsx(nn,{icon:t?"Check":"Copy",onClick:r,"aria-label":"Copy message",size:"sm"})})},Wt=()=>{const e=$e();return{...Ni,...e.config.translations??{}}},i2=300,Z5=V.memo(({field:e,isExpanded:t,canApply:n,onToggleExpand:r,onApply:a})=>{const i=Wt(),o=e.value.length>i2,s=o&&!t?`${e.value.slice(0,i2)}...`:e.value,l=V.useCallback(()=>{r(e.name)},[e.name,r]),u=V.useCallback(()=>{a(e)},[e,a]);return N.jsxs("div",{className:"mp-agent-form-proposal-row",children:[N.jsxs("div",{className:"mp-agent-form-proposal-main",children:[N.jsx("div",{className:"mp-agent-form-proposal-label",children:e.label||e.name}),N.jsx("div",{className:"mp-agent-form-proposal-value-container",children:N.jsxs("div",{className:"mp-agent-form-proposal-value",children:[s,o&&N.jsx("button",{type:"button",onClick:l,className:"mp-agent-form-proposal-show-all",children:t?i.formProposalShowLess:i.formProposalShowAll})]})})]}),N.jsxs("div",{className:"mp-agent-form-proposal-actions-row",children:[N.jsx(nn,{icon:"Check",onClick:u,tooltip:`${i.formProposalApplyFieldPrefix} ${e.label||e.name}`,size:"sm"}),N.jsx(Jd,{text:e.value})]})]})});Z5.displayName="FormFieldRow";const Ca=30*1e3,Ra=5*60*1e3,X5=20,Ht={all:["mp-agents","activities"],lists:()=>[...Ht.all,"list"],list:e=>[...Ht.lists(),e],infinites:()=>[...Ht.all,"infinite"],infinite:e=>[...Ht.infinites(),e],sourceTypes:e=>[...Ht.all,"sourceTypes",e],detail:e=>[...Ht.all,"detail",e],summary:e=>[...Ht.all,"summary",e]},o7e=e=>e?.pages.flatMap(t=>t.data)??[],Q5=(e,t,n)=>{const r=e.from instanceof Date?e.from.toISOString():e.from,a=e.to instanceof Date?e.to.toISOString():e.to;return{...e.groupId&&{groupId:e.groupId},...e.parentId&&{parentId:e.parentId},...e.sourceType&&{sourceType:e.sourceType},...e.sortField&&e.sortOrder&&{sort:{field:e.sortField,order:e.sortOrder}},...r&&{from:r},...a&&{to:a},...e.tenant&&{tenant:e.tenant},...e.ownerId&&{ownerId:e.ownerId},skip:t,limit:n}},J5=e=>({data:[],cursor:{total:0,skip:0,limit:e}}),s7e=e=>{const t=$e(),{groupId:n,parentId:r,sourceType:a,enabled:i=!0,sortOrder:o=exports.SortOrder.Desc,sortField:s="createdAt",pageSize:l=X5,from:u,to:d,tenant:p,ownerId:m}=e??{};return yt.useInfiniteQuery({queryKey:Ht.infinite({groupId:n,parentId:r,sourceType:a,sortField:s,sortOrder:o,pageSize:l,from:u,to:d,tenant:p,ownerId:m}),queryFn:async({pageParam:h})=>t.transport.listActivities?t.transport.listActivities(Q5({groupId:n,parentId:r,sourceType:a,sortField:s,sortOrder:o,from:u,to:d,tenant:p,ownerId:m},h,l)):J5(l),initialPageParam:0,getNextPageParam:h=>{const g=(h.cursor.skip??0)+h.data.length;return g<h.cursor.total?g:void 0},enabled:i&&!!t.transport.listActivities,staleTime:Ca,gcTime:Ra})},l7e=e=>{const t=$e(),{groupId:n,parentId:r,sourceType:a,page:i,enabled:o=!0,sortOrder:s=exports.SortOrder.Desc,sortField:l="createdAt",pageSize:u=X5,from:d,to:p,tenant:m,ownerId:h}=e,g=(i-1)*u,f=yt.useQuery({queryKey:Ht.list({groupId:n,parentId:r,sourceType:a,sortField:l,sortOrder:s,pageSize:u,page:i,from:d,to:p,tenant:m,ownerId:h}),queryFn:async()=>t.transport.listActivities?t.transport.listActivities(Q5({groupId:n,parentId:r,sourceType:a,sortField:l,sortOrder:s,from:d,to:p,tenant:m,ownerId:h},g,u)):J5(u),enabled:o&&!!t.transport.listActivities&&i>=1,staleTime:Ca,gcTime:Ra}),w=f.data?.cursor.total??0,v=Math.max(1,Math.ceil(w/u));return{...f,page:i,pageSize:u,totalPages:v,total:w,hasNextPage:i<v,hasPreviousPage:i>1}},c7e=e=>{const t=$e();return yt.useQuery({queryKey:Ht.detail(e),queryFn:async()=>!e||!t.transport.getActivity?null:t.transport.getActivity(e),enabled:!!e&&!!t.transport.getActivity,staleTime:Ca,gcTime:Ra})},u7e=e=>{const t=$e(),{enabled:n=!0,...r}=e??{};return yt.useQuery({queryKey:Ht.summary(r),queryFn:async()=>t.transport.getActivitySummary?t.transport.getActivitySummary(r):[],enabled:n&&!!t.transport.getActivitySummary,staleTime:Ca,gcTime:Ra})},d7e=e=>{const t=$e(),{enabled:n=!0,groupId:r,parentId:a,from:i,to:o,tenant:s,ownerId:l}=e??{},u=i instanceof Date?i.toISOString():i,d=o instanceof Date?o.toISOString():o;return yt.useQuery({queryKey:Ht.sourceTypes({groupId:r,parentId:a,from:u,to:d,tenant:s,ownerId:l}),queryFn:async()=>t.transport.listActivitySourceTypes?t.transport.listActivitySourceTypes({...r&&{groupId:r},...a&&{parentId:a},...u&&{from:u},...d&&{to:d},...s&&{tenant:s},...l&&{ownerId:l}}):[],enabled:n&&!!t.transport.listActivitySourceTypes,staleTime:Ca,gcTime:Ra})},o2="mp-agents-guest-user-id";function Hr(){if(typeof window>"u")return`${Ai.DefaultUserId}-${_t.nanoid()}`;const e=localStorage.getItem(o2);if(e)return e;const t=`${Ai.DefaultUserId}-${_t.nanoid()}`;return localStorage.setItem(o2,t),t}const e3=30*1e3,t3=5*60*1e3,uo=20,In={all:["mp-agents","chats"],lists:()=>[...In.all,"list"],list:e=>[...In.lists(),e],infinites:()=>[...In.all,"infinite"],infinite:e=>[...In.infinites(),e],detail:e=>[...In.all,"detail",e]},n3=e=>e?.pages.flatMap(t=>t.data)??[],ep=e=>{const t=$e(),n=t.config.user?.id??Hr(),r=t.config.appId,{pageSize:a=uo,sortOrder:i="desc",sortField:o="updatedAt",multiUser:s,enabled:l=!0}=e??{};return yt.useInfiniteQuery({queryKey:In.infinite({userId:n,appId:r,sortField:o,sortOrder:i,pageSize:a,multiUser:s}),queryFn:async({pageParam:u})=>await t.transport.listChats({userId:n,skip:u,limit:a,multiUser:s,sortOrder:i,sortField:o}),initialPageParam:0,getNextPageParam:u=>{const{cursor:d,data:p}=u,m=(d.skip??0)+p.length;return m<d.total?m:void 0},enabled:l&&!!n,staleTime:e3,gcTime:t3})},r3=ep,p7e=e=>{const t=$e(),n=t.config.user?.id??Hr(),r=t.config.appId,{page:a,pageSize:i=uo,sortOrder:o="desc",sortField:s="updatedAt",multiUser:l,enabled:u=!0}=e,d=(a-1)*i,p=yt.useQuery({queryKey:In.list({userId:n,appId:r,sortField:s,sortOrder:o,pageSize:i,page:a,multiUser:l}),queryFn:async()=>t.transport.listChats({userId:n,skip:d,limit:i,multiUser:l,sortOrder:o,sortField:s}),enabled:u&&!!n&&a>=1,staleTime:e3,gcTime:t3}),m=p.data?.cursor.total??0,h=Math.max(1,Math.ceil(m/i));return{...p,page:a,pageSize:i,totalPages:h,total:m,hasNextPage:a<h,hasPreviousPage:a>1}},tp=e=>{const t=r3(e),n=be(r=>r.hydrateChats);return V.useEffect(()=>{if(t.data?.pages){const r=t.data.pages.flatMap(a=>a.data);n(r)}},[t.data,n]),t},h7e=(e={},t=[])=>{const{threshold:n=50,scrollOnMount:r=!0,observeMutations:a=!0}=e,i=V.useRef(null),o=V.useRef(null),[s,l]=V.useState(!0),u=V.useRef(!1),d=V.useRef(!1),p=V.useRef(),m=V.useCallback(()=>{const f=i.current;if(!f)return!1;const{scrollTop:w,scrollHeight:v,clientHeight:k}=f;return v-w-k<=n},[n]),h=V.useCallback(()=>{const f=i.current,w=o.current;!f||!w||w.scrollIntoView({behavior:"auto",block:"end"})},[]),g=V.useCallback(()=>{const f=m();l(f),f&&(u.current=!1)},[m]);return V.useEffect(()=>{const f=i.current;if(!f)return;let w=f.scrollTop,v;const k=()=>{const _=f.scrollTop;if(!d.current){const E=_<w,S=_>w;(E||S&&!m())&&(u.current=!0)}w=_,g(),v&&clearTimeout(v),v=window.setTimeout(()=>{d.current=!1},150)};return f.addEventListener("scroll",k,{passive:!0}),()=>{f.removeEventListener("scroll",k),v&&clearTimeout(v)}},[m,g]),V.useEffect(()=>{if(!a)return;const f=i.current;if(!f)return;const w=new MutationObserver(()=>{!u.current&&s&&(p.current&&cancelAnimationFrame(p.current),p.current=requestAnimationFrame(()=>{d.current=!0,h(),setTimeout(()=>{d.current=!1},50)})),g()});return w.observe(f,{childList:!0,subtree:!0,characterData:!0,attributes:!1}),()=>{w.disconnect(),p.current&&cancelAnimationFrame(p.current)}},[s,a,h,g]),V.useEffect(()=>{t.length!==0&&!u.current&&s&&(p.current&&cancelAnimationFrame(p.current),p.current=requestAnimationFrame(()=>{d.current=!0,h(),setTimeout(()=>{d.current=!1},50)}))},[...t]),V.useEffect(()=>{if(r&&i.current){const f=window.setTimeout(()=>{d.current=!0,h(),setTimeout(()=>{d.current=!1},50)},100);return()=>{clearTimeout(f)}}},[r,h]),{containerRef:i,sentinelRef:o,isNearBottom:s,scrollToBottom:h,checkIsNearBottom:m}},a3=()=>{const e=$e();return yt.useQuery({queryKey:["mp-agents","models"],queryFn:async()=>e.transport.listModels?await e.transport.listModels():[],staleTime:5*60*1e3,refetchOnWindowFocus:!1})},ja=e=>e.type===exports.AgentAttachmentType.Context&&e?.metadata?.kind==="pageContext";var vt=(e=>(e.Idle="idle",e.Sending="sending",e.Streaming="streaming",e))(vt||{});const Di=e=>e===exports.AgentStatus.Streaming||e===exports.AgentStatus.Processing||e===exports.AgentStatus.WaitingForUserAction?"streaming":"idle",i3=()=>({messages:[],reasoning:[],artifacts:[],pendingAssistant:void 0,messageQueue:[],composerDraft:{value:"",attachments:[]},composerError:void 0,pageContextDismissed:!1,status:"idle"}),ze=(e,t)=>e.chatState[t]??i3(),m7e=e=>r5.create()((t,n)=>({contextKey:e,activeChatId:void 0,draftChatKey:`draft-${_t.nanoid()}`,chats:{},chatState:{},isChatHistoryOpen:!1,composer:{temperature:.4},setContextKey:r=>t({contextKey:r}),setActiveChat:r=>{t(a=>{let i=a.contextKey,o;if(r){const u=a.chats[r];u?.contextKey&&(i=u.contextKey),o=u?.model}const s=a.activeChatId!==r;return{activeChatId:r,contextKey:i,composer:r&&s?{...a.composer,model:o}:a.composer}})},upsertChat:r=>t(a=>{const i=a.chats[r.id],s=a.activeChatId===r.id&&(!i||i.model!==r.model);return{chats:{...a.chats,[r.id]:r},...s?{composer:{...a.composer,model:r.model}}:{}}}),upsertChatState:(r,a)=>t(i=>{const o=ze(i,r),s=typeof a=="function"?a(o):a,l={...o,...s};return{chatState:{...i.chatState,[r]:l}}}),hydrateChats:r=>t(a=>{const i={};r.forEach(u=>{i[u.id]=u});const o=a.activeChatId??r[0]?.id;o&&!i[o]&&a.chats[o]&&(i[o]=a.chats[o]);const l=o?i[o]:void 0;return{chats:i,activeChatId:o,composer:{...a.composer,model:l?.model}}}),removeChat:r=>t(a=>{if(!a.chats[r])return a;const{[r]:i,...o}=a.chats,{[r]:s,...l}=a.chatState,u=a.activeChatId===r;return{chats:o,chatState:l,...u?{activeChatId:void 0}:{}}}),pushReasoning:(r,a)=>t(i=>{const o=ze(i,r);return{chatState:{...i.chatState,[r]:{...o,reasoning:[...o.reasoning,a]}}}}),setArtifacts:(r,a)=>t(i=>{const o=ze(i,r);return{chatState:{...i.chatState,[r]:{...o,artifacts:a}}}}),setComposerOptions:r=>t(a=>({composer:{...a.composer,...r}})),setComposerDraft:(r,a)=>t(i=>{const o=ze(i,r);return{chatState:{...i.chatState,[r]:{...o,composerDraft:{value:a.value??"",attachments:a.attachments??[]}}}}}),setComposerValue:(r,a)=>t(i=>{const o=ze(i,r);return{chatState:{...i.chatState,[r]:{...o,composerDraft:{...o.composerDraft,value:a}}}}}),addComposerAttachments:(r,a)=>t(i=>{const o=ze(i,r),s=o.composerDraft.attachments??[];if(!a||a.length===0)return i;const l=s.find(ja),u=a.find(ja);if(u){const m=a.filter(v=>!ja(v)),h=s.filter(v=>!ja(v)),f=[l?{...u,id:l.id}:u,...m,...h],w=new Map;for(const v of f)w.set(v.id,v);return{chatState:{...i.chatState,[r]:{...o,composerDraft:{...o.composerDraft,attachments:Array.from(w.values())}}}}}const d=[...a,...s],p=new Map;for(const m of d)p.set(m.id,m);return{chatState:{...i.chatState,[r]:{...o,composerDraft:{...o.composerDraft,attachments:Array.from(p.values())}}}}}),removeComposerAttachment:(r,a)=>t(i=>{const o=ze(i,r);return{chatState:{...i.chatState,[r]:{...o,composerDraft:{...o.composerDraft,attachments:o.composerDraft.attachments.filter(s=>s.id!==a)}}}}}),clearComposerDraft:r=>t(a=>{const i=ze(a,r);return{chatState:{...a.chatState,[r]:{...i,composerDraft:{value:"",attachments:[]}}}}}),setComposerError:(r,a)=>t(i=>{const o=ze(i,r);return{chatState:{...i.chatState,[r]:{...o,composerError:a}}}}),setPageContextDismissed:(r,a)=>t(i=>{const o=ze(i,r);return{chatState:{...i.chatState,[r]:{...o,pageContextDismissed:a}}}}),setChatStatus:(r,a)=>t(i=>{const o=ze(i,r);return{chatState:{...i.chatState,[r]:{...o,status:a}}}}),setPendingAssistant:(r,a)=>t(i=>{const o=ze(i,r);return{chatState:{...i.chatState,[r]:{...o,pendingAssistant:a}}}}),commitPendingAssistant:r=>t(a=>{const i=ze(a,r),o=i.pendingAssistant;if(!o)return a;if(!a.chats[r])return{chatState:{...a.chatState,[r]:{...i,pendingAssistant:void 0}}};const u=typeof o.content=="string"&&o.content.trim().length>0?(()=>{if(i.messages[i.messages.length-1]?.id===o.id)return i.messages;const p={...o,chat:r};return[...i.messages,p]})():i.messages;return{chatState:{...a.chatState,[r]:{...i,messages:u,pendingAssistant:void 0}}}}),enqueueQueuedMessage:(r,a,i)=>t(o=>{const s=ze(o,r),l={id:_t.nanoid(),content:a,...i&&i.length>0?{attachments:i}:{},createdAt:new Date().toISOString()};return{chatState:{...o.chatState,[r]:{...s,messageQueue:[...s.messageQueue,l]}}}}),removeQueuedMessage:(r,a)=>t(i=>{const o=ze(i,r);if(o.messageQueue.length===0)return i;const s=o.messageQueue.filter(l=>l.id!==a);return{chatState:{...i.chatState,[r]:{...o,messageQueue:s}}}}),moveChatKeyState:(r,a)=>t(i=>{if(r===a)return i;const o=ze(i,r),s=ze(i,a);if(!(o.messageQueue.length>0||!!o.pendingAssistant||o.status!=="idle"||o.composerDraft.value.length>0||o.composerDraft.attachments.length>0||!!o.composerError))return i;const u=o.composerDraft.value.length>0||o.composerDraft.attachments.length>0,d=s.composerDraft.value.length>0||s.composerDraft.attachments.length>0,p={messages:s.messages,reasoning:s.reasoning,artifacts:s.artifacts,pendingAssistant:o.pendingAssistant??s.pendingAssistant,messageQueue:[...s.messageQueue,...o.messageQueue],composerDraft:u&&!d?o.composerDraft:s.composerDraft,composerError:o.composerError??s.composerError,pageContextDismissed:i.chatState[a]?s.pageContextDismissed:o.pageContextDismissed,status:o.status??s.status};return{chatState:{...i.chatState,[a]:p,[r]:i3()}}}),appendSystemMessage:(r,a)=>t(i=>{const o=ze(i,r),s={id:_t.nanoid(),chat:r,content:a,role:exports.MessageRole.System,createdAt:new Date().toISOString()};return{chatState:{...i.chatState,[r]:{...o,messages:[...o.messages,s]}}}}),upsertToolCall:(r,a)=>t(i=>{const o=ze(i,r),s=[...o.messages],l=s.findIndex(u=>u.role===exports.MessageRole.Tool&&u.toolCalls?.some(d=>d.id===a.id));if(l>=0){const u=s[l],d=(u.toolCalls??[]).map(p=>p.id===a.id?a:p);s[l]={...u,toolCalls:d}}else s.push({id:`tool-${a.id}`,content:"",chat:r,toolCalls:[a],role:exports.MessageRole.Tool,createdAt:new Date().toISOString()});return{chatState:{...i.chatState,[r]:{...o,messages:s}}}}),setChatHistoryOpen:r=>t({isChatHistoryOpen:r}),toggleChatHistory:()=>t(r=>({isChatHistoryOpen:!r.isChatHistoryOpen})),setChatMessages:(r,a)=>t(i=>{const o=ze(i,r),s=o.messages??[],l=typeof a=="function"?a(s):a;return{chatState:{...i.chatState,[r]:{...o,messages:l}}}}),appendMessagesToChat:(r,a)=>t(i=>{const o=ze(i,r);if(a.length===0)return i;const s=new Set(a.map(d=>d.id)),u=[...o.messages.filter(d=>!s.has(d.id)),...a].sort((d,p)=>d.createdAt.localeCompare(p.createdAt));return{chatState:{...i.chatState,[r]:{...o,messages:u}}}})})),o3=()=>{const e=be(s=>s.activeChatId??s.draftChatKey),t=be(s=>ze(s,e).composerDraft),n=be(s=>s.setComposerValue),r=be(s=>s.setComposerDraft),a=be(s=>s.clearComposerDraft),i=be(s=>s.addComposerAttachments),o=be(s=>s.removeComposerAttachment);return{chatKey:e,draft:t,setValue:s=>n(e,s),setDraft:s=>r(e,s),clearDraft:()=>a(e),addAttachments:s=>i(e,s),removeAttachment:s=>o(e,s)}},s3=e=>{const t=$e();return yt.useQuery({queryKey:["mp-agents","configurations",e??"all"],queryFn:async()=>t.transport.listAgentConfigurations?t.transport.listAgentConfigurations(e):[],staleTime:6e4,refetchOnWindowFocus:!1})},f7e=(e,t=[])=>{const n=$e(),r=V.useRef(e),a=V.useCallback(e,t);r.current=a;const i=V.useCallback(o=>r.current(o),[]);V.useEffect(()=>n.registerPageContextProvider(i),[n,i])},l3=e=>{const t=$e();return V.useCallback(r=>{t.events.dispatchEvent(new CustomEvent(e,{detail:r}))},[t,e])},c3=(e,t,n=[],r)=>{const a=$e(),i=V.useRef(t),o=V.useCallback(t,n);i.current=o;const s=V.useCallback(u=>{i.current(u)},[]),l=typeof r=="boolean"?r:r?.capture;V.useEffect(()=>(a.events.addEventListener(e,s,r),()=>{a.events.removeEventListener(e,s,l)}),[a,e,s,l])},g7e=({formId:e,onApply:t,enabled:n=!0})=>{c3(Pd,r=>{n&&r.detail.formId===e&&t(r.detail)},[n,e,t])},y7e=["mp-agents","configurations"],u3=()=>{const e=$e(),t=yt.useQueryClient(),n=()=>t.invalidateQueries({queryKey:y7e}),r=yt.useMutation({mutationFn:async({agentName:i,input:o})=>{if(!e.transport.upsertAgentPreferences)throw new Error("upsertAgentPreferences is not supported by this transport");return e.transport.upsertAgentPreferences(i,o)},onSuccess:n}),a=yt.useMutation({mutationFn:async i=>{if(!e.transport.upsertAgentPreferencesBatch)throw new Error("upsertAgentPreferencesBatch is not supported by this transport");return e.transport.upsertAgentPreferencesBatch(i)},onSuccess:n});return{upsertSingle:r,upsertBatch:a}},d3=()=>{const e=$e(),t=be(s=>s.activeChatId),n=be(s=>s.upsertChat),r=be(s=>s.setActiveChat),a=be(s=>s.setChatStatus),i=!!t,o=yt.useQuery({queryKey:["mp-agents","chat",t],queryFn:()=>e.transport.getChat(t),enabled:i,staleTime:6e4,retry:!1});return V.useEffect(()=>{o.data&&(n(o.data),a(o.data.id,Di(o.data.status)))},[o.data,n,a]),V.useEffect(()=>{o.isError&&t&&r(void 0)},[o.isError,t,r]),o},p3=20,np=e=>{const t=$e(),n=t.config.messagesPageSize??p3,r=be(o=>o.setChatMessages),a=be(o=>!!(e&&o.chats[e])),i=yt.useInfiniteQuery({queryKey:["mp-agents","messages",e,n],queryFn:async({pageParam:o})=>{if(!e||!t.transport.getMessages)throw new Error("No chat or transport");return await t.transport.getMessages(e,{limit:n,...o?{before:o}:{}})},initialPageParam:void 0,getNextPageParam:o=>o.hasMore&&o.messages.length>0?o.messages[0]?.id:void 0,enabled:!!e&&!!t.transport.getMessages&&a,retry:!1});return V.useEffect(()=>{if(!e||!i.data?.pages)return;const s=i.data.pages.slice().reverse().flatMap(u=>u.messages),l=new Set(s.map(u=>u.id));r(e,u=>{const d=u.filter(p=>!l.has(p.id));return[...s,...d]})},[e,i.data,r]),i},rp=()=>{const e=$e(),t=e.config.user?.id??Hr(),n=be(u=>u.activeChatId),r=be(u=>u.removeChat),a=be(u=>u.setActiveChat),[i,o]=V.useState(new Set),s=V.useCallback(async u=>{o(d=>new Set(d).add(u));try{await e.transport.deleteChat(u),r(u),n===u&&a(void 0),e.queryClient.invalidateQueries({queryKey:["mp-agents","chats",t]})}finally{o(d=>{const p=new Set(d);return p.delete(u),p})}},[n,r,e.queryClient,e.transport,a,t]),l=V.useCallback(u=>i.has(u),[i]);return{deleteChat:s,isDeleting:l}},b7e=e=>{if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);if(typeof e=="object")try{return JSON.stringify(e)}catch{return String(e)}return String(e)},k7e=e=>{const t=e.output??e.input??{},n=Array.isArray(t.fields)?t.fields.map(r=>({name:typeof r?.name=="string"?r.name:"",label:typeof r?.label=="string"?r.label:void 0,value:b7e(r?.value),inputType:typeof r?.inputType=="string"?r.inputType:void 0,options:Array.isArray(r?.options)?r.options:void 0})).filter(r=>r.name.length>0):[];return{formId:typeof t.formId=="string"?t.formId:void 0,formName:typeof t.formName=="string"?t.formName:void 0,fields:n,notes:typeof t.notes=="string"?t.notes:void 0}},h3=({call:e,chatId:t,applyAllButtonText:n,showStatus:r=!0})=>{const a=$e(),i=l3(Pd),o=Wt(),s=V.useMemo(()=>k7e(e),[e]),[l,u]=V.useState(new Set),d=V.useMemo(()=>{const x=(e.output??{})?._mp?.lastAction,D=typeof x?.action=="string"?x.action:void 0,P=typeof x?.at=="string"?x.at:void 0;return{action:D,at:P}},[e.output]),p=V.useMemo(()=>d.action==="apply",[d.action]),m=V.useMemo(()=>d.action==="reject",[d.action]),h=V.useMemo(()=>e.status===exports.AgentToolCallStatus.Succeeded&&!!s.formId&&s.fields.length>0&&!p,[e.status,s.formId,s.fields.length,p]);V.useMemo(()=>e.status===exports.AgentToolCallStatus.Succeeded&&!!s.formId&&s.fields.length>0&&!p&&!m,[e.status,s.formId,s.fields.length,p,m]);const g=V.useCallback(async E=>{s.formId&&a.transport.recordToolCallAction&&await a.transport.recordToolCallAction(t,{toolCallId:e.id,action:E.action,data:{formId:s.formId,formName:s.formName,fields:E.fields},systemMessage:E.action==="apply"?`Applied ${E.fields.length} field(s) to ${s.formName??s.formId}.`:`Rejected ${s.formName??s.formId} suggestion.`},{excludeSocketId:!1})},[s.formId,s.formName,t,e.id,a.transport]),f=V.useCallback(async E=>{if(s.formId){i({fields:E,chatId:t,toolCallId:e.id,formId:s.formId,...s.formName?{formName:s.formName}:{}});try{await g({action:"apply",fields:E})}catch{return}}},[s.formId,s.formName,t,e.id,i,g]);V.useCallback(async()=>{if(s.formId)try{await g({action:"reject",fields:s.fields})}catch{return}},[s.formId,s.fields,g]);const w=V.useCallback(E=>{u(S=>{if(S.has(E)){if(S.size===1)return new Set;const x=new Set(S);return x.delete(E),x}else{const x=new Set(S);return x.add(E),x}})},[]),v=V.useCallback(E=>{f([E])},[f]),k=V.useCallback(()=>{f(s.fields)},[f,s.fields]),_=s.formName?`${o.formProposalHeaderPrefix} ${s.formName}`:`${o.formProposalHeaderPrefix} ${s.formId}`;return e.status===exports.AgentToolCallStatus.Failed&&e.error?N.jsx("div",{className:"mp-agent-tool-body",children:N.jsx("div",{className:"mp-agent-tool-simple-message",children:o.formProposalFailed})}):e.status!==exports.AgentToolCallStatus.Succeeded?N.jsx("div",{className:"mp-agent-tool-simple-message",children:o.formProposalPreparing}):!s.formId||s.fields.length===0?N.jsx("div",{className:"mp-agent-tool-simple-message",children:o.formProposalNone}):N.jsxs("div",{className:"mp-agent-tool-body",children:[N.jsx("div",{className:"mp-agent-tool-simple-message",children:_}),s.notes?N.jsx("div",{className:"mp-agent-tool-simple-message",children:s.notes}):null,N.jsx("div",{className:"mp-agent-form-proposal-fields",children:s.fields.map(E=>N.jsx(Z5,{field:E,isExpanded:l.has(E.name),canApply:h,onToggleExpand:w,onApply:v},E.name))}),N.jsxs("div",{className:"mp-agent-form-proposal-actions",children:[r&&(p||m)&&N.jsxs("div",{className:"mp-agent-form-proposal-status",children:[N.jsx("span",{className:`mp-agent-form-proposal-badge ${p?"is-applied":"is-rejected"}`,children:p?o.formProposalApplied:o.formProposalRejected}),d.at?N.jsx("span",{className:"mp-agent-form-proposal-status-time",children:N.jsx(r6e,{date:d.at})}):null]}),N.jsxs("button",{type:"button",onClick:k,className:"mp-agent-form-proposal-apply-all",children:[N.jsx(b5,{size:14})," ",n||o.formProposalApplyAll]})]})]})},po=e=>{const{id:t,name:n,url:r,capturedAt:a,source:i,security:o,target:s,kind:l,...u}=e,d=r??i?.url,p=i||d?{...i??{},...d?{url:d}:{}}:void 0,m=l==="webSnippet"||l==="formSnapshot"||l==="formField"?!0:void 0,h=o||(m!==void 0?{containsPII:m,redactionsApplied:[]}:void 0),g=typeof n=="string"&&n.trim().length?n.trim():l==="webSnippet"?u?.title?`Selection: ${String(u.title)}`:"Selection":l==="formField"?"Form field":l==="formSnapshot"?"Form snapshot":"Context";return{id:t??_t.nanoid(),type:exports.AgentAttachmentType.Context,name:g,...d?{url:d}:{},metadata:{schemaVersion:1,kind:l,capturedAt:a??new Date().toISOString(),...p?{source:p}:{},...h?{security:h}:{},...s?{target:s}:{},...u}}},v7e=e=>{try{const t=new URL(e),n=`${t.searchParams.toString()} ${t.hash}`.toLowerCase();return/(token|key|auth|session|code|password|secret|email)/.test(n)}catch{return/(token|key|auth|session|code|password|secret|email)/.test(e.toLowerCase())}},m3=(e={})=>{if(typeof window>"u")return;const t=e.url??window.location?.href;if(!t)return;const n=e.includeTitle!==!1,r=e.includeReferrer!==!1,a=e.includeViewport!==!1,i=e.includeUserAgent===!0,o=n&&typeof document<"u"?document.title:void 0,s=r&&typeof document<"u"?document.referrer:void 0;let l;try{l=new URL(t)}catch{}const u={url:t,...l?{origin:l.origin,pathname:l.pathname,search:l.search,hash:l.hash}:{},...n&&o?{title:o}:{},...r&&s?{referrer:s}:{},...i&&typeof navigator<"u"?{userAgent:navigator.userAgent}:{},...typeof navigator<"u"&&navigator.language?{language:navigator.language}:{},...typeof Intl<"u"?{timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,locale:Intl.DateTimeFormat().resolvedOptions().locale}:{},...a&&typeof window<"u"?{viewport:{width:window.innerWidth,height:window.innerHeight,devicePixelRatio:window.devicePixelRatio}}:{},...e.extra?e.extra:{}},d=v7e(t)?!0:void 0;return po({kind:"pageContext",name:e.name??"Page context",url:t,title:o,data:u,summary:l?`${l.pathname}${l.search}${l.hash}`:void 0,source:{app:"browser",url:t,route:l?`${l.pathname}${l.search}${l.hash}`:void 0},...d?{security:{containsPII:!0,redactionsApplied:[]}}:{}})},f3=()=>{if(typeof window>"u"||typeof document>"u")return;const e=window.getSelection?.();if(!e||e.rangeCount===0)return;const t=e.getRangeAt(0),n=e.toString().trim();if(!n)return;const r=(t.commonAncestorContainer.nodeType===Node.ELEMENT_NODE?t.commonAncestorContainer:t.commonAncestorContainer.parentElement)??void 0,a=r?_7e(r):void 0,i=r?.textContent??"",o=i.indexOf(n),s=o>=0?o:void 0,l=o>=0?o+n.length:void 0,u=o>=0?i.slice(Math.max(0,o-80),o).trim():void 0,d=o>=0?i.slice(o+n.length,o+n.length+80).trim():void 0;return{selectedText:n,target:{type:"text",exact:n,...u?{prefix:u}:{},...d?{suffix:d}:{},...a?{domPath:a}:{},...s!==void 0?{startOffset:s}:{},...l!==void 0?{endOffset:l}:{}}}},_7e=e=>{if(e.id)return`#${s2(e.id)}`;const t=[];let n=e;for(;n&&n.nodeType===1&&t.length<6;){const r=n.tagName.toLowerCase();if(n.id){t.unshift(`#${s2(n.id)}`);break}const a=n.parentElement;if(!a){t.unshift(r);break}const o=Array.from(a.children).filter(s=>s.tagName===n.tagName).indexOf(n)+1;t.unshift(`${r}:nth-of-type(${o})`),n=a}return t.join(" > ")},s2=e=>e.replace(/[^a-zA-Z0-9_-]/g,"\\$&");class g3{constructor(t){this.rawConfig=t,this.events=new EventTarget;const n=Wu.parse(t);this.config={...n,tools:t.tools,pageContext:t.pageContext?{...n.pageContext,...t.pageContext}:n.pageContext,translations:t.translations?{...Ni,...t.translations}:Ni,transport:t.transport.onError?{...n.transport,onError:t.transport.onError}:n.transport,toolRenderers:t.toolRenderers,contextAttachmentIcons:t.contextAttachmentIcons,composerAttachmentActions:t.composerAttachmentActions},this.transport=this.createTransport(this.config.transport),this.tools=new J7(this.config.tools),this.tools.bindInvoke(this.invokeTool.bind(this)),this.configureTransportAfterCreate(this.transport),Object.entries(t.toolRenderers??{}).forEach(([r,a])=>{a&&this.toolRendererMap.set(r,a)}),this.toolRendererMap.has("propose_form_values")||this.toolRendererMap.set("propose_form_values",h3),this.queryClient=new yt.QueryClient({defaultOptions:{queries:{staleTime:3e4,refetchOnWindowFocus:!1}}})}config;transport;tools;queryClient;events;socketClient=null;toolRendererMap=new Map;storeRef;pageContextProviders=new Set;createTransport(t){return t.mode==="proxy"?new Or(t):new $o(t)}configureTransportAfterCreate(t){this.config.transport.mode==="direct"&&t instanceof $o&&(t.setToolRegistry(this.tools),t.setContextKeys(this.config.contextKeys.map(n=>({key:n.key,tools:n.tools}))),this.config.models&&t.setModels(this.config.models),t.setUntitledChatText(this.config.translations.untitledChat))}updateTransportConfig(t){const n=Wu.parse({...this.rawConfig,transport:t}),r=this.config.transport,a=this.transport;this.rawConfig={...this.rawConfig,transport:t},this.config.transport=t.onError?{...n.transport,onError:t.onError}:n.transport;const i=this.config.transport.mode;if(r.mode!==i){a.cancelStream?.(),this.transport=this.createTransport(this.config.transport),this.configureTransportAfterCreate(this.transport),this.events.dispatchEvent(new CustomEvent("runtime:transport-config-changed",{detail:{previous:r,next:this.config.transport}}));return}i==="proxy"&&a instanceof Or?a.updateConfig(this.config.transport):i==="direct"&&a instanceof $o?(a.updateConfig(this.config.transport),this.configureTransportAfterCreate(a)):(a.cancelStream?.(),this.transport=this.createTransport(this.config.transport),this.configureTransportAfterCreate(this.transport)),this.events.dispatchEvent(new CustomEvent("runtime:transport-config-changed",{detail:{previous:r,next:this.config.transport}}))}setTransportHeaders(t){const n=this.config.transport;this.updateTransportConfig({...n,headers:t})}mergeTransportHeaders(t){const n=this.config.transport;this.updateTransportConfig({...n,headers:{...n.headers??{},...t}})}removeTransportHeaders(t){const n=this.config.transport;if(!n.headers||t.length===0)return;const r={...n.headers};for(const a of t)delete r[a];this.updateTransportConfig({...n,headers:Object.keys(r).length?r:void 0})}get defaultContextKey(){return this.config.defaultContextKey??this.config.contextKeys[0]?.key}get store(){if(!this.storeRef)throw new Error("AgentRuntime store has not been attached yet");return this.storeRef}attachStore(t){this.storeRef=t}get socket(){return this.socketClient}setSocketClient(t){this.socketClient!==t&&(this.socketClient=t,this.events.dispatchEvent(new CustomEvent("runtime:socket-changed",{detail:{socket:t}})))}registerTool(t){this.tools.register(t)}registerToolRenderer(t,n){this.toolRendererMap.set(t,n)}registerPageContextProvider(t){return this.pageContextProviders.add(t),()=>{this.pageContextProviders.delete(t)}}getPageContextInput(){if(typeof window>"u")return{};const t=window.location?.href;let n;if(t)try{const a=new URL(t);n=`${a.pathname}${a.search}${a.hash}`}catch{}const r=typeof document<"u"?document.title:void 0;return{url:t,route:n,title:r}}getPageContextData(t){const n=t??this.getPageContextInput(),r={};let a=!1;const i=this.config.pageContext?.getData;if(i)try{const o=i(n);o&&typeof o=="object"&&(Object.assign(r,o),a=!0)}catch{}for(const o of this.pageContextProviders)try{const s=o(n);s&&typeof s=="object"&&(Object.assign(r,s),a=!0)}catch{}return a?r:void 0}buildPageContextAttachment(){const t=this.config.pageContext,n=this.getPageContextData();return m3({...t?.includeUserAgent!==void 0?{includeUserAgent:t.includeUserAgent}:{},...t?.includeReferrer!==void 0?{includeReferrer:t.includeReferrer}:{},...t?.includeViewport!==void 0?{includeViewport:t.includeViewport}:{},...t?.includeTitle!==void 0?{includeTitle:t.includeTitle}:{},...t?.name?{name:t.name}:{},...n?{extra:n}:{}})}getToolRenderer(t){return this.toolRendererMap.get(t.name)}ensureStore(t){if(!this.storeRef)throw new Error(`Cannot ${t} before AgentRuntime is mounted`);return this.storeRef}resolveChatId(t){const r=this.ensureStore("invoke tools").getState(),a=t?.chatId??r.activeChatId;if(!a||!r.chats[a])throw new Error("Tool invocation requires an active chat. Select or create a chat first.");return a}buildToolContext(t){const n=this.ensureStore("create tool context");return{chatId:t,agentId:this.config.appId,workspaceId:this.config.workspaceId,appendSystemMessage:r=>{n.getState().appendSystemMessage(t,r)}}}writeToolCall(t,n){this.ensureStore("write tool call").getState().upsertToolCall(t,{...n})}async invokeTool(t,n={},r){const a=this.resolveChatId(r),i={id:_t.nanoid(),name:t,input:n,status:exports.AgentToolCallStatus.Running};this.writeToolCall(a,i);const o=this.buildToolContext(a);try{const s=await this.tools.execute(t,n,o,i);return this.writeToolCall(a,s),s}catch(s){const l={...i,status:exports.AgentToolCallStatus.Failed,error:s instanceof Error?s.message:"Unknown tool error"};throw this.writeToolCall(a,l),s}}}const w7e={background:"#050505",surface:"#0f0f11",text:"#f7f7f7",subtext:"#8f9baa",border:"#1f2229",accent:"#6c63ff",accentSoft:"rgba(108, 99, 255, 0.14)",warning:"#ffb347",danger:"#ff5f56",fontFamily:'Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',radius:"12px",fontSize:"14px",colorMode:"light"},y3=e=>({...w7e,...e}),b3=V.createContext(y3()),x7e=e=>({"--mp-agents-bg":e.background,"--mp-agents-surface":e.surface,"--mp-agents-text":e.text,"--mp-agents-subtext":e.subtext,"--mp-agents-border":e.border,"--mp-agents-accent":e.accent,"--mp-agents-accent-soft":e.accentSoft,"--mp-agents-warning":e.warning,"--mp-agents-danger":e.danger,"--mp-agents-radius":e.radius,"--mp-agents-font-size":e.fontSize}),k3=({value:e,children:t})=>{const n=V.useMemo(()=>y3(e),[e]);return N.jsxs(b3.Provider,{value:n,children:[N.jsx("style",{children:`:root {
|
|
8291
8291
|
${Object.entries(x7e(n)).map(([r,a])=>`${r}: ${a};`).join(`
|
|
8292
8292
|
`)}
|
|
8293
8293
|
}`}),t]})},v3=()=>V.useContext(b3),l2="mp-agent-selected-model",ta="__auto__";function _3(e){return e.mode==="direct"?`${l2}-${e.mode}-${e.provider}`:`${l2}-${e.mode}`}function c2(e,t){try{const n=_3(e);localStorage.setItem(n,t)}catch(n){console.warn("Failed to save selected model to localStorage:",n)}}function E7e(e){try{const t=_3(e);return localStorage.getItem(t)}catch(t){return console.warn("Failed to load selected model from localStorage:",t),null}}function w3(e,t){return!e||e.length===0?[]:t.mode==="direct"&&t.provider!=="custom"?e.filter(n=>n.provider?n.provider===t.provider:!0):e}function M7e(e,t,n){const r=E7e(t);if(r){if(r===ta)return;if(w3(e,t).some(i=>i.id===r))return r}}const S7e="mp-agents-last-active-chat";function x3(e){return`${S7e}-${e}`}function E3(e){return typeof e=="string"&&e.length>0&&e.length<256}function N7e(e){if(typeof window>"u")return null;try{const t=localStorage.getItem(x3(e));return t&&E3(t)?t:null}catch{return null}}function A7e(e,t){if(!(typeof window>"u"))try{const n=x3(e);t&&E3(t)?localStorage.setItem(n,t):localStorage.removeItem(n)}catch{}}const wn=Object.create(null);wn.open="0";wn.close="1";wn.ping="2";wn.pong="3";wn.message="4";wn.upgrade="5";wn.noop="6";const bi=Object.create(null);Object.keys(wn).forEach(e=>{bi[wn[e]]=e});const ed={type:"error",data:"parser error"},M3=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",S3=typeof ArrayBuffer=="function",N3=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,ap=({type:e,data:t},n,r)=>M3&&t instanceof Blob?n?r(t):u2(t,r):S3&&(t instanceof ArrayBuffer||N3(t))?n?r(t):u2(new Blob([t]),r):r(wn[e]+(t||"")),u2=(e,t)=>{const n=new FileReader;return n.onload=function(){const r=n.result.split(",")[1];t("b"+(r||""))},n.readAsDataURL(e)};function d2(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let Xo;function T7e(e,t){if(M3&&e.data instanceof Blob)return e.data.arrayBuffer().then(d2).then(t);if(S3&&(e.data instanceof ArrayBuffer||N3(e.data)))return t(d2(e.data));ap(e,!1,n=>{Xo||(Xo=new TextEncoder),t(Xo.encode(n))})}const p2="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",na=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e<p2.length;e++)na[p2.charCodeAt(e)]=e;const C7e=e=>{let t=e.length*.75,n=e.length,r,a=0,i,o,s,l;e[e.length-1]==="="&&(t--,e[e.length-2]==="="&&t--);const u=new ArrayBuffer(t),d=new Uint8Array(u);for(r=0;r<n;r+=4)i=na[e.charCodeAt(r)],o=na[e.charCodeAt(r+1)],s=na[e.charCodeAt(r+2)],l=na[e.charCodeAt(r+3)],d[a++]=i<<2|o>>4,d[a++]=(o&15)<<4|s>>2,d[a++]=(s&3)<<6|l&63;return u},R7e=typeof ArrayBuffer=="function",ip=(e,t)=>{if(typeof e!="string")return{type:"message",data:A3(e,t)};const n=e.charAt(0);return n==="b"?{type:"message",data:I7e(e.substring(1),t)}:bi[n]?e.length>1?{type:bi[n],data:e.substring(1)}:{type:bi[n]}:ed},I7e=(e,t)=>{if(R7e){const n=C7e(e);return A3(n,t)}else return{base64:!0,data:e}},A3=(e,t)=>{switch(t){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},T3="",O7e=(e,t)=>{const n=e.length,r=new Array(n);let a=0;e.forEach((i,o)=>{ap(i,!1,s=>{r[o]=s,++a===n&&t(r.join(T3))})})},L7e=(e,t)=>{const n=e.split(T3),r=[];for(let a=0;a<n.length;a++){const i=ip(n[a],t);if(r.push(i),i.type==="error")break}return r};function D7e(){return new TransformStream({transform(e,t){T7e(e,n=>{const r=n.length;let a;if(r<126)a=new Uint8Array(1),new DataView(a.buffer).setUint8(0,r);else if(r<65536){a=new Uint8Array(3);const i=new DataView(a.buffer);i.setUint8(0,126),i.setUint16(1,r)}else{a=new Uint8Array(9);const i=new DataView(a.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(r))}e.data&&typeof e.data!="string"&&(a[0]|=128),t.enqueue(a),t.enqueue(n)})}})}let Qo;function Va(e){return e.reduce((t,n)=>t+n.length,0)}function Ga(e,t){if(e[0].length===t)return e.shift();const n=new Uint8Array(t);let r=0;for(let a=0;a<t;a++)n[a]=e[0][r++],r===e[0].length&&(e.shift(),r=0);return e.length&&r<e[0].length&&(e[0]=e[0].slice(r)),n}function z7e(e,t){Qo||(Qo=new TextDecoder);const n=[];let r=0,a=-1,i=!1;return new TransformStream({transform(o,s){for(n.push(o);;){if(r===0){if(Va(n)<1)break;const l=Ga(n,1);i=(l[0]&128)===128,a=l[0]&127,a<126?r=3:a===126?r=1:r=2}else if(r===1){if(Va(n)<2)break;const l=Ga(n,2);a=new DataView(l.buffer,l.byteOffset,l.length).getUint16(0),r=3}else if(r===2){if(Va(n)<8)break;const l=Ga(n,8),u=new DataView(l.buffer,l.byteOffset,l.length),d=u.getUint32(0);if(d>Math.pow(2,21)-1){s.enqueue(ed);break}a=d*Math.pow(2,32)+u.getUint32(4),r=3}else{if(Va(n)<a)break;const l=Ga(n,a);s.enqueue(ip(i?l:Qo.decode(l),t)),r=0}if(a===0||a>e){s.enqueue(ed);break}}}})}const C3=4;function ct(e){if(e)return $7e(e)}function $7e(e){for(var t in ct.prototype)e[t]=ct.prototype[t];return e}ct.prototype.on=ct.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this};ct.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this};ct.prototype.off=ct.prototype.removeListener=ct.prototype.removeAllListeners=ct.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var n=this._callbacks["$"+e];if(!n)return this;if(arguments.length==1)return delete this._callbacks["$"+e],this;for(var r,a=0;a<n.length;a++)if(r=n[a],r===t||r.fn===t){n.splice(a,1);break}return n.length===0&&delete this._callbacks["$"+e],this};ct.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),n=this._callbacks["$"+e],r=1;r<arguments.length;r++)t[r-1]=arguments[r];if(n){n=n.slice(0);for(var r=0,a=n.length;r<a;++r)n[r].apply(this,t)}return this};ct.prototype.emitReserved=ct.prototype.emit;ct.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]};ct.prototype.hasListeners=function(e){return!!this.listeners(e).length};const ho=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,n)=>n(t,0),Qt=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),F7e="arraybuffer";function R3(e,...t){return t.reduce((n,r)=>(e.hasOwnProperty(r)&&(n[r]=e[r]),n),{})}const P7e=Qt.setTimeout,q7e=Qt.clearTimeout;function mo(e,t){t.useNativeTimers?(e.setTimeoutFn=P7e.bind(Qt),e.clearTimeoutFn=q7e.bind(Qt)):(e.setTimeoutFn=Qt.setTimeout.bind(Qt),e.clearTimeoutFn=Qt.clearTimeout.bind(Qt))}const B7e=1.33;function U7e(e){return typeof e=="string"?H7e(e):Math.ceil((e.byteLength||e.size)*B7e)}function H7e(e){let t=0,n=0;for(let r=0,a=e.length;r<a;r++)t=e.charCodeAt(r),t<128?n+=1:t<2048?n+=2:t<55296||t>=57344?n+=3:(r++,n+=4);return n}function I3(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function j7e(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}function V7e(e){let t={},n=e.split("&");for(let r=0,a=n.length;r<a;r++){let i=n[r].split("=");t[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return t}class G7e extends Error{constructor(t,n,r){super(t),this.description=n,this.context=r,this.type="TransportError"}}class op extends ct{constructor(t){super(),this.writable=!1,mo(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,n,r){return super.emitReserved("error",new G7e(t,n,r)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(t){this.readyState==="open"&&this.write(t)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(t){const n=ip(t,this.socket.binaryType);this.onPacket(n)}onPacket(t){super.emitReserved("packet",t)}onClose(t){this.readyState="closed",super.emitReserved("close",t)}pause(t){}createUri(t,n={}){return t+"://"+this._hostname()+this._port()+this.opts.path+this._query(n)}_hostname(){const t=this.opts.hostname;return t.indexOf(":")===-1?t:"["+t+"]"}_port(){return this.opts.port&&(this.opts.secure&&+(this.opts.port!==443)||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(t){const n=j7e(t);return n.length?"?"+n:""}}class W7e extends op{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(t){this.readyState="pausing";const n=()=>{this.readyState="paused",t()};if(this._polling||!this.writable){let r=0;this._polling&&(r++,this.once("pollComplete",function(){--r||n()})),this.writable||(r++,this.once("drain",function(){--r||n()}))}else n()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){const n=r=>{if(this.readyState==="opening"&&r.type==="open"&&this.onOpen(),r.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(r)};L7e(t,this.socket.binaryType).forEach(n),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){const t=()=>{this.write([{type:"close"}])};this.readyState==="open"?t():this.once("open",t)}write(t){this.writable=!1,O7e(t,n=>{this.doWrite(n,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",n=this.query||{};return this.opts.timestampRequests!==!1&&(n[this.opts.timestampParam]=I3()),!this.supportsBinary&&!n.sid&&(n.b64=1),this.createUri(t,n)}}let O3=!1;try{O3=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const K7e=O3;function Y7e(){}class Z7e extends W7e{constructor(t){if(super(t),typeof location<"u"){const n=location.protocol==="https:";let r=location.port;r||(r=n?"443":"80"),this.xd=typeof location<"u"&&t.hostname!==location.hostname||r!==t.port}}doWrite(t,n){const r=this.request({method:"POST",data:t});r.on("success",n),r.on("error",(a,i)=>{this.onError("xhr post error",a,i)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(n,r)=>{this.onError("xhr poll error",n,r)}),this.pollXhr=t}}class _n extends ct{constructor(t,n,r){super(),this.createRequest=t,mo(this,r),this._opts=r,this._method=r.method||"GET",this._uri=n,this._data=r.data!==void 0?r.data:null,this._create()}_create(){var t;const n=R3(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");n.xdomain=!!this._opts.xd;const r=this._xhr=this.createRequest(n);try{r.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let a in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(a)&&r.setRequestHeader(a,this._opts.extraHeaders[a])}}catch{}if(this._method==="POST")try{r.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{r.setRequestHeader("Accept","*/*")}catch{}(t=this._opts.cookieJar)===null||t===void 0||t.addCookies(r),"withCredentials"in r&&(r.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(r.timeout=this._opts.requestTimeout),r.onreadystatechange=()=>{var a;r.readyState===3&&((a=this._opts.cookieJar)===null||a===void 0||a.parseCookies(r.getResponseHeader("set-cookie"))),r.readyState===4&&(r.status===200||r.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof r.status=="number"?r.status:0)},0))},r.send(this._data)}catch(a){this.setTimeoutFn(()=>{this._onError(a)},0);return}typeof document<"u"&&(this._index=_n.requestsCount++,_n.requests[this._index]=this)}_onError(t){this.emitReserved("error",t,this._xhr),this._cleanup(!0)}_cleanup(t){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=Y7e,t)try{this._xhr.abort()}catch{}typeof document<"u"&&delete _n.requests[this._index],this._xhr=null}}_onLoad(){const t=this._xhr.responseText;t!==null&&(this.emitReserved("data",t),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}_n.requestsCount=0;_n.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",h2);else if(typeof addEventListener=="function"){const e="onpagehide"in Qt?"pagehide":"unload";addEventListener(e,h2,!1)}}function h2(){for(let e in _n.requests)_n.requests.hasOwnProperty(e)&&_n.requests[e].abort()}const X7e=function(){const e=L3({xdomain:!1});return e&&e.responseType!==null}();class Q7e extends Z7e{constructor(t){super(t);const n=t&&t.forceBase64;this.supportsBinary=X7e&&!n}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new _n(L3,this.uri(),t)}}function L3(e){const t=e.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||K7e))return new XMLHttpRequest}catch{}if(!t)try{return new Qt[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const D3=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class J7e extends op{get name(){return"websocket"}doOpen(){const t=this.uri(),n=this.opts.protocols,r=D3?{}:R3(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,n,r)}catch(a){return this.emitReserved("error",a)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let n=0;n<t.length;n++){const r=t[n],a=n===t.length-1;ap(r,this.supportsBinary,i=>{try{this.doWrite(r,i)}catch{}a&&ho(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",n=this.query||{};return this.opts.timestampRequests&&(n[this.opts.timestampParam]=I3()),this.supportsBinary||(n.b64=1),this.createUri(t,n)}}const Jo=Qt.WebSocket||Qt.MozWebSocket;class e_e extends J7e{createSocket(t,n,r){return D3?new Jo(t,n,r):n?new Jo(t,n):new Jo(t)}doWrite(t,n){this.ws.send(n)}}class t_e extends op{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(t){return this.emitReserved("error",t)}this._transport.closed.then(()=>{this.onClose()}).catch(t=>{this.onError("webtransport error",t)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(t=>{const n=z7e(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=t.readable.pipeThrough(n).getReader(),a=D7e();a.readable.pipeTo(t.writable),this._writer=a.writable.getWriter();const i=()=>{r.read().then(({done:s,value:l})=>{s||(this.onPacket(l),i())}).catch(s=>{})};i();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this._writer.write(o).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let n=0;n<t.length;n++){const r=t[n],a=n===t.length-1;this._writer.write(r).then(()=>{a&&ho(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this._transport)===null||t===void 0||t.close()}}const n_e={websocket:e_e,webtransport:t_e,polling:Q7e},r_e=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,a_e=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function td(e){if(e.length>8e3)throw"URI too long";const t=e,n=e.indexOf("["),r=e.indexOf("]");n!=-1&&r!=-1&&(e=e.substring(0,n)+e.substring(n,r).replace(/:/g,";")+e.substring(r,e.length));let a=r_e.exec(e||""),i={},o=14;for(;o--;)i[a_e[o]]=a[o]||"";return n!=-1&&r!=-1&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=i_e(i,i.path),i.queryKey=o_e(i,i.query),i}function i_e(e,t){const n=/\/{2,9}/g,r=t.replace(n,"/").split("/");return(t.slice(0,1)=="/"||t.length===0)&&r.splice(0,1),t.slice(-1)=="/"&&r.splice(r.length-1,1),r}function o_e(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(r,a,i){a&&(n[a]=i)}),n}const nd=typeof addEventListener=="function"&&typeof removeEventListener=="function",ki=[];nd&&addEventListener("offline",()=>{ki.forEach(e=>e())},!1);class Qn extends ct{constructor(t,n){if(super(),this.binaryType=F7e,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,t&&typeof t=="object"&&(n=t,t=null),t){const r=td(t);n.hostname=r.host,n.secure=r.protocol==="https"||r.protocol==="wss",n.port=r.port,r.query&&(n.query=r.query)}else n.host&&(n.hostname=td(n.host).host);mo(this,n),this.secure=n.secure!=null?n.secure:typeof location<"u"&&location.protocol==="https:",n.hostname&&!n.port&&(n.port=this.secure?"443":"80"),this.hostname=n.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=n.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},n.transports.forEach(r=>{const a=r.prototype.name;this.transports.push(a),this._transportsByName[a]=r}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},n),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=V7e(this.opts.query)),nd&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},ki.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){const n=Object.assign({},this.opts.query);n.EIO=C3,n.transport=t,this.id&&(n.sid=this.id);const r=Object.assign({},this.opts,{query:n,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new this._transportsByName[t](r)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const t=this.opts.rememberUpgrade&&Qn.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const n=this.createTransport(t);n.open(),this.setTransport(n)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",n=>this._onClose("transport close",n))}onOpen(){this.readyState="open",Qn.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const n=new Error("server error");n.code=t.data,this._onError(n);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data);break}}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this._pingInterval=t.pingInterval,this._pingTimeout=t.pingTimeout,this._maxPayload=t.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const t=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+t,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},t),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this._getWritablePackets();this.transport.send(t),this._prevBufferLen=t.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let n=1;for(let r=0;r<this.writeBuffer.length;r++){const a=this.writeBuffer[r].data;if(a&&(n+=U7e(a)),r>0&&n>this._maxPayload)return this.writeBuffer.slice(0,r);n+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const t=Date.now()>this._pingTimeoutTime;return t&&(this._pingTimeoutTime=0,ho(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),t}write(t,n,r){return this._sendPacket("message",t,n,r),this}send(t,n,r){return this._sendPacket("message",t,n,r),this}_sendPacket(t,n,r,a){if(typeof n=="function"&&(a=n,n=void 0),typeof r=="function"&&(a=r,r=null),this.readyState==="closing"||this.readyState==="closed")return;r=r||{},r.compress=r.compress!==!1;const i={type:t,data:n,options:r};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),a&&this.once("flush",a),this.flush()}close(){const t=()=>{this._onClose("forced close"),this.transport.close()},n=()=>{this.off("upgrade",n),this.off("upgradeError",n),t()},r=()=>{this.once("upgrade",n),this.once("upgradeError",n)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?r():t()}):this.upgrading?r():t()),this}_onError(t){if(Qn.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",t),this._onClose("transport error",t)}_onClose(t,n){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),nd&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const r=ki.indexOf(this._offlineEventListener);r!==-1&&ki.splice(r,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,n),this.writeBuffer=[],this._prevBufferLen=0}}}Qn.protocol=C3;class s_e extends Qn{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let t=0;t<this._upgrades.length;t++)this._probe(this._upgrades[t])}_probe(t){let n=this.createTransport(t),r=!1;Qn.priorWebsocketSuccess=!1;const a=()=>{r||(n.send([{type:"ping",data:"probe"}]),n.once("packet",p=>{if(!r)if(p.type==="pong"&&p.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",n),!n)return;Qn.priorWebsocketSuccess=n.name==="websocket",this.transport.pause(()=>{r||this.readyState!=="closed"&&(d(),this.setTransport(n),n.send([{type:"upgrade"}]),this.emitReserved("upgrade",n),n=null,this.upgrading=!1,this.flush())})}else{const m=new Error("probe error");m.transport=n.name,this.emitReserved("upgradeError",m)}}))};function i(){r||(r=!0,d(),n.close(),n=null)}const o=p=>{const m=new Error("probe error: "+p);m.transport=n.name,i(),this.emitReserved("upgradeError",m)};function s(){o("transport closed")}function l(){o("socket closed")}function u(p){n&&p.name!==n.name&&i()}const d=()=>{n.removeListener("open",a),n.removeListener("error",o),n.removeListener("close",s),this.off("close",l),this.off("upgrading",u)};n.once("open",a),n.once("error",o),n.once("close",s),this.once("close",l),this.once("upgrading",u),this._upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{r||n.open()},200):n.open()}onHandshake(t){this._upgrades=this._filterUpgrades(t.upgrades),super.onHandshake(t)}_filterUpgrades(t){const n=[];for(let r=0;r<t.length;r++)~this.transports.indexOf(t[r])&&n.push(t[r]);return n}}let l_e=class extends s_e{constructor(t,n={}){const r=typeof t=="object"?t:n;(!r.transports||r.transports&&typeof r.transports[0]=="string")&&(r.transports=(r.transports||["polling","websocket","webtransport"]).map(a=>n_e[a]).filter(a=>!!a)),super(t,r)}};function c_e(e,t="",n){let r=e;n=n||typeof location<"u"&&location,e==null&&(e=n.protocol+"//"+n.host),typeof e=="string"&&(e.charAt(0)==="/"&&(e.charAt(1)==="/"?e=n.protocol+e:e=n.host+e),/^(https?|wss?):\/\//.test(e)||(typeof n<"u"?e=n.protocol+"//"+e:e="https://"+e),r=td(e)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443")),r.path=r.path||"/";const i=r.host.indexOf(":")!==-1?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+i+":"+r.port+t,r.href=r.protocol+"://"+i+(n&&n.port===r.port?"":":"+r.port),r}const u_e=typeof ArrayBuffer=="function",d_e=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,z3=Object.prototype.toString,p_e=typeof Blob=="function"||typeof Blob<"u"&&z3.call(Blob)==="[object BlobConstructor]",h_e=typeof File=="function"||typeof File<"u"&&z3.call(File)==="[object FileConstructor]";function sp(e){return u_e&&(e instanceof ArrayBuffer||d_e(e))||p_e&&e instanceof Blob||h_e&&e instanceof File}function vi(e,t){if(!e||typeof e!="object")return!1;if(Array.isArray(e)){for(let n=0,r=e.length;n<r;n++)if(vi(e[n]))return!0;return!1}if(sp(e))return!0;if(e.toJSON&&typeof e.toJSON=="function"&&arguments.length===1)return vi(e.toJSON(),!0);for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&vi(e[n]))return!0;return!1}function m_e(e){const t=[],n=e.data,r=e;return r.data=rd(n,t),r.attachments=t.length,{packet:r,buffers:t}}function rd(e,t){if(!e)return e;if(sp(e)){const n={_placeholder:!0,num:t.length};return t.push(e),n}else if(Array.isArray(e)){const n=new Array(e.length);for(let r=0;r<e.length;r++)n[r]=rd(e[r],t);return n}else if(typeof e=="object"&&!(e instanceof Date)){const n={};for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=rd(e[r],t));return n}return e}function f_e(e,t){return e.data=ad(e.data,t),delete e.attachments,e}function ad(e,t){if(!e)return e;if(e&&e._placeholder===!0){if(typeof e.num=="number"&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}else if(Array.isArray(e))for(let n=0;n<e.length;n++)e[n]=ad(e[n],t);else if(typeof e=="object")for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=ad(e[n],t));return e}const g_e=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],y_e=5;var qe;(function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"})(qe||(qe={}));class b_e{constructor(t){this.replacer=t}encode(t){return(t.type===qe.EVENT||t.type===qe.ACK)&&vi(t)?this.encodeAsBinary({type:t.type===qe.EVENT?qe.BINARY_EVENT:qe.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id}):[this.encodeAsString(t)]}encodeAsString(t){let n=""+t.type;return(t.type===qe.BINARY_EVENT||t.type===qe.BINARY_ACK)&&(n+=t.attachments+"-"),t.nsp&&t.nsp!=="/"&&(n+=t.nsp+","),t.id!=null&&(n+=t.id),t.data!=null&&(n+=JSON.stringify(t.data,this.replacer)),n}encodeAsBinary(t){const n=m_e(t),r=this.encodeAsString(n.packet),a=n.buffers;return a.unshift(r),a}}function m2(e){return Object.prototype.toString.call(e)==="[object Object]"}class lp extends ct{constructor(t){super(),this.reviver=t}add(t){let n;if(typeof t=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");n=this.decodeString(t);const r=n.type===qe.BINARY_EVENT;r||n.type===qe.BINARY_ACK?(n.type=r?qe.EVENT:qe.ACK,this.reconstructor=new k_e(n),n.attachments===0&&super.emitReserved("decoded",n)):super.emitReserved("decoded",n)}else if(sp(t)||t.base64)if(this.reconstructor)n=this.reconstructor.takeBinaryData(t),n&&(this.reconstructor=null,super.emitReserved("decoded",n));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+t)}decodeString(t){let n=0;const r={type:Number(t.charAt(0))};if(qe[r.type]===void 0)throw new Error("unknown packet type "+r.type);if(r.type===qe.BINARY_EVENT||r.type===qe.BINARY_ACK){const i=n+1;for(;t.charAt(++n)!=="-"&&n!=t.length;);const o=t.substring(i,n);if(o!=Number(o)||t.charAt(n)!=="-")throw new Error("Illegal attachments");r.attachments=Number(o)}if(t.charAt(n+1)==="/"){const i=n+1;for(;++n&&!(t.charAt(n)===","||n===t.length););r.nsp=t.substring(i,n)}else r.nsp="/";const a=t.charAt(n+1);if(a!==""&&Number(a)==a){const i=n+1;for(;++n;){const o=t.charAt(n);if(o==null||Number(o)!=o){--n;break}if(n===t.length)break}r.id=Number(t.substring(i,n+1))}if(t.charAt(++n)){const i=this.tryParse(t.substr(n));if(lp.isPayloadValid(r.type,i))r.data=i;else throw new Error("invalid payload")}return r}tryParse(t){try{return JSON.parse(t,this.reviver)}catch{return!1}}static isPayloadValid(t,n){switch(t){case qe.CONNECT:return m2(n);case qe.DISCONNECT:return n===void 0;case qe.CONNECT_ERROR:return typeof n=="string"||m2(n);case qe.EVENT:case qe.BINARY_EVENT:return Array.isArray(n)&&(typeof n[0]=="number"||typeof n[0]=="string"&&g_e.indexOf(n[0])===-1);case qe.ACK:case qe.BINARY_ACK:return Array.isArray(n)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class k_e{constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){const n=f_e(this.reconPack,this.buffers);return this.finishedReconstruction(),n}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const v_e=Object.freeze(Object.defineProperty({__proto__:null,Decoder:lp,Encoder:b_e,get PacketType(){return qe},protocol:y_e},Symbol.toStringTag,{value:"Module"}));function cn(e,t,n){return e.on(t,n),function(){e.off(t,n)}}const __e=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class $3 extends ct{constructor(t,n,r){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=t,this.nsp=n,r&&r.auth&&(this.auth=r.auth),this._opts=Object.assign({},r),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const t=this.io;this.subs=[cn(t,"open",this.onopen.bind(this)),cn(t,"packet",this.onpacket.bind(this)),cn(t,"error",this.onerror.bind(this)),cn(t,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...n){var r,a,i;if(__e.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(n.unshift(t),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(n),this;const o={type:qe.EVENT,data:n};if(o.options={},o.options.compress=this.flags.compress!==!1,typeof n[n.length-1]=="function"){const d=this.ids++,p=n.pop();this._registerAckCallback(d,p),o.id=d}const s=(a=(r=this.io.engine)===null||r===void 0?void 0:r.transport)===null||a===void 0?void 0:a.writable,l=this.connected&&!(!((i=this.io.engine)===null||i===void 0)&&i._hasPingExpired());return this.flags.volatile&&!s||(l?(this.notifyOutgoingListeners(o),this.packet(o)):this.sendBuffer.push(o)),this.flags={},this}_registerAckCallback(t,n){var r;const a=(r=this.flags.timeout)!==null&&r!==void 0?r:this._opts.ackTimeout;if(a===void 0){this.acks[t]=n;return}const i=this.io.setTimeoutFn(()=>{delete this.acks[t];for(let s=0;s<this.sendBuffer.length;s++)this.sendBuffer[s].id===t&&this.sendBuffer.splice(s,1);n.call(this,new Error("operation has timed out"))},a),o=(...s)=>{this.io.clearTimeoutFn(i),n.apply(this,s)};o.withError=!0,this.acks[t]=o}emitWithAck(t,...n){return new Promise((r,a)=>{const i=(o,s)=>o?a(o):r(s);i.withError=!0,n.push(i),this.emit(t,...n)})}_addToQueue(t){let n;typeof t[t.length-1]=="function"&&(n=t.pop());const r={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((a,...i)=>r!==this._queue[0]?void 0:(a!==null?r.tryCount>this._opts.retries&&(this._queue.shift(),n&&n(a)):(this._queue.shift(),n&&n(null,...i)),r.pending=!1,this._drainQueue())),this._queue.push(r),this._drainQueue()}_drainQueue(t=!1){if(!this.connected||this._queue.length===0)return;const n=this._queue[0];n.pending&&!t||(n.pending=!0,n.tryCount++,this.flags=n.flags,this.emit.apply(this,n.args))}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){typeof this.auth=="function"?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:qe.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,n){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,n),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(t=>{if(!this.sendBuffer.some(r=>String(r.id)===t)){const r=this.acks[t];delete this.acks[t],r.withError&&r.call(this,new Error("socket has been disconnected"))}})}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case qe.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case qe.EVENT:case qe.BINARY_EVENT:this.onevent(t);break;case qe.ACK:case qe.BINARY_ACK:this.onack(t);break;case qe.DISCONNECT:this.ondisconnect();break;case qe.CONNECT_ERROR:this.destroy();const r=new Error(t.data.message);r.data=t.data.data,this.emitReserved("connect_error",r);break}}onevent(t){const n=t.data||[];t.id!=null&&n.push(this.ack(t.id)),this.connected?this.emitEvent(n):this.receiveBuffer.push(Object.freeze(n))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const n=this._anyListeners.slice();for(const r of n)r.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&typeof t[t.length-1]=="string"&&(this._lastOffset=t[t.length-1])}ack(t){const n=this;let r=!1;return function(...a){r||(r=!0,n.packet({type:qe.ACK,id:t,data:a}))}}onack(t){const n=this.acks[t.id];typeof n=="function"&&(delete this.acks[t.id],n.withError&&t.data.unshift(null),n.apply(this,t.data))}onconnect(t,n){this.id=t,this.recovered=n&&this._pid===n,this._pid=n,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:qe.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const n=this._anyListeners;for(let r=0;r<n.length;r++)if(t===n[r])return n.splice(r,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(t),this}prependAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(t),this}offAnyOutgoing(t){if(!this._anyOutgoingListeners)return this;if(t){const n=this._anyOutgoingListeners;for(let r=0;r<n.length;r++)if(t===n[r])return n.splice(r,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(t){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const n=this._anyOutgoingListeners.slice();for(const r of n)r.apply(this,t.data)}}}function jr(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}jr.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=Math.floor(t*10)&1?e+n:e-n}return Math.min(e,this.max)|0};jr.prototype.reset=function(){this.attempts=0};jr.prototype.setMin=function(e){this.ms=e};jr.prototype.setMax=function(e){this.max=e};jr.prototype.setJitter=function(e){this.jitter=e};class id extends ct{constructor(t,n){var r;super(),this.nsps={},this.subs=[],t&&typeof t=="object"&&(n=t,t=void 0),n=n||{},n.path=n.path||"/socket.io",this.opts=n,mo(this,n),this.reconnection(n.reconnection!==!1),this.reconnectionAttempts(n.reconnectionAttempts||1/0),this.reconnectionDelay(n.reconnectionDelay||1e3),this.reconnectionDelayMax(n.reconnectionDelayMax||5e3),this.randomizationFactor((r=n.randomizationFactor)!==null&&r!==void 0?r:.5),this.backoff=new jr({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(n.timeout==null?2e4:n.timeout),this._readyState="closed",this.uri=t;const a=n.parser||v_e;this.encoder=new a.Encoder,this.decoder=new a.Decoder,this._autoConnect=n.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,t||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(t){return t===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var n;return t===void 0?this._reconnectionDelay:(this._reconnectionDelay=t,(n=this.backoff)===null||n===void 0||n.setMin(t),this)}randomizationFactor(t){var n;return t===void 0?this._randomizationFactor:(this._randomizationFactor=t,(n=this.backoff)===null||n===void 0||n.setJitter(t),this)}reconnectionDelayMax(t){var n;return t===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,(n=this.backoff)===null||n===void 0||n.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new l_e(this.uri,this.opts);const n=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const a=cn(n,"open",function(){r.onopen(),t&&t()}),i=s=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",s),t?t(s):this.maybeReconnectOnOpen()},o=cn(n,"error",i);if(this._timeout!==!1){const s=this._timeout,l=this.setTimeoutFn(()=>{a(),i(new Error("timeout")),n.close()},s);this.opts.autoUnref&&l.unref(),this.subs.push(()=>{this.clearTimeoutFn(l)})}return this.subs.push(a),this.subs.push(o),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(cn(t,"ping",this.onping.bind(this)),cn(t,"data",this.ondata.bind(this)),cn(t,"error",this.onerror.bind(this)),cn(t,"close",this.onclose.bind(this)),cn(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(n){this.onclose("parse error",n)}}ondecoded(t){ho(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,n){let r=this.nsps[t];return r?this._autoConnect&&!r.active&&r.connect():(r=new $3(this,t,n),this.nsps[t]=r),r}_destroy(t){const n=Object.keys(this.nsps);for(const r of n)if(this.nsps[r].active)return;this._close()}_packet(t){const n=this.encoder.encode(t);for(let r=0;r<n.length;r++)this.engine.write(n[r],t.options)}cleanup(){this.subs.forEach(t=>t()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(t,n){var r;this.cleanup(),(r=this.engine)===null||r===void 0||r.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,n),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const n=this.backoff.duration();this._reconnecting=!0;const r=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),!t.skipReconnect&&t.open(a=>{a?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",a)):t.onreconnect()}))},n);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const Zr={};function _i(e,t){typeof e=="object"&&(t=e,e=void 0),t=t||{};const n=c_e(e,t.path||"/socket.io"),r=n.source,a=n.id,i=n.path,o=Zr[a]&&i in Zr[a].nsps,s=t.forceNew||t["force new connection"]||t.multiplex===!1||o;let l;return s?l=new id(r,t):(Zr[a]||(Zr[a]=new id(r,t)),l=Zr[a]),n.query&&!t.query&&(t.query=n.queryKey),l.socket(n.path,t)}Object.assign(_i,{Manager:id,Socket:$3,io:_i,connect:_i});const w_e=V.createContext(null),x_e=({children:e})=>{const t=$e(),n=be(v=>v.upsertChat),r=be(v=>v.upsertChatState),a=be(v=>v.contextKey),i=be(v=>v.activeChatId),o=V.useMemo(()=>t.config.user?.id??Hr(),[t.config.user?.id]),s=t.config.transport,[l,u]=V.useState(null),[d,p]=V.useState(void 0),m=V.useRef(a),h=V.useRef(n),g=V.useRef(r),f=V.useRef(void 0);V.useEffect(()=>{m.current=a,h.current=n,g.current=r},[a,n,r]),V.useEffect(()=>{if(s.mode!=="proxy"){u(null),p(void 0),t.setSocketClient(null),t.transport instanceof Or&&t.transport.setSocketId(void 0);return}const v=s.baseUrl,k=new URL(v,window.location.origin),_=`${k.protocol}//${k.host}`,E=s.socketNamespace,S=E?`${_}${E}`:_,x={},D=s;D.headers&&Object.assign(x,D.headers);const P={},C=D.apiKey&&`Bearer ${D.apiKey}`||D.headers?.Authorization;C&&(P.authorization=C,x.Authorization=C);const L=s.socketPath??Ai.Path,G=_i(S,{path:L,auth:P,transports:["websocket","polling"],withCredentials:!0,...Object.keys(x).length>0&&{extraHeaders:x}});t.setSocketClient(G),u(G);const X=()=>{p(G.id),t.transport instanceof Or&&t.transport.setSocketId(G.id)},J=()=>{p(void 0),t.transport instanceof Or&&t.transport.setSocketId(void 0)},K=H=>{if(H.contextKey===m.current){h.current(H);const z=t.store.getState(),j=ze(z,H.id);g.current(H.id,{...j,status:Di(H.status)})}},R=H=>{const z=t.store.getState(),j=ze(z,H.chat),A=j.messages.findIndex(Y=>Y.id===H.id);if(A>=0){const Y=[...j.messages];Y[A]=H,g.current(H.chat,{...j,messages:Y});return}g.current(H.chat,{...j,messages:[...j.messages,H]})},U=H=>{h.current(H);const z=t.store.getState(),j=ze(z,H.id);g.current(H.id,{...j,status:Di(H.status)})};return G.on("connect",X),G.on("disconnect",J),G.on("connect_error",H=>{console.error("Socket.IO connection error:",H.message)}),G.on(fi.ChatNew,K),G.on(fi.MessageNew,R),G.on(fi.ChatUpdate,U),()=>{t.transport instanceof Or&&t.transport.setSocketId(void 0),t.setSocketClient(null),p(void 0),u(null),G.disconnect()}},[t,t.transport,s.mode,s.mode==="proxy"?s.baseUrl:void 0,s.mode==="proxy"?s.apiKey:void 0,s.mode==="proxy"?s.socketPath:void 0,s.mode==="proxy"?s.socketNamespace:void 0,s.mode==="proxy"?JSON.stringify(s.headers??{}):"",o]),V.useEffect(()=>{if(!l)return;const v=f.current;v&&v!==i&&l.emit("chat:unsubscribe",{chatId:v}),i&&i!==v&&(l.emit("chat:subscribe",{chatId:i}),f.current=i),i||(f.current=void 0)},[l,i]);const w=V.useMemo(()=>({socket:l,socketId:d}),[l,d]);return N.jsx(w_e.Provider,{value:w,children:e})},cp=V.createContext(null),E_e=({config:e,children:t})=>{const n=V.useRef();n.current||(n.current=new g3(e));const[,r]=V.useState(0);V.useEffect(()=>{const o=n.current,s=()=>r(l=>l+1);return o.events.addEventListener("runtime:transport-config-changed",s),()=>{o.events.removeEventListener("runtime:transport-config-changed",s)}},[]);const a=V.useRef();if(!a.current){const o=n.current.defaultContextKey??n.current.config.contextKeys[0]?.key??"default";a.current=m7e(o),n.current.attachStore(a.current);const s=M7e(n.current.config.models,n.current.config.transport);a.current.getState().setComposerOptions({model:s})}const i=V.useMemo(()=>({runtime:n.current,store:a.current}),[]);return V.useEffect(()=>{const o=a.current;if(!o)return;let s=o.getState().activeChatId;return o.subscribe(()=>{const l=o.getState().activeChatId;if(l===s)return;s=l;const u=n.current?.config.user?.id??Hr();A7e(u,l)})},[]),N.jsx(cp.Provider,{value:i,children:N.jsx(yt.QueryClientProvider,{client:i.runtime.queryClient,children:N.jsx(k3,{value:i.runtime.config.theme,children:N.jsx(x_e,{children:t})})})})},$e=()=>{const e=V.useContext(cp);if(!e)throw new Error("useAgentRuntime must be used inside <AgentProvider />");return e.runtime},be=e=>{const t=V.useContext(cp);if(!t)throw new Error("useAgentStore must be used inside <AgentProvider />");return r5.useStore(t.store,e)},M_e=({initialSystemPrompt:e,composerFormRef:t,multiUser:n=!1,participantIds:r=[]})=>{const a=$e(),{composer:i,contextKey:o,activeChatId:s,draftChatKey:l,queuedMessages:u,activeChatStatus:d,upsertChat:p,setChatStatus:m,setActiveChat:h,setComposerError:g,moveChatKeyState:f,removeQueuedMessage:w,setPendingAssistant:v,enqueueQueuedMessage:k,appendMessagesToChat:_,commitPendingAssistant:E,setPageContextDismissed:S}=be(j=>{const A=j.activeChatId??j.draftChatKey,Y=ze(j,A);return{composer:j.composer,contextKey:j.contextKey,activeChatId:j.activeChatId,draftChatKey:j.draftChatKey,queuedMessages:Y.messageQueue,activeChatStatus:Y.status,upsertChat:j.upsertChat,setActiveChat:j.setActiveChat,setChatStatus:j.setChatStatus,setComposerError:j.setComposerError,moveChatKeyState:j.moveChatKeyState,setPendingAssistant:j.setPendingAssistant,removeQueuedMessage:j.removeQueuedMessage,enqueueQueuedMessage:j.enqueueQueuedMessage,appendMessagesToChat:j.appendMessagesToChat,commitPendingAssistant:j.commitPendingAssistant,setPageContextDismissed:j.setPageContextDismissed}}),x=V.useCallback(j=>!j||j.length===0?!1:j.some(A=>A.type===exports.AgentAttachmentType.Context&&A?.metadata?.kind==="pageContext"),[]),D=V.useRef(!1),P=V.useRef(!1),C=V.useRef(void 0),L=V.useRef(new Set),G=s??l,X=V.useCallback(async(j,A)=>{if(!a.transport.generateTitle)return;const Y=a.config.features?.titleGeneration==="llm"?"llm":"local";let ee;try{ee=await a.transport.generateTitle({userId:A,content:j,strategy:Y,contextKey:o})}catch{}return ee},[a.transport,a.config.features?.titleGeneration,o]),J=V.useCallback(async(j,A=[])=>{const Y=a.config.user?.id??"guest",ee=!s,O=s??l,le={current:O};C.current=O;const fe={value:j,attachments:A};g(le.current,void 0);let ke;if(ee){const ce=await X(j,Y);ce&&ce.trim().length>0&&(ke={...ke??{},title:ce})}const Ce=a.store.getState(),Fe=s?Ce.chats[s]:void 0,Ve=(s?Ce.chatState[s]:void 0)?.messages??[],ae=A.filter(ce=>F3(ce)?!S_e(Ve,ce):!0),Se=Fe?.model,Be=i.model!==Se;let We,Ae=!1;Be?(We=i.model,Ae=!0):Se?(We=Se,Ae=!1):(We=void 0,Ae=!1);const ve=N_e(j),Ge={userId:Y,content:j,metadata:ke,contextKey:o,...ee?{}:{chatId:s},...Ae?{model:We??""}:{},...ae.length>0?{attachments:ae}:{},...n?{mentions:ve,participantIds:Array.from(new Set([Y,...r])),senderDisplayName:a.config.user?.displayName,senderAvatarUrl:a.config.user?.avatarUrl}:{}},de=()=>{v(le.current,void 0)},Ze=ce=>{if(ce?.name==="AbortError"){const Me=C.current??le.current;return L.current.has(Me)?(E(le.current),L.current.delete(Me)):(de(),t.current?.setDraft(fe)),{type:"aborted"}}throw ce},Ke=async()=>{m(le.current,vt.Sending);try{if(!a.transport.sendMultiUserMessage)throw new Error("Multi-user chat requires a transport that supports sendMultiUserMessage");const ce=await a.transport.sendMultiUserMessage(Ge);return p(ce.chat),ee&&(f(le.current,ce.chat.id),le.current=ce.chat.id,C.current=ce.chat.id,h(ce.chat.id)),_(ce.chat.id,[ce.message]),m(ce.chat.id,Di(ce.chat.status)),de(),{type:"success"}}catch(ce){return Ze(ce)}},He=async()=>{let ce=`pending-${Date.now()}`,Me="",ye;m(le.current,vt.Streaming),v(le.current,{id:ce,content:"",reasoning:"",toolCalls:[],attachments:[],chat:s||"",role:exports.MessageRole.Assistant,createdAt:new Date().toISOString()});try{let Pe=s;const q=ne=>{if(ne.type===exports.StreamChunkType.Chat&&ne.chat){p(ne.chat),Pe=ne.chat.id,ee&&(C.current=ne.chat.id,f(le.current,ne.chat.id),le.current=ne.chat.id,h(ne.chat.id));return}if(ne.type===exports.StreamChunkType.Reasoning&&ne.reasoning){Me+=ne.reasoning,ye={...ye??{id:ce,chat:Pe,role:exports.MessageRole.Assistant,content:"",createdAt:new Date().toISOString()},reasoning:Me},v(le.current,ye);return}if(ne.type===exports.StreamChunkType.Error&&ne.error)throw new Error(ne.error);if(ne.message&&ne.message.role===exports.MessageRole.User){_(ne.message.chat,[ne.message]);return}ne.message&&(ce=ne.message.id,ye={...ne.message,reasoning:Me||ne.message.reasoning},v(le.current,ye)),ne.done&&(ye&&_(le.current,[ye]),m(le.current,vt.Idle),de())},Z=await a.transport.streamMessage(Ge,q,{streamKey:C.current});if(Z){const ne=Z.messages.map(Le=>ye&&Le.id===ye.id&&Le.role===exports.MessageRole.Assistant?{...Le,reasoning:Me}:Le);_(Z.id,ne);const pe=a.store.getState();return(pe.activeChatId??pe.draftChatKey)===le.current&&h(Z.id),de(),{type:"success"}}return de(),{type:"success"}}catch(Pe){return Ze(Pe)}};try{const ce=await(n?Ke():He());return ce.type==="success"&&(D.current=!1),ce}catch(ce){de();const Me=ce?.chat;Me&&(p(Me),h(Me.id));const ye=ce instanceof Error?ce:new Error("Failed to send message");return g(le.current,ye.message||"Failed to send message"),m(le.current,vt.Idle),t.current?.setDraft(fe),D.current=!1,{type:"error",error:ye}}finally{P.current=!1,n||m(le.current,vt.Idle),C.current=void 0}},[s,o,i.model,n,r,a.transport,a.config.user?.displayName,a.config.user?.avatarUrl,a.config.user?.id,p,h,v,m,X,e,f,t,g]),K=V.useCallback(async()=>{if(d!==vt.Idle||P.current||!u.length||D.current)return;const j=u[0];P.current=!0,w(G,j.id);try{await J(j.content,j.attachments)}finally{P.current=!1}},[d,u,G,J,w]);V.useEffect(()=>{K()},[K]);const R=V.useCallback(async j=>{if(P.current)return;const A=u.find(Y=>Y.id===j);if(A){D.current=!1,P.current=!0,w(G,j);try{await J(A.content,A.attachments)}finally{P.current=!1}}},[u,G,w,J]),U=V.useCallback(async j=>{const Y=t.current.getDraft().attachments;if(!n&&d!==vt.Idle){k(G,j,Y),t.current?.clearDraft();return}D.current=!1,t.current?.clearDraft(),await J(j,Y)},[d,n,k,G,J,t,x,S]),H=V.useCallback(()=>{D.current=!0;const j=C.current??G;L.current.add(j),a.transport.cancelStream?.(j),E(j),m(j,vt.Idle)},[G,a.transport,E,m]),z=V.useCallback(async j=>{d===vt.Streaming&&H(),await R(j)},[d,H,R]);return{pendingKey:G,queuedMessages:u,activeChatStatus:n?vt.Idle:d,activeChatId:s,removeQueuedMessage:w,handleSubmit:U,handleStop:H,handleQueuedClick:z}},S_e=(e,t)=>{const n=JSON.stringify(t.metadata?.data);let r;for(let a=e.length-1;a>=0;a--){const o=e[a].attachments?.find(F3);if(o){r=o;break}}return!r||r.url!==t.url?!1:JSON.stringify(r.metadata?.data)===n},F3=e=>e.type===exports.AgentAttachmentType.Context&&e.metadata?.kind==="pageContext",N_e=e=>{const t=e.matchAll(/(^|[\s([{])@([a-zA-Z0-9_.-]+)/g),n=new Set,r=[];for(const a of t){const i=a[2],o=i.toLowerCase();n.has(o)||(n.add(o),r.push({type:o==="agent"?"agent":"user",name:i}))}return r.length>0?r:void 0},A_e=({queuedMessages:e,onSendQueued:t,onRemoveQueued:n})=>e.length?N.jsxs("div",{className:"mp-agent-composer-queue",children:[N.jsx("div",{className:"mp-agent-composer-queue-header",children:N.jsxs("span",{children:[e.length," message",e.length>1?"s":""," queued"]})}),N.jsx("div",{className:"mp-agent-composer-queue-items",children:e.map(r=>N.jsxs("div",{className:"mp-agent-composer-queue-item",children:[N.jsxs("span",{className:"mp-agent-composer-queue-item-text",children:[r.content,r.attachments?.length?N.jsxs("span",{style:{marginLeft:8,opacity:.7,display:"inline-flex",alignItems:"center",gap:4},children:[N.jsx(Qi,{size:12}),r.attachments.length]}):null]}),N.jsxs("div",{className:"mp-agent-composer-queue-item-actions",children:[N.jsx("button",{type:"button",className:"mp-agent-composer-queue-button",onClick:()=>t(r.id),"aria-label":"Send queued message",children:N.jsx(Dd,{size:12})}),N.jsx("button",{type:"button",className:"mp-agent-composer-queue-button",onClick:()=>n(r.id),"aria-label":"Remove queued message",children:N.jsx(v5,{size:12})})]})]},r.id))})]}):null;function T_e(e,t){return e.size>t.maxFileSize?{type:"size",message:`File "${e.name}" exceeds maximum size of ${up(t.maxFileSize)}`,fileName:e.name}:null}function C_e(e,t,n){if(e.length+t.filter(s=>s.type==="file").length>n.maxFilesPerMessage)return{type:"count",message:`Maximum ${n.maxFilesPerMessage} files per message allowed`};for(const s of e){const l=T_e(s,n);if(l)return l}const a=t.filter(s=>s.type==="file").reduce((s,l)=>{const u=l.metadata?.size||l.size||0;return s+u},0),i=e.reduce((s,l)=>s+l.size,0);return a+i>n.maxTotalAttachmentsSize?{type:"totalSize",message:`Total attachment size exceeds maximum of ${up(n.maxTotalAttachmentsSize)}`}:null}function up(e){if(e===0)return"0 Bytes";const t=1024,n=["Bytes","KB","MB","GB"],r=Math.floor(Math.log(e)/Math.log(t));return Math.round(e/Math.pow(t,r)*100)/100+" "+n[r]}function R_e(){return{maxFileSize:10*1024*1024,maxTotalAttachmentsSize:50*1024*1024,maxFilesPerMessage:10,allowedMimeTypes:void 0}}const P3=(e,t)=>{switch(e.type){case exports.AgentAttachmentType.Link:return N.jsx(g5,{size:12});case exports.AgentAttachmentType.Artifact:return N.jsx(Qi,{size:12});case exports.AgentAttachmentType.Context:{const n=e?.metadata?.kind;if(n&&t?.[n])return t[n];switch(n){case"pageContext":return N.jsx($d,{size:12});case"formSnapshot":case"formField":return N.jsx(f5,{size:12});default:return N.jsx(Fd,{size:12})}}case exports.AgentAttachmentType.File:default:return N.jsx(m5,{size:12})}},I_e=({attachments:e})=>{const{config:t}=$e();return!e||e.length===0?null:N.jsx("div",{className:"mp-agent-message-attachments","aria-label":"Message attachments",children:e.map((n,r)=>{const a=N.jsxs(N.Fragment,{children:[N.jsx("span",{className:"mp-agent-message-attachment-icon",children:P3(n,t.contextAttachmentIcons)}),N.jsx("span",{className:"mp-agent-message-attachment-name",children:n.name})]});return n.url?N.jsx("a",{className:"mp-agent-message-attachment",href:n.url,target:"_blank",rel:"noreferrer",title:n.url,children:a},n.id||r):N.jsx("span",{className:"mp-agent-message-attachment",title:n.mimeType??n.name,children:a},n.id||r)})})},O_e=({attachments:e,onRemove:t,uploadProgress:n,uploadErrors:r})=>{const a=Wt(),{config:i}=$e();return!e||e.length===0?null:N.jsx("div",{className:"mp-agent-composer-attachments","aria-label":a.attachments,children:e.map(o=>{const s=n?.get(o.id),l=r?.get(o.name),u=o.metadata?.size||o.size,d=u?` (${up(u)})`:"";return N.jsxs("span",{className:`mp-agent-attachment-chip ${l?"mp-agent-attachment-chip-error":""} ${s?.status==="uploading"?"mp-agent-attachment-chip-uploading":""}`,title:l||o.name,children:[N.jsx("span",{className:"mp-agent-attachment-chip-icon",children:P3(o,i.contextAttachmentIcons)}),N.jsxs("span",{className:"mp-agent-attachment-chip-name",title:o.name,children:[o.name,d]}),s?.status==="uploading"&&N.jsxs("span",{className:"mp-agent-attachment-chip-progress",children:[s.progress,"%"]}),l&&N.jsx("span",{className:"mp-agent-attachment-chip-error-text",title:l,children:"⚠"}),t?N.jsx(nn,{size:"sm",icon:"X",type:"button",onClick:p=>{p.preventDefault(),p.stopPropagation(),t(o.id)},"aria-label":`Remove attachment ${o.name}`}):null]},o.id)})})},L_e=e=>{const t=e.trim();if(!t||/\s/.test(t))return;const n=i=>i.replace(/[)\].,;:!?]+$/,"");if(!/^https?:\/\//i.test(t))return;const r=i=>{try{const o=new URL(i);return o.protocol!=="http:"&&o.protocol!=="https:"?void 0:o.toString()}catch{return}},a=n(t);return r(a)},D_e=e=>{try{const t=new URL(e);return t.hostname+(t.pathname&&t.pathname!=="/"?t.pathname:"")}catch{return e}},od="mp-agent:locationchange",f2="__mp_agent_history_patched__",g2=()=>{try{window.dispatchEvent(new Event(od))}catch{}},z_e=()=>{if(typeof window>"u")return;const e=window;if(!e[f2]){e[f2]=!0;try{const t=history.pushState;history.pushState=function(...n){const r=t.apply(this,n);return g2(),r}}catch{}try{const t=history.replaceState;history.replaceState=function(...n){const r=t.apply(this,n);return g2(),r}}catch{}}},$_e=e=>{if(typeof window>"u")return()=>{};z_e();const t=()=>e();return window.addEventListener("popstate",t),window.addEventListener("hashchange",t),window.addEventListener(od,t),()=>{window.removeEventListener("popstate",t),window.removeEventListener("hashchange",t),window.removeEventListener(od,t)}};async function F_e(e,t,n,r){const a=await fetch(r.presignedUrlEndpoint,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...r.getAuthHeaders?.()||{}},body:JSON.stringify({filename:e.name,mimeType:e.type||"application/octet-stream",size:e.size,chatId:t,userId:n})});if(!a.ok){const o=await a.text();throw new Error(`Failed to get presigned URL: ${a.status} ${o}`)}const i=await a.json();return{url:i.url,key:i.key}}async function P_e(e,t,n){return new Promise((r,a)=>{const i=new XMLHttpRequest;i.upload.addEventListener("progress",o=>{if(o.lengthComputable&&n){const s=Math.round(o.loaded/o.total*100);n(s)}}),i.addEventListener("load",()=>{i.status>=200&&i.status<300?r():a(new Error(`Upload failed: ${i.status} ${i.statusText}`))}),i.addEventListener("error",()=>{a(new Error("Upload failed: network error"))}),i.addEventListener("abort",()=>{a(new Error("Upload aborted"))}),i.open("PUT",t),i.setRequestHeader("Content-Type",e.type||"application/octet-stream"),i.send(e)})}async function q_e(e,t,n){const r=_t.nanoid(),a={fileId:r,fileName:e.name,progress:0,status:"pending"};try{n.onProgress?.({...a,status:"uploading",progress:0});const{url:i,key:o}=await F_e(e,n.chatId,n.userId,t);return await P_e(e,i,s=>{n.onProgress?.({...a,status:"uploading",progress:s})}),n.onProgress?.({...a,status:"completed",progress:100}),{id:r,type:exports.AgentAttachmentType.File,name:e.name,mimeType:e.type||void 0,size:e.size,metadata:{uploadedAt:new Date().toISOString(),s3Key:o,processingStatus:"pending",size:e.size,lastModified:e.lastModified}}}catch(i){const o=i instanceof Error?i.message:"Unknown error";throw n.onProgress?.({...a,status:"error",error:o}),i}}async function B_e(e,t,n){const r=await Promise.allSettled(e.map(o=>q_e(o,t,n))),a=[],i=[];if(r.forEach((o,s)=>{o.status==="fulfilled"?a.push(o.value):i.push(new Error(`Failed to process ${e[s].name}: ${o.reason}`))}),i.length>0&&a.length===0)throw i[0];return i.length>0&&console.warn("Some files failed to upload:",i),a}const U_e=({options:e,value:t,onChange:n,placeholder:r="Select...",disabled:a=!1,className:i="",triggerClassName:o="",placement:s="bottom-start",searchable:l=!1,searchPlaceholder:u="Search...",searchFilter:d})=>{const[p,m]=V.useState(!1),[h,g]=V.useState(null),[f,w]=V.useState(""),v=V.useRef([]),k=V.useRef(null),{refs:_,floatingStyles:E,context:S,isPositioned:x}=Zd({open:p,onOpenChange:m,placement:s,strategy:"absolute",whileElementsMounted:jd,middleware:[Vd(8),Wd({fallbackPlacements:["top-start","bottom-start","top-end","bottom-end"]}),Gd({padding:8})]}),D=Y5(S,{enabled:!a}),P=Yd(S),C=Qd(S),G=a7e(S,{listRef:v,activeIndex:h,onNavigate:g,enabled:p&&!l,virtual:!1}),{getReferenceProps:X,getFloatingProps:J,getItemProps:K}=Xd(l?[D,P,C]:[D,P,C,G]),R=e.findIndex(Y=>Y.value===t),U=R>=0?e[R]:void 0,H=V.useMemo(()=>{const Y=f.trim().toLowerCase();if(!l||!Y)return e;const O=d?le=>d(le,Y):le=>`${le.label} ${le.description??""}`.toLowerCase().includes(Y);return e.filter(O)},[e,f,l,d]);V.useEffect(()=>{if(!p){g(null),w("");return}l&&setTimeout(()=>k.current?.focus(),0);const Y=H.findIndex(ee=>ee.value===t);g(Y>=0?Y:0)},[p,l,t,H]),V.useEffect(()=>{p&&g(H.length>0?0:null)},[f,H.length,p]);const z=Y=>H.length===0?null:Y<0?H.length-1:Y>=H.length?0:Y,j=Y=>{Y!=null&&v.current[Y]?.scrollIntoView({block:"nearest"})},A=Y=>{n(Y),m(!1),g(null),w("")};return N.jsxs("div",{className:`mp-agent-dropdown ${i}`,children:[N.jsxs("button",{ref:_.setReference,type:"button",className:`mp-agent-dropdown-trigger ${o}`,disabled:a,"aria-expanded":p,"aria-haspopup":"listbox",...X(),children:[N.jsx("span",{className:"mp-agent-dropdown-trigger-content",children:U?N.jsxs(N.Fragment,{children:[U.icon&&N.jsx("span",{className:"mp-agent-dropdown-trigger-icon",children:U.icon}),N.jsx("span",{className:"mp-agent-dropdown-trigger-label",children:U.label})]}):N.jsx("span",{className:"mp-agent-dropdown-trigger-placeholder",children:r})}),N.jsx(zd,{size:16,className:`mp-agent-dropdown-chevron ${p?"open":""}`})]}),p&&N.jsxs("div",{role:"listbox",ref:_.setFloating,style:{...E,opacity:x?1:0,pointerEvents:x?"auto":"none",transition:x?"opacity 0.15s ease-out":"none"},className:"mp-agent-dropdown-menu",...J(),children:[l&&N.jsx("div",{className:"mp-agent-dropdown-search",onKeyDown:Y=>Y.stopPropagation(),children:N.jsx("input",{ref:k,className:"mp-agent-dropdown-search-input",value:f,placeholder:u,onChange:Y=>w(Y.target.value),onKeyDown:Y=>{if(Y.key==="Escape"){Y.preventDefault(),m(!1),w("");return}if(Y.key==="ArrowDown"||Y.key==="ArrowUp"){Y.preventDefault();const ee=Y.key==="ArrowDown"?1:-1,O=h??(ee>0?-1:0),le=z(O+ee);g(le),j(le);return}if(Y.key==="Enter"){if(h==null)return;const ee=H[h];if(!ee)return;Y.preventDefault(),A(ee.value)}}})}),N.jsxs("div",{className:"mp-agent-dropdown-list",children:[H.map((Y,ee)=>N.jsxs("button",{ref:O=>{v.current[ee]=O},type:"button",className:`mp-agent-dropdown-item ${t===Y.value?"selected":""} ${h===ee?"active":""}`,role:"option","aria-selected":t===Y.value,...K({onClick:()=>A(Y.value),onMouseEnter:()=>{g(ee)},onKeyDown:O=>{(O.key==="Enter"||O.key===" ")&&(O.preventDefault(),A(Y.value))}}),children:[Y.icon&&N.jsx("span",{className:"mp-agent-dropdown-item-icon",children:Y.icon}),N.jsxs("span",{className:"mp-agent-dropdown-item-content",children:[N.jsx("span",{className:"mp-agent-dropdown-item-label",children:Y.label}),Y.description&&N.jsx("span",{className:"mp-agent-dropdown-item-description",children:Y.description})]})]},Y.value)),l&&H.length===0&&N.jsx("div",{className:"mp-agent-dropdown-empty","aria-label":"No results",children:"No results"})]})]})]})},H_e=V.memo(()=>{const e=$e(),t=be(p=>p.composer),n=be(p=>p.contextKey),r=be(p=>p.setComposerOptions),a=e.config.models,{data:i,isLoading:o}=a3(),s=V.useMemo(()=>{const p=i&&i.length>0?i:a;return w3(p,e.config.transport).filter(h=>!h.contexts?.length||h.contexts.includes(n))},[i,a,e.config.transport,n]),l=V.useMemo(()=>{const p=s.slice().sort((m,h)=>m.label.localeCompare(h.label,void 0,{sensitivity:"base"})).map(m=>({value:m.id,label:m.label}));return[{value:ta,label:"Auto"},...p]},[s]),u=V.useMemo(()=>t.model!==void 0?t.model:ta,[t.model]),d=V.useCallback(p=>{p===ta?(r({model:void 0}),c2(e.config.transport,ta)):(r({model:p}),c2(e.config.transport,p))},[r,e.config.transport]);return o&&!a?.length||l.length===0?null:N.jsx(U_e,{options:l,value:u,onChange:d,placeholder:"Select model...",searchable:!0,searchPlaceholder:"Search models...",placement:"top-start",triggerClassName:"mp-agent-model-selector-trigger"})}),j_e=e=>{if(!e)return"";let t=e.replace(/[_-]+/g," ");return t=t.replace(/([a-z0-9])([A-Z])/g,"$1 $2"),t=t.trim().replace(/\s+/g," "),t?t.charAt(0).toUpperCase()+t.slice(1):""},V_e=({checked:e,disabled:t,onChange:n,className:r="",...a})=>{const i=o=>{o.preventDefault(),!t&&n(!e)};return N.jsx("button",{type:"button",role:"switch","aria-checked":e,disabled:t,className:`mp-agent-switch ${e?"on":"off"} ${r}`.trim(),onClick:i,...a,children:N.jsx("span",{className:"mp-agent-switch-thumb"})})},y2=e=>e.reduce((t,n)=>(t[n.agentName]={...n.tools},t),{}),q3=({preferences:e,disabled:t})=>{const n=Wt(),{upsertSingle:r}=u3(),[a,i]=V.useState(()=>y2(e)),[o,s]=V.useState({});V.useEffect(()=>{i(y2(e))},[e]);const l=r.error?.message,u=V.useMemo(()=>e.some(p=>Object.keys(p.tools).length>0),[e]),d=(p,m,h)=>{i(g=>{const f=g[p]??{},w=f,v={...f,[m]:h},k={...g,[p]:v};return s(_=>({..._,[p]:{..._[p]??{},[m]:!0}})),r.mutate({agentName:p,input:{tools:v}},{onError:()=>{i(_=>({..._,[p]:w}))},onSettled:()=>{s(_=>{const E={..._[p]??{}};if(delete E[m],Object.keys(E).length===0){const{[p]:S,...x}=_;return x}return{..._,[p]:E}})}}),k})};return N.jsxs("div",{className:"mp-agent-preferences-panel",children:[!u&&N.jsx("div",{className:"mp-agent-preferences-empty",children:n.agentSettingsNoConfigurableTools}),e.map(p=>{const m=a[p.agentName]??{},h=Object.entries(m);return N.jsxs("div",{className:"mp-agent-preferences-agent",children:[N.jsx("div",{className:"mp-agent-preferences-agent-header",children:N.jsx("strong",{children:p.agentName})}),h.length===0?N.jsx("div",{className:"mp-agent-preferences-empty",children:n.agentSettingsNoToolsForAgent}):N.jsx("div",{className:"mp-agent-preferences-tools",children:h.map(([g,f])=>{const w=!!o[p.agentName]?.[g];return N.jsxs("label",{className:"mp-agent-preferences-tool",children:[N.jsx("span",{className:"mp-agent-preferences-tool-label",children:j_e(g)}),N.jsx(V_e,{checked:f,onChange:v=>d(p.agentName,g,v),disabled:!!t||w})]},`${p.agentName}:${g}`)})})]},p.agentName)}),l&&N.jsx("div",{className:"mp-agent-preferences-error",children:l})]})};function G_e(e){return e.map(t=>{const n=(t.tools??[]).reduce((r,a)=>(a.userConfigurable&&(r[a.title]=!a.disabledByDefault),r),{});return{agentName:t.name,tools:n}})}const W_e=()=>{const e=Wt(),t=$e(),n=be(l=>l.contextKey),{data:r,isLoading:a,isError:i}=s3(n),o=V.useMemo(()=>G_e(r??[]),[r]),s=!!t.transport.upsertAgentPreferences&&!!t.transport.upsertAgentPreferencesBatch;return a?N.jsx(N.Fragment,{children:e.agentSettingsLoading}):i?N.jsx(N.Fragment,{children:e.agentSettingsError}):N.jsx(q3,{preferences:o,disabled:!s})},K_e=()=>{const[e,t]=V.useState(!1),n=Wt(),{refs:r,floatingStyles:a,context:i,isPositioned:o}=Zd({open:e,onOpenChange:t,placement:"top-start",strategy:"absolute",whileElementsMounted:jd,middleware:[Vd(8),Wd({fallbackPlacements:["bottom-start","top-end","bottom-end"]}),Gd({padding:8})]}),s=Y5(i),l=Yd(i),u=Qd(i),{getReferenceProps:d,getFloatingProps:p}=Xd([s,l,u]);return N.jsxs("div",{className:"mp-agent-tool-config-dropdown",children:[N.jsx(bn,{content:n.agentSettingsTooltip,children:N.jsx("button",{ref:r.setReference,type:"button",className:"mp-agent-composer-button mp-agent-composer-tool-button","aria-label":n.agentSettingsTooltip,...d(),children:N.jsx(y5,{size:16})})}),e&&N.jsx("div",{ref:r.setFloating,style:{...a,opacity:o?1:0,pointerEvents:o?"auto":"none",transition:o?"opacity 0.15s ease-out":"none"},className:"mp-agent-tool-config-panel",...p(),children:N.jsx(W_e,{})})]})},Y_e=V.forwardRef(({autoFocus:e,activeChatId:t,status:n,onStop:r,onSubmit:a},i)=>{const o=Wt(),s=$e(),l=V.useRef(null),u=V.useRef(null),d=be(ae=>ae.activeChatId??ae.draftChatKey),p=be(ae=>ze(ae,d).composerDraft),m=be(ae=>ze(ae,d).composerError),h=be(ae=>ze(ae,d).pageContextDismissed),g=be(ae=>ae.setComposerValue),f=be(ae=>ae.setComposerDraft),w=be(ae=>ae.clearComposerDraft),v=be(ae=>ae.setComposerError),k=be(ae=>ae.addComposerAttachments),_=be(ae=>ae.removeComposerAttachment),E=be(ae=>ae.setPageContextDismissed),S=p.value,x=p.attachments,[D,P]=V.useState(new Map),[C,L]=V.useState(new Map),G=V.useRef(S),X=V.useRef(x),J=V.useRef(h),K=s.config.features?.pageContextAttachments!==!1,R=s.config.composerAttachmentActions,U=ae=>ae.type===exports.AgentAttachmentType.Context&&ae?.metadata?.kind==="pageContext",H=x.some(U),z=()=>{if(K)return s.buildPageContextAttachment()};V.useEffect(()=>{X.current=x},[x]),V.useEffect(()=>{G.current=S},[S]),V.useEffect(()=>{J.current=h},[h]),V.useEffect(()=>{if(!K||h||H)return;const ae=z();ae&&k(d,[ae])},[K,h,H,d,k]),V.useEffect(()=>{if(K&&!(typeof window>"u"))return $_e(()=>{if(J.current)return;const ae=X.current,Se=ae.find(U);if(!Se)return;const Be=z();if(!Be)return;const We={...Be,id:Se.id},Ae=ae.map(ve=>ve.id===Se.id?We:ve);f(d,{value:G.current,attachments:Ae})})},[K,d,f]),V.useImperativeHandle(i,()=>({setValue:ae=>{g(d,ae)},getDraft:()=>({value:S,attachments:x}),setDraft:ae=>{f(d,{value:ae.value,attachments:ae.attachments??[]})},clearDraft:()=>{w(d)},buildPageContextAttachment:()=>z()})),V.useEffect(()=>{const ae=l.current;ae&&(ae.style.height="auto",ae.style.height=`${Math.min(ae.scrollHeight,200)}px`)},[S]);const j=async ae=>{if(!ae||ae.length===0)return;const Se=Array.from(ae),Be=R_e(),We=C_e(Se,x,Be);if(We){L(Ae=>{const ve=new Map(Ae);return Se.forEach(Ge=>{ve.set(Ge.name,We.message)}),ve});return}L(Ae=>{const ve=new Map(Ae);return Se.forEach(Ge=>ve.delete(Ge.name)),ve});try{const Ae=s.config.transport;if(Ae.mode!=="proxy")throw new Error("File uploads are only supported with proxy transport");const ve={presignedUrlEndpoint:`${Ae.baseUrl}/files/upload/presigned`,getAuthHeaders:()=>{const de={};return Ae.headers?Ae.headers:(Ae.apiKey&&(de.Authorization=`Bearer ${Ae.apiKey}`),de)}},Ge=await B_e(Se,ve,{chatId:t,userId:s.config.user?.id,onProgress:de=>{P(Ze=>{const Ke=new Map(Ze);return Ke.set(de.fileId,de),Ke})}});k(d,Ge),setTimeout(()=>{P(de=>{const Ze=new Map(de);return Ge.forEach(Ke=>Ze.delete(Ke.id)),Ze})},2e3)}catch(Ae){const ve=Ae instanceof Error?Ae.message:"Failed to upload files";L(Ge=>{const de=new Map(Ge);return Se.forEach(Ze=>{de.set(Ze.name,ve)}),de})}},A=()=>{u.current?.click()},Y=ae=>{const Se=L_e(ae);if(!Se)return!1;if(x.some(Ae=>Ae.type===exports.AgentAttachmentType.Link&&Ae.url===Se))return!0;const Be=D_e(Se),We={id:_t.nanoid(),url:Se,name:Be,type:exports.AgentAttachmentType.Link};return k(d,[We]),!0},ee=async ae=>{await j(ae.target.files),ae.target.value=""},O=ae=>{const Se=x.find(Be=>Be.id===ae);Se&&U(Se)&&E(d,!0),_(d,ae)},le=()=>{if(typeof window>"u"||typeof document>"u")return!1;const ae=f3(),Se=ae?.selectedText??window.getSelection?.()?.toString()?.trim()??"";if(!Se)return!1;const Be=window.location?.href,We=Se.slice(0,20),Ae=Se.length>20?We+"...":Se,ve=po({kind:"webSnippet",url:Be,title:Ae,selectedText:Se,source:{app:"browser",url:Be},...ae?.target?{target:ae.target}:{}});return k(d,[ve]),!0},fe=ae=>{ae.preventDefault();const Se=S.trim();Se&&(v(d,void 0),a(Se))},ke=ae=>{ae.key==="Enter"&&!ae.shiftKey&&(ae.preventDefault(),fe(ae))},Ce=ae=>{m&&v(d,void 0),g(d,ae.target.value)},Fe=ae=>{if(ae.nativeEvent.shiftKey)return;const Se=ae.clipboardData?.getData("text/plain")??"";if(!Se)return;Y(Se)&&ae.preventDefault()},Ve=!!S.trim();return N.jsxs(N.Fragment,{children:[N.jsxs("form",{onSubmit:fe,className:"mp-agent-composer-input-wrapper",id:"composer-form",children:[N.jsx("input",{ref:u,type:"file",multiple:!0,style:{display:"none"},onChange:ee}),N.jsx(O_e,{attachments:x,onRemove:O,uploadProgress:D,uploadErrors:C}),N.jsx("textarea",{rows:2,name:"message",ref:l,value:S,autoFocus:e,className:"mp-agent-composer-textarea",placeholder:t?o.followUp:o.newChat,onChange:Ce,onKeyDown:ke,onPaste:Fe})]}),N.jsxs("div",{className:"mp-agent-composer-actions",children:[N.jsxs("div",{className:"mp-agent-composer-actions-left",children:[s.config.features?.modelSwitching&&N.jsx(H_e,{}),s.config.features?.toolConfiguration&&N.jsx(K_e,{}),s.config.features?.fileAttachments&&N.jsx(bn,{content:o.attachFiles,children:N.jsx("button",{type:"button",className:"mp-agent-composer-button mp-agent-composer-tool-button",onClick:A,"aria-label":o.attachFiles,children:N.jsx(Qi,{size:16})})}),s.config.features?.selectionAttachments&&N.jsx(bn,{content:o.attachSelectionToContext,children:N.jsx("button",{type:"button",className:"mp-agent-composer-button mp-agent-composer-tool-button",onClick:()=>{le()},"aria-label":o.attachSelectionToContext,children:N.jsx(Fd,{size:16})})}),K&&!H&&N.jsx(bn,{content:"Attach page context",children:N.jsx("button",{type:"button",className:"mp-agent-composer-button mp-agent-composer-tool-button",onClick:()=>{E(d,!1);const ae=z();ae&&k(d,[ae])},"aria-label":"Attach page context",children:N.jsx($d,{size:16})})}),R&&N.jsx(R,{chatKey:d,activeChatId:t,attachments:x,addAttachments:ae=>k(d,ae),removeAttachment:O})]}),N.jsx("div",{className:"mp-agent-composer-actions-right",children:n===vt.Streaming&&!Ve?N.jsx(bn,{content:o.stopStreaming,children:N.jsx("button",{type:"button",onClick:r,"aria-label":o.stopStreaming,className:"mp-agent-composer-button mp-agent-composer-send-button",children:N.jsx(k5,{size:12})})}):N.jsx(bn,{content:Ve?o.sendMessage:o.typeMessageToSend,children:N.jsx("button",{type:"submit",form:"composer-form",disabled:!Ve,"aria-label":o.sendMessage,className:"mp-agent-composer-button mp-agent-composer-send-button",children:N.jsx(Dd,{size:16})})})})]})]})}),B3=({autoFocus:e,multiUser:t=!1,participantIds:n})=>{const r=V.useRef({setValue:()=>{},getDraft:()=>({value:"",attachments:[]}),setDraft:()=>{},clearDraft:()=>{}}),{pendingKey:a,queuedMessages:i,activeChatStatus:o,activeChatId:s,handleSubmit:l,handleStop:u,handleQueuedClick:d,removeQueuedMessage:p}=M_e({composerFormRef:r,multiUser:t,participantIds:n});return N.jsx("div",{className:"mp-agent-composer-wrapper",children:N.jsxs("div",{className:"mp-agent-composer",children:[N.jsx(A_e,{queuedMessages:i,onSendQueued:d,onRemoveQueued:m=>p(a,m)}),N.jsx(Y_e,{status:o,ref:r,autoFocus:e,activeChatId:s,onStop:u,onSubmit:l})]})})};function xr(e,t,n){let r=n.initialDeps??[],a,i=!0;function o(){var s,l,u;let d;n.key&&((s=n.debug)!=null&&s.call(n))&&(d=Date.now());const p=e();if(!(p.length!==r.length||p.some((g,f)=>r[f]!==g)))return a;r=p;let h;if(n.key&&((l=n.debug)!=null&&l.call(n))&&(h=Date.now()),a=t(...p),n.key&&((u=n.debug)!=null&&u.call(n))){const g=Math.round((Date.now()-d)*100)/100,f=Math.round((Date.now()-h)*100)/100,w=f/16,v=(k,_)=>{for(k=String(k);k.length<_;)k=" "+k;return k};console.info(`%c⏱ ${v(f,5)} /${v(g,5)} ms`,`
|