@multiplayer-app/ai-agent-react 0.1.0-beta.3 → 0.1.0-beta.5

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.
@@ -27,7 +27,7 @@ Check the top-level render call using <`+ye+">.")}return ie}}function wh(B,ie){{
27
27
  <%s {...props} />
28
28
  React keys must be passed directly to JSX without using spread:
29
29
  let props = %s;
30
- <%s key={someKey} {...props} />`,jo,hr,s7,hr),Eh[hr+jo]=!0}}return B===r?n7(gt):t7(gt),gt}}function r7(B,ie,ye){return Mh(B,ie,ye,!0)}function a7(B,ie,ye){return Mh(B,ie,ye,!1)}var i7=a7,o7=r7;sa.Fragment=r,sa.jsx=i7,sa.jsxs=o7}()),sa}process.env.NODE_ENV==="production"?ed.exports=d7():ed.exports=p7();var O=ed.exports;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"})(exports.AgentToolType||(exports.AgentToolType={}));const Mi={ChatNew:"chat:new",MessageNew:"message:new",ChatUpdate:"chat:update"},Fi={Path:"/socket.io",UserRoomPrefix:"user:",DefaultUserId:"guest"},Vk=["webSnippet","formSnapshot","formField"],h7=V.z.string().datetime({offset:!0}).or(V.z.string().datetime()),m7=V.z.object({app:V.z.string().min(1).optional(),url:V.z.string().url().optional(),route:V.z.string().min(1).optional(),domPath:V.z.string().min(1).optional()}).strict(),f7=V.z.object({containsPII:V.z.boolean().optional(),redactionsApplied:V.z.array(V.z.string().min(1)).max(50).optional()}).strict(),g7=V.z.union([V.z.object({type:V.z.literal("text"),exact:V.z.string().min(1).max(4e3),prefix:V.z.string().min(1).max(500).optional(),suffix:V.z.string().min(1).max(500).optional(),domPath:V.z.string().min(1).max(2e3).optional(),startOffset:V.z.number().int().min(0).optional(),endOffset:V.z.number().int().min(0).optional()}).strict(),V.z.object({type:V.z.literal("dom"),domPath:V.z.string().min(1).max(2e3)}).strict(),V.z.object({type:V.z.literal("form"),formId:V.z.string().min(1).max(200).optional(),fieldName:V.z.string().min(1).max(200).optional(),domPath:V.z.string().min(1).max(2e3).optional()}).strict()]),oo=V.z.object({schemaVersion:V.z.literal(1),kind:V.z.string().min(1).max(100),capturedAt:h7,source:m7.optional(),security:f7.optional(),target:g7.optional()}),y7=oo.extend({kind:V.z.literal("webSnippet"),title:V.z.string().min(1).max(200).optional(),selectedText:V.z.string().min(1).max(4e3)}).strict(),b7=oo.extend({kind:V.z.literal("formSnapshot"),formId:V.z.string().min(1).max(200).optional(),formName:V.z.string().min(1).max(200).optional(),fields:V.z.array(V.z.object({name:V.z.string().min(1).max(200),label:V.z.string().min(1).max(200).optional(),value:V.z.string().min(0).max(1e3),inputType:V.z.enum(["text","textarea","number","select","radio","checkbox","date","email","tel"]).optional(),options:V.z.array(V.z.object({value:V.z.string().min(0).max(500),label:V.z.string().min(0).max(500)}).strict()).max(200).optional(),domPath:V.z.string().min(1).max(2e3).optional()}).strict()).min(1).max(50)}).strict(),k7=oo.extend({kind:V.z.literal("formField"),formId:V.z.string().min(1).max(200).optional(),fieldName:V.z.string().min(1).max(200),fieldLabel:V.z.string().min(1).max(200).optional(),value:V.z.string().min(0).max(1e3),inputType:V.z.enum(["text","textarea","number","select","radio","checkbox","date","email","tel"]).optional(),options:V.z.array(V.z.object({value:V.z.string().min(0).max(500),label:V.z.string().min(0).max(500)}).strict()).max(200).optional(),domPath:V.z.string().min(1).max(2e3).optional()}).strict(),v7=oo.extend({kind:V.z.string().min(1).max(100).refine(e=>!Vk.includes(e),"kind must not collide with built-in kinds"),title:V.z.string().min(1).max(200).optional(),summary:V.z.string().min(1).max(4e3).optional(),data:V.z.record(V.z.string().min(1).max(200),V.z.unknown()).optional()}).strict().superRefine((e,t)=>{e.data&&JSON.stringify(e.data).length>12e3&&t.addIssue({code:"custom",message:"data is too large (max ~12k JSON chars)",path:["data"]})}),Gk=V.z.union([y7,b7,k7,v7]),Qa=V.z.object({id:V.z.string().min(1),type:V.z.nativeEnum(exports.AgentAttachmentType),name:V.z.string().min(1).max(500),url:V.z.string().url().optional(),mimeType:V.z.string().min(1).max(200).optional(),metadata:V.z.record(V.z.string(),V.z.unknown()).optional()}).strict(),Wk=V.z.union([Qa.extend({type:V.z.literal(exports.AgentAttachmentType.Context),metadata:Gk}).strict(),Qa.extend({type:V.z.literal(exports.AgentAttachmentType.File),size:V.z.number().int().min(0).optional(),metadata:V.z.object({uploadedAt:V.z.string().optional(),s3Key:V.z.string().optional(),processingStatus:V.z.enum(["pending","processed","failed"]).optional(),size:V.z.number().int().min(0).optional(),lastModified:V.z.number().optional()}).optional()}).strict(),Qa.extend({type:V.z.literal(exports.AgentAttachmentType.Link)}).strict(),Qa.extend({type:V.z.literal(exports.AgentAttachmentType.Artifact)}).strict()]),_7=V.z.object({chatId:V.z.string().optional(),content:V.z.string().min(1),contextKey:V.z.string().min(1),attachments:V.z.array(Wk).optional(),metadata:V.z.record(V.z.string(),V.z.unknown()).optional(),model:V.z.string().optional(),temperature:V.z.number().optional(),userId:V.z.string().optional()}).strict();new TextEncoder;const w7=new TextDecoder;class jr{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 request(t,n){const r=await fetch(`${this.config.baseUrl}${t}`,{...n,headers:this.withHeaders(n?.headers,n),signal:n?.signal});if(!r.ok){const i=await r.text();throw new Error(`ProxyTransport ${t} failed: ${r.status} ${i}`)}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??9e4);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 c=await fetch(`${this.config.baseUrl}/chats/stream`,{method:"POST",headers:this.withHeaders(s,{method:"POST",body:JSON.stringify(t)}),body:JSON.stringify(t),signal:i.signal});if(!c.body)throw new Error("Readable stream not provided by proxy");const u=c.body.getReader();let d="",p;for(;;){const{value:m,done:h}=await u.read();if(h)break;d+=w7.decode(m,{stream:!0});const y=d.split(`
30
+ <%s key={someKey} {...props} />`,jo,hr,s7,hr),Eh[hr+jo]=!0}}return B===r?n7(gt):t7(gt),gt}}function r7(B,ie,ye){return Mh(B,ie,ye,!0)}function a7(B,ie,ye){return Mh(B,ie,ye,!1)}var i7=a7,o7=r7;sa.Fragment=r,sa.jsx=i7,sa.jsxs=o7}()),sa}process.env.NODE_ENV==="production"?ed.exports=d7():ed.exports=p7();var O=ed.exports;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"})(exports.AgentToolType||(exports.AgentToolType={}));var Mi={ChatNew:"chat:new",MessageNew:"message:new",ChatUpdate:"chat:update"},Fi={Path:"/socket.io",UserRoomPrefix:"user:",DefaultUserId:"guest"},Vk=["webSnippet","formSnapshot","formField"],h7=V.z.string().datetime({offset:!0}).or(V.z.string().datetime()),m7=V.z.object({app:V.z.string().min(1).optional(),url:V.z.string().url().optional(),route:V.z.string().min(1).optional(),domPath:V.z.string().min(1).optional()}).strict(),f7=V.z.object({containsPII:V.z.boolean().optional(),redactionsApplied:V.z.array(V.z.string().min(1)).max(50).optional()}).strict(),g7=V.z.union([V.z.object({type:V.z.literal("text"),exact:V.z.string().min(1).max(4e3),prefix:V.z.string().min(1).max(500).optional(),suffix:V.z.string().min(1).max(500).optional(),domPath:V.z.string().min(1).max(2e3).optional(),startOffset:V.z.number().int().min(0).optional(),endOffset:V.z.number().int().min(0).optional()}).strict(),V.z.object({type:V.z.literal("dom"),domPath:V.z.string().min(1).max(2e3)}).strict(),V.z.object({type:V.z.literal("form"),formId:V.z.string().min(1).max(200).optional(),fieldName:V.z.string().min(1).max(200).optional(),domPath:V.z.string().min(1).max(2e3).optional()}).strict()]),oo=V.z.object({schemaVersion:V.z.literal(1),kind:V.z.string().min(1).max(100),capturedAt:h7,source:m7.optional(),security:f7.optional(),target:g7.optional()}),y7=oo.extend({kind:V.z.literal("webSnippet"),title:V.z.string().min(1).max(200).optional(),selectedText:V.z.string().min(1).max(4e3)}).strict(),b7=oo.extend({kind:V.z.literal("formSnapshot"),formId:V.z.string().min(1).max(200).optional(),formName:V.z.string().min(1).max(200).optional(),fields:V.z.array(V.z.object({name:V.z.string().min(1).max(200),label:V.z.string().min(1).max(200).optional(),value:V.z.string().min(0).max(1e3),inputType:V.z.enum(["text","textarea","number","select","radio","checkbox","date","email","tel"]).optional(),options:V.z.array(V.z.object({value:V.z.string().min(0).max(500),label:V.z.string().min(0).max(500)}).strict()).max(200).optional(),domPath:V.z.string().min(1).max(2e3).optional()}).strict()).min(1).max(50)}).strict(),k7=oo.extend({kind:V.z.literal("formField"),formId:V.z.string().min(1).max(200).optional(),fieldName:V.z.string().min(1).max(200),fieldLabel:V.z.string().min(1).max(200).optional(),value:V.z.string().min(0).max(1e3),inputType:V.z.enum(["text","textarea","number","select","radio","checkbox","date","email","tel"]).optional(),options:V.z.array(V.z.object({value:V.z.string().min(0).max(500),label:V.z.string().min(0).max(500)}).strict()).max(200).optional(),domPath:V.z.string().min(1).max(2e3).optional()}).strict(),v7=oo.extend({kind:V.z.string().min(1).max(100).refine(function(e){return!Vk.includes(e)},"kind must not collide with built-in kinds"),title:V.z.string().min(1).max(200).optional(),summary:V.z.string().min(1).max(4e3).optional(),data:V.z.record(V.z.string().min(1).max(200),V.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"]})}}),Gk=V.z.union([y7,b7,k7,v7]),Qa=V.z.object({id:V.z.string().min(1),type:V.z.nativeEnum(exports.AgentAttachmentType),name:V.z.string().min(1).max(500),url:V.z.string().url().optional(),mimeType:V.z.string().min(1).max(200).optional(),metadata:V.z.record(V.z.string(),V.z.unknown()).optional()}).strict(),Wk=V.z.union([Qa.extend({type:V.z.literal(exports.AgentAttachmentType.Context),metadata:Gk}).strict(),Qa.extend({type:V.z.literal(exports.AgentAttachmentType.File),size:V.z.number().int().min(0).optional(),metadata:V.z.object({uploadedAt:V.z.string().optional(),s3Key:V.z.string().optional(),processingStatus:V.z.enum(["pending","processed","failed"]).optional(),size:V.z.number().int().min(0).optional(),lastModified:V.z.number().optional()}).optional()}).strict(),Qa.extend({type:V.z.literal(exports.AgentAttachmentType.Link)}).strict(),Qa.extend({type:V.z.literal(exports.AgentAttachmentType.Artifact)}).strict()]),_7=V.z.object({chatId:V.z.string().optional(),content:V.z.string().min(1),contextKey:V.z.string().min(1),attachments:V.z.array(Wk).optional(),metadata:V.z.record(V.z.string(),V.z.unknown()).optional(),model:V.z.string().optional(),temperature:V.z.number().optional(),userId:V.z.string().optional()}).strict();new TextEncoder;const w7=new TextDecoder;class jr{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 request(t,n){const r=await fetch(`${this.config.baseUrl}${t}`,{...n,headers:this.withHeaders(n?.headers,n),signal:n?.signal});if(!r.ok){const i=await r.text();throw new Error(`ProxyTransport ${t} failed: ${r.status} ${i}`)}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??9e4);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 c=await fetch(`${this.config.baseUrl}/chats/stream`,{method:"POST",headers:this.withHeaders(s,{method:"POST",body:JSON.stringify(t)}),body:JSON.stringify(t),signal:i.signal});if(!c.body)throw new Error("Readable stream not provided by proxy");const u=c.body.getReader();let d="",p;for(;;){const{value:m,done:h}=await u.read();if(h)break;d+=w7.decode(m,{stream:!0});const y=d.split(`
31
31
 
