chat-agent-toolkit 1.2.11 → 1.2.13
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/research-agent.cjs.js +1 -1
- package/dist/research-agent.cjs.js.map +1 -1
- package/dist/research-agent.es.js +1 -1
- package/dist/research-agent.es.js.map +1 -1
- package/dist/tools/search/doc-utils.d.ts +15 -0
- package/dist/tools/search/index.d.ts +2 -1
- package/package.json +1 -1
- package/src/tools/search/doc-utils.ts +38 -2
- package/src/tools/search/index.ts +2 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{webSearchResponsePrompt as e,webSearchRetrieverFewShots as t,webSearchRetrieverPrompt as a,writeLanguageResponse as n,writingAssistantPrompt as r}from"write-language";import{and as o,desc as i,eq as s,like as c,or as m,sql as l}from"drizzle-orm";import{Mastra as d}from"@mastra/core";import{Agent as p}from"@mastra/core/agent";import{z as h}from"zod";import*as u from"qwksearch-api-client";import{generateText as g,streamText as y}from"ai";import f from"events";export*from"write-language";var v=/* @__PURE__ */(e=>"undefined"!=typeof require?require:"undefined"!=typeof Proxy?new Proxy(e,{get:(e,t)=>("undefined"!=typeof require?require:e)[t]}):e)(function(e){if("undefined"!=typeof require)return require.apply(this,arguments);throw Error('Calling `require` for "'+e+"\" in an environment that doesn't expose the `require` function. See https://rolldown.rs/in-depth/bundling-cjs#require-external-modules for more details.")}),L={FACT:"fact",CONVERSATION:"conversation",PREFERENCE:"preference",PERSONAL:"personal",WORK:"work",MANUAL:"manual"},b={DEFAULT_MAX_MEMORIES:100,DEFAULT_SUMMARY_THRESHOLD:10,DEFAULT_CACHE_EXPIRY:3e5,DEFAULT_BATCH_SIZE:5,DEFAULT_RELEVANCE_THRESHOLD:.3,DEFAULT_IMPORTANCE_RANGE:{min:0,max:10},DEFAULT_RATE_LIMIT:{requests:10,windowMs:6e4},DEFAULT_TIMEOUT:3e4,VECTOR_SEARCH_ENABLED:!0,AUTO_SUMMARIZATION_ENABLED:!0},w=class{userId;storage;maxMemories;summaryThreshold;cacheExpiry;batchSize;relevanceThreshold;enableVectorSearch;enableAutoSummarization;recentMessages;memoryCache;isProcessing;processingQueue;summarizeTimeout;metrics;constructor(e,t,a={}){if(!e||!t)throw new Error("userId and storage are required parameters");this.userId=e,this.storage=t,this.maxMemories=a.maxMemories||b.DEFAULT_MAX_MEMORIES,this.summaryThreshold=a.summaryThreshold||b.DEFAULT_SUMMARY_THRESHOLD,this.cacheExpiry=a.cacheExpiry||b.DEFAULT_CACHE_EXPIRY,this.batchSize=a.batchSize||b.DEFAULT_BATCH_SIZE,this.relevanceThreshold=a.relevanceThreshold||b.DEFAULT_RELEVANCE_THRESHOLD,this.enableVectorSearch=!1!==a.enableVectorSearch&&b.VECTOR_SEARCH_ENABLED,this.enableAutoSummarization=!1!==a.enableAutoSummarization&&b.AUTO_SUMMARIZATION_ENABLED,this.recentMessages=[],this.memoryCache=/* @__PURE__ */new Map,this.isProcessing=!1,this.processingQueue=[],this.metrics={cacheHits:0,cacheMisses:0,vectorSearches:0,summarizations:0,errors:0}}addMessage(e,t,a={}){if(!e||!t||"string"!=typeof t)return console.warn("Invalid message parameters:",{role:e,content:t}),!1;if(this.recentMessages.slice(-3).some(a=>a.role===e&&a.content===t&&Date.now()-a.timestamp<6e4))return!1;const n={role:e,content:t.trim(),timestamp:a.timestamp||Date.now(),metadata:{...a}};return this.recentMessages.push(n),this.enableAutoSummarization&&this.recentMessages.length>=this.summaryThreshold&&!this.isProcessing&&this.debouncedSummarize(),!0}debouncedSummarize(){this.summarizeTimeout&&clearTimeout(this.summarizeTimeout),this.summarizeTimeout=setTimeout(()=>{this.summarizeAndStore().catch(e=>{console.error("Auto-summarization failed:",e),this.metrics.errors++})},1e3)}async storeFact(e,t=1,a=L.FACT,n={}){if(!e||"string"!=typeof e||0===e.trim().length)throw new Error("Content cannot be empty");if(t<b.DEFAULT_IMPORTANCE_RANGE.min||t>b.DEFAULT_IMPORTANCE_RANGE.max)throw new Error(`Importance must be between ${b.DEFAULT_IMPORTANCE_RANGE.min} and ${b.DEFAULT_IMPORTANCE_RANGE.max}`);const r=e.trim(),o=Object.values(L).includes(a)?a:L.FACT;try{const e=await this.findSimilarFacts(r);if(e.length>0){const a=e[0];return t>a.importance&&await this.storage.updateMemory(a.id,{importance:t,updated_at:/* @__PURE__ */new Date,access_count:{increment:1},metadata:{...a.metadata,...n}}),a.id}const a=await this.storage.insertMemory(this.userId,o,r,Math.max(0,Math.min(10,t)),n);return this.clearCache(),a}catch(i){throw console.error("Error storing fact:",i),this.metrics.errors++,i}}async findSimilarFacts(e){try{return await this.storage.findSimilarMemories(this.userId,e,5)}catch(t){return console.error("Error finding similar facts:",t),[]}}async recallRelevantMemories(e="",t=10,a={}){const n=`${e}-${t}-${JSON.stringify(a)}`;if(this.memoryCache.has(n)){const e=this.memoryCache.get(n);if(Date.now()-e.timestamp<this.cacheExpiry)return this.metrics.cacheHits++,e.data;this.memoryCache.delete(n)}this.metrics.cacheMisses++;try{let r=await this.storage.findMemories(this.userId,e,t,a);if(0===r.length)return[];this.enableVectorSearch&&e.trim()&&r.length>0&&(r=await this.applyVectorSearch(e,r,a)),a.minImportance&&(r=r.filter(e=>e.importance>=a.minImportance));const o=r.map(e=>({...e,relevance_score:e.relevance_score||0,metadata:a.includeMetadata?e.metadata:void 0}));return this.memoryCache.set(n,{data:o,timestamp:Date.now()}),o}catch(r){return console.error("Error retrieving memories:",r),this.metrics.errors++,[]}}async applyVectorSearch(e,t,a){return t}async updateRelevanceScores(e,t){const a=t.filter(e=>e.relevance>this.relevanceThreshold).map(t=>{const a=e.find(e=>e.content===t.sentence);return a?{id:a.id,updates:{importance:Math.min(10,a.importance+.5*t.relevance),access_count:{increment:1},updated_at:/* @__PURE__ */new Date}}:null}).filter(Boolean);a.length>0&&await this.storage.batchUpdateMemories(a)}async summarizeAndStore(){if(0===this.recentMessages.length||this.isProcessing)return!1;this.isProcessing=!0,this.metrics.summarizations++;try{const e=this.recentMessages.map(e=>`${e.role}: ${e.content}`).join("\n"),t=await this.extractFactsFromConversation(e);return Array.isArray(t)&&0!==t.length?(await this.processFactsInBatches(t),this.recentMessages=[],!0):(console.warn("No facts extracted from conversation"),!1)}catch(e){return console.error("Error in summarizeAndStore:",e),this.metrics.errors++,!1}finally{this.isProcessing=!1}}async extractFactsFromConversation(e){try{const{extract:t}=await n({agent:"remember-facts",chat_history:e,provider:"groq",model:"mixtral-8x7b-32768",timeout:b.DEFAULT_TIMEOUT});return Array.isArray(t)?t:[]}catch(t){return console.error("Error extracting facts:",t),[]}}async processFactsInBatches(e){for(let t=0;t<e.length;t+=this.batchSize){const a=e.slice(t,t+this.batchSize).map(async e=>{try{if(e&&"object"==typeof e&&e.content)return await this.storeFact(e.content,e.importance||1,e.category||L.CONVERSATION,e.metadata||{});if("string"==typeof e&&e.trim())return await this.storeFact(e.trim(),1,L.CONVERSATION)}catch(t){return console.error("Error storing individual fact:",t),null}});await Promise.allSettled(a),t+this.batchSize<e.length&&await new Promise(e=>setTimeout(e,100))}}clearCache(){this.memoryCache.clear()}async getMemoryContext(e="",t=!0,a={}){const n=await this.recallRelevantMemories(e,a.maxMemories||8,{minImportance:a.minImportance||.5});if(0===n.length&&0===this.recentMessages.length)return"";let r="";return n.length>0&&(r+="What I remember about you:\n",n.filter(e=>e.importance>(a.minImportance||.5)).forEach(e=>{const t=e.importance>=8?"⭐":e.importance>=5?"•":"-";r+=`${t} ${e.content}\n`})),t&&this.recentMessages.length>0&&(r+=r?"\nRecent conversation:\n":"Recent conversation:\n",this.recentMessages.slice(-3).forEach(e=>{const t=e.content.length>100?e.content.substring(0,100)+"...":e.content;r+=`${e.role}: ${t}\n`})),r}getMetrics(){return{...this.metrics,cacheSize:this.memoryCache.size,recentMessagesCount:this.recentMessages.length,isProcessing:this.isProcessing}}},x=class{memory;defaultProvider;defaultApiKey;defaultModel;rateLimiter;rateLimitConfig;providers;sessionId;conversationHistory;analytics;userId;constructor(e,t,a={}){if(!e||!t)throw new Error("userId and storage are required parameters");this.userId=e,this.memory=new w(e,t,a.memoryOptions||{}),this.defaultProvider=a.defaultProvider||"groq",this.defaultApiKey=a.defaultApiKey,this.defaultModel=a.defaultModel,this.rateLimiter=/* @__PURE__ */new Map,this.rateLimitConfig={...b.DEFAULT_RATE_LIMIT,...a.rateLimit},this.providers=a.providers||this.getDefaultProviders(),this.sessionId=this.generateSessionId(),this.conversationHistory=[],this.analytics={totalMessages:0,totalTokens:0,averageResponseTime:0,errorCount:0,sessionStartTime:Date.now()}}getDefaultProviders(){return{groq:(e,t,a)=>({invoke:async e=>({content:"Default response",tokensUsed:0})}),openai:(e,t,a)=>({invoke:async e=>({content:"Default response",tokensUsed:0})})}}generateSessionId(){return`${this.userId}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}checkRateLimit(e,t,a){const n=t||this.rateLimitConfig.requests,r=a||this.rateLimitConfig.windowMs,o=Date.now(),i=(this.rateLimiter.get(e)||[]).filter(e=>o-e<r);return!(i.length>=n||(i.push(o),this.rateLimiter.set(e,i),0))}async chat(e,t={}){const a=Date.now();if(!e||"string"!=typeof e||0===e.trim().length)return{error:"Message cannot be empty",success:!1,timestamp:/* @__PURE__ */(new Date).toISOString()};const n=`chat-${this.userId}`;if(!this.checkRateLimit(n))return{error:"Rate limit exceeded. Please try again later.",success:!1,timestamp:/* @__PURE__ */(new Date).toISOString()};try{this.memory.addMessage("user",e,{sessionId:this.sessionId,timestamp:Date.now()});const n=await this.memory.getMemoryContext(e,!0,{maxMemories:t.maxMemories||8,minImportance:t.minImportance||.5}),r=this.buildPrompt(e,n,t),o=await this.generateResponse(r,t);if(!o||!o.content)throw new Error("Invalid response from LLM");return this.memory.addMessage("assistant",o.content,{sessionId:this.sessionId,tokensUsed:o.tokensUsed,timestamp:Date.now()}),this.updateAnalytics(o.tokensUsed,Date.now()-a),{content:o.content,memoryContext:n,success:!0,tokensUsed:o.tokensUsed||0,responseTime:Date.now()-a,sessionId:this.sessionId,timestamp:/* @__PURE__ */(new Date).toISOString()}}catch(r){return console.error("Chat error:",r),this.analytics.errorCount++,{error:r.message||"An unexpected error occurred",success:!1,timestamp:/* @__PURE__ */(new Date).toISOString()}}}async generateResponse(e,t){const a=t.provider||this.defaultProvider,n=t.apiKey||this.defaultApiKey,r=t.model||this.defaultModel,o=t.temperature||.7;if(!this.providers||!this.providers[a])throw new Error(`Provider ${a} not available`);const i=this.providers[a](n||"",r||"",o),s=new Promise((e,t)=>setTimeout(()=>t(/* @__PURE__ */new Error("LLM request timeout")),b.DEFAULT_TIMEOUT));return await Promise.race([i.invoke(e),s])}buildPrompt(e,t,a){let n="";return a.systemPrompt&&(n+=`${a.systemPrompt}\n\n`),t&&(n+=`${t}\n\n`),a.includeHistory&&this.conversationHistory.length>0&&(n+="Recent conversation history:\n",this.conversationHistory.slice(-5).forEach(e=>{n+=`${e.role}: ${e.content}\n`}),n+="\n"),n+=`User: ${e}\n\nAssistant:`,n}updateAnalytics(e,t){this.analytics.totalMessages++,this.analytics.totalTokens+=e||0,this.analytics.averageResponseTime=(this.analytics.averageResponseTime*(this.analytics.totalMessages-1)+t)/this.analytics.totalMessages}async remember(e,t=1,a=L.MANUAL,n={}){try{return await this.memory.storeFact(e,t,a,{...n,source:"manual",timestamp:Date.now()})}catch(r){throw console.error("Error remembering fact:",r),r}}async getMemories(e="",t=10,a={}){return await this.memory.recallRelevantMemories(e,t,a)}async forceStoreSummary(){return await this.memory.summarizeAndStore()}async healthCheck(){try{return{status:"healthy",memory:this.memory.getMetrics(),rateLimit:this.checkRateLimit("health-check",1,1e3),analytics:this.analytics,sessionId:this.sessionId,uptime:Date.now()-this.analytics.sessionStartTime,timestamp:/* @__PURE__ */(new Date).toISOString()}}catch(e){return{status:"unhealthy",error:e.message,timestamp:/* @__PURE__ */(new Date).toISOString()}}}getAnalytics(){return{...this.analytics,memory:this.memory.getMetrics(),sessionId:this.sessionId,uptime:Date.now()-this.analytics.sessionStartTime}}resetSession(){this.sessionId=this.generateSessionId(),this.conversationHistory=[],this.analytics.sessionStartTime=Date.now()}},I=class{db;table;constructor(e,t){this.db=e,this.table=t}async insertMemory(e,t,a,n,r){return(await this.db.insert(this.table).values({user_id:e,memory_type:t,content:a,importance:n,access_count:0,metadata:r||{},created_at:/* @__PURE__ */new Date,updated_at:/* @__PURE__ */new Date}).returning({id:this.table.id}))[0]?.id}async findMemories(e,t,a=10,n={}){const r=[s(this.table.user_id,e)];return t&&t.trim()&&r.push(c(this.table.content,`%${t}%`)),n.memoryType&&r.push(s(this.table.memory_type,n.memoryType)),await this.db.select({id:this.table.id,user_id:this.table.user_id,memory_type:this.table.memory_type,content:this.table.content,importance:this.table.importance,access_count:this.table.access_count,metadata:this.table.metadata,created_at:this.table.created_at,updated_at:this.table.updated_at}).from(this.table).where(o(...r)).orderBy(i(this.table.importance),i(this.table.access_count),i(this.table.updated_at)).limit(Math.min(a,50))}async findSimilarMemories(e,t,a=5){const n=t.toLowerCase().split(/\s+/).filter(e=>e.length>2).slice(0,3);if(0===n.length)return[];const r=n.map(e=>c(this.table.content,`%${e}%`));return await this.db.select().from(this.table).where(o(s(this.table.user_id,e),m(...r))).orderBy(i(this.table.importance),i(this.table.updated_at)).limit(a)}async updateMemory(e,t){const a={};void 0!==t.importance&&(a.importance=t.importance),void 0!==t.access_count&&("object"==typeof t.access_count&&t.access_count.increment?a.access_count=l`${this.table.access_count} + ${t.access_count.increment}`:a.access_count=t.access_count),void 0!==t.updated_at&&(a.updated_at=t.updated_at),void 0!==t.metadata&&(a.metadata=t.metadata),await this.db.update(this.table).set(a).where(s(this.table.id,e))}async deleteMemory(e){await this.db.delete(this.table).where(s(this.table.id,e))}async getMemoryById(e){return(await this.db.select().from(this.table).where(s(this.table.id,e)).limit(1))[0]||null}async batchUpdateMemories(e){const t=e.map(({id:e,updates:t})=>this.updateMemory(e,t));await Promise.allSettled(t)}};function A(e){return{user_memories:{id:"uuid",user_id:"string",memory_type:"string",content:"text",importance:"number",access_count:"number",metadata:"jsonb",created_at:"timestamp",updated_at:"timestamp"}}}var k=class{db;tableName;constructor(e,t="mastra_memories"){this.db=e,this.tableName=t}async initSchema(){await this.db.exec(`\n CREATE TABLE IF NOT EXISTS ${this.tableName} (\n id TEXT PRIMARY KEY,\n user_id TEXT NOT NULL,\n thread_id TEXT NOT NULL,\n resource_id TEXT,\n memory_type TEXT NOT NULL,\n content TEXT NOT NULL,\n importance REAL DEFAULT 1.0,\n access_count INTEGER DEFAULT 0,\n metadata TEXT,\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL\n );\n\n CREATE INDEX IF NOT EXISTS idx_user_thread ON ${this.tableName}(user_id, thread_id);\n CREATE INDEX IF NOT EXISTS idx_resource ON ${this.tableName}(resource_id);\n CREATE INDEX IF NOT EXISTS idx_importance ON ${this.tableName}(importance DESC);\n `)}async insertMemory(e,t,a,n,r){const o=crypto.randomUUID(),i=Date.now();return await this.db.prepare(`INSERT INTO ${this.tableName}\n (id, user_id, thread_id, resource_id, memory_type, content, importance, metadata, created_at, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).bind(o,e,r?.thread_id||"default",r?.resource_id||null,t,a,n,JSON.stringify(r||{}),i,i).run(),o}async findMemories(e,t,a=10,n={}){let r=`SELECT * FROM ${this.tableName} WHERE user_id = ?`;const o=[e];return n.memoryType&&(r+=" AND memory_type = ?",o.push(n.memoryType)),t&&(r+=" AND content LIKE ?",o.push(`%${t}%`)),void 0!==n.minImportance&&(r+=" AND importance >= ?",o.push(n.minImportance)),r+=" ORDER BY importance DESC, updated_at DESC LIMIT ?",o.push(a),((await this.db.prepare(r).bind(...o).all()).results||[]).map(e=>({id:e.id,user_id:e.user_id,memory_type:e.memory_type,content:e.content,importance:e.importance,access_count:e.access_count,metadata:JSON.parse(e.metadata||"{}"),created_at:new Date(e.created_at),updated_at:new Date(e.updated_at)}))}async findSimilarMemories(e,t,a=5){const n=t.toLowerCase().split(/\s+/).filter(e=>e.length>2).slice(0,3);if(0===n.length)return[];const r=n.map(()=>"content LIKE ?").join(" OR "),o=[e,...n.map(e=>`%${e}%`),a];return((await this.db.prepare(`SELECT * FROM ${this.tableName}\n WHERE user_id = ? AND (${r})\n ORDER BY importance DESC, updated_at DESC\n LIMIT ?`).bind(...o).all()).results||[]).map(e=>({id:e.id,user_id:e.user_id,memory_type:e.memory_type,content:e.content,importance:e.importance,access_count:e.access_count,metadata:JSON.parse(e.metadata||"{}"),created_at:new Date(e.created_at),updated_at:new Date(e.updated_at)}))}async updateMemory(e,t){const a=[],n=[];void 0!==t.importance&&(a.push("importance = ?"),n.push(t.importance)),void 0!==t.access_count&&("object"==typeof t.access_count&&t.access_count.increment?(a.push("access_count = access_count + ?"),n.push(t.access_count.increment)):(a.push("access_count = ?"),n.push(t.access_count))),void 0!==t.metadata&&(a.push("metadata = ?"),n.push(JSON.stringify(t.metadata))),a.push("updated_at = ?"),n.push(Date.now()),n.push(e),a.length>0&&await this.db.prepare(`UPDATE ${this.tableName} SET ${a.join(", ")} WHERE id = ?`).bind(...n).run()}async deleteMemory(e){await this.db.prepare(`DELETE FROM ${this.tableName} WHERE id = ?`).bind(e).run()}async getMemoryById(e){const t=await this.db.prepare(`SELECT * FROM ${this.tableName} WHERE id = ?`).bind(e).first();return t?{id:t.id,user_id:t.user_id,memory_type:t.memory_type,content:t.content,importance:t.importance,access_count:t.access_count,metadata:JSON.parse(t.metadata||"{}"),created_at:new Date(t.created_at),updated_at:new Date(t.updated_at)}:null}async batchUpdateMemories(e){for(const{id:t,updates:a}of e)await this.updateMemory(t,a)}},S=class{kv;prefix;constructor(e,t="mastra:memory:"){this.kv=e,this.prefix=t}getUserKey(e){return`${this.prefix}user:${e}`}getMemoryKey(e){return`${this.prefix}memory:${e}`}async insertMemory(e,t,a,n,r){const o=crypto.randomUUID(),i=Date.now(),s={id:o,user_id:e,memory_type:t,content:a,importance:n,access_count:0,metadata:r||{},created_at:new Date(i),updated_at:new Date(i)};await this.kv.put(this.getMemoryKey(o),JSON.stringify(s));const c=this.getUserKey(e),m=await this.kv.get(c,"json")||[];return m.push(o),await this.kv.put(c,JSON.stringify(m)),o}async findMemories(e,t,a=10,n={}){const r=this.getUserKey(e),o=await this.kv.get(r,"json")||[];let i=(await Promise.all(o.map(e=>this.getMemoryById(e)))).filter(e=>null!==e);return t&&(i=i.filter(e=>e.content.toLowerCase().includes(t.toLowerCase()))),n.memoryType&&(i=i.filter(e=>e.memory_type===n.memoryType)),void 0!==n.minImportance&&(i=i.filter(e=>e.importance>=n.minImportance)),i.sort((e,t)=>t.importance-e.importance||t.updated_at.getTime()-e.updated_at.getTime()).slice(0,a)}async findSimilarMemories(e,t,a=5){const n=t.toLowerCase().split(/\s+/).filter(e=>e.length>2).slice(0,3);return 0===n.length?[]:(await this.findMemories(e,"",50)).filter(e=>n.some(t=>e.content.toLowerCase().includes(t))).slice(0,a)}async updateMemory(e,t){const a=await this.getMemoryById(e);a&&(void 0!==t.importance&&(a.importance=t.importance),void 0!==t.access_count&&("object"==typeof t.access_count?a.access_count+=t.access_count.increment??0:a.access_count=t.access_count),void 0!==t.metadata&&(a.metadata={...a.metadata,...t.metadata}),a.updated_at=/* @__PURE__ */new Date,await this.kv.put(this.getMemoryKey(e),JSON.stringify(a)))}async deleteMemory(e){const t=await this.getMemoryById(e);if(!t)return;await this.kv.delete(this.getMemoryKey(e));const a=this.getUserKey(t.user_id),n=(await this.kv.get(a,"json")||[]).filter(t=>t!==e);await this.kv.put(a,JSON.stringify(n))}async getMemoryById(e){const t=await this.kv.get(this.getMemoryKey(e),"json");return t?{...t,created_at:new Date(t.created_at),updated_at:new Date(t.updated_at)}:null}async batchUpdateMemories(e){await Promise.all(e.map(({id:e,updates:t})=>this.updateMemory(e,t)))}},E=class{mastra=null;storage;config;constructor(e){if(this.config=e,"d1"===e.storage&&e.env?.DB)this.storage=new k(e.env.DB,e.tableName);else{if("kv"!==e.storage||!e.env?.KV)throw new Error(`Invalid storage configuration: ${e.storage}`);this.storage=new S(e.env.KV,e.kvPrefix)}}async initialize(){return this.mastra||(this.mastra=new d({}),"d1"===this.config.storage&&this.storage instanceof k&&await this.storage.initSchema()),this.mastra}getStorage(){return this.storage}async createAgent(e){await this.initialize();const t=new p({id:e.id,name:e.name,instructions:e.instructions,model:e.model,tools:e.tools||{}});return t.memoryContext={userId:e.userId,threadId:e.threadId||"default",resourceId:e.resourceId},t}async storeMessage(e,t,a,n,r){return await this.storage.insertMemory(e,"conversation",n,1,{thread_id:t,role:a,...r})}async recallConversation(e,t,a=20){return(await this.storage.findMemories(e,void 0,a,{memoryType:"conversation"})).filter(e=>e.metadata?.thread_id===t).map(e=>({role:e.metadata?.role||"user",content:e.content,timestamp:e.created_at})).sort((e,t)=>e.timestamp.getTime()-t.timestamp.getTime())}async getRelevantContext(e,t,a=5){const n=await this.storage.findSimilarMemories(e,t,a);return 0===n.length?"":n.map(e=>e.content).join("\n\n")}};function _(e){return new E(e)}var P={baseURL:"undefined"!=typeof process&&process?.env.QWKSEARCH_URL||"https://app.qwksearch.com/api",apiKey:"undefined"!=typeof process&&process?.env.QWKSEARCH_API_KEY||null},T=[{name:"web_search",description:"Search the web for information on any topic using QwkSearch API. Input: search query string and optional category. Returns relevant search results with titles, descriptions, and URLs from 100+ sources via SearXNG metasearch engine.",schema:h.object({query:h.string(),category:h.enum(["general","news","videos","images","science","files","it"]).optional().default("general"),recency:h.enum(["none","day","week","month","year"]).optional().default("none"),page:h.number().optional().default(1),language:h.string().optional().default("en-US"),public:h.boolean().optional().default(!1),timeout:h.number().optional().default(10),baseURL:h.string().optional(),apiKey:h.string().optional()}),func:async({query:e,category:t="general",recency:a="none",page:n=1,language:r="en-US",public:o=!1,timeout:i=10,baseURL:s,apiKey:c})=>{try{const m=s||P.baseURL,l=c||P.apiKey?{"x-api-key":c||P.apiKey}:void 0,d=await u.searchWeb({query:{q:e,cat:t,recency:a,page:n,lang:r,public:o,timeout:i},baseUrl:m,...l&&{headers:l}});if(!d.data||!d.data.results||0===d.data.results.length)return`No search results found for "${e}". Please try a different search term.`;let p=`Web search results for "${e}" (${t} category):\n\n`;return d.data.results.forEach((e,t)=>{p+=`${t+1}. ${e.title}\n`,p+=` URL: ${e.url}\n`,e.domain&&(p+=` Domain: ${e.domain}\n`),e.snippet&&(p+=` Description: ${e.snippet}\n`),e.engines&&e.engines.length>0&&(p+=` Sources: ${e.engines.join(", ")}\n`),p+="\n"}),p+=`Found ${d.data.results.length} results from multiple search engines. This is the complete search information.`,p}catch(m){return`Unable to perform web search for "${e}". Error: ${m.message}`}}},{name:"extract_page",description:"Extract and summarize content from a web page using QwkSearch API. Supports articles, PDFs, and YouTube videos. Uses Mozilla Readability and Postlight Mercury algorithms with 100+ custom adapters for major sites. Input: URL of the page to extract. Returns structured content with citation information.",schema:h.object({url:h.string().url(),images:h.boolean().optional().default(!0),links:h.boolean().optional().default(!0),formatting:h.boolean().optional().default(!0),absoluteURLs:h.boolean().optional().default(!0),timeout:h.number().min(1).max(30).optional().default(10),baseURL:h.string().optional(),apiKey:h.string().optional()}),func:async({url:e,images:t=!0,links:a=!0,formatting:n=!0,absoluteURLs:r=!0,timeout:o=10,baseURL:i,apiKey:s})=>{try{const c=i||P.baseURL,m=s||P.apiKey?{"x-api-key":s||P.apiKey}:void 0,l=await u.extractContent({query:{url:e,images:t,links:a,formatting:n,absoluteURLs:r,timeout:o},baseUrl:c,...m&&{headers:m}});if(!l.data)return`No content could be extracted from "${e}". Please check the URL and try again.`;const d=l.data;let p=`Content extracted from: ${d.url||e}\n\n`;return d.title&&(p+=`Title: ${d.title}\n\n`),d.author&&(p+=`Author: ${d.author}\n`,d.author_cite&&(p+=`Author (Citation Format): ${d.author_cite}\n`),d.author_type&&(p+=`Author Type: ${d.author_type}\n`)),d.date&&(p+=`Publication Date: ${d.date}\n`),d.source&&(p+=`Source: ${d.source}\n`),d.word_count&&(p+=`Word Count: ${d.word_count}\n`),d.cite&&(p+=`\nCitation (APA Format): ${d.cite}\n`),d.html&&(p+=`\nContent:\n${d.html}\n\n`),p+="This is the complete page extraction information.",p}catch(c){return`Unable to extract content from "${e}". Error: ${c.message}`}}},{name:"generate_ai_response",description:"Generate AI language model responses using QwkSearch API with various agent templates. Supports multiple providers (Groq, OpenAI, Anthropic, etc.) and agent types for different tasks like summarization, question answering, and content generation.",schema:h.object({provider:h.enum(["groq","openai","anthropic","together","xai","google","perplexity","cloudflare"]),key:h.string().optional(),agent:h.enum(["question","summarize-bullets","summarize","suggest-followups","answer-cite-sources","query-resolution","knowledge-graph-nodes","summary-longtext"]).optional().default("question"),model:h.string().optional().default("meta-llama/llama-4-maverick-17b-128e-instruct"),temperature:h.number().min(0).max(2).optional().default(.7),html:h.boolean().optional().default(!0),query:h.string().optional(),chat_history:h.string().optional(),article:h.string().optional(),baseURL:h.string().optional(),apiKey:h.string().optional()}),func:async({provider:e,key:t,agent:a="question",model:n="meta-llama/llama-4-maverick-17b-128e-instruct",temperature:r=.7,html:o=!0,query:i,chat_history:s,article:c,baseURL:m,apiKey:l})=>{try{const d=m||P.baseURL,p=l||P.apiKey?{"x-api-key":l||P.apiKey}:void 0,h={agent:a,provider:e,model:n,html:o,temperature:r};t&&(h.key=t),i&&(h.query=i),s&&(h.chat_history=s),c&&(h.article=c);const g=await u.writeLanguage({body:h,baseUrl:d,...p&&{headers:p}});if(!g.data)return"No response generated. Please check your input parameters and try again.";let y=`AI Response (${a} agent, ${e} provider):\n\n`;return g.data.content&&(y+=g.data.content),g.data.extract&&(y+=`\n\nStructured Extract:\n${JSON.stringify(g.data.extract,null,2)}`),y+="\n\nThis is the complete AI-generated response.",y}catch(d){return`Unable to generate AI response. Error: ${d.message}`}}},{name:"render_page_with_javascript",description:"Render a web page with JavaScript execution using Cloudflare Browser Rendering. Use this for JavaScript-heavy sites (SPAs, React apps), pages behind bot protection (Cloudflare, reCAPTCHA), or when extract_page fails. Returns fully rendered HTML with JavaScript executed. Slower but more complete than extract_page.",schema:h.object({url:h.string().url(),blockImages:h.boolean().optional().default(!0),wait:h.number().min(0).max(1e4).optional().default(0),timeout:h.number().min(1e3).max(6e4).optional().default(3e4),waitUntil:h.enum(["domcontentloaded","load","networkidle0","networkidle2"]).optional().default("networkidle2"),bypassCaptcha:h.boolean().optional().default(!0),sessionId:h.string().optional().default("default"),format:h.enum(["html","json"]).optional().default("html"),scraperUrl:h.string().optional(),scraperApiKey:h.string().optional()}),func:async({url:e,blockImages:t=!0,wait:a=0,timeout:n=3e4,waitUntil:r="networkidle2",bypassCaptcha:o=!0,sessionId:i="default",format:s="html",scraperUrl:c,scraperApiKey:m})=>{try{const l=c||"undefined"!=typeof process&&process?.env?.SCRAPER_URL||"https://scraper.qwksearch.workers.dev",d=m||"undefined"!=typeof process&&process?.env?.SCRAPER_API_KEY,p=new URL("/api/render",l),h={url:e,blockImages:t,wait:a,timeout:n,waitUntil:r,bypassCaptcha:o,sessionId:i,format:s},u={"Content-Type":"application/json"};d&&(u.Authorization=`Bearer ${d}`);const g=await fetch(p.toString(),{method:"POST",headers:u,body:JSON.stringify(h)});if(!g.ok)return`Failed to render page: ${await g.text()}`;if("json"===s){const e=await g.json();let t=`Page rendered successfully: ${e.url}\n\n`;return e.title&&(t+=`Title: ${e.title}\n`),t+=`Load Time: ${e.loadTime}ms\n`,e.challengeBypassed&&(t+=`Challenge Bypassed: Yes (${e.retryCount} retries)\n`),t+=`\nRendered HTML Content:\n${e.html}\n\n`,t+="This is the complete rendered page content.",t}return`Page rendered successfully.\n\nHTML Content:\n${await g.text()}`}catch(l){return`Unable to render page "${e}". Error: ${l.message}`}}}],M=/^(\s*(-|\*|\d+\.\s|\d+\)\s|•)\s*)+/,R=class{key="questions";constructor(e){this.key=e?.key??this.key}async parse(e){const t=(e=e.trim()||"").indexOf(`<${this.key}>`),a=e.indexOf(`</${this.key}>`);if(-1===t||-1===a)return[];const n=t+`<${this.key}>`.length;return e.slice(n,a).trim().split("\n").filter(e=>""!==e.trim()).map(e=>e.replace(M,""))}},C=class{key="questions";constructor(e){this.key=e?.key??this.key}async parse(e){const t=(e=e.trim()||"").indexOf(`<${this.key}>`),a=e.indexOf(`</${this.key}>`);if(-1===t||-1===a)return;const n=t+`<${this.key}>`.length;return e.slice(n,a).trim().replace(M,"")}},B=e=>e.map(e=>`${"assistant"===e.role||"ai"===e.type?"AI":"User"}: ${String(e.content??"")}`).join("\n");function N(e){const t=(e||"").trim(),a=t.length>0?t:"web search";return[{pageContent:"No indexed sources were returned by the configured search providers for this query.",metadata:{title:`Search results for: ${a}`,url:`https://www.google.com/search?q=${encodeURIComponent(a)}`,source:"Google Search"}}]}function D(e,t){return Array.isArray(e)&&e.length>0?e:N(t)}async function U(e,t,a,n,r){if(0===t.length&&0===a.length)return t;let o=[];if(a.length>0&&r&&(o=(await Promise.all(a.map(e=>async function(e,t){try{const{manageStorage:a}=await import("manage-storage"),n={provider:"cloudflare",BUCKET_NAME:t.bucket,ACCESS_KEY_ID:t.accessKeyId,SECRET_ACCESS_KEY:t.secretAccessKey,BUCKET_URL:`https://${t.accountId}.r2.cloudflarestorage.com`},r=`${e}-extracted.json`,o=await a("download",{...n,key:r}),i=JSON.parse(o);return{title:i.title||"Uploaded Document",content:i.content||""}}catch(a){return console.error(`[rerankDocs] Failed to download extracted content for fileId ${e}:`,a),null}}(e,r)))).filter(e=>null!==e)),"summarize"===e.toLocaleLowerCase())return t.slice(0,15);const i=t.filter(e=>e.pageContent&&e.pageContent.length>0);return[...o.map(e=>({pageContent:e.content,metadata:{title:e.title,url:"File"}})),...i].slice(0,15)}function q(e){return e.map((t,a)=>`${a+1}. ${e[a].metadata.title} ${e[a].pageContent}`).join("\n")}async function O(e,t,a){const n=[];for(const o of t){const e=n.find(e=>e.metadata.url===o.metadata.url&&e.metadata.totalDocs<10);e?(e.pageContent+=`\n\n${o.pageContent}`,e.metadata.totalDocs+=1):n.push({...o,metadata:{...o.metadata,totalDocs:1}})}const r=[];return await Promise.all(n.map(async t=>{const{text:n}=await g({model:e,prompt:'You are a web search summarizer, tasked with summarizing a piece of text retrieved from a web search. Your job is to summarize the\ntext into a detailed, 2-4 paragraph explanation that captures the main ideas and provides a comprehensive answer to the query.\nIf the query is "summarize", you should provide a detailed summary of the text. If the query is a specific question, you should answer it in the summary.\n\n- **Journalistic tone**: The summary should sound professional and journalistic, not too casual or vague.\n- **Thorough and detailed**: Ensure that every key point from the text is captured and that the summary directly answers the query.\n- **Not too lengthy, but detailed**: The summary should be informative but not excessively long. Focus on providing detailed information in a concise format.\n\nThe text will be shared inside the `text` XML tag, and the query inside the `query` XML tag.\n\n<example>\n1. `<text>\nDocker is a set of platform-as-a-service products that use OS-level virtualization to deliver software in packages called containers.\nIt was first released in 2013 and is developed by Docker, Inc. Docker is designed to make it easier to create, deploy, and run applications\nby using containers.\n</text>\n\n<query>\nWhat is Docker and how does it work?\n</query>\n\nResponse:\nDocker is a revolutionary platform-as-a-service product developed by Docker, Inc., that uses container technology to make application\ndeployment more efficient. It allows developers to package their software with all necessary dependencies, making it easier to run in\nany environment. Released in 2013, Docker has transformed the way applications are built, deployed, and managed.\n`\n2. `<text>\nThe theory of relativity, or simply relativity, encompasses two interrelated theories of Albert Einstein: special relativity and general\nrelativity. However, the word "relativity" is sometimes used in reference to Galilean invariance. The term "theory of relativity" was based\non the expression "relative theory" used by Max Planck in 1906. The theory of relativity usually encompasses two interrelated theories by\nAlbert Einstein: special relativity and general relativity. Special relativity applies to all physical phenomena in the absence of gravity.\nGeneral relativity explains the law of gravitation and its relation to other forces of nature. It applies to the cosmological and astrophysical\nrealm, including astronomy.\n</text>\n\n<query>\nsummarize\n</query>\n\nResponse:\nThe theory of relativity, developed by Albert Einstein, encompasses two main theories: special relativity and general relativity. Special\nrelativity applies to all physical phenomena in the absence of gravity, while general relativity explains the law of gravitation and its\nrelation to other forces of nature. The theory of relativity is based on the concept of "relative theory," as introduced by Max Planck in\n1906. It is a fundamental theory in physics that has revolutionized our understanding of the universe.\n`\n</example>\n\nEverything below is the actual data you will be working with. Good luck!\n\n<query>\n{question}\n</query>\n\n<text>\n{content}\n</text>\n\nMake sure to answer the query in the summary.'.replace("{question}",a).replace("{content}",t.pageContent)});r.push({pageContent:n,metadata:{title:t.metadata.title,url:t.metadata.url}})})),r.length>0?r:N(a)}var K=class{config;constructor(e){this.config=e}async retrieveSearchDocs(e,t,a,n="general",r=!1,o=0,i){const{text:s}=await g({model:e,temperature:0,system:this.config.queryGeneratorPrompt,messages:[...this.config.queryGeneratorFewShots.map(([e,t])=>({role:e,content:t})),{role:"user",content:`\n <conversation>\n ${t}\n </conversation>\n\n <query>\n ${a}\n </query>\n `}]}),c=new R({key:"links"}),m=new C({key:"question"}),l=await c.parse(s);let d=await m.parse(s)??s;if("not_needed"===d&&(d="latest information"),l.length>0&&this.config.getDocumentsFromLinks){0===d.length&&(d="summarize");const t=await O(e,await this.config.getDocumentsFromLinks({links:l}),d);return{query:d,docs:t}}if(d=d.replace(/<think>.*?<\/think>/g,""),d&&0!==d.trim().length||(d="latest information"),d=d.trim(),d.length>500||d.split(/[.!?]\s+/).length>5){console.warn(`[MetaSearchAgent] Query is too long (${d.length} chars), truncating or using fallback`);const e=d.split(/[.!?]\s+/)[0].trim();d=e.length>0&&e.length<200?e:a.slice(0,200)}const p=this.config.activeEngines.length>0?this.config.activeEngines.slice(0,2).join(", "):"Web",h=(e,t,a)=>{i?.emit("data",JSON.stringify({type:"searching",data:{query:t,category:a??p,status:e}}))};h("running",d);let u={results:[],suggestions:[]};if(this.config.searchSearxng||this.config.searchTavily){const e=async()=>{try{const e=await this.config.searchSearxng(d,{language:"en",engines:this.config.activeEngines,categories:[n]});return e&&"object"==typeof e&&"results"in e?e:{results:[],suggestions:[]}}catch(e){return console.error("[MetaSearchAgent] SearXNG search failed:",e),{results:[],suggestions:[]}}},t=this.config.isTavilyConfigured?.()??!1;if(t&&0===this.config.activeEngines.length&&"general"===n)try{const e=await this.config.searchTavily(d,{searchDepth:"basic",maxResults:10});u=e&&"object"==typeof e&&"results"in e?e:{results:[],suggestions:[]}}catch(L){console.error("Tavily search failed, falling back to SearXNG:",L),u=this.config.searchSearxng?await e():{results:[],suggestions:[]}}else if(t&&this.config.searchTavily)try{u=await Promise.race([e(),new Promise((e,t)=>setTimeout(()=>t(/* @__PURE__ */new Error("Timeout")),1e4))])}catch(b){if("Timeout"===b.message){console.warn("[MetaSearchAgent] SearXNG search did not respond in 10 seconds, falling back to Tavily.");try{const e=await this.config.searchTavily(d,{searchDepth:"basic",maxResults:10});u=e&&"object"==typeof e&&"results"in e?e:{results:[],suggestions:[]}}catch(w){console.error("[MetaSearchAgent] Tavily fallback also failed, awaiting SearXNG directly:",w),u=this.config.searchSearxng?await e():{results:[],suggestions:[]}}}else{console.error("[MetaSearchAgent] SearXNG search failed, falling back to Tavily:",b);try{const e=await this.config.searchTavily(d,{searchDepth:"basic",maxResults:10});u=e&&"object"==typeof e&&"results"in e?e:{results:[],suggestions:[]}}catch(w){console.error("[MetaSearchAgent] Tavily fallback also failed:",w),u={results:[],suggestions:[]}}}}else u=this.config.searchSearxng?await e():{results:[],suggestions:[]}}else u={results:[],suggestions:[]};let y,f,v=(u?.results??[]).map(e=>({pageContent:e.content||(this.config.activeEngines.includes("youtube")?e.title:""),metadata:{title:e.title,url:e.url,source:e.source,...e.img_src&&{img_src:e.img_src}}}));if(0===v.length&&(v=N(d)),h("done",d),o>0?(y=3,f=Math.max(2,Math.floor(o/y))):r?(y=3,f=5):(y=0,f=0),y>0){const e=v.slice(0,y);h("running",`Extracting top ${e.length} sources`,"extract");const t=this.config.scrapeURL?e.map(async(e,t)=>{const a=e.metadata?.url;var n;if(a&&this.config.scrapeURL)try{const e=await(async(e,t)=>Promise.race([e,new Promise(e=>{setTimeout(()=>e(void 0),t)})]))(this.config.scrapeURL(a,{timeout:f}),1e3*f+1500);if("string"==typeof e&&e.length>100){const a=(n=e,n.replace(/<(script|style)[^>]*>[\s\S]*?<\/(script|style)>/gi," ").replace(/<[^>]+>/g," ").replace(/ /g," ").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/&[a-z#][a-z0-9]+;/gi," ").replace(/\s+/g," ").trim()).replace(/(\r\n|\n|\r)/gm," ").replace(/\s+/g," ").trim().slice(0,5e3);a.length>100&&(v[t].pageContent=a)}}catch{}}):[];await Promise.allSettled(t),h("done",`Extracting top ${e.length} sources`,"extract")}return{query:d,docs:v}}async runPipeline(e,t,a,n,r,o,i,s,c,m){try{let r=null,p=t;if(this.config.searchWeb){const o=await this.retrieveSearchDocs(n,B(a),t,s,c,m,e);p=o.query,r=o.docs}const h=process.env.R2_ACCOUNT_ID?{accountId:process.env.R2_ACCOUNT_ID,accessKeyId:process.env.R2_ACCESS_KEY_ID||"",secretAccessKey:process.env.R2_SECRET_ACCESS_KEY||"",bucket:process.env.R2_UPLOADS_BUCKET||"qwksearch-uploads"}:void 0,u=await U(p,r??[],o,0,h),g=D(u,t);g.length,e.emit("data",JSON.stringify({type:"sources",data:g}));const f=y({model:n,temperature:.7,system:(l=this.config.responsePrompt,d={systemInstructions:i,context:q(u),date:/* @__PURE__ */(new Date).toISOString()},Object.entries(d).reduce((e,[t,a])=>e.split(`{${t}}`).join(a),l)),messages:[...a,{role:"user",content:t}]});let v=0;for await(const t of f.textStream)v+=1,e.emit("data",JSON.stringify({type:"response",data:t}));if(0===v){const t=["I couldn't generate a full answer, but I ran a web search and found these source URLs:",...g.map(e=>e.metadata?.url).filter(e=>"string"==typeof e).slice(0,5).map(e=>`- ${e}`)].join("\n");e.emit("data",JSON.stringify({type:"response",data:t}))}e.emit("end")}catch(p){const t=p instanceof Error?p.message:String(p);console.error("[MetaSearchAgent] caught error from AI SDK stream:",t,p);let a=t;t.includes("404")||t.toLowerCase().includes("not found")?a="The selected AI model was not found at the provider. Please go to Settings → Model Providers and select a different model.":t.includes("410")?a="The selected AI model is no longer available (deprecated by the provider). Please go to Settings → Model Providers and select a different model.":t.includes("401")||t.includes("authentication")?a="Authentication failed with the AI provider. Please check your API key in Settings.":(t.includes("429")||t.includes("rate limit"))&&(a="Rate limit reached for the AI provider. Please wait a moment and try again."),e.emit("error",JSON.stringify({data:a}))}var l,d}async searchAndAnswer(e,t,a,n,r,o,i="general",s=!1,c=0){const m=new f;return setTimeout(()=>{this.runPipeline(m,e,t,a,n,r,o,i,s,c)},0),m}},G={webSearchRetrieverPrompt:a,webSearchResponsePrompt:e,webSearchRetrieverFewShots:t,writingAssistantPrompt:r},$=e=>({webSearch:new K({activeEngines:[],queryGeneratorPrompt:G.webSearchRetrieverPrompt,responsePrompt:G.webSearchResponsePrompt,queryGeneratorFewShots:G.webSearchRetrieverFewShots,rerank:!0,rerankThreshold:.3,searchWeb:!0,...e}),academicSearch:new K({activeEngines:["arxiv","google scholar","pubmed"],queryGeneratorPrompt:G.webSearchRetrieverPrompt,responsePrompt:G.webSearchResponsePrompt,queryGeneratorFewShots:G.webSearchRetrieverFewShots,rerank:!0,rerankThreshold:0,searchWeb:!0,...e}),writingAssistant:new K({activeEngines:[],queryGeneratorPrompt:"",queryGeneratorFewShots:[],responsePrompt:G.writingAssistantPrompt,rerank:!0,rerankThreshold:0,searchWeb:!0,...e}),wolframAlphaSearch:new K({activeEngines:["wolframalpha"],queryGeneratorPrompt:G.webSearchRetrieverPrompt,responsePrompt:G.webSearchResponsePrompt,queryGeneratorFewShots:G.webSearchRetrieverFewShots,rerank:!1,rerankThreshold:0,searchWeb:!0,...e}),youtubeSearch:new K({activeEngines:["youtube"],queryGeneratorPrompt:G.webSearchRetrieverPrompt,responsePrompt:G.webSearchResponsePrompt,queryGeneratorFewShots:G.webSearchRetrieverFewShots,rerank:!0,rerankThreshold:.3,searchWeb:!0,...e}),redditSearch:new K({activeEngines:["reddit"],queryGeneratorPrompt:G.webSearchRetrieverPrompt,responsePrompt:G.webSearchResponsePrompt,queryGeneratorFewShots:G.webSearchRetrieverFewShots,rerank:!0,rerankThreshold:.3,searchWeb:!0,...e})}),z=$(),F=(e=4)=>`\nYou are an AI suggestion generator for an AI powered search engine. You will be given a conversation below. You need to generate ${e} suggestions based on the conversation. The suggestion should be relevant to the conversation that can be used by the user to ask the chat model for more information.\nYou need to make sure the suggestions are relevant to the conversation and are helpful to the user. Keep a note that the user might use these suggestions to ask a chat model for more information.\nMake sure the suggestions are medium in length and are informative and relevant to the conversation.\n\nProvide these suggestions separated by newlines between the XML tags <suggestions> and </suggestions>. For example:\n\n<suggestions>\nTell me more about SpaceX and their recent projects\nWhat is the latest news on SpaceX?\nWho is the CEO of SpaceX?\n</suggestions>\n\nConversation:\n{chat_history}\n`,Y=new R({key:"suggestions"}),V=async(e,t)=>{const a=e.maxQuestions??4,{text:n}=await g({model:t,temperature:0,prompt:F(a).replace("{chat_history}",B(e.chat_history))});return Y.parse(n)};function H(e,t=1e3,a=200){const n=(e||"").trim();if(n.length<=t)return n.length>0?[n]:[];const r=[];let o=0;for(;o<n.length;){let e=Math.min(o+t,n.length);if(e<n.length){const t=n.lastIndexOf(" ",e);t>o&&(e=t)}if(r.push(n.slice(o,e).trim()),e>=n.length)break;o=Math.max(e-a,o+1)}return r.filter(e=>e.length>0)}var Q=()=>[{key:"openai",name:"OpenAI",fields:[{type:"password",name:"API Key",key:"apiKey",description:"Your OpenAI API key",required:!0,placeholder:"OpenAI API Key",env:"OPENAI_API_KEY",scope:"server"},{type:"string",name:"Base URL",key:"baseURL",description:"The base URL for the OpenAI API",required:!0,placeholder:"OpenAI Base URL",default:"https://api.openai.com/v1",env:"OPENAI_BASE_URL",scope:"server"}]},{key:"anthropic",name:"Anthropic",fields:[{type:"password",name:"API Key",key:"apiKey",description:"Your Anthropic API key",required:!0,placeholder:"Anthropic API Key",env:"ANTHROPIC_API_KEY",scope:"server"}]},{key:"gemini",name:"Google Gemini",fields:[{type:"password",name:"API Key",key:"apiKey",description:"Your Google Gemini API key",required:!0,placeholder:"Google Gemini API Key",env:"GEMINI_API_KEY",scope:"server"}]},{key:"groq",name:"Groq",fields:[{type:"password",name:"API Key",key:"apiKey",description:"Your Groq API key. Free tier includes fast inference on Llama and Mixtral models - get yours at console.groq.com",required:!0,placeholder:"gsk_...",env:"GROQ_API_KEY",scope:"server"}]},{key:"deepseek",name:"DeepSeek",fields:[{type:"password",name:"API Key",key:"apiKey",description:"Your DeepSeek API key",required:!0,placeholder:"DeepSeek API Key",env:"DEEPSEEK_API_KEY",scope:"server"}]},{key:"nvidia",name:"NVIDIA",fields:[{type:"password",name:"API Key",key:"apiKey",description:"Your NVIDIA API key. Free tier includes access to Nemotron, Llama, and other models - get yours at build.nvidia.com",required:!0,placeholder:"nvapi-...",env:"NVIDIA_API_KEY",scope:"server"},{type:"string",name:"Base URL",key:"baseURL",description:"The base URL for NVIDIA's OpenAI-compatible API",required:!0,placeholder:"https://integrate.api.nvidia.com/v1",default:"https://integrate.api.nvidia.com/v1",env:"NVIDIA_BASE_URL",scope:"server"}]},{key:"openrouter",name:"OpenRouter",fields:[{type:"password",name:"API Key",key:"apiKey",description:"Your OpenRouter API key. Get one free at openrouter.ai - includes free access to Llama 3.3 70B, Nemotron, and other models.",required:!0,placeholder:"sk-or-v1-...",env:"OPENROUTER_API_KEY",scope:"server"},{type:"string",name:"Base URL",key:"baseURL",description:"The base URL for OpenRouter's OpenAI-compatible API",required:!0,placeholder:"https://openrouter.ai/api/v1",default:"https://openrouter.ai/api/v1",env:"OPENROUTER_BASE_URL",scope:"server"}]}];function j(e){try{return v("cloudflare:workers").env?.[e]}catch{return process.env[e]}}var W=[{provider:"NVIDIA",docs:"https://docs.api.nvidia.com/nim/reference/llm-apis",api_key:"https://build.nvidia.com/settings/api-keys",default:"nvidia/llama-3.1-nemotron-70b-instruct",models:[{name:"Llama 3.1 Nemotron 70B Instruct",id:"nvidia/llama-3.1-nemotron-70b-instruct",contextLength:131072,free:!0,type:"text-generation"},{name:"Nemotron 3 Super 120B",id:"nvidia/nemotron-3-super-120b-a12b",contextLength:1e6,free:!0,type:"text-generation"},{name:"Nemotron-4 340B",id:"nvidia/nemotron-4-340b",contextLength:131072,free:!1,type:"text-generation"},{name:"Llama 3.3 70B Instruct",id:"meta/llama-3.3-70b-instruct",contextLength:131072,free:!0,type:"text-generation"},{name:"Llama 3.1 405B Instruct",id:"meta/llama-3.1-405b-instruct",contextLength:131072,free:!1,type:"text-generation"},{name:"Llama 3.1 8B Instruct",id:"meta/llama-3.1-8b-instruct",contextLength:131072,free:!0,type:"text-generation"},{name:"Gemma 4 31B IT",id:"google/gemma-4-31b-it",contextLength:131072,free:!0,type:"text-generation"},{name:"Mistral Large 2",id:"mistralai/mistral-large-2",contextLength:131072,free:!1,type:"text-generation"}]},{provider:"Cloudflare",docs:"https://developers.cloudflare.com/workers-ai/",api_key:"https://dash.cloudflare.com/profile/api-tokens",default:"llama-4-scout-17b-16e-instruct",models:[{name:"Llama 4 Scout 17B 16E Instruct",id:"llama-4-scout-17b-16e-instruct",contextLength:128e3},{name:"Llama 3.3 70B Instruct FP8 Fast",id:"llama-3.3-70b-instruct-fp8-fast",contextLength:128e3},{name:"Llama 3.1 8B Instruct Fast",id:"llama-3.1-8b-instruct-fast",contextLength:128e3},{name:"Gemma 3 12B IT",id:"gemma-3-12b-it",contextLength:128e3},{name:"Mistral Small 3.1 24B Instruct",id:"mistral-small-3.1-24b-instruct",contextLength:128e3},{name:"QwQ 32B",id:"qwq-32b",contextLength:32768},{name:"Qwen2.5 Coder 32B Instruct",id:"qwen2.5-coder-32b-instruct",contextLength:32768},{name:"Llama Guard 3 8B",id:"llama-guard-3-8b",contextLength:8192},{name:"DeepSeek R1 Distill Qwen 32B",id:"deepseek-r1-distill-qwen-32b",contextLength:32768},{name:"Llama 3.2 1B Instruct",id:"llama-3.2-1b-instruct",contextLength:131072},{name:"Llama 3.2 3B Instruct",id:"llama-3.2-3b-instruct",contextLength:131072},{name:"Llama 3.2 11B Vision Instruct",id:"llama-3.2-11b-vision-instruct",contextLength:131072},{name:"Llama 3.1 8B Instruct AWQ",id:"llama-3.1-8b-instruct-awq",contextLength:128e3},{name:"Llama 3.1 8B Instruct FP8",id:"llama-3.1-8b-instruct-fp8",contextLength:128e3},{name:"MeloTTS",id:"melotts",contextLength:1024},{name:"Llama 3.1 8B Instruct",id:"llama-3.1-8b-instruct",contextLength:128e3},{name:"Meta Llama 3 8B Instruct",id:"meta-llama-3-8b-instruct",contextLength:8192},{name:"Whisper Large V3 Turbo",id:"whisper-large-v3-turbo",contextLength:448e3},{name:"Llama 3 8B Instruct AWQ",id:"llama-3-8b-instruct-awq",contextLength:8192},{name:"LLaVA 1.5 7B HF",id:"llava-1.5-7b-hf",contextLength:4096},{name:"Una Cybertron 7B V2 BF16",id:"una-cybertron-7b-v2-bf16",contextLength:32768},{name:"Whisper Tiny EN",id:"whisper-tiny-en",contextLength:448e3},{name:"Llama 3 8B Instruct",id:"llama-3-8b-instruct",contextLength:8192},{name:"Mistral 7B Instruct v0.2",id:"mistral-7b-instruct-v0.2",contextLength:32768},{name:"Gemma 7B IT LoRA",id:"gemma-7b-it-lora",contextLength:8192},{name:"Gemma 2B IT LoRA",id:"gemma-2b-it-lora",contextLength:8192},{name:"Llama 2 7B Chat HF LoRA",id:"llama-2-7b-chat-hf-lora",contextLength:4096},{name:"Gemma 7B IT",id:"gemma-7b-it",contextLength:8192},{name:"Starling LM 7B Beta",id:"starling-lm-7b-beta",contextLength:8192},{name:"Hermes 2 Pro Mistral 7B",id:"hermes-2-pro-mistral-7b",contextLength:32768},{name:"Mistral 7B Instruct v0.2 LoRA",id:"mistral-7b-instruct-v0.2-lora",contextLength:32768},{name:"Qwen1.5 1.8B Chat",id:"qwen1.5-1.8b-chat",contextLength:32768},{name:"UForm Gen2 Qwen 500M",id:"uform-gen2-qwen-500m",contextLength:2048},{name:"BART Large CNN",id:"bart-large-cnn",contextLength:1024},{name:"Phi-2",id:"phi-2",contextLength:2048},{name:"TinyLlama 1.1B Chat v1.0",id:"tinyllama-1.1b-chat-v1.0",contextLength:2048},{name:"Qwen1.5 14B Chat AWQ",id:"qwen1.5-14b-chat-awq",contextLength:32768},{name:"Qwen1.5 7B Chat AWQ",id:"qwen1.5-7b-chat-awq",contextLength:32768},{name:"Qwen1.5 0.5B Chat",id:"qwen1.5-0.5b-chat",contextLength:32768},{name:"DiscoLM German 7B v1 AWQ",id:"discolm-german-7b-v1-awq",contextLength:32768},{name:"Falcon 7B Instruct",id:"falcon-7b-instruct",contextLength:2048},{name:"OpenChat 3.5 0106",id:"openchat-3.5-0106",contextLength:8192},{name:"SQLCoder 7B 2",id:"sqlcoder-7b-2",contextLength:16384},{name:"DeepSeek Math 7B Instruct",id:"deepseek-math-7b-instruct",contextLength:4096},{name:"DETR ResNet-50",id:"detr-resnet-50",contextLength:1024},{name:"Stable Diffusion XL Lightning",id:"stable-diffusion-xl-lightning",contextLength:77},{name:"DreamShaper 8 LCM",id:"dreamshaper-8-lcm",contextLength:77},{name:"Stable Diffusion v1.5 Img2Img",id:"stable-diffusion-v1-5-img2img",contextLength:77},{name:"Stable Diffusion v1.5 Inpainting",id:"stable-diffusion-v1-5-inpainting",contextLength:77},{name:"DeepSeek Coder 6.7B Instruct AWQ",id:"deepseek-coder-6.7b-instruct-awq",contextLength:16384},{name:"DeepSeek Coder 6.7B Base AWQ",id:"deepseek-coder-6.7b-base-awq",contextLength:16384},{name:"LlamaGuard 7B AWQ",id:"llamaguard-7b-awq",contextLength:4096},{name:"Neural Chat 7B v3.1 AWQ",id:"neural-chat-7b-v3-1-awq",contextLength:8192},{name:"OpenHermes 2.5 Mistral 7B AWQ",id:"openhermes-2.5-mistral-7b-awq",contextLength:8192},{name:"Llama 2 13B Chat AWQ",id:"llama-2-13b-chat-awq",contextLength:4096},{name:"Mistral 7B Instruct v0.1 AWQ",id:"mistral-7b-instruct-v0.1-awq",contextLength:8192},{name:"Zephyr 7B Beta AWQ",id:"zephyr-7b-beta-awq",contextLength:8192},{name:"Stable Diffusion XL Base 1.0",id:"stable-diffusion-xl-base-1.0",contextLength:77},{name:"BGE Large EN v1.5",id:"bge-large-en-v1.5",contextLength:512},{name:"BGE Small EN v1.5",id:"bge-small-en-v1.5",contextLength:512},{name:"Llama 2 7B Chat FP16",id:"llama-2-7b-chat-fp16",contextLength:4096},{name:"Mistral 7B Instruct v0.1",id:"mistral-7b-instruct-v0.1",contextLength:8192},{name:"BGE Base EN v1.5",id:"bge-base-en-v1.5",contextLength:512},{name:"DistilBERT SST-2 Int8",id:"distilbert-sst-2-int8",contextLength:512},{name:"Llama 2 7B Chat Int8",id:"llama-2-7b-chat-int8",contextLength:4096},{name:"M2M100 1.2B",id:"m2m100-1.2b",contextLength:1024},{name:"ResNet-50",id:"resnet-50",contextLength:224},{name:"Whisper",id:"whisper",contextLength:448e3},{name:"Llama 3.1 70B Instruct",id:"llama-3.1-70b-instruct",contextLength:128e3}]},{provider:"Perplexity",docs:"https://docs.perplexity.ai/models/model-cards",api_key:"https://www.perplexity.ai/account/api/keys",default:"sonar",models:[{name:"Sonar Pro",id:"sonar-pro",contextLength:2e5},{name:"Sonar",id:"sonar",contextLength:128e3},{name:"Sonar Reasoning Pro",id:"sonar-reasoning-pro",contextLength:128e3},{name:"Sonar Reasoning",id:"sonar-reasoning",contextLength:128e3},{name:"Sonar Deep Research",id:"sonar-deep-research",contextLength:128e3},{name:"Llama 3.1 Sonar Small 128k Online",id:"llama-3.1-sonar-small-128k-online",contextLength:127072},{name:"Llama 3.1 Sonar Large 128k Online",id:"llama-3.1-sonar-large-128k-online",contextLength:127072},{name:"Llama 3.1 Sonar Huge 128k Online",id:"llama-3.1-sonar-huge-128k-online",contextLength:127072}]},{provider:"Groq",docs:"https://console.groq.com/docs/overview",api_key:"https://console.groq.com/keys",default:"llama-3.3-70b-versatile",models:[{name:"Llama 3.3 70B Versatile (Free)",id:"llama-3.3-70b-versatile",contextLength:131072,free:!0,type:"text-generation",rateLimit:"300K TPM / 1K RPM = ~432M tokens/day"},{name:"Llama 3.1 8B Instant (Free)",id:"llama-3.1-8b-instant",contextLength:8192,free:!0,type:"text-generation",rateLimit:"250K TPM / 1K RPM = ~360M tokens/day"},{name:"Llama 4 Scout 17B (Free)",id:"meta-llama/llama-4-scout-17b-16e-instruct",contextLength:131072,free:!0,type:"text-generation",rateLimit:"300K TPM / 1K RPM = ~432M tokens/day"},{name:"Qwen 3 32B (Free)",id:"qwen/qwen3-32b",contextLength:128e3,free:!0,type:"text-generation",rateLimit:"300K TPM / 1K RPM = ~432M tokens/day"},{name:"GPT-OSS 120B (Free)",id:"openai/gpt-oss-120b",contextLength:32768,free:!0,type:"text-generation",rateLimit:"250K TPM / 1K RPM = ~360M tokens/day"},{name:"GPT-OSS 20B (Free)",id:"openai/gpt-oss-20b",contextLength:32768,free:!0,type:"text-generation",rateLimit:"250K TPM / 1K RPM = ~360M tokens/day"},{name:"Groq Compound (Free)",id:"groq/compound",contextLength:32768,free:!0,type:"text-generation",rateLimit:"200K TPM / 200 RPM = ~288M tokens/day"},{name:"Groq Compound Mini (Free)",id:"groq/compound-mini",contextLength:32768,free:!0,type:"text-generation",rateLimit:"200K TPM / 200 RPM = ~288M tokens/day"},{name:"GPT-OSS Safeguard 20B (Free)",id:"openai/gpt-oss-safeguard-20b",contextLength:32768,free:!0,type:"text-generation",rateLimit:"150K TPM / 1K RPM = ~216M tokens/day"}]},{provider:"OpenAI",docs:"https://platform.openai.com/docs/overview",api_key:"https://platform.openai.com/api-keys",default:"gpt-4o",models:[{name:"GPT-4 Omni",id:"gpt-4o",contextLength:128e3},{name:"GPT-4 Omni Mini",id:"gpt-4o-mini",contextLength:128e3},{name:"GPT-4 Turbo",id:"gpt-4-turbo",contextLength:128e3},{name:"GPT-4",id:"gpt-4",contextLength:8192},{name:"GPT-3.5 Turbo",id:"gpt-3.5-turbo",contextLength:16385}]},{provider:"Anthropic",docs:"https://docs.anthropic.com/en/docs/welcome",api_key:"https://console.anthropic.com/settings/keys",default:"claude-3-7-sonnet-20250219",models:[{name:"Claude 3.7 Sonnet",id:"claude-3-7-sonnet-20250219",contextLength:2e5},{name:"Claude 3.5 Sonnet",id:"claude-3-5-sonnet-20241022",contextLength:2e5},{name:"Claude 3 Opus",id:"claude-3-opus-20240229",contextLength:2e5},{name:"Claude 3 Sonnet",id:"claude-3-sonnet-20240229",contextLength:2e5},{name:"Claude 3 Haiku",id:"claude-3-haiku-20240307",contextLength:2e5}]},{provider:"TogetherAI",docs:"https://docs.together.ai/docs/quickstart",api_key:"https://api.together.xyz/settings/api-keys",default:"meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo",models:[{name:"Llama 3.1 8B Instruct Turbo",id:"meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo",contextLength:131072},{name:"Llama 3.1 70B Instruct Turbo",id:"meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo",contextLength:131072},{name:"Llama 3.1 405B Instruct Turbo",id:"meta-llama/Meta-Llama-3.1-405B-Instruct-Turbo",contextLength:130815},{name:"Llama 3 8B Instruct Turbo",id:"meta-llama/Meta-Llama-3-8B-Instruct-Turbo",contextLength:8192},{name:"Llama 3 70B Instruct Turbo",id:"meta-llama/Meta-Llama-3-70B-Instruct-Turbo",contextLength:8192},{name:"Llama 3.2 3B Instruct Turbo",id:"meta-llama/Llama-3.2-3B-Instruct-Turbo",contextLength:131072},{name:"Llama 3 8B Instruct Lite",id:"meta-llama/Meta-Llama-3-8B-Instruct-Lite",contextLength:8192},{name:"Llama 3 70B Instruct Lite",id:"meta-llama/Meta-Llama-3-70B-Instruct-Lite",contextLength:8192},{name:"Llama 3 8B Instruct Reference",id:"meta-llama/Llama-3-8b-chat-hf",contextLength:8192},{name:"Llama 3 70B Instruct Reference",id:"meta-llama/Llama-3-70b-chat-hf",contextLength:8192},{name:"Llama 3.1 Nemotron 70B",id:"nvidia/Llama-3.1-Nemotron-70B-Instruct-HF",contextLength:32768},{name:"Qwen 2.5 Coder 32B Instruct",id:"Qwen/Qwen2.5-Coder-32B-Instruct",contextLength:32769},{name:"WizardLM-2 8x22B",id:"microsoft/WizardLM-2-8x22B",contextLength:65536},{name:"Gemma 2 27B",id:"google/gemma-2-27b-it",contextLength:8192},{name:"Gemma 2 9B",id:"google/gemma-2-9b-it",contextLength:8192},{name:"DBRX Instruct",id:"databricks/dbrx-instruct",contextLength:32768},{name:"DeepSeek LLM Chat (67B)",id:"deepseek-ai/deepseek-llm-67b-chat",contextLength:4096},{name:"Gemma Instruct (2B)",id:"google/gemma-2b-it",contextLength:8192},{name:"MythoMax-L2 (13B)",id:"Gryphe/MythoMax-L2-13b",contextLength:4096},{name:"LLaMA-2 Chat (13B)",id:"meta-llama/Llama-2-13b-chat-hf",contextLength:4096},{name:"Mistral (7B) Instruct",id:"mistralai/Mistral-7B-Instruct-v0.1",contextLength:8192},{name:"Mistral (7B) Instruct v0.2",id:"mistralai/Mistral-7B-Instruct-v0.2",contextLength:32768},{name:"Mistral (7B) Instruct v0.3",id:"mistralai/Mistral-7B-Instruct-v0.3",contextLength:32768},{name:"Mixtral-8x7B Instruct (46.7B)",id:"mistralai/Mixtral-8x7B-Instruct-v0.1",contextLength:32768},{name:"Mixtral-8x22B Instruct (141B)",id:"mistralai/Mixtral-8x22B-Instruct-v0.1",contextLength:65536},{name:"Nous Hermes 2 - Mixtral 8x7B-DPO (46.7B)",id:"NousResearch/Nous-Hermes-2-Mixtral-8x7B-DPO",contextLength:32768},{name:"Qwen 2.5 7B Instruct Turbo",id:"Qwen/Qwen2.5-7B-Instruct-Turbo",contextLength:32768},{name:"Qwen 2.5 72B Instruct Turbo",id:"Qwen/Qwen2.5-72B-Instruct-Turbo",contextLength:32768},{name:"Qwen 2 Instruct (72B)",id:"Qwen/Qwen2-72B-Instruct",contextLength:32768},{name:"StripedHyena Nous (7B)",id:"togethercomputer/StripedHyena-Nous-7B",contextLength:32768},{name:"Upstage SOLAR Instruct v1 (11B)",id:"upstage/SOLAR-10.7B-Instruct-v1.0",contextLength:4096},{name:"Llama 3.2 11B Vision Instruct Turbo (Free)",id:"meta-llama/Llama-Vision-Free",contextLength:131072},{name:"Llama 3.2 11B Vision Instruct Turbo",id:"meta-llama/Llama-3.2-11B-Vision-Instruct-Turbo",contextLength:131072},{name:"Llama 3.2 90B Vision Instruct Turbo",id:"meta-llama/Llama-3.2-90B-Vision-Instruct-Turbo",contextLength:131072}]},{provider:"XAI",docs:"https://docs.x.ai/docs#models",api_key:"https://console.x.ai/",default:"grok-beta",models:[{name:"Grok",id:"grok-beta",contextLength:131072},{name:"Grok Vision",id:"grok-vision-beta",contextLength:8192}]},{provider:"Google",docs:"https://cloud.google.com/vertex-ai/generative-ai/docs/learn/models",api_key:"https://cloud.google.com/vertex-ai/generative-ai/docs/start/express-mode/overview#api-keys",models:[{name:"Gemini 2.5 Pro Preview",id:"gemini-2.5-pro-preview-05-06",contextLength:1048576},{name:"Gemini 2.5 Flash Preview",id:"gemini-2.5-flash-preview-04-17",contextLength:1048576},{name:"Gemini 2.0 Flash",id:"gemini-2.0-flash-001",contextLength:1048576},{name:"Gemini 2.0 Flash-Lite",id:"gemini-2.0-flash-lite-001",contextLength:1048576},{name:"Gemini 2.0 Flash-Live",id:"gemini-2.0-flash-live-preview-04-09",contextLength:32768},{name:"Imagen 3",id:"imagen-3.0-generate-002",contextLength:480},{name:"Imagen 3 Fast",id:"imagen-3.0-fast-generate-001",contextLength:480},{name:"Llama 3.2 90B Vision Instruct Turbo",id:"meta-llama/Llama-3.2-90B-Vision-Instruct-Turbo",contextLength:131072},{name:"Llama 3.3 70B",id:"meta-llama/Llama-3.3-70B",contextLength:131072},{name:"Gemma 3",id:"gemma-3",contextLength:131072},{name:"Gemma 2",id:"gemma-2",contextLength:131072},{name:"Gemma",id:"gemma",contextLength:131072}]},{provider:"Amazon",docs:"https://docs.aws.amazon.com/bedrock/",api_key:"https://console.aws.amazon.com/iam/home#/security_credentials",default:"anthropic.claude-3-5-sonnet-20241022-v2:0",models:[{name:"AI21 Jamba 1.5 Mini",id:"ai21.jamba-1-5-mini-v1:0",contextLength:256e3,provider:"AI21 Labs"},{name:"AI21 Jamba 1.5 Large",id:"ai21.jamba-1-5-large-v1:0",contextLength:256e3,provider:"AI21 Labs"},{name:"Amazon Nova Canvas",id:"amazon.nova-canvas-v1:0",contextLength:77,provider:"Amazon",type:"image"},{name:"Amazon Nova Lite",id:"amazon.nova-lite-v1:0",contextLength:3e5,provider:"Amazon"},{name:"Amazon Nova Micro",id:"amazon.nova-micro-v1:0",contextLength:128e3,provider:"Amazon"},{name:"Amazon Nova Pro",id:"amazon.nova-pro-v1:0",contextLength:3e5,provider:"Amazon"},{name:"Amazon Nova Reel",id:"amazon.nova-reel-v1:0",contextLength:1e4,provider:"Amazon",type:"video"},{name:"Amazon Nova Reel V2 Lite",id:"amazon.nova-reel-v2-lite-v1:0",contextLength:1e4,provider:"Amazon",type:"video"},{name:"Amazon Nova Reel V2 Standard",id:"amazon.nova-reel-v2-standard-v1:0",contextLength:1e4,provider:"Amazon",type:"video"},{name:"Amazon Rerank",id:"amazon.rerank-v1:0",contextLength:8192,provider:"Amazon",type:"reranker"},{name:"Amazon Titan Embeddings G1 - Text",id:"amazon.titan-embed-text-v1",contextLength:8192,provider:"Amazon",type:"embedding"},{name:"Amazon Titan Embeddings G1 - Text v2",id:"amazon.titan-embed-text-v2:0",contextLength:8192,provider:"Amazon",type:"embedding"},{name:"Amazon Titan Image Generator G1",id:"amazon.titan-image-generator-v1",contextLength:128,provider:"Amazon",type:"image"},{name:"Amazon Titan Image Generator G2",id:"amazon.titan-image-generator-v2:0",contextLength:128,provider:"Amazon",type:"image"},{name:"Amazon Titan Multimodal Embeddings G1",id:"amazon.titan-embed-image-v1",contextLength:8192,provider:"Amazon",type:"embedding"},{name:"Amazon Titan Text G1 - Express",id:"amazon.titan-text-express-v1",contextLength:8192,provider:"Amazon"},{name:"Amazon Titan Text G1 - Lite",id:"amazon.titan-text-lite-v1",contextLength:4096,provider:"Amazon"},{name:"Amazon Titan Text G1 - Premier",id:"amazon.titan-text-premier-v1:0",contextLength:32e3,provider:"Amazon"},{name:"Claude 3.5 Sonnet v2",id:"anthropic.claude-3-5-sonnet-20241022-v2:0",contextLength:2e5,provider:"Anthropic"},{name:"Claude 3.5 Sonnet v1",id:"anthropic.claude-3-5-sonnet-20240620-v1:0",contextLength:2e5,provider:"Anthropic"},{name:"Claude 3.5 Haiku",id:"anthropic.claude-3-5-haiku-20241022-v1:0",contextLength:2e5,provider:"Anthropic"},{name:"Claude 3 Opus",id:"anthropic.claude-3-opus-20240229-v1:0",contextLength:2e5,provider:"Anthropic"},{name:"Claude 3 Sonnet",id:"anthropic.claude-3-sonnet-20240229-v1:0",contextLength:2e5,provider:"Anthropic"},{name:"Claude 3 Haiku",id:"anthropic.claude-3-haiku-20240307-v1:0",contextLength:2e5,provider:"Anthropic"},{name:"Claude Instant",id:"anthropic.claude-instant-v1",contextLength:1e5,provider:"Anthropic"},{name:"Cohere Command",id:"cohere.command-text-v14",contextLength:4096,provider:"Cohere"},{name:"Cohere Command Light",id:"cohere.command-light-text-v14",contextLength:4096,provider:"Cohere"},{name:"Cohere Command R",id:"cohere.command-r-v1:0",contextLength:128e3,provider:"Cohere"},{name:"Cohere Command R+",id:"cohere.command-r-plus-v1:0",contextLength:128e3,provider:"Cohere"},{name:"Cohere Embed English",id:"cohere.embed-english-v3",contextLength:512,provider:"Cohere",type:"embedding"},{name:"Cohere Embed Multilingual",id:"cohere.embed-multilingual-v3",contextLength:512,provider:"Cohere",type:"embedding"},{name:"Cohere Rerank English",id:"cohere.rerank-english-v3:0",contextLength:4096,provider:"Cohere",type:"reranker"},{name:"Cohere Rerank Multilingual",id:"cohere.rerank-multilingual-v3:0",contextLength:4096,provider:"Cohere",type:"reranker"},{name:"DeepSeek R1",id:"deepseek.deepseek-r1-distill-qwen-32b-v1:0",contextLength:32768,provider:"DeepSeek"},{name:"Luma Dream Machine",id:"luma.dream-machine-v1:0",contextLength:512,provider:"Luma AI",type:"video"},{name:"Llama 3.2 11B Vision Instruct",id:"meta.llama3-2-11b-instruct-v1:0",contextLength:128e3,provider:"Meta"},{name:"Llama 3.2 90B Vision Instruct",id:"meta.llama3-2-90b-instruct-v1:0",contextLength:128e3,provider:"Meta"},{name:"Mistral 7B Instruct",id:"mistral.mistral-7b-instruct-v0:2",contextLength:32768,provider:"Mistral AI"},{name:"Mixtral 8x7B Instruct",id:"mistral.mixtral-8x7b-instruct-v0:1",contextLength:32768,provider:"Mistral AI"},{name:"Mistral Small",id:"mistral.mistral-small-2402-v1:0",contextLength:32768,provider:"Mistral AI"},{name:"Mistral Large",id:"mistral.mistral-large-2402-v1:0",contextLength:32768,provider:"Mistral AI"},{name:"Mistral Large 2",id:"mistral.mistral-large-2407-v1:0",contextLength:128e3,provider:"Mistral AI"},{name:"Mistral Large 2411",id:"mistral.mistral-large-2411-v1:0",contextLength:128e3,provider:"Mistral AI"},{name:"Stable Diffusion XL",id:"stability.stable-diffusion-xl-v1",contextLength:77,provider:"Stability AI",type:"image"},{name:"SDXL 1.0",id:"stability.stable-diffusion-xl-v0",contextLength:77,provider:"Stability AI",type:"image"},{name:"Stable Image Ultra",id:"stability.stable-image-ultra-v1:0",contextLength:77,provider:"Stability AI",type:"image"},{name:"Stable Image Core",id:"stability.stable-image-core-v1:0",contextLength:77,provider:"Stability AI",type:"image"}]},{provider:"OpenRouter",docs:"https://openrouter.ai/docs",api_key:"https://openrouter.ai/settings/keys",default:"openrouter/free",models:[{name:"OpenRouter Free (rotating)",id:"openrouter/free",contextLength:2e5,free:!0,type:"text-generation"},{name:"Nemotron 3 Super 120B",id:"nvidia/nemotron-3-super-120b-a12b:free",contextLength:1e6,free:!0,type:"text-generation"},{name:"Nemotron 3 Ultra 550B",id:"nvidia/nemotron-3-ultra-550b-a55b:free",contextLength:1e6,free:!0,type:"text-generation"},{name:"Nemotron 3 Nano 30B A3B",id:"nvidia/nemotron-3-nano-30b-a3b:free",contextLength:256e3,free:!0,type:"text-generation"},{name:"Nemotron 3 Nano Omni 30B A3B Reasoning",id:"nvidia/nemotron-3-nano-omni-30b-a3b-reasoning:free",contextLength:256e3,free:!0,type:"text-generation"},{name:"Nemotron Nano 12B v2 VL",id:"nvidia/nemotron-nano-12b-v2-vl:free",contextLength:128e3,free:!0,type:"text-generation"},{name:"Nemotron Nano 9B v2",id:"nvidia/nemotron-nano-9b-v2:free",contextLength:128e3,free:!0,type:"text-generation"},{name:"Nemotron 3.5 Content Safety",id:"nvidia/nemotron-3.5-content-safety:free",contextLength:128e3,free:!0,type:"text-generation"},{name:"Gemma 4 31B IT",id:"google/gemma-4-31b-it:free",contextLength:262e3,free:!0,type:"text-generation"},{name:"Gemma 4 26B A4B IT",id:"google/gemma-4-26b-a4b-it:free",contextLength:262e3,free:!0,type:"text-generation"},{name:"GPT-OSS 120B",id:"openai/gpt-oss-120b:free",contextLength:131072,free:!0,type:"text-generation"},{name:"GPT-OSS 20B",id:"openai/gpt-oss-20b:free",contextLength:131072,free:!0,type:"text-generation"},{name:"Qwen3 Coder",id:"qwen/qwen3-coder:free",contextLength:1e6,free:!0,type:"text-generation"},{name:"Qwen3 Next 80B A3B Instruct",id:"qwen/qwen3-next-80b-a3b-instruct:free",contextLength:262e3,free:!0,type:"text-generation"},{name:"Llama 3.3 70B Instruct",id:"meta-llama/llama-3.3-70b-instruct:free",contextLength:131072,free:!0,type:"text-generation"},{name:"Llama 3.2 3B Instruct",id:"meta-llama/llama-3.2-3b-instruct:free",contextLength:131072,free:!0,type:"text-generation"},{name:"Hermes 3 Llama 3.1 405B",id:"nousresearch/hermes-3-llama-3.1-405b:free",contextLength:131072,free:!0,type:"text-generation"},{name:"Laguna XS 2.1",id:"poolside/laguna-xs-2.1:free",contextLength:262e3,free:!0,type:"text-generation"},{name:"Laguna XS 2",id:"poolside/laguna-xs.2:free",contextLength:262e3,free:!0,type:"text-generation"},{name:"Laguna M 1",id:"poolside/laguna-m.1:free",contextLength:262e3,free:!0,type:"text-generation"},{name:"North Mini Code",id:"cohere/north-mini-code:free",contextLength:256e3,free:!0,type:"text-generation"},{name:"Dolphin Mistral 24B Venice Edition",id:"cognitivecomputations/dolphin-mistral-24b-venice-edition:free",contextLength:33e3,free:!0,type:"text-generation"},{name:"LFM 2.5 1.2B Thinking",id:"liquid/lfm-2.5-1.2b-thinking:free",contextLength:33e3,free:!0,type:"text-generation"},{name:"LFM 2.5 1.2B Instruct",id:"liquid/lfm-2.5-1.2b-instruct:free",contextLength:33e3,free:!0,type:"text-generation"},{name:"OpenRouter Free (rotating)",id:"openrouter/free",contextLength:2e5,free:!0,type:"text-generation"}]}],X=(W.map(e=>e.provider.toLocaleLowerCase()),{openrouter:["openrouter/free","nvidia/nemotron-3-super-120b-a12b:free","nvidia/nemotron-3-ultra-550b-a55b:free","nvidia/nemotron-3-nano-30b-a3b:free","nvidia/nemotron-3-nano-omni-30b-a3b-reasoning:free","nvidia/nemotron-nano-9b-v2:free","nvidia/nemotron-3.5-content-safety:free","google/gemma-4-31b-it:free","google/gemma-4-26b-a4b-it:free","openai/gpt-oss-20b:free","poolside/laguna-xs-2.1:free","poolside/laguna-m.1:free","cohere/north-mini-code:free"],nvidia:["nvidia/nemotron-3-super-120b-a12b","meta/llama-3.1-8b-instruct"]}),J={openai:"openai",anthropic:"anthropic",gemini:"google",groq:"groq",deepseek:"deepseek",nvidia:"nvidia",openrouter:"openrouter"},Z=e=>{const t=J[e]??e,a=W.find(e=>e.provider.toLowerCase()===t.toLowerCase());return a?.models?a.models.map(e=>({name:e.name,key:e.id})):[]},ee=e=>{const t=JSON.stringify(e,Object.keys(e).sort());let a=0;for(let n=0;n<t.length;n++)a=(a<<5)-a+t.charCodeAt(n),a|=0;return String(Math.abs(a).toString(36))},te=new class{configVersion=1;currentConfig={version:this.configVersion,setupComplete:"true"===j("SETUP_COMPLETE")||!1,preferences:{},personalization:{},modelProviders:[],mcpServers:[],search:{searxngURL:"",tavilyApiKey:"",sourceScrapeCount:3,sourceScrapeTimeout:5}};uiConfigSections={preferences:[],personalization:[],modelProviders:[],mcpServers:[],search:[{name:"SearXNG URL",key:"searxngURL",type:"string",required:!1,description:"The URL of your SearXNG instance",placeholder:"http://localhost:4000",default:"",scope:"server",env:"SEARXNG_API_URL"},{name:"Tavily API Key",key:"tavilyApiKey",type:"string",required:!1,description:"Your Tavily API key for enhanced search capabilities.",placeholder:"tvly-...",default:"",scope:"server",env:"TAVILY_API_KEY"},{name:"Source pages to scrape",key:"sourceScrapeCount",type:"select",options:[{name:"Disabled (snippet only)",value:"0"},{name:"1 page",value:"1"},{name:"2 pages",value:"2"},{name:"3 pages (default)",value:"3"},{name:"5 pages",value:"5"}],required:!1,description:"Number of top search result URLs to fully scrape.",default:"3",scope:"server"},{name:"Scrape timeout (seconds)",key:"sourceScrapeTimeout",type:"select",options:[{name:"3 seconds",value:"3"},{name:"5 seconds (default)",value:"5"},{name:"10 seconds",value:"10"},{name:"15 seconds",value:"15"},{name:"20 seconds",value:"20"}],required:!1,description:"Maximum time to wait when scraping each source URL.",default:"5",scope:"server"}]};initialized=!1;constructor(){}ensureInitialized(){this.initialized||(this.initialize(),this.initialized=!0)}initialize(){const e=[{key:"openai",name:"OpenAI",fields:[{type:"password",name:"API Key",key:"apiKey",description:"Your OpenAI API key",required:!0,placeholder:"OpenAI API Key",env:"OPENAI_API_KEY",scope:"server"},{type:"string",name:"Base URL",key:"baseURL",description:"The base URL for the OpenAI API",required:!0,placeholder:"OpenAI Base URL",default:"https://api.openai.com/v1",env:"OPENAI_BASE_URL",scope:"server"}]},{key:"anthropic",name:"Anthropic",fields:[{type:"password",name:"API Key",key:"apiKey",description:"Your Anthropic API key",required:!0,placeholder:"Anthropic API Key",env:"ANTHROPIC_API_KEY",scope:"server"}]},{key:"gemini",name:"Google Gemini",fields:[{type:"password",name:"API Key",key:"apiKey",description:"Your Google Gemini API key",required:!0,placeholder:"Google Gemini API Key",env:"GEMINI_API_KEY",scope:"server"}]},{key:"groq",name:"Groq",fields:[{type:"password",name:"API Key",key:"apiKey",description:"Your Groq API key. Free tier includes fast inference on Llama and Mixtral models - get yours at console.groq.com",required:!0,placeholder:"gsk_...",env:"GROQ_API_KEY",scope:"server"}]},{key:"deepseek",name:"DeepSeek",fields:[{type:"password",name:"API Key",key:"apiKey",description:"Your DeepSeek API key",required:!0,placeholder:"DeepSeek API Key",env:"DEEPSEEK_API_KEY",scope:"server"}]},{key:"nvidia",name:"NVIDIA",fields:[{type:"password",name:"API Key",key:"apiKey",description:"Your NVIDIA API key. Free tier includes access to Nemotron, Llama, and other models - get yours at build.nvidia.com",required:!0,placeholder:"nvapi-...",env:"NVIDIA_API_KEY",scope:"server"},{type:"string",name:"Base URL",key:"baseURL",description:"The base URL for NVIDIA's OpenAI-compatible API",required:!0,placeholder:"https://integrate.api.nvidia.com/v1",default:"https://integrate.api.nvidia.com/v1",env:"NVIDIA_BASE_URL",scope:"server"}]},{key:"openrouter",name:"OpenRouter",fields:[{type:"password",name:"API Key",key:"apiKey",description:"Your OpenRouter API key. Get one free at openrouter.ai - includes free access to Llama 3.3 70B, Nemotron, and other models.",required:!0,placeholder:"sk-or-v1-...",env:"OPENROUTER_API_KEY",scope:"server"},{type:"string",name:"Base URL",key:"baseURL",description:"The base URL for OpenRouter's OpenAI-compatible API",required:!0,placeholder:"https://openrouter.ai/api/v1",default:"https://openrouter.ai/api/v1",env:"OPENROUTER_BASE_URL",scope:"server"}]}];this.uiConfigSections.modelProviders=e;const t=[];e.forEach(e=>{const a={},n=[];e.fields.forEach(e=>{a[e.key]=j(e.env)||e.default||"",e.required&&n.push(e.key)});let r=!0;if(n.forEach(e=>{a[e]||(r=!1)}),r){const n=ee(a);this.currentConfig.modelProviders.find(e=>e.hash===n)||t.push({id:n,name:`${e.name}`,type:e.key,chatModels:Z(e.key),config:a,hash:n,isEnvBased:!0})}}),t.length>0&&this.currentConfig.modelProviders.push(...t),this.uiConfigSections.search.forEach(e=>{e.env&&!this.currentConfig.search[e.key]&&(this.currentConfig.search[e.key]=j(e.env)??e.default??"")})}getConfig(e,t){this.ensureInitialized();const a=e.split(".");let n=this.currentConfig;for(let r=0;r<a.length;r++){const e=a[r];if(null==n)return t;n=n[e]}return void 0===n?t:n}updateConfig(e,t){const a=e.split(".");if(0===a.length)return;let n=this.currentConfig;for(let r=0;r<a.length-1;r++){const e=a[r];null!==n[e]&&"object"==typeof n[e]||(n[e]={}),n=n[e]}n[a[a.length-1]]=t}addModelProvider(e,t,a){this.ensureInitialized();const n=ee(a),r={id:n,name:t,type:e,config:a,chatModels:[],hash:n};return this.currentConfig.modelProviders.push(r),r}removeModelProvider(e){this.currentConfig.modelProviders=this.currentConfig.modelProviders.filter(t=>t.id!==e)}async updateModelProvider(e,t,a){const n=this.currentConfig.modelProviders.find(t=>t.id===e);if(!n)throw new Error("Provider not found");return n.name=t,n.config=a,n}addProviderModel(e,t,a){const n=this.currentConfig.modelProviders.find(t=>t.id===e);if(!n)throw new Error("Invalid provider id");return delete a.type,n.chatModels.push(a),a}removeProviderModel(e,t,a){const n=this.currentConfig.modelProviders.find(t=>t.id===e);if(!n)throw new Error("Invalid provider id");n.chatModels=n.chatModels.filter(e=>e.key!==a)}isSetupComplete(){return this.currentConfig.setupComplete}markSetupComplete(){this.currentConfig.setupComplete||(this.currentConfig.setupComplete=!0)}getUIConfigSections(){return this.ensureInitialized(),this.uiConfigSections}getCurrentConfig(){return this.ensureInitialized(),JSON.parse(JSON.stringify(this.currentConfig))}},ae={openai:"openai",anthropic:"anthropic",gemini:"google",groq:"groq",deepseek:"deepseek",nvidia:"nvidia",openrouter:"openrouter"},ne=e=>{const t=ae[e]??e,a=W.find(e=>e.provider.toLowerCase()===t.toLowerCase());return a?.models?a.models.map(e=>({name:e.name,key:e.id})):[]},re=e=>{const t=/* @__PURE__ */new Map;for(const a of ne(e.type))t.set(a.key,a);for(const a of e.chatModels||[])t.set(a.key,{key:a.key,name:a.name});return[...t.values()]},oe=class{get activeProviders(){return te.getCurrentConfig().modelProviders}async getActiveProviders(e=!1){const t=this.activeProviders,a=e?W.map(e=>({...e,models:e.models.filter(t=>X[e.provider.toLowerCase()]?.includes(t.id)||!1)})).filter(e=>e.models.length>0):W;return t.map(t=>({id:t.id,name:t.name,type:t.type,chatModels:e?this.getGuestChatModels(t,a):re(t)})).filter(e=>e.chatModels.length>0)}getGuestChatModels(e,t){const a=ae[e.type.toLowerCase()],n=t.find(t=>t.provider.toLowerCase()===(a?.toLowerCase()||e.type.toLowerCase()));return n?.models?n.models.map(e=>({name:e.name,key:e.id})):[]}findProvider(e){const t=this.activeProviders;let a=t.find(t=>t.id===e);return!a&&t.length>0&&(a=t.find(e=>e.name.toLowerCase().includes("openrouter"))??t.find(e=>e.name.toLowerCase().includes("groq"))??t.find(e=>e.name.toLowerCase().includes("nvidia"))??t[0]),a}isProviderEnvBased(e){return!0===this.findProvider(e)?.isEnvBased}async loadChatModel(e,t){const a=this.findProvider(e);if(!a)throw new Error("No model providers configured. Please add a provider in settings.");const n=a.type.toLowerCase(),r=a.config||{},o=r.apiKey||"",i=re(a),s=t||i[0]?.key||"";if(a.name,!s)throw new Error(`No chat models available for provider "${a.name}"`);if(t&&!i.some(e=>e.key===t))throw console.warn(`[ModelRegistry] Requested model "${t}" not found in provider "${a.name}". Available models: ${i.map(e=>e.key).join(", ")}`),new Error(`Model "${t}" is not available for provider "${a.name}". Please select a different model in Settings.`);if(!o)throw new Error(`No API key configured for provider "${a.name}". Please add your API key in Settings → Model Providers.`);const c={openai:"https://api.openai.com/v1",togetherai:"https://api.together.xyz/v1",perplexity:"https://api.perplexity.ai",nvidia:"https://integrate.api.nvidia.com/v1",openrouter:"https://openrouter.ai/api/v1",deepseek:"https://api.deepseek.com",xai:"https://api.x.ai/v1"};if(n in c){const{createOpenAI:e}=await import("@ai-sdk/openai");return e({apiKey:o,baseURL:r.baseURL||c[n]}).chat(s)}switch(n){case"cloudflare":{const{createOpenAI:e}=await import("@ai-sdk/openai"),[t,a]=o.split(":");return e({apiKey:t,baseURL:`https://api.cloudflare.com/client/v4/accounts/${a}/ai/v1`}).chat(s)}case"groq":{const{createGroq:e}=await import("@ai-sdk/groq");return e({apiKey:o})(s)}case"anthropic":{const{createAnthropic:e}=await import("@ai-sdk/anthropic");return e({apiKey:o})(s)}case"gemini":case"google":{const{createGoogleGenerativeAI:e}=await import("@ai-sdk/google");return e({apiKey:o})(s)}default:throw new Error(`Unsupported provider type: ${n}`)}}async addProvider(e,t,a){let n,r;return"object"!=typeof t||null===t||a?(n=String(t),r=a||{}):(r=t,n=[{key:"openai",name:"OpenAI",fields:[{type:"password",name:"API Key",key:"apiKey",description:"Your OpenAI API key",required:!0,placeholder:"OpenAI API Key",env:"OPENAI_API_KEY",scope:"server"},{type:"string",name:"Base URL",key:"baseURL",description:"The base URL for the OpenAI API",required:!0,placeholder:"OpenAI Base URL",default:"https://api.openai.com/v1",env:"OPENAI_BASE_URL",scope:"server"}]},{key:"anthropic",name:"Anthropic",fields:[{type:"password",name:"API Key",key:"apiKey",description:"Your Anthropic API key",required:!0,placeholder:"Anthropic API Key",env:"ANTHROPIC_API_KEY",scope:"server"}]},{key:"gemini",name:"Google Gemini",fields:[{type:"password",name:"API Key",key:"apiKey",description:"Your Google Gemini API key",required:!0,placeholder:"Google Gemini API Key",env:"GEMINI_API_KEY",scope:"server"}]},{key:"groq",name:"Groq",fields:[{type:"password",name:"API Key",key:"apiKey",description:"Your Groq API key. Free tier includes fast inference on Llama and Mixtral models - get yours at console.groq.com",required:!0,placeholder:"gsk_...",env:"GROQ_API_KEY",scope:"server"}]},{key:"deepseek",name:"DeepSeek",fields:[{type:"password",name:"API Key",key:"apiKey",description:"Your DeepSeek API key",required:!0,placeholder:"DeepSeek API Key",env:"DEEPSEEK_API_KEY",scope:"server"}]},{key:"nvidia",name:"NVIDIA",fields:[{type:"password",name:"API Key",key:"apiKey",description:"Your NVIDIA API key. Free tier includes access to Nemotron, Llama, and other models - get yours at build.nvidia.com",required:!0,placeholder:"nvapi-...",env:"NVIDIA_API_KEY",scope:"server"},{type:"string",name:"Base URL",key:"baseURL",description:"The base URL for NVIDIA's OpenAI-compatible API",required:!0,placeholder:"https://integrate.api.nvidia.com/v1",default:"https://integrate.api.nvidia.com/v1",env:"NVIDIA_BASE_URL",scope:"server"}]},{key:"openrouter",name:"OpenRouter",fields:[{type:"password",name:"API Key",key:"apiKey",description:"Your OpenRouter API key. Get one free at openrouter.ai - includes free access to Llama 3.3 70B, Nemotron, and other models.",required:!0,placeholder:"sk-or-v1-...",env:"OPENROUTER_API_KEY",scope:"server"},{type:"string",name:"Base URL",key:"baseURL",description:"The base URL for OpenRouter's OpenAI-compatible API",required:!0,placeholder:"https://openrouter.ai/api/v1",default:"https://openrouter.ai/api/v1",env:"OPENROUTER_BASE_URL",scope:"server"}]}].find(t=>t.key===e)?.name||e.toUpperCase()),{...te.addModelProvider(e,n,r),chatModels:ne(e)}}async removeProvider(e){te.removeModelProvider(e)}async updateProvider(e,t,a){let n,r;"object"!=typeof t||null===t||a?(n=String(t),r=a||{}):(r=t,n=this.activeProviders.find(t=>t.id===e)?.name||e);const o=await te.updateModelProvider(e,n,r);return{...o,chatModels:re(o)}}async addProviderModel(e,t,a){return te.addProviderModel(e,t,a)}async removeProviderModel(e,t,a){te.removeProviderModel(e,t,a)}},ie={openrouter:{row:0,col:0},tongyi:{row:0,col:1},ollama:{row:0,col:2},huggingface:{row:0,col:3},localai:{row:0,col:4},openllm:{row:0,col:5},zhipu:{row:1,col:0},replicate:{row:1,col:1},azure:{row:1,col:2},anthropic:{row:1,col:3},groq:{row:1,col:4},sagemaker:{row:1,col:5},"01ai":{row:2,col:0},bedrock:{row:2,col:1},openai:{row:2,col:2},cohere:{row:2,col:3},together:{row:2,col:4},xorbits:{row:2,col:5},wenxin:{row:3,col:0},moonshot:{row:3,col:1},gemini:{row:3,col:2},mistral:{row:3,col:3},jina:{row:3,col:4},chatglm:{row:3,col:5}};async function se(e,t){if(!(t in ie))throw new Error(`Unknown provider: ${t}`);const{row:a,col:n}=ie[t],r=e.width/6,o=e.height/4,i=document.createElement("canvas");i.width=r,i.height=o;const s=i.getContext("2d");if(!s)throw new Error("Failed to get 2D context");return s.drawImage(e,n*r,a*o,r,o,0,0,r,o),i}async function ce(e,t,a="image/png",n){const r=await se(e,t);return new Promise((e,t)=>{r.toBlob(a=>{a?e(a):t(/* @__PURE__ */new Error("Failed to create blob"))},a,n)})}async function me(e,t,a="image/png",n){return(await se(e,t)).toDataURL(a,n)}async function le(e,t){const a=new Image;return a.src=e,await a.decode(),se(a,t)}function de(){return Object.keys(ie)}export{T as AGENT_TOOLS,I as DrizzleMemoryStorage,R as LineListOutputParser,C as LineOutputParser,b as MEMORY_CONFIG,L as MEMORY_TYPES,k as MastraD1MemoryStorage,S as MastraKVMemoryStorage,E as MastraMemoryManager,x as MemoryAgent,K as MetaSearchAgent,oe as ModelRegistry,w as SimpleMemory,N as buildFallbackDocs,te as configManager,_ as createMastraMemory,A as createMemorySchema,$ as createSearchHandlers,se as cropProvider,ce as cropProviderAsBlob,me as cropProviderAsDataURL,B as formatChatHistoryAsString,V as generateSuggestions,j as getEnv,Q as getModelProvidersUIConfigSection,le as getProviderImage,de as getProviderNames,O as groupAndSummarizeDocs,D as normalizeSourcesOutput,q as processDocs,U as rerankDocs,z as searchHandlers,H as splitTextIntoChunks};
|
|
1
|
+
import{webSearchResponsePrompt as e,webSearchRetrieverFewShots as t,webSearchRetrieverPrompt as n,writeLanguageResponse as a,writingAssistantPrompt as r}from"write-language";import{and as o,desc as i,eq as s,like as c,or as m,sql as l}from"drizzle-orm";import{Mastra as d}from"@mastra/core";import{Agent as p}from"@mastra/core/agent";import{z as h}from"zod";import*as u from"qwksearch-api-client";import{generateText as g,streamText as y}from"ai";import f from"events";export*from"write-language";var v=/* @__PURE__ */(e=>"undefined"!=typeof require?require:"undefined"!=typeof Proxy?new Proxy(e,{get:(e,t)=>("undefined"!=typeof require?require:e)[t]}):e)(function(e){if("undefined"!=typeof require)return require.apply(this,arguments);throw Error('Calling `require` for "'+e+"\" in an environment that doesn't expose the `require` function. See https://rolldown.rs/in-depth/bundling-cjs#require-external-modules for more details.")}),L={FACT:"fact",CONVERSATION:"conversation",PREFERENCE:"preference",PERSONAL:"personal",WORK:"work",MANUAL:"manual"},b={DEFAULT_MAX_MEMORIES:100,DEFAULT_SUMMARY_THRESHOLD:10,DEFAULT_CACHE_EXPIRY:3e5,DEFAULT_BATCH_SIZE:5,DEFAULT_RELEVANCE_THRESHOLD:.3,DEFAULT_IMPORTANCE_RANGE:{min:0,max:10},DEFAULT_RATE_LIMIT:{requests:10,windowMs:6e4},DEFAULT_TIMEOUT:3e4,VECTOR_SEARCH_ENABLED:!0,AUTO_SUMMARIZATION_ENABLED:!0},w=class{userId;storage;maxMemories;summaryThreshold;cacheExpiry;batchSize;relevanceThreshold;enableVectorSearch;enableAutoSummarization;recentMessages;memoryCache;isProcessing;processingQueue;summarizeTimeout;metrics;constructor(e,t,n={}){if(!e||!t)throw new Error("userId and storage are required parameters");this.userId=e,this.storage=t,this.maxMemories=n.maxMemories||b.DEFAULT_MAX_MEMORIES,this.summaryThreshold=n.summaryThreshold||b.DEFAULT_SUMMARY_THRESHOLD,this.cacheExpiry=n.cacheExpiry||b.DEFAULT_CACHE_EXPIRY,this.batchSize=n.batchSize||b.DEFAULT_BATCH_SIZE,this.relevanceThreshold=n.relevanceThreshold||b.DEFAULT_RELEVANCE_THRESHOLD,this.enableVectorSearch=!1!==n.enableVectorSearch&&b.VECTOR_SEARCH_ENABLED,this.enableAutoSummarization=!1!==n.enableAutoSummarization&&b.AUTO_SUMMARIZATION_ENABLED,this.recentMessages=[],this.memoryCache=/* @__PURE__ */new Map,this.isProcessing=!1,this.processingQueue=[],this.metrics={cacheHits:0,cacheMisses:0,vectorSearches:0,summarizations:0,errors:0}}addMessage(e,t,n={}){if(!e||!t||"string"!=typeof t)return console.warn("Invalid message parameters:",{role:e,content:t}),!1;if(this.recentMessages.slice(-3).some(n=>n.role===e&&n.content===t&&Date.now()-n.timestamp<6e4))return!1;const a={role:e,content:t.trim(),timestamp:n.timestamp||Date.now(),metadata:{...n}};return this.recentMessages.push(a),this.enableAutoSummarization&&this.recentMessages.length>=this.summaryThreshold&&!this.isProcessing&&this.debouncedSummarize(),!0}debouncedSummarize(){this.summarizeTimeout&&clearTimeout(this.summarizeTimeout),this.summarizeTimeout=setTimeout(()=>{this.summarizeAndStore().catch(e=>{console.error("Auto-summarization failed:",e),this.metrics.errors++})},1e3)}async storeFact(e,t=1,n=L.FACT,a={}){if(!e||"string"!=typeof e||0===e.trim().length)throw new Error("Content cannot be empty");if(t<b.DEFAULT_IMPORTANCE_RANGE.min||t>b.DEFAULT_IMPORTANCE_RANGE.max)throw new Error(`Importance must be between ${b.DEFAULT_IMPORTANCE_RANGE.min} and ${b.DEFAULT_IMPORTANCE_RANGE.max}`);const r=e.trim(),o=Object.values(L).includes(n)?n:L.FACT;try{const e=await this.findSimilarFacts(r);if(e.length>0){const n=e[0];return t>n.importance&&await this.storage.updateMemory(n.id,{importance:t,updated_at:/* @__PURE__ */new Date,access_count:{increment:1},metadata:{...n.metadata,...a}}),n.id}const n=await this.storage.insertMemory(this.userId,o,r,Math.max(0,Math.min(10,t)),a);return this.clearCache(),n}catch(i){throw console.error("Error storing fact:",i),this.metrics.errors++,i}}async findSimilarFacts(e){try{return await this.storage.findSimilarMemories(this.userId,e,5)}catch(t){return console.error("Error finding similar facts:",t),[]}}async recallRelevantMemories(e="",t=10,n={}){const a=`${e}-${t}-${JSON.stringify(n)}`;if(this.memoryCache.has(a)){const e=this.memoryCache.get(a);if(Date.now()-e.timestamp<this.cacheExpiry)return this.metrics.cacheHits++,e.data;this.memoryCache.delete(a)}this.metrics.cacheMisses++;try{let r=await this.storage.findMemories(this.userId,e,t,n);if(0===r.length)return[];this.enableVectorSearch&&e.trim()&&r.length>0&&(r=await this.applyVectorSearch(e,r,n)),n.minImportance&&(r=r.filter(e=>e.importance>=n.minImportance));const o=r.map(e=>({...e,relevance_score:e.relevance_score||0,metadata:n.includeMetadata?e.metadata:void 0}));return this.memoryCache.set(a,{data:o,timestamp:Date.now()}),o}catch(r){return console.error("Error retrieving memories:",r),this.metrics.errors++,[]}}async applyVectorSearch(e,t,n){return t}async updateRelevanceScores(e,t){const n=t.filter(e=>e.relevance>this.relevanceThreshold).map(t=>{const n=e.find(e=>e.content===t.sentence);return n?{id:n.id,updates:{importance:Math.min(10,n.importance+.5*t.relevance),access_count:{increment:1},updated_at:/* @__PURE__ */new Date}}:null}).filter(Boolean);n.length>0&&await this.storage.batchUpdateMemories(n)}async summarizeAndStore(){if(0===this.recentMessages.length||this.isProcessing)return!1;this.isProcessing=!0,this.metrics.summarizations++;try{const e=this.recentMessages.map(e=>`${e.role}: ${e.content}`).join("\n"),t=await this.extractFactsFromConversation(e);return Array.isArray(t)&&0!==t.length?(await this.processFactsInBatches(t),this.recentMessages=[],!0):(console.warn("No facts extracted from conversation"),!1)}catch(e){return console.error("Error in summarizeAndStore:",e),this.metrics.errors++,!1}finally{this.isProcessing=!1}}async extractFactsFromConversation(e){try{const{extract:t}=await a({agent:"remember-facts",chat_history:e,provider:"groq",model:"mixtral-8x7b-32768",timeout:b.DEFAULT_TIMEOUT});return Array.isArray(t)?t:[]}catch(t){return console.error("Error extracting facts:",t),[]}}async processFactsInBatches(e){for(let t=0;t<e.length;t+=this.batchSize){const n=e.slice(t,t+this.batchSize).map(async e=>{try{if(e&&"object"==typeof e&&e.content)return await this.storeFact(e.content,e.importance||1,e.category||L.CONVERSATION,e.metadata||{});if("string"==typeof e&&e.trim())return await this.storeFact(e.trim(),1,L.CONVERSATION)}catch(t){return console.error("Error storing individual fact:",t),null}});await Promise.allSettled(n),t+this.batchSize<e.length&&await new Promise(e=>setTimeout(e,100))}}clearCache(){this.memoryCache.clear()}async getMemoryContext(e="",t=!0,n={}){const a=await this.recallRelevantMemories(e,n.maxMemories||8,{minImportance:n.minImportance||.5});if(0===a.length&&0===this.recentMessages.length)return"";let r="";return a.length>0&&(r+="What I remember about you:\n",a.filter(e=>e.importance>(n.minImportance||.5)).forEach(e=>{const t=e.importance>=8?"⭐":e.importance>=5?"•":"-";r+=`${t} ${e.content}\n`})),t&&this.recentMessages.length>0&&(r+=r?"\nRecent conversation:\n":"Recent conversation:\n",this.recentMessages.slice(-3).forEach(e=>{const t=e.content.length>100?e.content.substring(0,100)+"...":e.content;r+=`${e.role}: ${t}\n`})),r}getMetrics(){return{...this.metrics,cacheSize:this.memoryCache.size,recentMessagesCount:this.recentMessages.length,isProcessing:this.isProcessing}}},I=class{memory;defaultProvider;defaultApiKey;defaultModel;rateLimiter;rateLimitConfig;providers;sessionId;conversationHistory;analytics;userId;constructor(e,t,n={}){if(!e||!t)throw new Error("userId and storage are required parameters");this.userId=e,this.memory=new w(e,t,n.memoryOptions||{}),this.defaultProvider=n.defaultProvider||"groq",this.defaultApiKey=n.defaultApiKey,this.defaultModel=n.defaultModel,this.rateLimiter=/* @__PURE__ */new Map,this.rateLimitConfig={...b.DEFAULT_RATE_LIMIT,...n.rateLimit},this.providers=n.providers||this.getDefaultProviders(),this.sessionId=this.generateSessionId(),this.conversationHistory=[],this.analytics={totalMessages:0,totalTokens:0,averageResponseTime:0,errorCount:0,sessionStartTime:Date.now()}}getDefaultProviders(){return{groq:(e,t,n)=>({invoke:async e=>({content:"Default response",tokensUsed:0})}),openai:(e,t,n)=>({invoke:async e=>({content:"Default response",tokensUsed:0})})}}generateSessionId(){return`${this.userId}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}checkRateLimit(e,t,n){const a=t||this.rateLimitConfig.requests,r=n||this.rateLimitConfig.windowMs,o=Date.now(),i=(this.rateLimiter.get(e)||[]).filter(e=>o-e<r);return!(i.length>=a||(i.push(o),this.rateLimiter.set(e,i),0))}async chat(e,t={}){const n=Date.now();if(!e||"string"!=typeof e||0===e.trim().length)return{error:"Message cannot be empty",success:!1,timestamp:/* @__PURE__ */(new Date).toISOString()};const a=`chat-${this.userId}`;if(!this.checkRateLimit(a))return{error:"Rate limit exceeded. Please try again later.",success:!1,timestamp:/* @__PURE__ */(new Date).toISOString()};try{this.memory.addMessage("user",e,{sessionId:this.sessionId,timestamp:Date.now()});const a=await this.memory.getMemoryContext(e,!0,{maxMemories:t.maxMemories||8,minImportance:t.minImportance||.5}),r=this.buildPrompt(e,a,t),o=await this.generateResponse(r,t);if(!o||!o.content)throw new Error("Invalid response from LLM");return this.memory.addMessage("assistant",o.content,{sessionId:this.sessionId,tokensUsed:o.tokensUsed,timestamp:Date.now()}),this.updateAnalytics(o.tokensUsed,Date.now()-n),{content:o.content,memoryContext:a,success:!0,tokensUsed:o.tokensUsed||0,responseTime:Date.now()-n,sessionId:this.sessionId,timestamp:/* @__PURE__ */(new Date).toISOString()}}catch(r){return console.error("Chat error:",r),this.analytics.errorCount++,{error:r.message||"An unexpected error occurred",success:!1,timestamp:/* @__PURE__ */(new Date).toISOString()}}}async generateResponse(e,t){const n=t.provider||this.defaultProvider,a=t.apiKey||this.defaultApiKey,r=t.model||this.defaultModel,o=t.temperature||.7;if(!this.providers||!this.providers[n])throw new Error(`Provider ${n} not available`);const i=this.providers[n](a||"",r||"",o),s=new Promise((e,t)=>setTimeout(()=>t(/* @__PURE__ */new Error("LLM request timeout")),b.DEFAULT_TIMEOUT));return await Promise.race([i.invoke(e),s])}buildPrompt(e,t,n){let a="";return n.systemPrompt&&(a+=`${n.systemPrompt}\n\n`),t&&(a+=`${t}\n\n`),n.includeHistory&&this.conversationHistory.length>0&&(a+="Recent conversation history:\n",this.conversationHistory.slice(-5).forEach(e=>{a+=`${e.role}: ${e.content}\n`}),a+="\n"),a+=`User: ${e}\n\nAssistant:`,a}updateAnalytics(e,t){this.analytics.totalMessages++,this.analytics.totalTokens+=e||0,this.analytics.averageResponseTime=(this.analytics.averageResponseTime*(this.analytics.totalMessages-1)+t)/this.analytics.totalMessages}async remember(e,t=1,n=L.MANUAL,a={}){try{return await this.memory.storeFact(e,t,n,{...a,source:"manual",timestamp:Date.now()})}catch(r){throw console.error("Error remembering fact:",r),r}}async getMemories(e="",t=10,n={}){return await this.memory.recallRelevantMemories(e,t,n)}async forceStoreSummary(){return await this.memory.summarizeAndStore()}async healthCheck(){try{return{status:"healthy",memory:this.memory.getMetrics(),rateLimit:this.checkRateLimit("health-check",1,1e3),analytics:this.analytics,sessionId:this.sessionId,uptime:Date.now()-this.analytics.sessionStartTime,timestamp:/* @__PURE__ */(new Date).toISOString()}}catch(e){return{status:"unhealthy",error:e.message,timestamp:/* @__PURE__ */(new Date).toISOString()}}}getAnalytics(){return{...this.analytics,memory:this.memory.getMetrics(),sessionId:this.sessionId,uptime:Date.now()-this.analytics.sessionStartTime}}resetSession(){this.sessionId=this.generateSessionId(),this.conversationHistory=[],this.analytics.sessionStartTime=Date.now()}},x=class{db;table;constructor(e,t){this.db=e,this.table=t}async insertMemory(e,t,n,a,r){return(await this.db.insert(this.table).values({user_id:e,memory_type:t,content:n,importance:a,access_count:0,metadata:r||{},created_at:/* @__PURE__ */new Date,updated_at:/* @__PURE__ */new Date}).returning({id:this.table.id}))[0]?.id}async findMemories(e,t,n=10,a={}){const r=[s(this.table.user_id,e)];return t&&t.trim()&&r.push(c(this.table.content,`%${t}%`)),a.memoryType&&r.push(s(this.table.memory_type,a.memoryType)),await this.db.select({id:this.table.id,user_id:this.table.user_id,memory_type:this.table.memory_type,content:this.table.content,importance:this.table.importance,access_count:this.table.access_count,metadata:this.table.metadata,created_at:this.table.created_at,updated_at:this.table.updated_at}).from(this.table).where(o(...r)).orderBy(i(this.table.importance),i(this.table.access_count),i(this.table.updated_at)).limit(Math.min(n,50))}async findSimilarMemories(e,t,n=5){const a=t.toLowerCase().split(/\s+/).filter(e=>e.length>2).slice(0,3);if(0===a.length)return[];const r=a.map(e=>c(this.table.content,`%${e}%`));return await this.db.select().from(this.table).where(o(s(this.table.user_id,e),m(...r))).orderBy(i(this.table.importance),i(this.table.updated_at)).limit(n)}async updateMemory(e,t){const n={};void 0!==t.importance&&(n.importance=t.importance),void 0!==t.access_count&&("object"==typeof t.access_count&&t.access_count.increment?n.access_count=l`${this.table.access_count} + ${t.access_count.increment}`:n.access_count=t.access_count),void 0!==t.updated_at&&(n.updated_at=t.updated_at),void 0!==t.metadata&&(n.metadata=t.metadata),await this.db.update(this.table).set(n).where(s(this.table.id,e))}async deleteMemory(e){await this.db.delete(this.table).where(s(this.table.id,e))}async getMemoryById(e){return(await this.db.select().from(this.table).where(s(this.table.id,e)).limit(1))[0]||null}async batchUpdateMemories(e){const t=e.map(({id:e,updates:t})=>this.updateMemory(e,t));await Promise.allSettled(t)}};function A(e){return{user_memories:{id:"uuid",user_id:"string",memory_type:"string",content:"text",importance:"number",access_count:"number",metadata:"jsonb",created_at:"timestamp",updated_at:"timestamp"}}}var k=class{db;tableName;constructor(e,t="mastra_memories"){this.db=e,this.tableName=t}async initSchema(){await this.db.exec(`\n CREATE TABLE IF NOT EXISTS ${this.tableName} (\n id TEXT PRIMARY KEY,\n user_id TEXT NOT NULL,\n thread_id TEXT NOT NULL,\n resource_id TEXT,\n memory_type TEXT NOT NULL,\n content TEXT NOT NULL,\n importance REAL DEFAULT 1.0,\n access_count INTEGER DEFAULT 0,\n metadata TEXT,\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL\n );\n\n CREATE INDEX IF NOT EXISTS idx_user_thread ON ${this.tableName}(user_id, thread_id);\n CREATE INDEX IF NOT EXISTS idx_resource ON ${this.tableName}(resource_id);\n CREATE INDEX IF NOT EXISTS idx_importance ON ${this.tableName}(importance DESC);\n `)}async insertMemory(e,t,n,a,r){const o=crypto.randomUUID(),i=Date.now();return await this.db.prepare(`INSERT INTO ${this.tableName}\n (id, user_id, thread_id, resource_id, memory_type, content, importance, metadata, created_at, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).bind(o,e,r?.thread_id||"default",r?.resource_id||null,t,n,a,JSON.stringify(r||{}),i,i).run(),o}async findMemories(e,t,n=10,a={}){let r=`SELECT * FROM ${this.tableName} WHERE user_id = ?`;const o=[e];return a.memoryType&&(r+=" AND memory_type = ?",o.push(a.memoryType)),t&&(r+=" AND content LIKE ?",o.push(`%${t}%`)),void 0!==a.minImportance&&(r+=" AND importance >= ?",o.push(a.minImportance)),r+=" ORDER BY importance DESC, updated_at DESC LIMIT ?",o.push(n),((await this.db.prepare(r).bind(...o).all()).results||[]).map(e=>({id:e.id,user_id:e.user_id,memory_type:e.memory_type,content:e.content,importance:e.importance,access_count:e.access_count,metadata:JSON.parse(e.metadata||"{}"),created_at:new Date(e.created_at),updated_at:new Date(e.updated_at)}))}async findSimilarMemories(e,t,n=5){const a=t.toLowerCase().split(/\s+/).filter(e=>e.length>2).slice(0,3);if(0===a.length)return[];const r=a.map(()=>"content LIKE ?").join(" OR "),o=[e,...a.map(e=>`%${e}%`),n];return((await this.db.prepare(`SELECT * FROM ${this.tableName}\n WHERE user_id = ? AND (${r})\n ORDER BY importance DESC, updated_at DESC\n LIMIT ?`).bind(...o).all()).results||[]).map(e=>({id:e.id,user_id:e.user_id,memory_type:e.memory_type,content:e.content,importance:e.importance,access_count:e.access_count,metadata:JSON.parse(e.metadata||"{}"),created_at:new Date(e.created_at),updated_at:new Date(e.updated_at)}))}async updateMemory(e,t){const n=[],a=[];void 0!==t.importance&&(n.push("importance = ?"),a.push(t.importance)),void 0!==t.access_count&&("object"==typeof t.access_count&&t.access_count.increment?(n.push("access_count = access_count + ?"),a.push(t.access_count.increment)):(n.push("access_count = ?"),a.push(t.access_count))),void 0!==t.metadata&&(n.push("metadata = ?"),a.push(JSON.stringify(t.metadata))),n.push("updated_at = ?"),a.push(Date.now()),a.push(e),n.length>0&&await this.db.prepare(`UPDATE ${this.tableName} SET ${n.join(", ")} WHERE id = ?`).bind(...a).run()}async deleteMemory(e){await this.db.prepare(`DELETE FROM ${this.tableName} WHERE id = ?`).bind(e).run()}async getMemoryById(e){const t=await this.db.prepare(`SELECT * FROM ${this.tableName} WHERE id = ?`).bind(e).first();return t?{id:t.id,user_id:t.user_id,memory_type:t.memory_type,content:t.content,importance:t.importance,access_count:t.access_count,metadata:JSON.parse(t.metadata||"{}"),created_at:new Date(t.created_at),updated_at:new Date(t.updated_at)}:null}async batchUpdateMemories(e){for(const{id:t,updates:n}of e)await this.updateMemory(t,n)}},S=class{kv;prefix;constructor(e,t="mastra:memory:"){this.kv=e,this.prefix=t}getUserKey(e){return`${this.prefix}user:${e}`}getMemoryKey(e){return`${this.prefix}memory:${e}`}async insertMemory(e,t,n,a,r){const o=crypto.randomUUID(),i=Date.now(),s={id:o,user_id:e,memory_type:t,content:n,importance:a,access_count:0,metadata:r||{},created_at:new Date(i),updated_at:new Date(i)};await this.kv.put(this.getMemoryKey(o),JSON.stringify(s));const c=this.getUserKey(e),m=await this.kv.get(c,"json")||[];return m.push(o),await this.kv.put(c,JSON.stringify(m)),o}async findMemories(e,t,n=10,a={}){const r=this.getUserKey(e),o=await this.kv.get(r,"json")||[];let i=(await Promise.all(o.map(e=>this.getMemoryById(e)))).filter(e=>null!==e);return t&&(i=i.filter(e=>e.content.toLowerCase().includes(t.toLowerCase()))),a.memoryType&&(i=i.filter(e=>e.memory_type===a.memoryType)),void 0!==a.minImportance&&(i=i.filter(e=>e.importance>=a.minImportance)),i.sort((e,t)=>t.importance-e.importance||t.updated_at.getTime()-e.updated_at.getTime()).slice(0,n)}async findSimilarMemories(e,t,n=5){const a=t.toLowerCase().split(/\s+/).filter(e=>e.length>2).slice(0,3);return 0===a.length?[]:(await this.findMemories(e,"",50)).filter(e=>a.some(t=>e.content.toLowerCase().includes(t))).slice(0,n)}async updateMemory(e,t){const n=await this.getMemoryById(e);n&&(void 0!==t.importance&&(n.importance=t.importance),void 0!==t.access_count&&("object"==typeof t.access_count?n.access_count+=t.access_count.increment??0:n.access_count=t.access_count),void 0!==t.metadata&&(n.metadata={...n.metadata,...t.metadata}),n.updated_at=/* @__PURE__ */new Date,await this.kv.put(this.getMemoryKey(e),JSON.stringify(n)))}async deleteMemory(e){const t=await this.getMemoryById(e);if(!t)return;await this.kv.delete(this.getMemoryKey(e));const n=this.getUserKey(t.user_id),a=(await this.kv.get(n,"json")||[]).filter(t=>t!==e);await this.kv.put(n,JSON.stringify(a))}async getMemoryById(e){const t=await this.kv.get(this.getMemoryKey(e),"json");return t?{...t,created_at:new Date(t.created_at),updated_at:new Date(t.updated_at)}:null}async batchUpdateMemories(e){await Promise.all(e.map(({id:e,updates:t})=>this.updateMemory(e,t)))}},E=class{mastra=null;storage;config;constructor(e){if(this.config=e,"d1"===e.storage&&e.env?.DB)this.storage=new k(e.env.DB,e.tableName);else{if("kv"!==e.storage||!e.env?.KV)throw new Error(`Invalid storage configuration: ${e.storage}`);this.storage=new S(e.env.KV,e.kvPrefix)}}async initialize(){return this.mastra||(this.mastra=new d({}),"d1"===this.config.storage&&this.storage instanceof k&&await this.storage.initSchema()),this.mastra}getStorage(){return this.storage}async createAgent(e){await this.initialize();const t=new p({id:e.id,name:e.name,instructions:e.instructions,model:e.model,tools:e.tools||{}});return t.memoryContext={userId:e.userId,threadId:e.threadId||"default",resourceId:e.resourceId},t}async storeMessage(e,t,n,a,r){return await this.storage.insertMemory(e,"conversation",a,1,{thread_id:t,role:n,...r})}async recallConversation(e,t,n=20){return(await this.storage.findMemories(e,void 0,n,{memoryType:"conversation"})).filter(e=>e.metadata?.thread_id===t).map(e=>({role:e.metadata?.role||"user",content:e.content,timestamp:e.created_at})).sort((e,t)=>e.timestamp.getTime()-t.timestamp.getTime())}async getRelevantContext(e,t,n=5){const a=await this.storage.findSimilarMemories(e,t,n);return 0===a.length?"":a.map(e=>e.content).join("\n\n")}};function _(e){return new E(e)}var P={baseURL:"undefined"!=typeof process&&process?.env.QWKSEARCH_URL||"https://app.qwksearch.com/api",apiKey:"undefined"!=typeof process&&process?.env.QWKSEARCH_API_KEY||null},T=[{name:"web_search",description:"Search the web for information on any topic using QwkSearch API. Input: search query string and optional category. Returns relevant search results with titles, descriptions, and URLs from 100+ sources via SearXNG metasearch engine.",schema:h.object({query:h.string(),category:h.enum(["general","news","videos","images","science","files","it"]).optional().default("general"),recency:h.enum(["none","day","week","month","year"]).optional().default("none"),page:h.number().optional().default(1),language:h.string().optional().default("en-US"),public:h.boolean().optional().default(!1),timeout:h.number().optional().default(10),baseURL:h.string().optional(),apiKey:h.string().optional()}),func:async({query:e,category:t="general",recency:n="none",page:a=1,language:r="en-US",public:o=!1,timeout:i=10,baseURL:s,apiKey:c})=>{try{const m=s||P.baseURL,l=c||P.apiKey?{"x-api-key":c||P.apiKey}:void 0,d=await u.searchWeb({query:{q:e,cat:t,recency:n,page:a,lang:r,public:o,timeout:i},baseUrl:m,...l&&{headers:l}});if(!d.data||!d.data.results||0===d.data.results.length)return`No search results found for "${e}". Please try a different search term.`;let p=`Web search results for "${e}" (${t} category):\n\n`;return d.data.results.forEach((e,t)=>{p+=`${t+1}. ${e.title}\n`,p+=` URL: ${e.url}\n`,e.domain&&(p+=` Domain: ${e.domain}\n`),e.snippet&&(p+=` Description: ${e.snippet}\n`),e.engines&&e.engines.length>0&&(p+=` Sources: ${e.engines.join(", ")}\n`),p+="\n"}),p+=`Found ${d.data.results.length} results from multiple search engines. This is the complete search information.`,p}catch(m){return`Unable to perform web search for "${e}". Error: ${m.message}`}}},{name:"extract_page",description:"Extract and summarize content from a web page using QwkSearch API. Supports articles, PDFs, and YouTube videos. Uses Mozilla Readability and Postlight Mercury algorithms with 100+ custom adapters for major sites. Input: URL of the page to extract. Returns structured content with citation information.",schema:h.object({url:h.string().url(),images:h.boolean().optional().default(!0),links:h.boolean().optional().default(!0),formatting:h.boolean().optional().default(!0),absoluteURLs:h.boolean().optional().default(!0),timeout:h.number().min(1).max(30).optional().default(10),baseURL:h.string().optional(),apiKey:h.string().optional()}),func:async({url:e,images:t=!0,links:n=!0,formatting:a=!0,absoluteURLs:r=!0,timeout:o=10,baseURL:i,apiKey:s})=>{try{const c=i||P.baseURL,m=s||P.apiKey?{"x-api-key":s||P.apiKey}:void 0,l=await u.extractContent({query:{url:e,images:t,links:n,formatting:a,absoluteURLs:r,timeout:o},baseUrl:c,...m&&{headers:m}});if(!l.data)return`No content could be extracted from "${e}". Please check the URL and try again.`;const d=l.data;let p=`Content extracted from: ${d.url||e}\n\n`;return d.title&&(p+=`Title: ${d.title}\n\n`),d.author&&(p+=`Author: ${d.author}\n`,d.author_cite&&(p+=`Author (Citation Format): ${d.author_cite}\n`),d.author_type&&(p+=`Author Type: ${d.author_type}\n`)),d.date&&(p+=`Publication Date: ${d.date}\n`),d.source&&(p+=`Source: ${d.source}\n`),d.word_count&&(p+=`Word Count: ${d.word_count}\n`),d.cite&&(p+=`\nCitation (APA Format): ${d.cite}\n`),d.html&&(p+=`\nContent:\n${d.html}\n\n`),p+="This is the complete page extraction information.",p}catch(c){return`Unable to extract content from "${e}". Error: ${c.message}`}}},{name:"generate_ai_response",description:"Generate AI language model responses using QwkSearch API with various agent templates. Supports multiple providers (Groq, OpenAI, Anthropic, etc.) and agent types for different tasks like summarization, question answering, and content generation.",schema:h.object({provider:h.enum(["groq","openai","anthropic","together","xai","google","perplexity","cloudflare"]),key:h.string().optional(),agent:h.enum(["question","summarize-bullets","summarize","suggest-followups","answer-cite-sources","query-resolution","knowledge-graph-nodes","summary-longtext"]).optional().default("question"),model:h.string().optional().default("meta-llama/llama-4-maverick-17b-128e-instruct"),temperature:h.number().min(0).max(2).optional().default(.7),html:h.boolean().optional().default(!0),query:h.string().optional(),chat_history:h.string().optional(),article:h.string().optional(),baseURL:h.string().optional(),apiKey:h.string().optional()}),func:async({provider:e,key:t,agent:n="question",model:a="meta-llama/llama-4-maverick-17b-128e-instruct",temperature:r=.7,html:o=!0,query:i,chat_history:s,article:c,baseURL:m,apiKey:l})=>{try{const d=m||P.baseURL,p=l||P.apiKey?{"x-api-key":l||P.apiKey}:void 0,h={agent:n,provider:e,model:a,html:o,temperature:r};t&&(h.key=t),i&&(h.query=i),s&&(h.chat_history=s),c&&(h.article=c);const g=await u.writeLanguage({body:h,baseUrl:d,...p&&{headers:p}});if(!g.data)return"No response generated. Please check your input parameters and try again.";let y=`AI Response (${n} agent, ${e} provider):\n\n`;return g.data.content&&(y+=g.data.content),g.data.extract&&(y+=`\n\nStructured Extract:\n${JSON.stringify(g.data.extract,null,2)}`),y+="\n\nThis is the complete AI-generated response.",y}catch(d){return`Unable to generate AI response. Error: ${d.message}`}}},{name:"render_page_with_javascript",description:"Render a web page with JavaScript execution using Cloudflare Browser Rendering. Use this for JavaScript-heavy sites (SPAs, React apps), pages behind bot protection (Cloudflare, reCAPTCHA), or when extract_page fails. Returns fully rendered HTML with JavaScript executed. Slower but more complete than extract_page.",schema:h.object({url:h.string().url(),blockImages:h.boolean().optional().default(!0),wait:h.number().min(0).max(1e4).optional().default(0),timeout:h.number().min(1e3).max(6e4).optional().default(3e4),waitUntil:h.enum(["domcontentloaded","load","networkidle0","networkidle2"]).optional().default("networkidle2"),bypassCaptcha:h.boolean().optional().default(!0),sessionId:h.string().optional().default("default"),format:h.enum(["html","json"]).optional().default("html"),scraperUrl:h.string().optional(),scraperApiKey:h.string().optional()}),func:async({url:e,blockImages:t=!0,wait:n=0,timeout:a=3e4,waitUntil:r="networkidle2",bypassCaptcha:o=!0,sessionId:i="default",format:s="html",scraperUrl:c,scraperApiKey:m})=>{try{const l=c||"undefined"!=typeof process&&process?.env?.SCRAPER_URL||"https://scraper.qwksearch.workers.dev",d=m||"undefined"!=typeof process&&process?.env?.SCRAPER_API_KEY,p=new URL("/api/render",l),h={url:e,blockImages:t,wait:n,timeout:a,waitUntil:r,bypassCaptcha:o,sessionId:i,format:s},u={"Content-Type":"application/json"};d&&(u.Authorization=`Bearer ${d}`);const g=await fetch(p.toString(),{method:"POST",headers:u,body:JSON.stringify(h)});if(!g.ok)return`Failed to render page: ${await g.text()}`;if("json"===s){const e=await g.json();let t=`Page rendered successfully: ${e.url}\n\n`;return e.title&&(t+=`Title: ${e.title}\n`),t+=`Load Time: ${e.loadTime}ms\n`,e.challengeBypassed&&(t+=`Challenge Bypassed: Yes (${e.retryCount} retries)\n`),t+=`\nRendered HTML Content:\n${e.html}\n\n`,t+="This is the complete rendered page content.",t}return`Page rendered successfully.\n\nHTML Content:\n${await g.text()}`}catch(l){return`Unable to render page "${e}". Error: ${l.message}`}}}],M=/^(\s*(-|\*|\d+\.\s|\d+\)\s|•)\s*)+/,R=class{key="questions";constructor(e){this.key=e?.key??this.key}async parse(e){const t=(e=e.trim()||"").indexOf(`<${this.key}>`),n=e.indexOf(`</${this.key}>`);if(-1===t||-1===n)return[];const a=t+`<${this.key}>`.length;return e.slice(a,n).trim().split("\n").filter(e=>""!==e.trim()).map(e=>e.replace(M,""))}},C=class{key="questions";constructor(e){this.key=e?.key??this.key}async parse(e){const t=(e=e.trim()||"").indexOf(`<${this.key}>`),n=e.indexOf(`</${this.key}>`);if(-1===t||-1===n)return;const a=t+`<${this.key}>`.length;return e.slice(a,n).trim().replace(M,"")}},B=e=>e.map(e=>`${"assistant"===e.role||"ai"===e.type?"AI":"User"}: ${String(e.content??"")}`).join("\n");function N(e){const t=(e||"").trim(),n=t.length>0?t:"web search";return[{pageContent:"No indexed sources were returned by the configured search providers for this query.",metadata:{title:`Search results for: ${n}`,url:`https://www.google.com/search?q=${encodeURIComponent(n)}`,source:"Google Search"}}]}function D(e,t){return Array.isArray(e)&&e.length>0?e:N(t)}var U=null;function q(e){U=e}async function O(e,t,n,a,r){if(0===t.length&&0===n.length)return t;let o=[];if(n.length>0&&(o=(await Promise.all(n.map(async e=>{if(U)try{const t=await U(e);if(t)return t}catch(t){console.error(`[rerankDocs] Registered upload loader failed for fileId ${e}:`,t)}return r?async function(e,n){try{const{manageStorage:t}=await import("manage-storage"),a={provider:"cloudflare",BUCKET_NAME:n.bucket,ACCESS_KEY_ID:n.accessKeyId,SECRET_ACCESS_KEY:n.secretAccessKey,BUCKET_URL:`https://${n.accountId}.r2.cloudflarestorage.com`},r=`${e}-extracted.json`,o=await t("download",{...a,key:r}),i=JSON.parse(o);return{title:i.title||"Uploaded Document",content:i.content||""}}catch(t){return console.error(`[rerankDocs] Failed to download extracted content for fileId ${e}:`,t),null}}(e,r):null}))).filter(e=>null!==e)),"summarize"===e.toLocaleLowerCase())return t.slice(0,15);const i=t.filter(e=>e.pageContent&&e.pageContent.length>0);return[...o.map(e=>({pageContent:e.content,metadata:{title:e.title,url:"File"}})),...i].slice(0,15)}function K(e){return e.map((t,n)=>`${n+1}. ${e[n].metadata.title} ${e[n].pageContent}`).join("\n")}async function G(e,t,n){const a=[];for(const o of t){const e=a.find(e=>e.metadata.url===o.metadata.url&&e.metadata.totalDocs<10);e?(e.pageContent+=`\n\n${o.pageContent}`,e.metadata.totalDocs+=1):a.push({...o,metadata:{...o.metadata,totalDocs:1}})}const r=[];return await Promise.all(a.map(async t=>{const{text:a}=await g({model:e,prompt:'You are a web search summarizer, tasked with summarizing a piece of text retrieved from a web search. Your job is to summarize the\ntext into a detailed, 2-4 paragraph explanation that captures the main ideas and provides a comprehensive answer to the query.\nIf the query is "summarize", you should provide a detailed summary of the text. If the query is a specific question, you should answer it in the summary.\n\n- **Journalistic tone**: The summary should sound professional and journalistic, not too casual or vague.\n- **Thorough and detailed**: Ensure that every key point from the text is captured and that the summary directly answers the query.\n- **Not too lengthy, but detailed**: The summary should be informative but not excessively long. Focus on providing detailed information in a concise format.\n\nThe text will be shared inside the `text` XML tag, and the query inside the `query` XML tag.\n\n<example>\n1. `<text>\nDocker is a set of platform-as-a-service products that use OS-level virtualization to deliver software in packages called containers.\nIt was first released in 2013 and is developed by Docker, Inc. Docker is designed to make it easier to create, deploy, and run applications\nby using containers.\n</text>\n\n<query>\nWhat is Docker and how does it work?\n</query>\n\nResponse:\nDocker is a revolutionary platform-as-a-service product developed by Docker, Inc., that uses container technology to make application\ndeployment more efficient. It allows developers to package their software with all necessary dependencies, making it easier to run in\nany environment. Released in 2013, Docker has transformed the way applications are built, deployed, and managed.\n`\n2. `<text>\nThe theory of relativity, or simply relativity, encompasses two interrelated theories of Albert Einstein: special relativity and general\nrelativity. However, the word "relativity" is sometimes used in reference to Galilean invariance. The term "theory of relativity" was based\non the expression "relative theory" used by Max Planck in 1906. The theory of relativity usually encompasses two interrelated theories by\nAlbert Einstein: special relativity and general relativity. Special relativity applies to all physical phenomena in the absence of gravity.\nGeneral relativity explains the law of gravitation and its relation to other forces of nature. It applies to the cosmological and astrophysical\nrealm, including astronomy.\n</text>\n\n<query>\nsummarize\n</query>\n\nResponse:\nThe theory of relativity, developed by Albert Einstein, encompasses two main theories: special relativity and general relativity. Special\nrelativity applies to all physical phenomena in the absence of gravity, while general relativity explains the law of gravitation and its\nrelation to other forces of nature. The theory of relativity is based on the concept of "relative theory," as introduced by Max Planck in\n1906. It is a fundamental theory in physics that has revolutionized our understanding of the universe.\n`\n</example>\n\nEverything below is the actual data you will be working with. Good luck!\n\n<query>\n{question}\n</query>\n\n<text>\n{content}\n</text>\n\nMake sure to answer the query in the summary.'.replace("{question}",n).replace("{content}",t.pageContent)});r.push({pageContent:a,metadata:{title:t.metadata.title,url:t.metadata.url}})})),r.length>0?r:N(n)}var $=class{config;constructor(e){this.config=e}async retrieveSearchDocs(e,t,n,a="general",r=!1,o=0,i){const{text:s}=await g({model:e,temperature:0,system:this.config.queryGeneratorPrompt,messages:[...this.config.queryGeneratorFewShots.map(([e,t])=>({role:e,content:t})),{role:"user",content:`\n <conversation>\n ${t}\n </conversation>\n\n <query>\n ${n}\n </query>\n `}]}),c=new R({key:"links"}),m=new C({key:"question"}),l=await c.parse(s);let d=await m.parse(s)??s;if("not_needed"===d&&(d="latest information"),l.length>0&&this.config.getDocumentsFromLinks){0===d.length&&(d="summarize");const t=await G(e,await this.config.getDocumentsFromLinks({links:l}),d);return{query:d,docs:t}}if(d=d.replace(/<think>.*?<\/think>/g,""),d&&0!==d.trim().length||(d="latest information"),d=d.trim(),d.length>500||d.split(/[.!?]\s+/).length>5){console.warn(`[MetaSearchAgent] Query is too long (${d.length} chars), truncating or using fallback`);const e=d.split(/[.!?]\s+/)[0].trim();d=e.length>0&&e.length<200?e:n.slice(0,200)}const p=this.config.activeEngines.length>0?this.config.activeEngines.slice(0,2).join(", "):"Web",h=(e,t,n)=>{i?.emit("data",JSON.stringify({type:"searching",data:{query:t,category:n??p,status:e}}))};h("running",d);let u={results:[],suggestions:[]};if(this.config.searchSearxng||this.config.searchTavily){const e=async()=>{try{const e=await this.config.searchSearxng(d,{language:"en",engines:this.config.activeEngines,categories:[a]});return e&&"object"==typeof e&&"results"in e?e:{results:[],suggestions:[]}}catch(e){return console.error("[MetaSearchAgent] SearXNG search failed:",e),{results:[],suggestions:[]}}},t=this.config.isTavilyConfigured?.()??!1;if(t&&0===this.config.activeEngines.length&&"general"===a)try{const e=await this.config.searchTavily(d,{searchDepth:"basic",maxResults:10});u=e&&"object"==typeof e&&"results"in e?e:{results:[],suggestions:[]}}catch(L){console.error("Tavily search failed, falling back to SearXNG:",L),u=this.config.searchSearxng?await e():{results:[],suggestions:[]}}else if(t&&this.config.searchTavily)try{u=await Promise.race([e(),new Promise((e,t)=>setTimeout(()=>t(/* @__PURE__ */new Error("Timeout")),1e4))])}catch(b){if("Timeout"===b.message){console.warn("[MetaSearchAgent] SearXNG search did not respond in 10 seconds, falling back to Tavily.");try{const e=await this.config.searchTavily(d,{searchDepth:"basic",maxResults:10});u=e&&"object"==typeof e&&"results"in e?e:{results:[],suggestions:[]}}catch(w){console.error("[MetaSearchAgent] Tavily fallback also failed, awaiting SearXNG directly:",w),u=this.config.searchSearxng?await e():{results:[],suggestions:[]}}}else{console.error("[MetaSearchAgent] SearXNG search failed, falling back to Tavily:",b);try{const e=await this.config.searchTavily(d,{searchDepth:"basic",maxResults:10});u=e&&"object"==typeof e&&"results"in e?e:{results:[],suggestions:[]}}catch(w){console.error("[MetaSearchAgent] Tavily fallback also failed:",w),u={results:[],suggestions:[]}}}}else u=this.config.searchSearxng?await e():{results:[],suggestions:[]}}else u={results:[],suggestions:[]};let y,f,v=(u?.results??[]).map(e=>({pageContent:e.content||(this.config.activeEngines.includes("youtube")?e.title:""),metadata:{title:e.title,url:e.url,source:e.source,...e.img_src&&{img_src:e.img_src}}}));if(0===v.length&&(v=N(d)),h("done",d),o>0?(y=3,f=Math.max(2,Math.floor(o/y))):r?(y=3,f=5):(y=0,f=0),y>0){const e=v.slice(0,y);h("running",`Extracting top ${e.length} sources`,"extract");const t=this.config.scrapeURL?e.map(async(e,t)=>{const n=e.metadata?.url;var a;if(n&&this.config.scrapeURL)try{const e=await(async(e,t)=>Promise.race([e,new Promise(e=>{setTimeout(()=>e(void 0),t)})]))(this.config.scrapeURL(n,{timeout:f}),1e3*f+1500);if("string"==typeof e&&e.length>100){const n=(a=e,a.replace(/<(script|style)[^>]*>[\s\S]*?<\/(script|style)>/gi," ").replace(/<[^>]+>/g," ").replace(/ /g," ").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/&[a-z#][a-z0-9]+;/gi," ").replace(/\s+/g," ").trim()).replace(/(\r\n|\n|\r)/gm," ").replace(/\s+/g," ").trim().slice(0,5e3);n.length>100&&(v[t].pageContent=n)}}catch{}}):[];await Promise.allSettled(t),h("done",`Extracting top ${e.length} sources`,"extract")}return{query:d,docs:v}}async runPipeline(e,t,n,a,r,o,i,s,c,m){try{let r=null,p=t;if(this.config.searchWeb){const o=await this.retrieveSearchDocs(a,B(n),t,s,c,m,e);p=o.query,r=o.docs}const h=process.env.R2_ACCOUNT_ID?{accountId:process.env.R2_ACCOUNT_ID,accessKeyId:process.env.R2_ACCESS_KEY_ID||"",secretAccessKey:process.env.R2_SECRET_ACCESS_KEY||"",bucket:process.env.R2_UPLOADS_BUCKET||"qwksearch-uploads"}:void 0,u=await O(p,r??[],o,0,h),g=D(u,t);g.length,e.emit("data",JSON.stringify({type:"sources",data:g}));const f=y({model:a,temperature:.7,system:(l=this.config.responsePrompt,d={systemInstructions:i,context:K(u),date:/* @__PURE__ */(new Date).toISOString()},Object.entries(d).reduce((e,[t,n])=>e.split(`{${t}}`).join(n),l)),messages:[...n,{role:"user",content:t}]});let v=0;for await(const t of f.textStream)v+=1,e.emit("data",JSON.stringify({type:"response",data:t}));if(0===v){const t=["I couldn't generate a full answer, but I ran a web search and found these source URLs:",...g.map(e=>e.metadata?.url).filter(e=>"string"==typeof e).slice(0,5).map(e=>`- ${e}`)].join("\n");e.emit("data",JSON.stringify({type:"response",data:t}))}e.emit("end")}catch(p){const t=p instanceof Error?p.message:String(p);console.error("[MetaSearchAgent] caught error from AI SDK stream:",t,p);let n=t;t.includes("404")||t.toLowerCase().includes("not found")?n="The selected AI model was not found at the provider. Please go to Settings → Model Providers and select a different model.":t.includes("410")?n="The selected AI model is no longer available (deprecated by the provider). Please go to Settings → Model Providers and select a different model.":t.includes("401")||t.includes("authentication")?n="Authentication failed with the AI provider. Please check your API key in Settings.":(t.includes("429")||t.includes("rate limit"))&&(n="Rate limit reached for the AI provider. Please wait a moment and try again."),e.emit("error",JSON.stringify({data:n}))}var l,d}async searchAndAnswer(e,t,n,a,r,o,i="general",s=!1,c=0){const m=new f;return setTimeout(()=>{this.runPipeline(m,e,t,n,a,r,o,i,s,c)},0),m}},z={webSearchRetrieverPrompt:n,webSearchResponsePrompt:e,webSearchRetrieverFewShots:t,writingAssistantPrompt:r},F=e=>({webSearch:new $({activeEngines:[],queryGeneratorPrompt:z.webSearchRetrieverPrompt,responsePrompt:z.webSearchResponsePrompt,queryGeneratorFewShots:z.webSearchRetrieverFewShots,rerank:!0,rerankThreshold:.3,searchWeb:!0,...e}),academicSearch:new $({activeEngines:["arxiv","google scholar","pubmed"],queryGeneratorPrompt:z.webSearchRetrieverPrompt,responsePrompt:z.webSearchResponsePrompt,queryGeneratorFewShots:z.webSearchRetrieverFewShots,rerank:!0,rerankThreshold:0,searchWeb:!0,...e}),writingAssistant:new $({activeEngines:[],queryGeneratorPrompt:"",queryGeneratorFewShots:[],responsePrompt:z.writingAssistantPrompt,rerank:!0,rerankThreshold:0,searchWeb:!0,...e}),wolframAlphaSearch:new $({activeEngines:["wolframalpha"],queryGeneratorPrompt:z.webSearchRetrieverPrompt,responsePrompt:z.webSearchResponsePrompt,queryGeneratorFewShots:z.webSearchRetrieverFewShots,rerank:!1,rerankThreshold:0,searchWeb:!0,...e}),youtubeSearch:new $({activeEngines:["youtube"],queryGeneratorPrompt:z.webSearchRetrieverPrompt,responsePrompt:z.webSearchResponsePrompt,queryGeneratorFewShots:z.webSearchRetrieverFewShots,rerank:!0,rerankThreshold:.3,searchWeb:!0,...e}),redditSearch:new $({activeEngines:["reddit"],queryGeneratorPrompt:z.webSearchRetrieverPrompt,responsePrompt:z.webSearchResponsePrompt,queryGeneratorFewShots:z.webSearchRetrieverFewShots,rerank:!0,rerankThreshold:.3,searchWeb:!0,...e})}),Y=F(),V=(e=4)=>`\nYou are an AI suggestion generator for an AI powered search engine. You will be given a conversation below. You need to generate ${e} suggestions based on the conversation. The suggestion should be relevant to the conversation that can be used by the user to ask the chat model for more information.\nYou need to make sure the suggestions are relevant to the conversation and are helpful to the user. Keep a note that the user might use these suggestions to ask a chat model for more information.\nMake sure the suggestions are medium in length and are informative and relevant to the conversation.\n\nProvide these suggestions separated by newlines between the XML tags <suggestions> and </suggestions>. For example:\n\n<suggestions>\nTell me more about SpaceX and their recent projects\nWhat is the latest news on SpaceX?\nWho is the CEO of SpaceX?\n</suggestions>\n\nConversation:\n{chat_history}\n`,H=new R({key:"suggestions"}),Q=async(e,t)=>{const n=e.maxQuestions??4,{text:a}=await g({model:t,temperature:0,prompt:V(n).replace("{chat_history}",B(e.chat_history))});return H.parse(a)};function j(e,t=1e3,n=200){const a=(e||"").trim();if(a.length<=t)return a.length>0?[a]:[];const r=[];let o=0;for(;o<a.length;){let e=Math.min(o+t,a.length);if(e<a.length){const t=a.lastIndexOf(" ",e);t>o&&(e=t)}if(r.push(a.slice(o,e).trim()),e>=a.length)break;o=Math.max(e-n,o+1)}return r.filter(e=>e.length>0)}var W=()=>[{key:"openai",name:"OpenAI",fields:[{type:"password",name:"API Key",key:"apiKey",description:"Your OpenAI API key",required:!0,placeholder:"OpenAI API Key",env:"OPENAI_API_KEY",scope:"server"},{type:"string",name:"Base URL",key:"baseURL",description:"The base URL for the OpenAI API",required:!0,placeholder:"OpenAI Base URL",default:"https://api.openai.com/v1",env:"OPENAI_BASE_URL",scope:"server"}]},{key:"anthropic",name:"Anthropic",fields:[{type:"password",name:"API Key",key:"apiKey",description:"Your Anthropic API key",required:!0,placeholder:"Anthropic API Key",env:"ANTHROPIC_API_KEY",scope:"server"}]},{key:"gemini",name:"Google Gemini",fields:[{type:"password",name:"API Key",key:"apiKey",description:"Your Google Gemini API key",required:!0,placeholder:"Google Gemini API Key",env:"GEMINI_API_KEY",scope:"server"}]},{key:"groq",name:"Groq",fields:[{type:"password",name:"API Key",key:"apiKey",description:"Your Groq API key. Free tier includes fast inference on Llama and Mixtral models - get yours at console.groq.com",required:!0,placeholder:"gsk_...",env:"GROQ_API_KEY",scope:"server"}]},{key:"deepseek",name:"DeepSeek",fields:[{type:"password",name:"API Key",key:"apiKey",description:"Your DeepSeek API key",required:!0,placeholder:"DeepSeek API Key",env:"DEEPSEEK_API_KEY",scope:"server"}]},{key:"nvidia",name:"NVIDIA",fields:[{type:"password",name:"API Key",key:"apiKey",description:"Your NVIDIA API key. Free tier includes access to Nemotron, Llama, and other models - get yours at build.nvidia.com",required:!0,placeholder:"nvapi-...",env:"NVIDIA_API_KEY",scope:"server"},{type:"string",name:"Base URL",key:"baseURL",description:"The base URL for NVIDIA's OpenAI-compatible API",required:!0,placeholder:"https://integrate.api.nvidia.com/v1",default:"https://integrate.api.nvidia.com/v1",env:"NVIDIA_BASE_URL",scope:"server"}]},{key:"openrouter",name:"OpenRouter",fields:[{type:"password",name:"API Key",key:"apiKey",description:"Your OpenRouter API key. Get one free at openrouter.ai - includes free access to Llama 3.3 70B, Nemotron, and other models.",required:!0,placeholder:"sk-or-v1-...",env:"OPENROUTER_API_KEY",scope:"server"},{type:"string",name:"Base URL",key:"baseURL",description:"The base URL for OpenRouter's OpenAI-compatible API",required:!0,placeholder:"https://openrouter.ai/api/v1",default:"https://openrouter.ai/api/v1",env:"OPENROUTER_BASE_URL",scope:"server"}]}];function X(e){try{return v("cloudflare:workers").env?.[e]}catch{return process.env[e]}}var J=[{provider:"NVIDIA",docs:"https://docs.api.nvidia.com/nim/reference/llm-apis",api_key:"https://build.nvidia.com/settings/api-keys",default:"nvidia/llama-3.1-nemotron-70b-instruct",models:[{name:"Llama 3.1 Nemotron 70B Instruct",id:"nvidia/llama-3.1-nemotron-70b-instruct",contextLength:131072,free:!0,type:"text-generation"},{name:"Nemotron 3 Super 120B",id:"nvidia/nemotron-3-super-120b-a12b",contextLength:1e6,free:!0,type:"text-generation"},{name:"Nemotron-4 340B",id:"nvidia/nemotron-4-340b",contextLength:131072,free:!1,type:"text-generation"},{name:"Llama 3.3 70B Instruct",id:"meta/llama-3.3-70b-instruct",contextLength:131072,free:!0,type:"text-generation"},{name:"Llama 3.1 405B Instruct",id:"meta/llama-3.1-405b-instruct",contextLength:131072,free:!1,type:"text-generation"},{name:"Llama 3.1 8B Instruct",id:"meta/llama-3.1-8b-instruct",contextLength:131072,free:!0,type:"text-generation"},{name:"Gemma 4 31B IT",id:"google/gemma-4-31b-it",contextLength:131072,free:!0,type:"text-generation"},{name:"Mistral Large 2",id:"mistralai/mistral-large-2",contextLength:131072,free:!1,type:"text-generation"}]},{provider:"Cloudflare",docs:"https://developers.cloudflare.com/workers-ai/",api_key:"https://dash.cloudflare.com/profile/api-tokens",default:"llama-4-scout-17b-16e-instruct",models:[{name:"Llama 4 Scout 17B 16E Instruct",id:"llama-4-scout-17b-16e-instruct",contextLength:128e3},{name:"Llama 3.3 70B Instruct FP8 Fast",id:"llama-3.3-70b-instruct-fp8-fast",contextLength:128e3},{name:"Llama 3.1 8B Instruct Fast",id:"llama-3.1-8b-instruct-fast",contextLength:128e3},{name:"Gemma 3 12B IT",id:"gemma-3-12b-it",contextLength:128e3},{name:"Mistral Small 3.1 24B Instruct",id:"mistral-small-3.1-24b-instruct",contextLength:128e3},{name:"QwQ 32B",id:"qwq-32b",contextLength:32768},{name:"Qwen2.5 Coder 32B Instruct",id:"qwen2.5-coder-32b-instruct",contextLength:32768},{name:"Llama Guard 3 8B",id:"llama-guard-3-8b",contextLength:8192},{name:"DeepSeek R1 Distill Qwen 32B",id:"deepseek-r1-distill-qwen-32b",contextLength:32768},{name:"Llama 3.2 1B Instruct",id:"llama-3.2-1b-instruct",contextLength:131072},{name:"Llama 3.2 3B Instruct",id:"llama-3.2-3b-instruct",contextLength:131072},{name:"Llama 3.2 11B Vision Instruct",id:"llama-3.2-11b-vision-instruct",contextLength:131072},{name:"Llama 3.1 8B Instruct AWQ",id:"llama-3.1-8b-instruct-awq",contextLength:128e3},{name:"Llama 3.1 8B Instruct FP8",id:"llama-3.1-8b-instruct-fp8",contextLength:128e3},{name:"MeloTTS",id:"melotts",contextLength:1024},{name:"Llama 3.1 8B Instruct",id:"llama-3.1-8b-instruct",contextLength:128e3},{name:"Meta Llama 3 8B Instruct",id:"meta-llama-3-8b-instruct",contextLength:8192},{name:"Whisper Large V3 Turbo",id:"whisper-large-v3-turbo",contextLength:448e3},{name:"Llama 3 8B Instruct AWQ",id:"llama-3-8b-instruct-awq",contextLength:8192},{name:"LLaVA 1.5 7B HF",id:"llava-1.5-7b-hf",contextLength:4096},{name:"Una Cybertron 7B V2 BF16",id:"una-cybertron-7b-v2-bf16",contextLength:32768},{name:"Whisper Tiny EN",id:"whisper-tiny-en",contextLength:448e3},{name:"Llama 3 8B Instruct",id:"llama-3-8b-instruct",contextLength:8192},{name:"Mistral 7B Instruct v0.2",id:"mistral-7b-instruct-v0.2",contextLength:32768},{name:"Gemma 7B IT LoRA",id:"gemma-7b-it-lora",contextLength:8192},{name:"Gemma 2B IT LoRA",id:"gemma-2b-it-lora",contextLength:8192},{name:"Llama 2 7B Chat HF LoRA",id:"llama-2-7b-chat-hf-lora",contextLength:4096},{name:"Gemma 7B IT",id:"gemma-7b-it",contextLength:8192},{name:"Starling LM 7B Beta",id:"starling-lm-7b-beta",contextLength:8192},{name:"Hermes 2 Pro Mistral 7B",id:"hermes-2-pro-mistral-7b",contextLength:32768},{name:"Mistral 7B Instruct v0.2 LoRA",id:"mistral-7b-instruct-v0.2-lora",contextLength:32768},{name:"Qwen1.5 1.8B Chat",id:"qwen1.5-1.8b-chat",contextLength:32768},{name:"UForm Gen2 Qwen 500M",id:"uform-gen2-qwen-500m",contextLength:2048},{name:"BART Large CNN",id:"bart-large-cnn",contextLength:1024},{name:"Phi-2",id:"phi-2",contextLength:2048},{name:"TinyLlama 1.1B Chat v1.0",id:"tinyllama-1.1b-chat-v1.0",contextLength:2048},{name:"Qwen1.5 14B Chat AWQ",id:"qwen1.5-14b-chat-awq",contextLength:32768},{name:"Qwen1.5 7B Chat AWQ",id:"qwen1.5-7b-chat-awq",contextLength:32768},{name:"Qwen1.5 0.5B Chat",id:"qwen1.5-0.5b-chat",contextLength:32768},{name:"DiscoLM German 7B v1 AWQ",id:"discolm-german-7b-v1-awq",contextLength:32768},{name:"Falcon 7B Instruct",id:"falcon-7b-instruct",contextLength:2048},{name:"OpenChat 3.5 0106",id:"openchat-3.5-0106",contextLength:8192},{name:"SQLCoder 7B 2",id:"sqlcoder-7b-2",contextLength:16384},{name:"DeepSeek Math 7B Instruct",id:"deepseek-math-7b-instruct",contextLength:4096},{name:"DETR ResNet-50",id:"detr-resnet-50",contextLength:1024},{name:"Stable Diffusion XL Lightning",id:"stable-diffusion-xl-lightning",contextLength:77},{name:"DreamShaper 8 LCM",id:"dreamshaper-8-lcm",contextLength:77},{name:"Stable Diffusion v1.5 Img2Img",id:"stable-diffusion-v1-5-img2img",contextLength:77},{name:"Stable Diffusion v1.5 Inpainting",id:"stable-diffusion-v1-5-inpainting",contextLength:77},{name:"DeepSeek Coder 6.7B Instruct AWQ",id:"deepseek-coder-6.7b-instruct-awq",contextLength:16384},{name:"DeepSeek Coder 6.7B Base AWQ",id:"deepseek-coder-6.7b-base-awq",contextLength:16384},{name:"LlamaGuard 7B AWQ",id:"llamaguard-7b-awq",contextLength:4096},{name:"Neural Chat 7B v3.1 AWQ",id:"neural-chat-7b-v3-1-awq",contextLength:8192},{name:"OpenHermes 2.5 Mistral 7B AWQ",id:"openhermes-2.5-mistral-7b-awq",contextLength:8192},{name:"Llama 2 13B Chat AWQ",id:"llama-2-13b-chat-awq",contextLength:4096},{name:"Mistral 7B Instruct v0.1 AWQ",id:"mistral-7b-instruct-v0.1-awq",contextLength:8192},{name:"Zephyr 7B Beta AWQ",id:"zephyr-7b-beta-awq",contextLength:8192},{name:"Stable Diffusion XL Base 1.0",id:"stable-diffusion-xl-base-1.0",contextLength:77},{name:"BGE Large EN v1.5",id:"bge-large-en-v1.5",contextLength:512},{name:"BGE Small EN v1.5",id:"bge-small-en-v1.5",contextLength:512},{name:"Llama 2 7B Chat FP16",id:"llama-2-7b-chat-fp16",contextLength:4096},{name:"Mistral 7B Instruct v0.1",id:"mistral-7b-instruct-v0.1",contextLength:8192},{name:"BGE Base EN v1.5",id:"bge-base-en-v1.5",contextLength:512},{name:"DistilBERT SST-2 Int8",id:"distilbert-sst-2-int8",contextLength:512},{name:"Llama 2 7B Chat Int8",id:"llama-2-7b-chat-int8",contextLength:4096},{name:"M2M100 1.2B",id:"m2m100-1.2b",contextLength:1024},{name:"ResNet-50",id:"resnet-50",contextLength:224},{name:"Whisper",id:"whisper",contextLength:448e3},{name:"Llama 3.1 70B Instruct",id:"llama-3.1-70b-instruct",contextLength:128e3}]},{provider:"Perplexity",docs:"https://docs.perplexity.ai/models/model-cards",api_key:"https://www.perplexity.ai/account/api/keys",default:"sonar",models:[{name:"Sonar Pro",id:"sonar-pro",contextLength:2e5},{name:"Sonar",id:"sonar",contextLength:128e3},{name:"Sonar Reasoning Pro",id:"sonar-reasoning-pro",contextLength:128e3},{name:"Sonar Reasoning",id:"sonar-reasoning",contextLength:128e3},{name:"Sonar Deep Research",id:"sonar-deep-research",contextLength:128e3},{name:"Llama 3.1 Sonar Small 128k Online",id:"llama-3.1-sonar-small-128k-online",contextLength:127072},{name:"Llama 3.1 Sonar Large 128k Online",id:"llama-3.1-sonar-large-128k-online",contextLength:127072},{name:"Llama 3.1 Sonar Huge 128k Online",id:"llama-3.1-sonar-huge-128k-online",contextLength:127072}]},{provider:"Groq",docs:"https://console.groq.com/docs/overview",api_key:"https://console.groq.com/keys",default:"llama-3.3-70b-versatile",models:[{name:"Llama 3.3 70B Versatile (Free)",id:"llama-3.3-70b-versatile",contextLength:131072,free:!0,type:"text-generation",rateLimit:"300K TPM / 1K RPM = ~432M tokens/day"},{name:"Llama 3.1 8B Instant (Free)",id:"llama-3.1-8b-instant",contextLength:8192,free:!0,type:"text-generation",rateLimit:"250K TPM / 1K RPM = ~360M tokens/day"},{name:"Llama 4 Scout 17B (Free)",id:"meta-llama/llama-4-scout-17b-16e-instruct",contextLength:131072,free:!0,type:"text-generation",rateLimit:"300K TPM / 1K RPM = ~432M tokens/day"},{name:"Qwen 3 32B (Free)",id:"qwen/qwen3-32b",contextLength:128e3,free:!0,type:"text-generation",rateLimit:"300K TPM / 1K RPM = ~432M tokens/day"},{name:"GPT-OSS 120B (Free)",id:"openai/gpt-oss-120b",contextLength:32768,free:!0,type:"text-generation",rateLimit:"250K TPM / 1K RPM = ~360M tokens/day"},{name:"GPT-OSS 20B (Free)",id:"openai/gpt-oss-20b",contextLength:32768,free:!0,type:"text-generation",rateLimit:"250K TPM / 1K RPM = ~360M tokens/day"},{name:"Groq Compound (Free)",id:"groq/compound",contextLength:32768,free:!0,type:"text-generation",rateLimit:"200K TPM / 200 RPM = ~288M tokens/day"},{name:"Groq Compound Mini (Free)",id:"groq/compound-mini",contextLength:32768,free:!0,type:"text-generation",rateLimit:"200K TPM / 200 RPM = ~288M tokens/day"},{name:"GPT-OSS Safeguard 20B (Free)",id:"openai/gpt-oss-safeguard-20b",contextLength:32768,free:!0,type:"text-generation",rateLimit:"150K TPM / 1K RPM = ~216M tokens/day"}]},{provider:"OpenAI",docs:"https://platform.openai.com/docs/overview",api_key:"https://platform.openai.com/api-keys",default:"gpt-4o",models:[{name:"GPT-4 Omni",id:"gpt-4o",contextLength:128e3},{name:"GPT-4 Omni Mini",id:"gpt-4o-mini",contextLength:128e3},{name:"GPT-4 Turbo",id:"gpt-4-turbo",contextLength:128e3},{name:"GPT-4",id:"gpt-4",contextLength:8192},{name:"GPT-3.5 Turbo",id:"gpt-3.5-turbo",contextLength:16385}]},{provider:"Anthropic",docs:"https://docs.anthropic.com/en/docs/welcome",api_key:"https://console.anthropic.com/settings/keys",default:"claude-3-7-sonnet-20250219",models:[{name:"Claude 3.7 Sonnet",id:"claude-3-7-sonnet-20250219",contextLength:2e5},{name:"Claude 3.5 Sonnet",id:"claude-3-5-sonnet-20241022",contextLength:2e5},{name:"Claude 3 Opus",id:"claude-3-opus-20240229",contextLength:2e5},{name:"Claude 3 Sonnet",id:"claude-3-sonnet-20240229",contextLength:2e5},{name:"Claude 3 Haiku",id:"claude-3-haiku-20240307",contextLength:2e5}]},{provider:"TogetherAI",docs:"https://docs.together.ai/docs/quickstart",api_key:"https://api.together.xyz/settings/api-keys",default:"meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo",models:[{name:"Llama 3.1 8B Instruct Turbo",id:"meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo",contextLength:131072},{name:"Llama 3.1 70B Instruct Turbo",id:"meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo",contextLength:131072},{name:"Llama 3.1 405B Instruct Turbo",id:"meta-llama/Meta-Llama-3.1-405B-Instruct-Turbo",contextLength:130815},{name:"Llama 3 8B Instruct Turbo",id:"meta-llama/Meta-Llama-3-8B-Instruct-Turbo",contextLength:8192},{name:"Llama 3 70B Instruct Turbo",id:"meta-llama/Meta-Llama-3-70B-Instruct-Turbo",contextLength:8192},{name:"Llama 3.2 3B Instruct Turbo",id:"meta-llama/Llama-3.2-3B-Instruct-Turbo",contextLength:131072},{name:"Llama 3 8B Instruct Lite",id:"meta-llama/Meta-Llama-3-8B-Instruct-Lite",contextLength:8192},{name:"Llama 3 70B Instruct Lite",id:"meta-llama/Meta-Llama-3-70B-Instruct-Lite",contextLength:8192},{name:"Llama 3 8B Instruct Reference",id:"meta-llama/Llama-3-8b-chat-hf",contextLength:8192},{name:"Llama 3 70B Instruct Reference",id:"meta-llama/Llama-3-70b-chat-hf",contextLength:8192},{name:"Llama 3.1 Nemotron 70B",id:"nvidia/Llama-3.1-Nemotron-70B-Instruct-HF",contextLength:32768},{name:"Qwen 2.5 Coder 32B Instruct",id:"Qwen/Qwen2.5-Coder-32B-Instruct",contextLength:32769},{name:"WizardLM-2 8x22B",id:"microsoft/WizardLM-2-8x22B",contextLength:65536},{name:"Gemma 2 27B",id:"google/gemma-2-27b-it",contextLength:8192},{name:"Gemma 2 9B",id:"google/gemma-2-9b-it",contextLength:8192},{name:"DBRX Instruct",id:"databricks/dbrx-instruct",contextLength:32768},{name:"DeepSeek LLM Chat (67B)",id:"deepseek-ai/deepseek-llm-67b-chat",contextLength:4096},{name:"Gemma Instruct (2B)",id:"google/gemma-2b-it",contextLength:8192},{name:"MythoMax-L2 (13B)",id:"Gryphe/MythoMax-L2-13b",contextLength:4096},{name:"LLaMA-2 Chat (13B)",id:"meta-llama/Llama-2-13b-chat-hf",contextLength:4096},{name:"Mistral (7B) Instruct",id:"mistralai/Mistral-7B-Instruct-v0.1",contextLength:8192},{name:"Mistral (7B) Instruct v0.2",id:"mistralai/Mistral-7B-Instruct-v0.2",contextLength:32768},{name:"Mistral (7B) Instruct v0.3",id:"mistralai/Mistral-7B-Instruct-v0.3",contextLength:32768},{name:"Mixtral-8x7B Instruct (46.7B)",id:"mistralai/Mixtral-8x7B-Instruct-v0.1",contextLength:32768},{name:"Mixtral-8x22B Instruct (141B)",id:"mistralai/Mixtral-8x22B-Instruct-v0.1",contextLength:65536},{name:"Nous Hermes 2 - Mixtral 8x7B-DPO (46.7B)",id:"NousResearch/Nous-Hermes-2-Mixtral-8x7B-DPO",contextLength:32768},{name:"Qwen 2.5 7B Instruct Turbo",id:"Qwen/Qwen2.5-7B-Instruct-Turbo",contextLength:32768},{name:"Qwen 2.5 72B Instruct Turbo",id:"Qwen/Qwen2.5-72B-Instruct-Turbo",contextLength:32768},{name:"Qwen 2 Instruct (72B)",id:"Qwen/Qwen2-72B-Instruct",contextLength:32768},{name:"StripedHyena Nous (7B)",id:"togethercomputer/StripedHyena-Nous-7B",contextLength:32768},{name:"Upstage SOLAR Instruct v1 (11B)",id:"upstage/SOLAR-10.7B-Instruct-v1.0",contextLength:4096},{name:"Llama 3.2 11B Vision Instruct Turbo (Free)",id:"meta-llama/Llama-Vision-Free",contextLength:131072},{name:"Llama 3.2 11B Vision Instruct Turbo",id:"meta-llama/Llama-3.2-11B-Vision-Instruct-Turbo",contextLength:131072},{name:"Llama 3.2 90B Vision Instruct Turbo",id:"meta-llama/Llama-3.2-90B-Vision-Instruct-Turbo",contextLength:131072}]},{provider:"XAI",docs:"https://docs.x.ai/docs#models",api_key:"https://console.x.ai/",default:"grok-beta",models:[{name:"Grok",id:"grok-beta",contextLength:131072},{name:"Grok Vision",id:"grok-vision-beta",contextLength:8192}]},{provider:"Google",docs:"https://cloud.google.com/vertex-ai/generative-ai/docs/learn/models",api_key:"https://cloud.google.com/vertex-ai/generative-ai/docs/start/express-mode/overview#api-keys",models:[{name:"Gemini 2.5 Pro Preview",id:"gemini-2.5-pro-preview-05-06",contextLength:1048576},{name:"Gemini 2.5 Flash Preview",id:"gemini-2.5-flash-preview-04-17",contextLength:1048576},{name:"Gemini 2.0 Flash",id:"gemini-2.0-flash-001",contextLength:1048576},{name:"Gemini 2.0 Flash-Lite",id:"gemini-2.0-flash-lite-001",contextLength:1048576},{name:"Gemini 2.0 Flash-Live",id:"gemini-2.0-flash-live-preview-04-09",contextLength:32768},{name:"Imagen 3",id:"imagen-3.0-generate-002",contextLength:480},{name:"Imagen 3 Fast",id:"imagen-3.0-fast-generate-001",contextLength:480},{name:"Llama 3.2 90B Vision Instruct Turbo",id:"meta-llama/Llama-3.2-90B-Vision-Instruct-Turbo",contextLength:131072},{name:"Llama 3.3 70B",id:"meta-llama/Llama-3.3-70B",contextLength:131072},{name:"Gemma 3",id:"gemma-3",contextLength:131072},{name:"Gemma 2",id:"gemma-2",contextLength:131072},{name:"Gemma",id:"gemma",contextLength:131072}]},{provider:"Amazon",docs:"https://docs.aws.amazon.com/bedrock/",api_key:"https://console.aws.amazon.com/iam/home#/security_credentials",default:"anthropic.claude-3-5-sonnet-20241022-v2:0",models:[{name:"AI21 Jamba 1.5 Mini",id:"ai21.jamba-1-5-mini-v1:0",contextLength:256e3,provider:"AI21 Labs"},{name:"AI21 Jamba 1.5 Large",id:"ai21.jamba-1-5-large-v1:0",contextLength:256e3,provider:"AI21 Labs"},{name:"Amazon Nova Canvas",id:"amazon.nova-canvas-v1:0",contextLength:77,provider:"Amazon",type:"image"},{name:"Amazon Nova Lite",id:"amazon.nova-lite-v1:0",contextLength:3e5,provider:"Amazon"},{name:"Amazon Nova Micro",id:"amazon.nova-micro-v1:0",contextLength:128e3,provider:"Amazon"},{name:"Amazon Nova Pro",id:"amazon.nova-pro-v1:0",contextLength:3e5,provider:"Amazon"},{name:"Amazon Nova Reel",id:"amazon.nova-reel-v1:0",contextLength:1e4,provider:"Amazon",type:"video"},{name:"Amazon Nova Reel V2 Lite",id:"amazon.nova-reel-v2-lite-v1:0",contextLength:1e4,provider:"Amazon",type:"video"},{name:"Amazon Nova Reel V2 Standard",id:"amazon.nova-reel-v2-standard-v1:0",contextLength:1e4,provider:"Amazon",type:"video"},{name:"Amazon Rerank",id:"amazon.rerank-v1:0",contextLength:8192,provider:"Amazon",type:"reranker"},{name:"Amazon Titan Embeddings G1 - Text",id:"amazon.titan-embed-text-v1",contextLength:8192,provider:"Amazon",type:"embedding"},{name:"Amazon Titan Embeddings G1 - Text v2",id:"amazon.titan-embed-text-v2:0",contextLength:8192,provider:"Amazon",type:"embedding"},{name:"Amazon Titan Image Generator G1",id:"amazon.titan-image-generator-v1",contextLength:128,provider:"Amazon",type:"image"},{name:"Amazon Titan Image Generator G2",id:"amazon.titan-image-generator-v2:0",contextLength:128,provider:"Amazon",type:"image"},{name:"Amazon Titan Multimodal Embeddings G1",id:"amazon.titan-embed-image-v1",contextLength:8192,provider:"Amazon",type:"embedding"},{name:"Amazon Titan Text G1 - Express",id:"amazon.titan-text-express-v1",contextLength:8192,provider:"Amazon"},{name:"Amazon Titan Text G1 - Lite",id:"amazon.titan-text-lite-v1",contextLength:4096,provider:"Amazon"},{name:"Amazon Titan Text G1 - Premier",id:"amazon.titan-text-premier-v1:0",contextLength:32e3,provider:"Amazon"},{name:"Claude 3.5 Sonnet v2",id:"anthropic.claude-3-5-sonnet-20241022-v2:0",contextLength:2e5,provider:"Anthropic"},{name:"Claude 3.5 Sonnet v1",id:"anthropic.claude-3-5-sonnet-20240620-v1:0",contextLength:2e5,provider:"Anthropic"},{name:"Claude 3.5 Haiku",id:"anthropic.claude-3-5-haiku-20241022-v1:0",contextLength:2e5,provider:"Anthropic"},{name:"Claude 3 Opus",id:"anthropic.claude-3-opus-20240229-v1:0",contextLength:2e5,provider:"Anthropic"},{name:"Claude 3 Sonnet",id:"anthropic.claude-3-sonnet-20240229-v1:0",contextLength:2e5,provider:"Anthropic"},{name:"Claude 3 Haiku",id:"anthropic.claude-3-haiku-20240307-v1:0",contextLength:2e5,provider:"Anthropic"},{name:"Claude Instant",id:"anthropic.claude-instant-v1",contextLength:1e5,provider:"Anthropic"},{name:"Cohere Command",id:"cohere.command-text-v14",contextLength:4096,provider:"Cohere"},{name:"Cohere Command Light",id:"cohere.command-light-text-v14",contextLength:4096,provider:"Cohere"},{name:"Cohere Command R",id:"cohere.command-r-v1:0",contextLength:128e3,provider:"Cohere"},{name:"Cohere Command R+",id:"cohere.command-r-plus-v1:0",contextLength:128e3,provider:"Cohere"},{name:"Cohere Embed English",id:"cohere.embed-english-v3",contextLength:512,provider:"Cohere",type:"embedding"},{name:"Cohere Embed Multilingual",id:"cohere.embed-multilingual-v3",contextLength:512,provider:"Cohere",type:"embedding"},{name:"Cohere Rerank English",id:"cohere.rerank-english-v3:0",contextLength:4096,provider:"Cohere",type:"reranker"},{name:"Cohere Rerank Multilingual",id:"cohere.rerank-multilingual-v3:0",contextLength:4096,provider:"Cohere",type:"reranker"},{name:"DeepSeek R1",id:"deepseek.deepseek-r1-distill-qwen-32b-v1:0",contextLength:32768,provider:"DeepSeek"},{name:"Luma Dream Machine",id:"luma.dream-machine-v1:0",contextLength:512,provider:"Luma AI",type:"video"},{name:"Llama 3.2 11B Vision Instruct",id:"meta.llama3-2-11b-instruct-v1:0",contextLength:128e3,provider:"Meta"},{name:"Llama 3.2 90B Vision Instruct",id:"meta.llama3-2-90b-instruct-v1:0",contextLength:128e3,provider:"Meta"},{name:"Mistral 7B Instruct",id:"mistral.mistral-7b-instruct-v0:2",contextLength:32768,provider:"Mistral AI"},{name:"Mixtral 8x7B Instruct",id:"mistral.mixtral-8x7b-instruct-v0:1",contextLength:32768,provider:"Mistral AI"},{name:"Mistral Small",id:"mistral.mistral-small-2402-v1:0",contextLength:32768,provider:"Mistral AI"},{name:"Mistral Large",id:"mistral.mistral-large-2402-v1:0",contextLength:32768,provider:"Mistral AI"},{name:"Mistral Large 2",id:"mistral.mistral-large-2407-v1:0",contextLength:128e3,provider:"Mistral AI"},{name:"Mistral Large 2411",id:"mistral.mistral-large-2411-v1:0",contextLength:128e3,provider:"Mistral AI"},{name:"Stable Diffusion XL",id:"stability.stable-diffusion-xl-v1",contextLength:77,provider:"Stability AI",type:"image"},{name:"SDXL 1.0",id:"stability.stable-diffusion-xl-v0",contextLength:77,provider:"Stability AI",type:"image"},{name:"Stable Image Ultra",id:"stability.stable-image-ultra-v1:0",contextLength:77,provider:"Stability AI",type:"image"},{name:"Stable Image Core",id:"stability.stable-image-core-v1:0",contextLength:77,provider:"Stability AI",type:"image"}]},{provider:"OpenRouter",docs:"https://openrouter.ai/docs",api_key:"https://openrouter.ai/settings/keys",default:"openrouter/free",models:[{name:"OpenRouter Free (rotating)",id:"openrouter/free",contextLength:2e5,free:!0,type:"text-generation"},{name:"Nemotron 3 Super 120B",id:"nvidia/nemotron-3-super-120b-a12b:free",contextLength:1e6,free:!0,type:"text-generation"},{name:"Nemotron 3 Ultra 550B",id:"nvidia/nemotron-3-ultra-550b-a55b:free",contextLength:1e6,free:!0,type:"text-generation"},{name:"Nemotron 3 Nano 30B A3B",id:"nvidia/nemotron-3-nano-30b-a3b:free",contextLength:256e3,free:!0,type:"text-generation"},{name:"Nemotron 3 Nano Omni 30B A3B Reasoning",id:"nvidia/nemotron-3-nano-omni-30b-a3b-reasoning:free",contextLength:256e3,free:!0,type:"text-generation"},{name:"Nemotron Nano 12B v2 VL",id:"nvidia/nemotron-nano-12b-v2-vl:free",contextLength:128e3,free:!0,type:"text-generation"},{name:"Nemotron Nano 9B v2",id:"nvidia/nemotron-nano-9b-v2:free",contextLength:128e3,free:!0,type:"text-generation"},{name:"Nemotron 3.5 Content Safety",id:"nvidia/nemotron-3.5-content-safety:free",contextLength:128e3,free:!0,type:"text-generation"},{name:"Gemma 4 31B IT",id:"google/gemma-4-31b-it:free",contextLength:262e3,free:!0,type:"text-generation"},{name:"Gemma 4 26B A4B IT",id:"google/gemma-4-26b-a4b-it:free",contextLength:262e3,free:!0,type:"text-generation"},{name:"GPT-OSS 120B",id:"openai/gpt-oss-120b:free",contextLength:131072,free:!0,type:"text-generation"},{name:"GPT-OSS 20B",id:"openai/gpt-oss-20b:free",contextLength:131072,free:!0,type:"text-generation"},{name:"Qwen3 Coder",id:"qwen/qwen3-coder:free",contextLength:1e6,free:!0,type:"text-generation"},{name:"Qwen3 Next 80B A3B Instruct",id:"qwen/qwen3-next-80b-a3b-instruct:free",contextLength:262e3,free:!0,type:"text-generation"},{name:"Llama 3.3 70B Instruct",id:"meta-llama/llama-3.3-70b-instruct:free",contextLength:131072,free:!0,type:"text-generation"},{name:"Llama 3.2 3B Instruct",id:"meta-llama/llama-3.2-3b-instruct:free",contextLength:131072,free:!0,type:"text-generation"},{name:"Hermes 3 Llama 3.1 405B",id:"nousresearch/hermes-3-llama-3.1-405b:free",contextLength:131072,free:!0,type:"text-generation"},{name:"Laguna XS 2.1",id:"poolside/laguna-xs-2.1:free",contextLength:262e3,free:!0,type:"text-generation"},{name:"Laguna XS 2",id:"poolside/laguna-xs.2:free",contextLength:262e3,free:!0,type:"text-generation"},{name:"Laguna M 1",id:"poolside/laguna-m.1:free",contextLength:262e3,free:!0,type:"text-generation"},{name:"North Mini Code",id:"cohere/north-mini-code:free",contextLength:256e3,free:!0,type:"text-generation"},{name:"Dolphin Mistral 24B Venice Edition",id:"cognitivecomputations/dolphin-mistral-24b-venice-edition:free",contextLength:33e3,free:!0,type:"text-generation"},{name:"LFM 2.5 1.2B Thinking",id:"liquid/lfm-2.5-1.2b-thinking:free",contextLength:33e3,free:!0,type:"text-generation"},{name:"LFM 2.5 1.2B Instruct",id:"liquid/lfm-2.5-1.2b-instruct:free",contextLength:33e3,free:!0,type:"text-generation"},{name:"OpenRouter Free (rotating)",id:"openrouter/free",contextLength:2e5,free:!0,type:"text-generation"}]}],Z=(J.map(e=>e.provider.toLocaleLowerCase()),{openrouter:["openrouter/free","nvidia/nemotron-3-super-120b-a12b:free","nvidia/nemotron-3-ultra-550b-a55b:free","nvidia/nemotron-3-nano-30b-a3b:free","nvidia/nemotron-3-nano-omni-30b-a3b-reasoning:free","nvidia/nemotron-nano-9b-v2:free","nvidia/nemotron-3.5-content-safety:free","google/gemma-4-31b-it:free","google/gemma-4-26b-a4b-it:free","openai/gpt-oss-20b:free","poolside/laguna-xs-2.1:free","poolside/laguna-m.1:free","cohere/north-mini-code:free"],nvidia:["nvidia/nemotron-3-super-120b-a12b","meta/llama-3.1-8b-instruct"]}),ee={openai:"openai",anthropic:"anthropic",gemini:"google",groq:"groq",deepseek:"deepseek",nvidia:"nvidia",openrouter:"openrouter"},te=e=>{const t=ee[e]??e,n=J.find(e=>e.provider.toLowerCase()===t.toLowerCase());return n?.models?n.models.map(e=>({name:e.name,key:e.id})):[]},ne=e=>{const t=JSON.stringify(e,Object.keys(e).sort());let n=0;for(let a=0;a<t.length;a++)n=(n<<5)-n+t.charCodeAt(a),n|=0;return String(Math.abs(n).toString(36))},ae=new class{configVersion=1;currentConfig={version:this.configVersion,setupComplete:"true"===X("SETUP_COMPLETE")||!1,preferences:{},personalization:{},modelProviders:[],mcpServers:[],search:{searxngURL:"",tavilyApiKey:"",sourceScrapeCount:3,sourceScrapeTimeout:5}};uiConfigSections={preferences:[],personalization:[],modelProviders:[],mcpServers:[],search:[{name:"SearXNG URL",key:"searxngURL",type:"string",required:!1,description:"The URL of your SearXNG instance",placeholder:"http://localhost:4000",default:"",scope:"server",env:"SEARXNG_API_URL"},{name:"Tavily API Key",key:"tavilyApiKey",type:"string",required:!1,description:"Your Tavily API key for enhanced search capabilities.",placeholder:"tvly-...",default:"",scope:"server",env:"TAVILY_API_KEY"},{name:"Source pages to scrape",key:"sourceScrapeCount",type:"select",options:[{name:"Disabled (snippet only)",value:"0"},{name:"1 page",value:"1"},{name:"2 pages",value:"2"},{name:"3 pages (default)",value:"3"},{name:"5 pages",value:"5"}],required:!1,description:"Number of top search result URLs to fully scrape.",default:"3",scope:"server"},{name:"Scrape timeout (seconds)",key:"sourceScrapeTimeout",type:"select",options:[{name:"3 seconds",value:"3"},{name:"5 seconds (default)",value:"5"},{name:"10 seconds",value:"10"},{name:"15 seconds",value:"15"},{name:"20 seconds",value:"20"}],required:!1,description:"Maximum time to wait when scraping each source URL.",default:"5",scope:"server"}]};initialized=!1;constructor(){}ensureInitialized(){this.initialized||(this.initialize(),this.initialized=!0)}initialize(){const e=[{key:"openai",name:"OpenAI",fields:[{type:"password",name:"API Key",key:"apiKey",description:"Your OpenAI API key",required:!0,placeholder:"OpenAI API Key",env:"OPENAI_API_KEY",scope:"server"},{type:"string",name:"Base URL",key:"baseURL",description:"The base URL for the OpenAI API",required:!0,placeholder:"OpenAI Base URL",default:"https://api.openai.com/v1",env:"OPENAI_BASE_URL",scope:"server"}]},{key:"anthropic",name:"Anthropic",fields:[{type:"password",name:"API Key",key:"apiKey",description:"Your Anthropic API key",required:!0,placeholder:"Anthropic API Key",env:"ANTHROPIC_API_KEY",scope:"server"}]},{key:"gemini",name:"Google Gemini",fields:[{type:"password",name:"API Key",key:"apiKey",description:"Your Google Gemini API key",required:!0,placeholder:"Google Gemini API Key",env:"GEMINI_API_KEY",scope:"server"}]},{key:"groq",name:"Groq",fields:[{type:"password",name:"API Key",key:"apiKey",description:"Your Groq API key. Free tier includes fast inference on Llama and Mixtral models - get yours at console.groq.com",required:!0,placeholder:"gsk_...",env:"GROQ_API_KEY",scope:"server"}]},{key:"deepseek",name:"DeepSeek",fields:[{type:"password",name:"API Key",key:"apiKey",description:"Your DeepSeek API key",required:!0,placeholder:"DeepSeek API Key",env:"DEEPSEEK_API_KEY",scope:"server"}]},{key:"nvidia",name:"NVIDIA",fields:[{type:"password",name:"API Key",key:"apiKey",description:"Your NVIDIA API key. Free tier includes access to Nemotron, Llama, and other models - get yours at build.nvidia.com",required:!0,placeholder:"nvapi-...",env:"NVIDIA_API_KEY",scope:"server"},{type:"string",name:"Base URL",key:"baseURL",description:"The base URL for NVIDIA's OpenAI-compatible API",required:!0,placeholder:"https://integrate.api.nvidia.com/v1",default:"https://integrate.api.nvidia.com/v1",env:"NVIDIA_BASE_URL",scope:"server"}]},{key:"openrouter",name:"OpenRouter",fields:[{type:"password",name:"API Key",key:"apiKey",description:"Your OpenRouter API key. Get one free at openrouter.ai - includes free access to Llama 3.3 70B, Nemotron, and other models.",required:!0,placeholder:"sk-or-v1-...",env:"OPENROUTER_API_KEY",scope:"server"},{type:"string",name:"Base URL",key:"baseURL",description:"The base URL for OpenRouter's OpenAI-compatible API",required:!0,placeholder:"https://openrouter.ai/api/v1",default:"https://openrouter.ai/api/v1",env:"OPENROUTER_BASE_URL",scope:"server"}]}];this.uiConfigSections.modelProviders=e;const t=[];e.forEach(e=>{const n={},a=[];e.fields.forEach(e=>{n[e.key]=X(e.env)||e.default||"",e.required&&a.push(e.key)});let r=!0;if(a.forEach(e=>{n[e]||(r=!1)}),r){const a=ne(n);this.currentConfig.modelProviders.find(e=>e.hash===a)||t.push({id:a,name:`${e.name}`,type:e.key,chatModels:te(e.key),config:n,hash:a,isEnvBased:!0})}}),t.length>0&&this.currentConfig.modelProviders.push(...t),this.uiConfigSections.search.forEach(e=>{e.env&&!this.currentConfig.search[e.key]&&(this.currentConfig.search[e.key]=X(e.env)??e.default??"")})}getConfig(e,t){this.ensureInitialized();const n=e.split(".");let a=this.currentConfig;for(let r=0;r<n.length;r++){const e=n[r];if(null==a)return t;a=a[e]}return void 0===a?t:a}updateConfig(e,t){const n=e.split(".");if(0===n.length)return;let a=this.currentConfig;for(let r=0;r<n.length-1;r++){const e=n[r];null!==a[e]&&"object"==typeof a[e]||(a[e]={}),a=a[e]}a[n[n.length-1]]=t}addModelProvider(e,t,n){this.ensureInitialized();const a=ne(n),r={id:a,name:t,type:e,config:n,chatModels:[],hash:a};return this.currentConfig.modelProviders.push(r),r}removeModelProvider(e){this.currentConfig.modelProviders=this.currentConfig.modelProviders.filter(t=>t.id!==e)}async updateModelProvider(e,t,n){const a=this.currentConfig.modelProviders.find(t=>t.id===e);if(!a)throw new Error("Provider not found");return a.name=t,a.config=n,a}addProviderModel(e,t,n){const a=this.currentConfig.modelProviders.find(t=>t.id===e);if(!a)throw new Error("Invalid provider id");return delete n.type,a.chatModels.push(n),n}removeProviderModel(e,t,n){const a=this.currentConfig.modelProviders.find(t=>t.id===e);if(!a)throw new Error("Invalid provider id");a.chatModels=a.chatModels.filter(e=>e.key!==n)}isSetupComplete(){return this.currentConfig.setupComplete}markSetupComplete(){this.currentConfig.setupComplete||(this.currentConfig.setupComplete=!0)}getUIConfigSections(){return this.ensureInitialized(),this.uiConfigSections}getCurrentConfig(){return this.ensureInitialized(),JSON.parse(JSON.stringify(this.currentConfig))}},re={openai:"openai",anthropic:"anthropic",gemini:"google",groq:"groq",deepseek:"deepseek",nvidia:"nvidia",openrouter:"openrouter"},oe=e=>{const t=re[e]??e,n=J.find(e=>e.provider.toLowerCase()===t.toLowerCase());return n?.models?n.models.map(e=>({name:e.name,key:e.id})):[]},ie=e=>{const t=/* @__PURE__ */new Map;for(const n of oe(e.type))t.set(n.key,n);for(const n of e.chatModels||[])t.set(n.key,{key:n.key,name:n.name});return[...t.values()]},se=class{get activeProviders(){return ae.getCurrentConfig().modelProviders}async getActiveProviders(e=!1){const t=this.activeProviders,n=e?J.map(e=>({...e,models:e.models.filter(t=>Z[e.provider.toLowerCase()]?.includes(t.id)||!1)})).filter(e=>e.models.length>0):J;return t.map(t=>({id:t.id,name:t.name,type:t.type,chatModels:e?this.getGuestChatModels(t,n):ie(t)})).filter(e=>e.chatModels.length>0)}getGuestChatModels(e,t){const n=re[e.type.toLowerCase()],a=t.find(t=>t.provider.toLowerCase()===(n?.toLowerCase()||e.type.toLowerCase()));return a?.models?a.models.map(e=>({name:e.name,key:e.id})):[]}findProvider(e){const t=this.activeProviders;let n=t.find(t=>t.id===e);return!n&&t.length>0&&(n=t.find(e=>e.name.toLowerCase().includes("openrouter"))??t.find(e=>e.name.toLowerCase().includes("groq"))??t.find(e=>e.name.toLowerCase().includes("nvidia"))??t[0]),n}isProviderEnvBased(e){return!0===this.findProvider(e)?.isEnvBased}async loadChatModel(e,t){const n=this.findProvider(e);if(!n)throw new Error("No model providers configured. Please add a provider in settings.");const a=n.type.toLowerCase(),r=n.config||{},o=r.apiKey||"",i=ie(n),s=t||i[0]?.key||"";if(n.name,!s)throw new Error(`No chat models available for provider "${n.name}"`);if(t&&!i.some(e=>e.key===t))throw console.warn(`[ModelRegistry] Requested model "${t}" not found in provider "${n.name}". Available models: ${i.map(e=>e.key).join(", ")}`),new Error(`Model "${t}" is not available for provider "${n.name}". Please select a different model in Settings.`);if(!o)throw new Error(`No API key configured for provider "${n.name}". Please add your API key in Settings → Model Providers.`);const c={openai:"https://api.openai.com/v1",togetherai:"https://api.together.xyz/v1",perplexity:"https://api.perplexity.ai",nvidia:"https://integrate.api.nvidia.com/v1",openrouter:"https://openrouter.ai/api/v1",deepseek:"https://api.deepseek.com",xai:"https://api.x.ai/v1"};if(a in c){const{createOpenAI:e}=await import("@ai-sdk/openai");return e({apiKey:o,baseURL:r.baseURL||c[a]}).chat(s)}switch(a){case"cloudflare":{const{createOpenAI:e}=await import("@ai-sdk/openai"),[t,n]=o.split(":");return e({apiKey:t,baseURL:`https://api.cloudflare.com/client/v4/accounts/${n}/ai/v1`}).chat(s)}case"groq":{const{createGroq:e}=await import("@ai-sdk/groq");return e({apiKey:o})(s)}case"anthropic":{const{createAnthropic:e}=await import("@ai-sdk/anthropic");return e({apiKey:o})(s)}case"gemini":case"google":{const{createGoogleGenerativeAI:e}=await import("@ai-sdk/google");return e({apiKey:o})(s)}default:throw new Error(`Unsupported provider type: ${a}`)}}async addProvider(e,t,n){let a,r;return"object"!=typeof t||null===t||n?(a=String(t),r=n||{}):(r=t,a=[{key:"openai",name:"OpenAI",fields:[{type:"password",name:"API Key",key:"apiKey",description:"Your OpenAI API key",required:!0,placeholder:"OpenAI API Key",env:"OPENAI_API_KEY",scope:"server"},{type:"string",name:"Base URL",key:"baseURL",description:"The base URL for the OpenAI API",required:!0,placeholder:"OpenAI Base URL",default:"https://api.openai.com/v1",env:"OPENAI_BASE_URL",scope:"server"}]},{key:"anthropic",name:"Anthropic",fields:[{type:"password",name:"API Key",key:"apiKey",description:"Your Anthropic API key",required:!0,placeholder:"Anthropic API Key",env:"ANTHROPIC_API_KEY",scope:"server"}]},{key:"gemini",name:"Google Gemini",fields:[{type:"password",name:"API Key",key:"apiKey",description:"Your Google Gemini API key",required:!0,placeholder:"Google Gemini API Key",env:"GEMINI_API_KEY",scope:"server"}]},{key:"groq",name:"Groq",fields:[{type:"password",name:"API Key",key:"apiKey",description:"Your Groq API key. Free tier includes fast inference on Llama and Mixtral models - get yours at console.groq.com",required:!0,placeholder:"gsk_...",env:"GROQ_API_KEY",scope:"server"}]},{key:"deepseek",name:"DeepSeek",fields:[{type:"password",name:"API Key",key:"apiKey",description:"Your DeepSeek API key",required:!0,placeholder:"DeepSeek API Key",env:"DEEPSEEK_API_KEY",scope:"server"}]},{key:"nvidia",name:"NVIDIA",fields:[{type:"password",name:"API Key",key:"apiKey",description:"Your NVIDIA API key. Free tier includes access to Nemotron, Llama, and other models - get yours at build.nvidia.com",required:!0,placeholder:"nvapi-...",env:"NVIDIA_API_KEY",scope:"server"},{type:"string",name:"Base URL",key:"baseURL",description:"The base URL for NVIDIA's OpenAI-compatible API",required:!0,placeholder:"https://integrate.api.nvidia.com/v1",default:"https://integrate.api.nvidia.com/v1",env:"NVIDIA_BASE_URL",scope:"server"}]},{key:"openrouter",name:"OpenRouter",fields:[{type:"password",name:"API Key",key:"apiKey",description:"Your OpenRouter API key. Get one free at openrouter.ai - includes free access to Llama 3.3 70B, Nemotron, and other models.",required:!0,placeholder:"sk-or-v1-...",env:"OPENROUTER_API_KEY",scope:"server"},{type:"string",name:"Base URL",key:"baseURL",description:"The base URL for OpenRouter's OpenAI-compatible API",required:!0,placeholder:"https://openrouter.ai/api/v1",default:"https://openrouter.ai/api/v1",env:"OPENROUTER_BASE_URL",scope:"server"}]}].find(t=>t.key===e)?.name||e.toUpperCase()),{...ae.addModelProvider(e,a,r),chatModels:oe(e)}}async removeProvider(e){ae.removeModelProvider(e)}async updateProvider(e,t,n){let a,r;"object"!=typeof t||null===t||n?(a=String(t),r=n||{}):(r=t,a=this.activeProviders.find(t=>t.id===e)?.name||e);const o=await ae.updateModelProvider(e,a,r);return{...o,chatModels:ie(o)}}async addProviderModel(e,t,n){return ae.addProviderModel(e,t,n)}async removeProviderModel(e,t,n){ae.removeProviderModel(e,t,n)}},ce={openrouter:{row:0,col:0},tongyi:{row:0,col:1},ollama:{row:0,col:2},huggingface:{row:0,col:3},localai:{row:0,col:4},openllm:{row:0,col:5},zhipu:{row:1,col:0},replicate:{row:1,col:1},azure:{row:1,col:2},anthropic:{row:1,col:3},groq:{row:1,col:4},sagemaker:{row:1,col:5},"01ai":{row:2,col:0},bedrock:{row:2,col:1},openai:{row:2,col:2},cohere:{row:2,col:3},together:{row:2,col:4},xorbits:{row:2,col:5},wenxin:{row:3,col:0},moonshot:{row:3,col:1},gemini:{row:3,col:2},mistral:{row:3,col:3},jina:{row:3,col:4},chatglm:{row:3,col:5}};async function me(e,t){if(!(t in ce))throw new Error(`Unknown provider: ${t}`);const{row:n,col:a}=ce[t],r=e.width/6,o=e.height/4,i=document.createElement("canvas");i.width=r,i.height=o;const s=i.getContext("2d");if(!s)throw new Error("Failed to get 2D context");return s.drawImage(e,a*r,n*o,r,o,0,0,r,o),i}async function le(e,t,n="image/png",a){const r=await me(e,t);return new Promise((e,t)=>{r.toBlob(n=>{n?e(n):t(/* @__PURE__ */new Error("Failed to create blob"))},n,a)})}async function de(e,t,n="image/png",a){return(await me(e,t)).toDataURL(n,a)}async function pe(e,t){const n=new Image;return n.src=e,await n.decode(),me(n,t)}function he(){return Object.keys(ce)}export{T as AGENT_TOOLS,x as DrizzleMemoryStorage,R as LineListOutputParser,C as LineOutputParser,b as MEMORY_CONFIG,L as MEMORY_TYPES,k as MastraD1MemoryStorage,S as MastraKVMemoryStorage,E as MastraMemoryManager,I as MemoryAgent,$ as MetaSearchAgent,se as ModelRegistry,w as SimpleMemory,N as buildFallbackDocs,ae as configManager,_ as createMastraMemory,A as createMemorySchema,F as createSearchHandlers,me as cropProvider,le as cropProviderAsBlob,de as cropProviderAsDataURL,B as formatChatHistoryAsString,Q as generateSuggestions,X as getEnv,W as getModelProvidersUIConfigSection,pe as getProviderImage,he as getProviderNames,G as groupAndSummarizeDocs,D as normalizeSourcesOutput,K as processDocs,q as registerUploadFileLoader,O as rerankDocs,Y as searchHandlers,j as splitTextIntoChunks};
|
|
2
2
|
//# sourceMappingURL=research-agent.es.js.map
|