@multiplayer-app/ai-agent-react 0.4.28 → 0.4.30

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.
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const U=require("zod"),w=require("react/jsx-runtime"),H=require("react"),xt=require("@tanstack/react-query"),d5=require("zustand"),vt=require("nanoid"),p5=require("react-dom");function h5(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=h5(H),m5=h5(p5);class nd extends Error{constructor(t,n){super(t),this.statusCode=n,this.name="HttpError"}}const f5=U.z.object({background:U.z.string(),surface:U.z.string(),text:U.z.string(),subtext:U.z.string(),border:U.z.string(),accent:U.z.string(),accentSoft:U.z.string(),warning:U.z.string(),danger:U.z.string(),fontFamily:U.z.string(),radius:U.z.string(),fontSize:U.z.string(),colorMode:U.z.enum(["light","dark"])}),g5=U.z.object({key:U.z.string(),label:U.z.string(),description:U.z.string().optional(),tools:U.z.array(U.z.string()).default([]),defaultModel:U.z.string().optional(),autoConfirmTools:U.z.array(U.z.string()).optional()}),rd=U.z.object({appId:U.z.string(),workspaceId:U.z.string().optional(),debug:U.z.boolean().optional(),user:U.z.object({id:U.z.string(),displayName:U.z.string().optional(),email:U.z.string().optional(),avatarUrl:U.z.string().optional()}).optional(),contextKeys:U.z.array(g5),transport:U.z.union([U.z.object({mode:U.z.literal("proxy"),baseUrl:U.z.string(),apiKey:U.z.string().optional(),socketPath:U.z.string().optional(),socketNamespace:U.z.string().optional(),timeoutMs:U.z.number().optional(),headers:U.z.record(U.z.string()).optional()}),U.z.object({mode:U.z.literal("direct"),provider:U.z.enum(["openrouter","openai","custom"]),endpoint:U.z.string().optional(),apiKey:U.z.string().optional(),model:U.z.string().optional(),titleGenerationModel:U.z.string().optional(),timeoutMs:U.z.number().optional(),headers:U.z.record(U.z.string()).optional()})]),theme:f5.partial().optional(),tools:U.z.array(U.z.object({name:U.z.string(),label:U.z.string(),description:U.z.string().optional(),icon:U.z.string().optional(),schema:U.z.record(U.z.any()).optional(),confirmation:U.z.enum(["auto","manual"]).optional(),category:U.z.string().optional()})).optional(),models:U.z.array(U.z.object({id:U.z.string(),label:U.z.string(),provider:U.z.string().optional(),reasoning:U.z.enum(["disabled","concise","deep"]).optional(),contexts:U.z.array(U.z.string()).optional()})).optional(),features:U.z.object({reasoning:U.z.boolean().optional(),artifactsPanel:U.z.boolean().optional(),modelSwitching:U.z.boolean().optional(),toolConfiguration:U.z.boolean().optional(),fileAttachments:U.z.boolean().optional(),selectionAttachments:U.z.boolean().optional(),multiAgentControl:U.z.boolean().optional(),sandboxControls:U.z.boolean().optional(),historySidebar:U.z.boolean().optional(),titleGeneration:U.z.enum(["local","llm"]).optional(),pageContextAttachments:U.z.boolean().optional()}).optional(),pageContext:U.z.object({includeUserAgent:U.z.boolean().optional(),includeReferrer:U.z.boolean().optional(),includeViewport:U.z.boolean().optional(),includeTitle:U.z.boolean().optional(),name:U.z.string().optional()}).optional(),chatMetadata:U.z.object({}).optional(),defaultContextKey:U.z.string().optional(),messagesPageSize:U.z.number().int().positive().max(200).optional(),translations:U.z.object({newChat:U.z.string().optional(),followUp:U.z.string().optional(),sendMessage:U.z.string().optional(),stopStreaming:U.z.string().optional(),typeMessageToSend:U.z.string().optional(),attachFiles:U.z.string().optional(),attachSelectionToContext:U.z.string().optional(),attachments:U.z.string().optional(),chats:U.z.string().optional(),multiUserChats:U.z.string().optional(),noMultiUserChats:U.z.string().optional(),noChatsYet:U.z.string().optional(),untitledChat:U.z.string().optional(),deleteChat:U.z.string().optional(),showChatHistory:U.z.string().optional(),hideChatHistory:U.z.string().optional(),fetchingChats:U.z.string().optional(),fetchingChatError:U.z.string().optional(),helloThere:U.z.string().optional(),howCanIHelpYou:U.z.string().optional()}).optional()}),Ri={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",imageGenerationFailed:"Image generation failed",imageGenerationGenerating:"Generating image…",imageGenerationNone:"No images were generated.",imageGenerationOpen:"Open full size",imageGenerationDownload:"Download image"},j7={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",e.IMAGE_GENERATION="image_generation"})(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.RESPONSE_DECISION="responseDecision",e.SUBAGENT="subagent"})(exports.ActivityOperationName||(exports.ActivityOperationName={}));exports.ActivitySourceType=void 0;(function(e){e.AGENT_MESSAGE="AgentMessage",e.CHAT="Chat",e.UNKNOWN="Unknown"})(exports.ActivitySourceType||(exports.ActivitySourceType={}));exports.AgentSessionKind=void 0;(function(e){e.ROOT="ROOT",e.SUBAGENT="SUBAGENT"})(exports.AgentSessionKind||(exports.AgentSessionKind={}));exports.AgentRunStatus=void 0;(function(e){e.Running="running",e.Delegating="delegating",e.Completed="completed",e.Failed="failed",e.Aborted="aborted"})(exports.AgentRunStatus||(exports.AgentRunStatus={}));var bi={ChatNew:"chat:new",MessageNew:"message:new",ChatUpdate:"chat:update",ChatSubscribe:"chat:subscribe",ChatUnsubscribe:"chat:unsubscribe"},Ii={Path:"/socket.io",UserRoomPrefix:"user:",DefaultUserId:"guest"},y5=["webSnippet","formSnapshot","formField"],V7=U.z.string().datetime({offset:!0}).or(U.z.string().datetime()),G7=U.z.object({app:U.z.string().min(1).optional(),url:U.z.string().url().optional(),route:U.z.string().min(1).optional(),domPath:U.z.string().min(1).optional()}).strict(),W7=U.z.object({containsPII:U.z.boolean().optional(),redactionsApplied:U.z.array(U.z.string().min(1)).max(50).optional()}).strict(),K7=U.z.union([U.z.object({type:U.z.literal("text"),exact:U.z.string().min(1).max(4e3),prefix:U.z.string().min(1).max(500).optional(),suffix:U.z.string().min(1).max(500).optional(),domPath:U.z.string().min(1).max(2e3).optional(),startOffset:U.z.number().int().min(0).optional(),endOffset:U.z.number().int().min(0).optional()}).strict(),U.z.object({type:U.z.literal("dom"),domPath:U.z.string().min(1).max(2e3)}).strict(),U.z.object({type:U.z.literal("form"),formId:U.z.string().min(1).max(200).optional(),fieldName:U.z.string().min(1).max(200).optional(),domPath:U.z.string().min(1).max(2e3).optional()}).strict()]),no=U.z.object({schemaVersion:U.z.literal(1),kind:U.z.string().min(1).max(100),capturedAt:V7,source:G7.optional(),security:W7.optional(),target:K7.optional()}),Y7=no.extend({kind:U.z.literal("webSnippet"),title:U.z.string().min(1).max(200).optional(),selectedText:U.z.string().min(1).max(4e3)}).strict(),Z7=no.extend({kind:U.z.literal("formSnapshot"),formId:U.z.string().min(1).max(200).optional(),formName:U.z.string().min(1).max(200).optional(),fields:U.z.array(U.z.object({name:U.z.string().min(1).max(200),label:U.z.string().min(1).max(200).optional(),value:U.z.string().min(0).max(1e3),inputType:U.z.enum(["text","textarea","number","select","radio","checkbox","date","email","tel"]).optional(),options:U.z.array(U.z.object({value:U.z.string().min(0).max(500),label:U.z.string().min(0).max(500)}).strict()).max(200).optional(),domPath:U.z.string().min(1).max(2e3).optional()}).strict()).min(1).max(50)}).strict(),X7=no.extend({kind:U.z.literal("formField"),formId:U.z.string().min(1).max(200).optional(),fieldName:U.z.string().min(1).max(200),fieldLabel:U.z.string().min(1).max(200).optional(),value:U.z.string().min(0).max(1e3),inputType:U.z.enum(["text","textarea","number","select","radio","checkbox","date","email","tel"]).optional(),options:U.z.array(U.z.object({value:U.z.string().min(0).max(500),label:U.z.string().min(0).max(500)}).strict()).max(200).optional(),domPath:U.z.string().min(1).max(2e3).optional()}).strict(),Q7=no.extend({kind:U.z.string().min(1).max(100).refine(function(e){return!y5.includes(e)},"kind must not collide with built-in kinds"),title:U.z.string().min(1).max(200).optional(),summary:U.z.string().min(1).max(4e3).optional(),data:U.z.record(U.z.string().min(1).max(200),U.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"]})}}),b5=U.z.union([Y7,Z7,X7,Q7]),ja=U.z.object({id:U.z.string().min(1),type:U.z.nativeEnum(exports.AgentAttachmentType),name:U.z.string().min(1).max(500),url:U.z.string().url().optional(),mimeType:U.z.string().min(1).max(200).optional(),metadata:U.z.record(U.z.string(),U.z.unknown()).optional()}).strict(),k5=U.z.union([ja.extend({type:U.z.literal(exports.AgentAttachmentType.Context),metadata:b5}).strict(),ja.extend({type:U.z.literal(exports.AgentAttachmentType.File),size:U.z.number().int().min(0).optional(),metadata:U.z.object({uploadedAt:U.z.string().optional(),s3Key:U.z.string().optional(),processingStatus:U.z.enum(["pending","processed","failed"]).optional(),size:U.z.number().int().min(0).optional(),lastModified:U.z.number().optional()}).optional()}).strict(),ja.extend({type:U.z.literal(exports.AgentAttachmentType.Link)}).strict(),ja.extend({type:U.z.literal(exports.AgentAttachmentType.Artifact)}).strict()]),J7=U.z.object({chatId:U.z.string().optional(),content:U.z.string().min(1),contextKey:U.z.string().min(1),attachments:U.z.array(k5).optional(),metadata:U.z.record(U.z.string(),U.z.unknown()).optional(),model:U.z.string().optional(),temperature:U.z.number().optional(),userId:U.z.string().optional(),participantIds:U.z.array(U.z.string().min(1)).optional(),mentions:U.z.array(U.z.object({type:U.z.enum(["user","agent"]),name:U.z.string().min(1),id:U.z.string().optional()}).strict()).optional()}).strict();new TextEncoder;const e_=new TextDecoder,t_=3;class Lr{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 nd(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:f}=await this.formatHttpError("/chats/stream",l),g=new nd(m,f);throw this.config.onError?.(g),g}if(!l.body)throw new Error("Streaming response body missing");const u=l.body.getReader();let d="",p,h=!1;for(;;){const{value:m,done:f}=await u.read();if(f)break;d+=e_.decode(m,{stream:!0});const g=d.split(`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const U=require("zod"),w=require("react/jsx-runtime"),H=require("react"),xt=require("@tanstack/react-query"),d5=require("zustand"),vt=require("nanoid"),p5=require("react-dom");function h5(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=h5(H),m5=h5(p5);class nd extends Error{constructor(t,n){super(t),this.statusCode=n,this.name="HttpError"}}const f5=U.z.object({background:U.z.string(),surface:U.z.string(),text:U.z.string(),subtext:U.z.string(),border:U.z.string(),accent:U.z.string(),accentSoft:U.z.string(),warning:U.z.string(),danger:U.z.string(),fontFamily:U.z.string(),radius:U.z.string(),fontSize:U.z.string(),colorMode:U.z.enum(["light","dark"])}),g5=U.z.object({key:U.z.string(),label:U.z.string(),description:U.z.string().optional(),tools:U.z.array(U.z.string()).default([]),defaultModel:U.z.string().optional(),autoConfirmTools:U.z.array(U.z.string()).optional()}),rd=U.z.object({appId:U.z.string(),workspaceId:U.z.string().optional(),debug:U.z.boolean().optional(),user:U.z.object({id:U.z.string(),displayName:U.z.string().optional(),email:U.z.string().optional(),avatarUrl:U.z.string().optional()}).optional(),contextKeys:U.z.array(g5),transport:U.z.union([U.z.object({mode:U.z.literal("proxy"),baseUrl:U.z.string(),apiKey:U.z.string().optional(),socketPath:U.z.string().optional(),socketNamespace:U.z.string().optional(),timeoutMs:U.z.number().optional(),headers:U.z.record(U.z.string()).optional()}),U.z.object({mode:U.z.literal("direct"),provider:U.z.enum(["openrouter","openai","custom"]),endpoint:U.z.string().optional(),apiKey:U.z.string().optional(),model:U.z.string().optional(),titleGenerationModel:U.z.string().optional(),timeoutMs:U.z.number().optional(),headers:U.z.record(U.z.string()).optional()})]),theme:f5.partial().optional(),tools:U.z.array(U.z.object({name:U.z.string(),label:U.z.string(),description:U.z.string().optional(),icon:U.z.string().optional(),schema:U.z.record(U.z.any()).optional(),confirmation:U.z.enum(["auto","manual"]).optional(),category:U.z.string().optional()})).optional(),models:U.z.array(U.z.object({id:U.z.string(),label:U.z.string(),provider:U.z.string().optional(),reasoning:U.z.enum(["disabled","concise","deep"]).optional(),contexts:U.z.array(U.z.string()).optional()})).optional(),features:U.z.object({reasoning:U.z.boolean().optional(),artifactsPanel:U.z.boolean().optional(),modelSwitching:U.z.boolean().optional(),toolConfiguration:U.z.boolean().optional(),fileAttachments:U.z.boolean().optional(),selectionAttachments:U.z.boolean().optional(),multiAgentControl:U.z.boolean().optional(),sandboxControls:U.z.boolean().optional(),historySidebar:U.z.boolean().optional(),titleGeneration:U.z.enum(["local","llm"]).optional(),pageContextAttachments:U.z.boolean().optional()}).optional(),pageContext:U.z.object({includeUserAgent:U.z.boolean().optional(),includeReferrer:U.z.boolean().optional(),includeViewport:U.z.boolean().optional(),includeTitle:U.z.boolean().optional(),name:U.z.string().optional()}).optional(),chatMetadata:U.z.object({}).optional(),defaultContextKey:U.z.string().optional(),messagesPageSize:U.z.number().int().positive().max(200).optional(),translations:U.z.object({newChat:U.z.string().optional(),followUp:U.z.string().optional(),sendMessage:U.z.string().optional(),stopStreaming:U.z.string().optional(),typeMessageToSend:U.z.string().optional(),attachFiles:U.z.string().optional(),attachSelectionToContext:U.z.string().optional(),attachments:U.z.string().optional(),chats:U.z.string().optional(),multiUserChats:U.z.string().optional(),noMultiUserChats:U.z.string().optional(),noChatsYet:U.z.string().optional(),untitledChat:U.z.string().optional(),deleteChat:U.z.string().optional(),showChatHistory:U.z.string().optional(),hideChatHistory:U.z.string().optional(),fetchingChats:U.z.string().optional(),fetchingChatError:U.z.string().optional(),helloThere:U.z.string().optional(),howCanIHelpYou:U.z.string().optional()}).optional()}),Ri={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",imageGenerationFailed:"Image generation failed",imageGenerationGenerating:"Generating image…",imageGenerationNone:"No images were generated.",imageGenerationOpen:"Open full size",imageGenerationDownload:"Download image"},j7={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",e.IMAGE_GENERATION="image_generation"})(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.RESPONSE_DECISION="responseDecision",e.SUBAGENT="subagent",e.IMAGE_GENERATION="imageGeneration"})(exports.ActivityOperationName||(exports.ActivityOperationName={}));exports.ActivitySourceType=void 0;(function(e){e.AGENT_MESSAGE="AgentMessage",e.CHAT="Chat",e.UNKNOWN="Unknown"})(exports.ActivitySourceType||(exports.ActivitySourceType={}));exports.AgentSessionKind=void 0;(function(e){e.ROOT="ROOT",e.SUBAGENT="SUBAGENT"})(exports.AgentSessionKind||(exports.AgentSessionKind={}));exports.AgentRunStatus=void 0;(function(e){e.Running="running",e.Delegating="delegating",e.Completed="completed",e.Failed="failed",e.Aborted="aborted"})(exports.AgentRunStatus||(exports.AgentRunStatus={}));var bi={ChatNew:"chat:new",MessageNew:"message:new",ChatUpdate:"chat:update",ChatSubscribe:"chat:subscribe",ChatUnsubscribe:"chat:unsubscribe"},Ii={Path:"/socket.io",UserRoomPrefix:"user:",DefaultUserId:"guest"},y5=["webSnippet","formSnapshot","formField"],V7=U.z.string().datetime({offset:!0}).or(U.z.string().datetime()),G7=U.z.object({app:U.z.string().min(1).optional(),url:U.z.string().url().optional(),route:U.z.string().min(1).optional(),domPath:U.z.string().min(1).optional()}).strict(),W7=U.z.object({containsPII:U.z.boolean().optional(),redactionsApplied:U.z.array(U.z.string().min(1)).max(50).optional()}).strict(),K7=U.z.union([U.z.object({type:U.z.literal("text"),exact:U.z.string().min(1).max(4e3),prefix:U.z.string().min(1).max(500).optional(),suffix:U.z.string().min(1).max(500).optional(),domPath:U.z.string().min(1).max(2e3).optional(),startOffset:U.z.number().int().min(0).optional(),endOffset:U.z.number().int().min(0).optional()}).strict(),U.z.object({type:U.z.literal("dom"),domPath:U.z.string().min(1).max(2e3)}).strict(),U.z.object({type:U.z.literal("form"),formId:U.z.string().min(1).max(200).optional(),fieldName:U.z.string().min(1).max(200).optional(),domPath:U.z.string().min(1).max(2e3).optional()}).strict()]),no=U.z.object({schemaVersion:U.z.literal(1),kind:U.z.string().min(1).max(100),capturedAt:V7,source:G7.optional(),security:W7.optional(),target:K7.optional()}),Y7=no.extend({kind:U.z.literal("webSnippet"),title:U.z.string().min(1).max(200).optional(),selectedText:U.z.string().min(1).max(4e3)}).strict(),Z7=no.extend({kind:U.z.literal("formSnapshot"),formId:U.z.string().min(1).max(200).optional(),formName:U.z.string().min(1).max(200).optional(),fields:U.z.array(U.z.object({name:U.z.string().min(1).max(200),label:U.z.string().min(1).max(200).optional(),value:U.z.string().min(0).max(1e3),inputType:U.z.enum(["text","textarea","number","select","radio","checkbox","date","email","tel"]).optional(),options:U.z.array(U.z.object({value:U.z.string().min(0).max(500),label:U.z.string().min(0).max(500)}).strict()).max(200).optional(),domPath:U.z.string().min(1).max(2e3).optional()}).strict()).min(1).max(50)}).strict(),X7=no.extend({kind:U.z.literal("formField"),formId:U.z.string().min(1).max(200).optional(),fieldName:U.z.string().min(1).max(200),fieldLabel:U.z.string().min(1).max(200).optional(),value:U.z.string().min(0).max(1e3),inputType:U.z.enum(["text","textarea","number","select","radio","checkbox","date","email","tel"]).optional(),options:U.z.array(U.z.object({value:U.z.string().min(0).max(500),label:U.z.string().min(0).max(500)}).strict()).max(200).optional(),domPath:U.z.string().min(1).max(2e3).optional()}).strict(),Q7=no.extend({kind:U.z.string().min(1).max(100).refine(function(e){return!y5.includes(e)},"kind must not collide with built-in kinds"),title:U.z.string().min(1).max(200).optional(),summary:U.z.string().min(1).max(4e3).optional(),data:U.z.record(U.z.string().min(1).max(200),U.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"]})}}),b5=U.z.union([Y7,Z7,X7,Q7]),ja=U.z.object({id:U.z.string().min(1),type:U.z.nativeEnum(exports.AgentAttachmentType),name:U.z.string().min(1).max(500),url:U.z.string().url().optional(),mimeType:U.z.string().min(1).max(200).optional(),metadata:U.z.record(U.z.string(),U.z.unknown()).optional()}).strict(),k5=U.z.union([ja.extend({type:U.z.literal(exports.AgentAttachmentType.Context),metadata:b5}).strict(),ja.extend({type:U.z.literal(exports.AgentAttachmentType.File),size:U.z.number().int().min(0).optional(),metadata:U.z.object({uploadedAt:U.z.string().optional(),s3Key:U.z.string().optional(),processingStatus:U.z.enum(["pending","processed","failed"]).optional(),size:U.z.number().int().min(0).optional(),lastModified:U.z.number().optional()}).optional()}).strict(),ja.extend({type:U.z.literal(exports.AgentAttachmentType.Link)}).strict(),ja.extend({type:U.z.literal(exports.AgentAttachmentType.Artifact)}).strict()]),J7=U.z.object({chatId:U.z.string().optional(),content:U.z.string().min(1),contextKey:U.z.string().min(1),attachments:U.z.array(k5).optional(),metadata:U.z.record(U.z.string(),U.z.unknown()).optional(),model:U.z.string().optional(),temperature:U.z.number().optional(),userId:U.z.string().optional(),participantIds:U.z.array(U.z.string().min(1)).optional(),mentions:U.z.array(U.z.object({type:U.z.enum(["user","agent"]),name:U.z.string().min(1),id:U.z.string().optional()}).strict()).optional()}).strict();new TextEncoder;const e_=new TextDecoder,t_=3;class Lr{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 nd(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:f}=await this.formatHttpError("/chats/stream",l),g=new nd(m,f);throw this.config.onError?.(g),g}if(!l.body)throw new Error("Streaming response body missing");const u=l.body.getReader();let d="",p,h=!1;for(;;){const{value:m,done:f}=await u.read();if(f)break;d+=e_.decode(m,{stream:!0});const g=d.split(`
2
2
 
3
3
  `);d=g.pop()??"";for(const _ of g){const k=_.trim();if(!k.startsWith("data:"))continue;const b=k.replace(/^data:\s*/,"");if(!b||b==="[DONE]"){h=!0,n({type:exports.StreamChunkType.Message,done:!0});continue}let x;try{x=JSON.parse(b)}catch(M){console.error("Failed to parse SSE chunk",M);continue}x.type===exports.StreamChunkType.Chat&&x.chatId&&(p=x.chatId),x.message?.chat&&(p=x.message.chat,this.streamControllers.set(p,i)),n(x)}}if(h||n({type:exports.StreamChunkType.Message,done:!0}),p)try{const m=await this.getMessages(p,{limit:t_});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 n_="mp-agents-chats",r_=4,Bt="chats",Ot="messages";class a_{db=null;initPromise=null;async init(){if(!this.db)return this.initPromise?this.initPromise:(this.initPromise=new Promise((t,n)=>{const r=indexedDB.open(n_,r_);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 gt=new a_,i_=new TextDecoder,o_=3;class jo{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 gt.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 gt.getMessages(t);if(!n.length)return;const r=n.filter(a=>a.role!==exports.MessageRole.Error);r.length!==n.length&&await gt.saveMessages(t,r)}async appendErrorMessage(t,n){const r={id:vt.nanoid(),chat:t,content:n,role:exports.MessageRole.Error,createdAt:new Date().toISOString(),reasoning:"",toolCalls:[],attachments:[]};await gt.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 gt.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??vt.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),gt.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(`