32
32
  `);d=y.pop()??"";for(const g of y){const _=g.trim();if(!_.startsWith("data:"))continue;const v=_.replace(/^data:\s*/,"");if(!v||v==="[DONE]"){n({type:exports.StreamChunkType.Message,done:!0});continue}try{const k=JSON.parse(v);k.message?.chat&&(p=k.message.chat,this.streamControllers.set(p,i)),n(k)}catch(k){console.error("Failed to parse SSE chunk",k)}}}if(p)try{return await this.getChat(p)}catch(m){console.error("Failed to fetch chat after streaming",m)}}finally{clearTimeout(o);const s=[];for(const[c,u]of this.streamControllers.entries())u===i&&s.push(c);s.forEach(c=>this.streamControllers.delete(c))}}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;return t?.contextKey&&n.set("contextKey",t.contextKey),t?.limit&&n.set("limit",String(t.limit)),t?.userId&&n.set("userId",t.userId),t?.sortField&&n.set("sortField",t.sortField),t?.sortOrder&&n.set("sortOrder",t.sortOrder),this.request(`/chats?${n.toString()}`)}getChat(t){return this.request(`/chats/${t}`)}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`)}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 generateTitle(t){return`${t.contextKey} request ${new Date().toISOString()}`}async listModels(){return(await this.request("/models")).models}}const x7="mp-agents-chats",E7=2,Kt="chats";class M7{db=null;initPromise=null;async init(){if(!this.db)return this.initPromise?this.initPromise:(this.initPromise=new Promise((t,n)=>{const r=indexedDB.open(x7,E7);r.onerror=()=>n(new Error("Failed to open IndexedDB")),r.onsuccess=()=>{this.db=r.result,t()},r.onupgradeneeded=a=>{const i=a.target.result;let o;i.objectStoreNames.contains(Kt)?o=r.transaction.objectStore(Kt):o=i.createObjectStore(Kt,{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.createIndex("userId","userId",{unique:!1})}}),this.initPromise)}async saveChat(t){if(await this.init(),!this.db)throw new Error("IndexedDB not initialized");return new Promise((n,r)=>{const o=this.db.transaction([Kt],"readwrite").objectStore(Kt).put(t);o.onsuccess=()=>n(),o.onerror=()=>r(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 o=this.db.transaction([Kt],"readonly").objectStore(Kt).get(t);o.onsuccess=()=>n(o.result||null),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 o=this.db.transaction([Kt],"readonly").objectStore(Kt).getAll();o.onsuccess=()=>{let s=o.result;if(t?.contextKey&&(s=s.filter(c=>c.contextKey===t.contextKey)),t?.userId){const c=t.userId??"guest";s=s.filter(u=>(u.userId??"guest")===c)}s.sort((c,u)=>c.updatedAt<u.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 o=this.db.transaction([Kt],"readwrite").objectStore(Kt).delete(t);o.onsuccess=()=>n(),o.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 i=this.db.transaction([Kt],"readwrite").objectStore(Kt).clear();i.onsuccess=()=>t(),i.onerror=()=>n(new Error("Failed to clear chats"))})}}const Lr=new M7,S7=new TextDecoder;class Vo{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;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 Lr.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(`
33
33
  `).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}clearErrorMessages(t){t.messages?.length&&(t.messages=t.messages.filter(n=>n.role!==exports.MessageRole.Error))}appendErrorMessage(t,n){t.messages.push({id:Tt.nanoid(),chat:t.id,content:n,role:exports.MessageRole.Error,createdAt:new Date().toISOString(),reasoning:"",toolCalls:[],attachments:[]})}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 Lr.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??"guest",i={id:t.chatId??Tt.nanoid(),title:r,type:exports.ChatType.Chat,status:exports.AgentStatus.Processing,contextKey:t.contextKey,userId:a,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),messages:[]};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),Lr.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(`