research-agent-ui 0.1.84 → 0.1.85
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/api.cjs +15 -15
- package/dist/api.mjs +183 -179
- package/dist/index.cjs +1 -1
- package/dist/index.mjs +14 -14
- package/package.json +7 -6
package/dist/api.cjs
CHANGED
|
@@ -1,22 +1,22 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./rolldown-runtime-CMqjfN_6.cjs");let t=require("chat-agent-toolkit/models/registry");
|
|
2
|
-
`)}`:``,
|
|
3
|
-
Generate ${
|
|
4
|
-
Return ONLY the questions, one per line, without numbering or bullet points.`,
|
|
5
|
-
${
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./rolldown-runtime-CMqjfN_6.cjs");let t=require("ai"),n=require("chat-agent-toolkit/models/registry");n=e.t(n,1);let r=require("drizzle-orm"),i=require("chat-agent-toolkit/tools/search/titleGeneratorAgent");i=e.t(i,1);let a=require("search-web-api/search/public-searxng"),o=require("extract-webpage/suggest-next-words/autocomplete-search-engines"),s=require("fuse.js");s=e.t(s,1);let c=require("domain-rank/data/domain-rank-merged.json");c=e.t(c,1);let l=require("chat-agent-toolkit/tools/search/suggestionGeneratorAgent");l=e.t(l,1);let u=require("chat-agent-toolkit/config/model-tester"),d=require("chat-agent-toolkit/config/language-models-database");function f(e){return async e=>{try{let{article:r,chatHistory:i=[],maxQuestions:a=5,chatModel:o}=await e.json();if(!r)return Response.json({error:`Article is required`},{status:400});let s=new n.default,c;try{c=await s.loadChatModel(o?.providerId,o?.key)}catch(e){return Response.json({error:e instanceof Error?e.message:`Failed to load language model`},{status:500})}let l=i.length>0?`\n\nPrevious questions asked:\n${i.filter(e=>e.role===`user`).map(e=>`- ${e.content}`).join(`
|
|
2
|
+
`)}`:``,u=`You are a helpful AI that generates insightful follow-up questions about articles.
|
|
3
|
+
Generate ${a} thought-provoking questions that would help readers understand the article better.
|
|
4
|
+
Return ONLY the questions, one per line, without numbering or bullet points.`,d=`Article content:
|
|
5
|
+
${r.slice(0,15e3)}
|
|
6
6
|
|
|
7
|
-
${
|
|
7
|
+
${l}
|
|
8
8
|
|
|
9
|
-
Generate ${
|
|
10
|
-
`).map(e=>e.trim()).filter(e=>e.length>0).map(e=>e.replace(/^[\d\-\*\.\)]+\s*/,``).trim()).filter(e=>e.length>10).slice(0,
|
|
11
|
-
`)}`:``,
|
|
12
|
-
${
|
|
9
|
+
Generate ${a} follow-up questions that would help readers dive deeper into this article.`,{text:f}=await(0,t.generateText)({model:c,messages:[{role:`system`,content:u},{role:`user`,content:d}]}),p=f.split(`
|
|
10
|
+
`).map(e=>e.trim()).filter(e=>e.length>0).map(e=>e.replace(/^[\d\-\*\.\)]+\s*/,``).trim()).filter(e=>e.length>10).slice(0,a);return Response.json({extract:p,success:!0})}catch(e){return console.error(`Error generating follow-up questions:`,e),Response.json({error:`An error occurred while generating follow-up questions`,details:e instanceof Error?e.message:String(e)},{status:500})}}}function p(e){return async e=>{try{let{article:r,question:i,chatHistory:a=[],chatModel:o}=await e.json();if(!r||!i)return Response.json({error:`Article and question are required`},{status:400});let s=new n.default,c;try{c=await s.loadChatModel(o?.providerId,o?.key)}catch(e){return Response.json({error:e instanceof Error?e.message:`Failed to load language model`},{status:500})}let l=a.length>0?`\n\nPrevious conversation:\n${a.map(e=>`${e.role===`user`?`User`:`Assistant`}: ${e.content}`).join(`
|
|
11
|
+
`)}`:``,u=`Article content:
|
|
12
|
+
${r.slice(0,15e3)}
|
|
13
13
|
|
|
14
|
-
${
|
|
14
|
+
${l}
|
|
15
15
|
|
|
16
|
-
User question: ${
|
|
16
|
+
User question: ${i}
|
|
17
17
|
|
|
18
|
-
Please provide a helpful answer based on the article content above.`,
|
|
18
|
+
Please provide a helpful answer based on the article content above.`,{text:d}=await(0,t.generateText)({model:c,messages:[{role:`system`,content:`You are a helpful AI assistant that answers questions about articles.
|
|
19
19
|
Provide clear, concise, and accurate answers based on the article content provided.
|
|
20
|
-
If the answer is not in the article, say so.`},{role:`user`,content:l}]),d=``;for await(let e of u)d+=e.content;return Response.json({content:d,success:!0})}catch(e){return console.error(`Error in article Q&A:`,e),Response.json({error:`An error occurred while generating the answer`,details:e instanceof Error?e.message:String(e)},{status:500})}}}function p(e){let{chats:t,messages:r}=e.schema;return{GET:async i=>{try{let i=e.getDB(),a=await e.requireUserId(),o=await i.select({id:t.id,title:t.title,createdAt:t.createdAt,focusMode:t.focusMode,userId:t.userId,files:t.files,messageCount:(0,n.count)(r.id),lastMessageAt:(0,n.max)(r.createdAt)}).from(t).leftJoin(r,(0,n.and)((0,n.eq)(r.chatId,t.id),(0,n.eq)(r.role,`user`))).where((0,n.eq)(t.userId,a)).groupBy(t.id,t.title,t.createdAt,t.focusMode,t.userId,t.files).orderBy(n.sql`${t.createdAt} DESC`);return Response.json({chats:o},{status:200})}catch(e){return e instanceof Error&&e.message===`Unauthorized`?Response.json({message:`Authentication required`},{status:401}):(console.error(`Error in getting chats: `,e),Response.json({message:`An error has occurred.`},{status:500}))}},DELETE:async i=>{try{let i=e.getDB(),a=await e.requireUserId(),o=await i.query.chats.findMany({where:(0,n.eq)(t.userId,a),columns:{id:!0}});if(o.length>0){let e=o.map(e=>e.id);await i.delete(r).where((0,n.inArray)(r.chatId,e)),await i.delete(t).where((0,n.eq)(t.userId,a))}return Response.json({message:`All chats deleted`},{status:200})}catch(e){return e instanceof Error&&e.message===`Unauthorized`?Response.json({message:`Authentication required`},{status:401}):(console.error(`Error in deleting all chats: `,e),Response.json({message:`An error has occurred.`},{status:500}))}}}}function m(e){let{chats:t,messages:r}=e.schema;return{GET:async(i,{params:a})=>{try{let i=e.getDB(),{id:o}=await a,s;try{s=await e.requireUserId()}catch{s=void 0}let c=await i.query.chats.findFirst({where:(0,n.eq)(t.id,o)});if(!c)return Response.json({message:`Chat not found`},{status:404});if(!(c.userId===s||c.isPublic))return Response.json({message:`Unauthorized - this chat is private`},{status:403});let l=await i.query.messages.findMany({where:(0,n.eq)(r.chatId,o)});return Response.json({chat:c,messages:l},{status:200})}catch(e){return console.error(`Error in getting chat by id: `,e),Response.json({message:`An error has occurred.`},{status:500})}},DELETE:async(i,{params:a})=>{try{let i=e.getDB(),{id:o}=await a,s=await e.requireUserId();return await i.query.chats.findFirst({where:(0,n.and)((0,n.eq)(t.id,o),(0,n.eq)(t.userId,s))})?(await i.delete(t).where((0,n.eq)(t.id,o)).execute(),await i.delete(r).where((0,n.eq)(r.chatId,o)).execute(),Response.json({message:`Chat deleted successfully`},{status:200})):Response.json({message:`Chat not found`},{status:404})}catch(e){return e instanceof Error&&e.message===`Unauthorized`?Response.json({message:`Authentication required`},{status:401}):(console.error(`Error in deleting chat by id: `,e),Response.json({message:`An error has occurred.`},{status:500}))}}}}function h(e){let{chats:t,messages:r}=e.schema;return{GET:async i=>{try{let a=e.getDB(),o=await e.requireUserId(),{searchParams:s}=new URL(i.url),c=s.get(`q`);if(!c||c.trim().length===0)return Response.json({chats:[]},{status:200});let l=`%${c.trim()}%`,u=await a.select({id:t.id,title:t.title,createdAt:t.createdAt,focusMode:t.focusMode,userId:t.userId,files:t.files}).from(t).where((0,n.and)((0,n.eq)(t.userId,o),(0,n.like)(t.title,l))).orderBy(n.sql`${t.createdAt} DESC`),d=await a.selectDistinct({id:t.id,title:t.title,createdAt:t.createdAt,focusMode:t.focusMode,userId:t.userId,files:t.files}).from(r).innerJoin(t,(0,n.eq)(r.chatId,t.id)).where((0,n.and)((0,n.eq)(t.userId,o),(0,n.or)((0,n.like)(r.content,l)))).orderBy(n.sql`${t.createdAt} DESC`),f=[...u,...d],p=Array.from(new Map(f.map(e=>[e.id,e])).values()),m=p.map(e=>e.id),h=m.length?await a.select({chatId:r.chatId,count:n.sql`count(*)`}).from(r).where((0,n.and)(n.sql`${r.chatId} IN (${n.sql.join(m.map(e=>n.sql`${e}`),n.sql`, `)})`,(0,n.eq)(r.role,`user`))).groupBy(r.chatId):[],g=new Map(h.map(e=>[e.chatId,Number(e.count)])),_=p.map(e=>({...e,messageCount:g.get(e.id)||0}));return Response.json({chats:_},{status:200})}catch(e){return e instanceof Error&&e.message===`Unauthorized`?Response.json({message:`Authentication required`},{status:401}):(console.error(`Error searching chats:`,e),Response.json({message:`An error has occurred.`},{status:500}))}}}}function g(e){let{chats:t}=e.schema;return{POST:async r=>{try{let i=e.getDB(),{chatId:a}=await r.json();if(!a)return Response.json({success:!1,error:`Chat ID is required`},{status:400});let o=await e.requireUserId(),s=await i.query.chats.findFirst({where:(0,n.eq)(t.id,a)});if(!s)return Response.json({success:!1,error:`Chat not found`},{status:404});if(s.userId!==o)return Response.json({success:!1,error:`Unauthorized`},{status:403});await i.update(t).set({isPublic:1}).where((0,n.eq)(t.id,a)).execute();let c=`${new URL(r.url).origin}/c/${a}`;return Response.json({success:!0,data:{chatId:a,shareUrl:c}})}catch(e){return e instanceof Error&&e.message===`Unauthorized`?Response.json({success:!1,error:`Authentication required`},{status:401}):(console.error(`Error in making chat public: `,e),Response.json({success:!1,error:`An error has occurred.`},{status:500}))}}}}function _(e){let{chats:i}=e.schema;return{POST:async a=>{try{let o=await a.json(),s=o.chatHistory.filter(e=>e.role===`user`||e.role===`assistant`).map(e=>({role:e.role,content:String(e.content??``)}));if(s.length===0)return Response.json({message:`No conversation content`},{status:400});let c=await new t.default().loadChatModel(o.chatModel.providerId,o.chatModel.key),l=await(0,r.default)({chat_history:s},c);if(!l)return Response.json({message:`Failed to generate title`},{status:500});let u=e.getUserId?await e.getUserId():null;if(u&&o.chatId)try{let t=e.getDB(),r=await t.query.chats.findFirst({where:(0,n.eq)(i.id,o.chatId)});r&&r.userId===u&&await t.update(i).set({title:l}).where((0,n.eq)(i.id,o.chatId)).execute()}catch(e){console.error(`Failed to persist chat title:`,e)}return Response.json({title:l},{status:200})}catch(e){return console.error(`Error generating chat title:`,e),Response.json({message:`Failed to generate title`},{status:500})}}}}var v=[`assistant`,`user`,`source`,`suggestion`];function y(e){let t=[],n=e;for(let e=0;n!=null&&e<5;e++)t.push(n instanceof Error?n.message:String(n)),n=n instanceof Error?n.cause:void 0;return t.join(` <- caused by: `)}function b(e){return{POST:async t=>{try{let n=e.getDB(),r=await e.requireUserId(),{chatId:i,messageId:a,role:o,suggestions:s,content:c,sources:l}=await t.json();return!i||!a||!o?Response.json({message:`Missing required fields`},{status:400}):v.includes(o)?(await n.insert(e.messagesSchema).values({chatId:i,userId:r,messageId:a,role:o,content:c||``,suggestions:s||[],sources:l||[],createdAt:new Date().toISOString()}),Response.json({message:`Message saved successfully`},{status:200})):Response.json({message:`Invalid role: ${o}`},{status:400})}catch(e){return console.error(`Error saving message:`,y(e)),Response.json({message:`Failed to save message`},{status:500})}}}}function x(e){return{GET:async n=>{try{let r=new t.default,i=new URL(n.url).searchParams.get(`guest`),a=i===`true`;i===null&&(a=!await e.getSession());let o=(await r.getActiveProviders(a)).filter(e=>!e.chatModels.some(e=>e.key===`error`));return o.length===0?Response.json({providers:[],error:a?`No guest-safe AI providers available. Please sign in for more options.`:`No AI providers configured. Please add OPENROUTER_API_KEY to your environment variables or configure your own API keys in Settings.`},{status:200}):Response.json({providers:o,isGuest:a},{status:200})}catch(e){return console.error(`An error occurred while fetching providers`,e),Response.json({message:`An error has occurred.`},{status:500})}},POST:async e=>{try{let{type:n,config:r}=await e.json();if(!n||!r)return Response.json({message:`Missing required fields.`},{status:400});let i=await new t.default().addProvider(n,r);return Response.json({provider:i},{status:200})}catch(e){return console.error(`An error occurred while creating provider`,e),Response.json({message:`An error has occurred.`},{status:500})}}}}function S(){return{DELETE:async(e,{params:n})=>{try{let{id:e}=await n;return e?(await new t.default().removeProvider(e),Response.json({message:`Provider deleted successfully.`},{status:200})):Response.json({message:`Provider ID is required.`},{status:400})}catch(e){return console.error(`An error occurred while deleting provider`,e.message),Response.json({message:`An error has occurred.`},{status:500})}},PATCH:async(e,{params:n})=>{try{let{config:r}=await e.json(),{id:i}=await n;if(!i||!r)return Response.json({message:`Missing required fields.`},{status:400});let a=await new t.default().updateProvider(i,r);return Response.json({provider:a},{status:200})}catch(e){return console.error(`An error occurred while updating provider`,e.message),Response.json({message:`An error has occurred.`},{status:500})}}}}function C(){return{POST:async(e,{params:n})=>{try{let{id:r}=await n,i=await e.json();return!i.key||!i.name?Response.json({message:`Key and name must be provided`},{status:400}):(await new t.default().addProviderModel(r,i.type,i),Response.json({message:`Model added successfully`},{status:200}))}catch(e){return console.error(`An error occurred while adding provider model`,e),Response.json({message:`An error has occurred.`},{status:500})}},DELETE:async(e,{params:n})=>{try{let{id:r}=await n,i=await e.json();return i.key?(await new t.default().removeProviderModel(r,i.type,i.key),Response.json({message:`Model added successfully`},{status:200})):Response.json({message:`Key and name must be provided`},{status:400})}catch(e){return console.error(`An error occurred while deleting provider model`,e),Response.json({message:`An error has occurred.`},{status:500})}}}}function w(e){return{GET:async t=>{try{let t=e.getConfiguredMCPServers();return Response.json({servers:t},{status:200})}catch(e){return console.error(`An error occurred while fetching MCP servers`,e),Response.json({message:`An error has occurred.`},{status:500})}},POST:async t=>{try{let{type:n,name:r,config:i}=await t.json();if(!n||!r||!i)return Response.json({message:`Missing required fields.`},{status:400});let a=e.configManager.addMCPServer(n,r,i);return Response.json({server:a},{status:200})}catch(e){return console.error(`An error occurred while creating MCP server`,e),Response.json({message:`An error has occurred.`},{status:500})}}}}function T(e){return{DELETE:async(t,{params:n})=>{try{let{id:t}=await n;return t?(e.configManager.removeMCPServer(t),Response.json({message:`MCP server deleted successfully.`},{status:200})):Response.json({message:`MCP Server ID is required.`},{status:400})}catch(e){return console.error(`An error occurred while deleting MCP server`,e.message),Response.json({message:`An error has occurred.`},{status:500})}},PATCH:async(t,{params:n})=>{try{let{name:r,config:i}=await t.json(),{id:a}=await n;if(!a||!r||!i)return Response.json({message:`Missing required fields.`},{status:400});let o=await e.configManager.updateMCPServer(a,r,i);return Response.json({server:o},{status:200})}catch(e){return console.error(`An error occurred while updating MCP server`,e.message),Response.json({message:`An error has occurred.`},{status:500})}}}}function E(e){return{POST:async(t,{params:n})=>{try{let{enabled:r}=await t.json(),{id:i}=await n;if(!i||typeof r!=`boolean`)return Response.json({message:`Missing required fields.`},{status:400});let a=e.configManager.toggleMCPServer(i,r);return Response.json({server:a},{status:200})}catch(e){return console.error(`An error occurred while toggling MCP server`,e.message),Response.json({message:`An error has occurred.`},{status:500})}}}}var D={tech:{query:[`technology news`,`latest tech`,`AI`,`science and innovation`],links:[`techcrunch.com`,`wired.com`,`theverge.com`]},finance:{query:[`finance news`,`economy`,`stock market`,`investing`],links:[`bloomberg.com`,`cnbc.com`,`marketwatch.com`]},art:{query:[`art news`,`culture`,`modern art`,`cultural events`],links:[`artnews.com`,`hyperallergic.com`,`theartnewspaper.com`]},sports:{query:[`sports news`,`latest sports`,`cricket football tennis`],links:[`espn.com`,`bbc.com/sport`,`skysports.com`]},entertainment:{query:[`entertainment news`,`movies`,`TV shows`,`celebrities`],links:[`hollywoodreporter.com`,`variety.com`,`deadline.com`]}};function O(e={}){let t=e.searxngDomain??`https://search.qwksearch.com`;return{GET:async e=>{let n=new URL(e.url).searchParams,r=n.get(`q`),a=n.get(`cat`)||`general`,o=parseInt(n.get(`page`)||`1`,10),s=n.get(`lang`)||`en-US`,c=n.get(`safesearch`)===`true`,l=n.get(`recency`)||void 0,u=n.get(`publicInstances`)===`true`;if(!r)return Response.json({error:`Query parameter is required`},{status:400});let d=Date.now();try{let e=await(0,i.searchWeb)(r,{category:a,recency:l,safesearch:c,maxRetries:6,privateSearxng:!u&&t,proxy:``,lang:s,page:o});e&&(Array.isArray(e)?e.length>0:e.results&&e.results.length>0)||(e=await(0,i.searchWeb)(r,{category:a,recency:l,safesearch:c,maxRetries:6,privateSearxng:!1,proxy:``,lang:s,page:o}));let n=Date.now()-d;return e?Array.isArray(e)?Response.json({results:e,elapsedTime:n}):Response.json({...e,elapsedTime:n}):Response.json({results:[],suggestions:[],elapsedTime:n})}catch(e){return console.error(`Search error:`,e),Response.json({error:`Search failed`,results:[]},{status:500})}}}}function k(){return{GET:async e=>{try{let t=new URL(e.url).searchParams,n=t.get(`mode`)||`normal`,r=D[t.get(`topic`)||`tech`],a=[];if(n===`normal`){let e=new Set;a=(await Promise.all(r.links.flatMap(e=>r.query.map(async t=>(await(0,i.searchSearxng)(`site:${e} ${t}`,{engines:[`bing news`],pageno:1,language:`en`})).results)))).flat().filter(t=>{let n=t.url?.toLowerCase().trim();return e.has(n)?!1:(e.add(n),!0)}).sort(()=>Math.random()-.5)}else a=(await(0,i.searchSearxng)(`site:${r.links[Math.floor(Math.random()*r.links.length)]} ${r.query[Math.floor(Math.random()*r.query.length)]}`,{engines:[`bing news`],pageno:1,language:`en`})).results;return Response.json({blogs:a},{status:200})}catch(e){return console.error(`An error occurred in discover route: ${e}`),Response.json({message:`An error has occurred`},{status:500})}}}}var A=[`google`,`duckduckgo`,`wikipedia`],j=3,M=3,N=Object.entries(s.default).map(([e,t])=>({domain:e,name:typeof t?.[0]==`string`?t[0]:``,rank:typeof t?.[1]==`number`?t[1]:2**53-1})),P=null;function F(){return P||=new o.default(N,{keys:[{name:`name`,weight:.6},{name:`domain`,weight:.4}],threshold:.1,ignoreLocation:!0,includeScore:!0,minMatchCharLength:3}),P}function I(e){let t=e.split(/\s+/).filter(Boolean),n=t[t.length-1]||``;return n.length<3?[]:F().search(n,{limit:12}).sort((e,t)=>Math.round((e.score??1)*10)-Math.round((t.score??1)*10)||e.item.rank-t.item.rank).slice(0,M).map(({item:e})=>({domain:e.domain,name:e.name,favicon:`https://www.google.com/s2/favicons?domain=${encodeURIComponent(e.domain)}&sz=64`}))}async function L(e,t,n){let r=await(0,a.searchAutocompleteMulti)(e,t,n);if(r.length>0)return r;let i=t.split(/\s+/).filter(Boolean),o=Math.min(j,i.length-1);for(let r=o;r>=1;r--){let o=i.slice(-r).join(` `),s=i.slice(0,-r).join(` `),c=await(0,a.searchAutocompleteMulti)(e,o,n);if(c.length>0){let e=new Set;for(let n of c){let r=s?`${s} ${n}`:n;r.toLowerCase()!==t.toLowerCase()&&e.add(r)}if(e.size>0)return Array.from(e)}}return[]}function R(){return{GET:async e=>{let{searchParams:t}=new URL(e.url),n=t.get(`q`)?.trim(),r=t.get(`locale`)||`en-US`,i=t.get(`backends`),a=parseInt(t.get(`limit`)||`8`,10);if(!n)return Response.json({suggestions:[],domains:[]});let o=i?i.split(`,`).map(e=>e.trim()).filter(Boolean):A;try{let e=await L(o,n,r),t=I(n);return Response.json({suggestions:e.slice(0,a),domains:t})}catch(e){return console.error(`Autocomplete error:`,e),Response.json({suggestions:[],domains:[]},{status:500})}}}}function z(){return{POST:async e=>{let n=await e.json(),r=n.chatHistory.filter(e=>e.role===`user`||e.role===`assistant`).map(e=>({role:e.role,content:String(e.content??``)})),i=await new t.default().loadChatModel(n.chatModel.providerId,n.chatModel.key),a=(await(0,c.default)({chat_history:r,maxQuestions:n.maxQuestions},i)).flatMap(e=>(e.match(/\?/g)||[]).length>1?e.split(/\?/).map(e=>e.trim()).filter(e=>e.length>0).map(e=>e+`?`):[e]);return Response.json({suggestions:a},{status:200})}}}function B(e){return{POST:async t=>{let r;try{r=await t.json()}catch{return Response.json({error:`Invalid JSON input`},{status:500})}r.ip=t.headers?.get?.(`x-forwarded-for`)||t.headers?.get?.(`x-real-ip`)||`unknown`;let i=e.getDB(),a=await e.getUserId(),o=null;return a&&(o=await i.query.user.findFirst({where:(0,n.eq)(e.userSchema.id,a)})),o&&(r.apiKey=o.settings?.providerApiKeys?.find(e=>e.provider==r.provider)?.key),r.apiKey||=r.provider==`groq`&&e.getEnv(`GROQ_API_KEY`),r.apiKey?Response.json({error:`Language generation endpoint is deprecated. Please use /api/agent/chat instead.`},{status:501}):Response.json({error:`API key is required`},{status:500})}}}function V(e){return{POST:async t=>{try{let{text:n,prompt:r}=await t.json();if(!n||typeof n!=`string`)return Response.json({error:`Text is required and must be a string`},{status:400});let i=e.getEnv(`GROQ_API_KEY`);if(!i)return console.error(`GROQ_API_KEY is not configured`),Response.json({error:`AI service is not configured. Please contact the administrator.`},{status:500});let a=e.createGroq({apiKey:i})(`llama-3.3-70b-versatile`),o=r||`Rewrite the following text to improve clarity, grammar, and style while maintaining the original meaning and tone. Only return the rewritten text without any explanation or additional commentary:
|
|
20
|
+
If the answer is not in the article, say so.`},{role:`user`,content:u}]});return Response.json({content:d,success:!0})}catch(e){return console.error(`Error in article Q&A:`,e),Response.json({error:`An error occurred while generating the answer`,details:e instanceof Error?e.message:String(e)},{status:500})}}}function m(e){let{chats:t,messages:n}=e.schema;return{GET:async i=>{try{let i=e.getDB(),a=await e.requireUserId(),o=await i.select({id:t.id,title:t.title,createdAt:t.createdAt,focusMode:t.focusMode,userId:t.userId,files:t.files,messageCount:(0,r.count)(n.id),lastMessageAt:(0,r.max)(n.createdAt)}).from(t).leftJoin(n,(0,r.and)((0,r.eq)(n.chatId,t.id),(0,r.eq)(n.role,`user`))).where((0,r.eq)(t.userId,a)).groupBy(t.id,t.title,t.createdAt,t.focusMode,t.userId,t.files).orderBy(r.sql`${t.createdAt} DESC`);return Response.json({chats:o},{status:200})}catch(e){return e instanceof Error&&e.message===`Unauthorized`?Response.json({message:`Authentication required`},{status:401}):(console.error(`Error in getting chats: `,e),Response.json({message:`An error has occurred.`},{status:500}))}},DELETE:async i=>{try{let i=e.getDB(),a=await e.requireUserId(),o=await i.query.chats.findMany({where:(0,r.eq)(t.userId,a),columns:{id:!0}});if(o.length>0){let e=o.map(e=>e.id);await i.delete(n).where((0,r.inArray)(n.chatId,e)),await i.delete(t).where((0,r.eq)(t.userId,a))}return Response.json({message:`All chats deleted`},{status:200})}catch(e){return e instanceof Error&&e.message===`Unauthorized`?Response.json({message:`Authentication required`},{status:401}):(console.error(`Error in deleting all chats: `,e),Response.json({message:`An error has occurred.`},{status:500}))}}}}function h(e){let{chats:t,messages:n}=e.schema;return{GET:async(i,{params:a})=>{try{let i=e.getDB(),{id:o}=await a,s;try{s=await e.requireUserId()}catch{s=void 0}let c=await i.query.chats.findFirst({where:(0,r.eq)(t.id,o)});if(!c)return Response.json({message:`Chat not found`},{status:404});if(!(c.userId===s||c.isPublic))return Response.json({message:`Unauthorized - this chat is private`},{status:403});let l=await i.query.messages.findMany({where:(0,r.eq)(n.chatId,o)});return Response.json({chat:c,messages:l},{status:200})}catch(e){return console.error(`Error in getting chat by id: `,e),Response.json({message:`An error has occurred.`},{status:500})}},DELETE:async(i,{params:a})=>{try{let i=e.getDB(),{id:o}=await a,s=await e.requireUserId();return await i.query.chats.findFirst({where:(0,r.and)((0,r.eq)(t.id,o),(0,r.eq)(t.userId,s))})?(await i.delete(t).where((0,r.eq)(t.id,o)).execute(),await i.delete(n).where((0,r.eq)(n.chatId,o)).execute(),Response.json({message:`Chat deleted successfully`},{status:200})):Response.json({message:`Chat not found`},{status:404})}catch(e){return e instanceof Error&&e.message===`Unauthorized`?Response.json({message:`Authentication required`},{status:401}):(console.error(`Error in deleting chat by id: `,e),Response.json({message:`An error has occurred.`},{status:500}))}}}}function g(e){let{chats:t,messages:n}=e.schema;return{GET:async i=>{try{let a=e.getDB(),o=await e.requireUserId(),{searchParams:s}=new URL(i.url),c=s.get(`q`);if(!c||c.trim().length===0)return Response.json({chats:[]},{status:200});let l=`%${c.trim()}%`,u=await a.select({id:t.id,title:t.title,createdAt:t.createdAt,focusMode:t.focusMode,userId:t.userId,files:t.files}).from(t).where((0,r.and)((0,r.eq)(t.userId,o),(0,r.like)(t.title,l))).orderBy(r.sql`${t.createdAt} DESC`),d=await a.selectDistinct({id:t.id,title:t.title,createdAt:t.createdAt,focusMode:t.focusMode,userId:t.userId,files:t.files}).from(n).innerJoin(t,(0,r.eq)(n.chatId,t.id)).where((0,r.and)((0,r.eq)(t.userId,o),(0,r.or)((0,r.like)(n.content,l)))).orderBy(r.sql`${t.createdAt} DESC`),f=[...u,...d],p=Array.from(new Map(f.map(e=>[e.id,e])).values()),m=p.map(e=>e.id),h=m.length?await a.select({chatId:n.chatId,count:r.sql`count(*)`}).from(n).where((0,r.and)(r.sql`${n.chatId} IN (${r.sql.join(m.map(e=>r.sql`${e}`),r.sql`, `)})`,(0,r.eq)(n.role,`user`))).groupBy(n.chatId):[],g=new Map(h.map(e=>[e.chatId,Number(e.count)])),_=p.map(e=>({...e,messageCount:g.get(e.id)||0}));return Response.json({chats:_},{status:200})}catch(e){return e instanceof Error&&e.message===`Unauthorized`?Response.json({message:`Authentication required`},{status:401}):(console.error(`Error searching chats:`,e),Response.json({message:`An error has occurred.`},{status:500}))}}}}function _(e){let{chats:t}=e.schema;return{POST:async n=>{try{let i=e.getDB(),{chatId:a}=await n.json();if(!a)return Response.json({success:!1,error:`Chat ID is required`},{status:400});let o=await e.requireUserId(),s=await i.query.chats.findFirst({where:(0,r.eq)(t.id,a)});if(!s)return Response.json({success:!1,error:`Chat not found`},{status:404});if(s.userId!==o)return Response.json({success:!1,error:`Unauthorized`},{status:403});await i.update(t).set({isPublic:1}).where((0,r.eq)(t.id,a)).execute();let c=`${new URL(n.url).origin}/c/${a}`;return Response.json({success:!0,data:{chatId:a,shareUrl:c}})}catch(e){return e instanceof Error&&e.message===`Unauthorized`?Response.json({success:!1,error:`Authentication required`},{status:401}):(console.error(`Error in making chat public: `,e),Response.json({success:!1,error:`An error has occurred.`},{status:500}))}}}}function v(e){let{chats:t}=e.schema;return{POST:async a=>{try{let o=await a.json(),s=o.chatHistory.filter(e=>e.role===`user`||e.role===`assistant`).map(e=>({role:e.role,content:String(e.content??``)}));if(s.length===0)return Response.json({message:`No conversation content`},{status:400});let c=await new n.default().loadChatModel(o.chatModel.providerId,o.chatModel.key),l=await(0,i.default)({chat_history:s},c);if(!l)return Response.json({message:`Failed to generate title`},{status:500});let u=e.getUserId?await e.getUserId():null;if(u&&o.chatId)try{let n=e.getDB(),i=await n.query.chats.findFirst({where:(0,r.eq)(t.id,o.chatId)});i&&i.userId===u&&await n.update(t).set({title:l}).where((0,r.eq)(t.id,o.chatId)).execute()}catch(e){console.error(`Failed to persist chat title:`,e)}return Response.json({title:l},{status:200})}catch(e){return console.error(`Error generating chat title:`,e),Response.json({message:`Failed to generate title`},{status:500})}}}}var y=[`assistant`,`user`,`source`,`suggestion`];function b(e){let t=[],n=e;for(let e=0;n!=null&&e<5;e++)t.push(n instanceof Error?n.message:String(n)),n=n instanceof Error?n.cause:void 0;return t.join(` <- caused by: `)}function x(e){return{POST:async t=>{try{let n=e.getDB(),r=await e.requireUserId(),{chatId:i,messageId:a,role:o,suggestions:s,content:c,sources:l}=await t.json();return!i||!a||!o?Response.json({message:`Missing required fields`},{status:400}):y.includes(o)?(await n.insert(e.messagesSchema).values({chatId:i,userId:r,messageId:a,role:o,content:c||``,suggestions:s||[],sources:l||[],createdAt:new Date().toISOString()}),Response.json({message:`Message saved successfully`},{status:200})):Response.json({message:`Invalid role: ${o}`},{status:400})}catch(e){return console.error(`Error saving message:`,b(e)),Response.json({message:`Failed to save message`},{status:500})}}}}function S(e){return{GET:async t=>{try{let r=new n.default,i=new URL(t.url).searchParams.get(`guest`),a=i===`true`;i===null&&(a=!await e.getSession());let o=(await r.getActiveProviders(a)).filter(e=>!e.chatModels.some(e=>e.key===`error`));return o.length===0?Response.json({providers:[],error:a?`No guest-safe AI providers available. Please sign in for more options.`:`No AI providers configured. Please add OPENROUTER_API_KEY to your environment variables or configure your own API keys in Settings.`},{status:200}):Response.json({providers:o,isGuest:a},{status:200})}catch(e){return console.error(`An error occurred while fetching providers`,e),Response.json({message:`An error has occurred.`},{status:500})}},POST:async e=>{try{let{type:t,config:r}=await e.json();if(!t||!r)return Response.json({message:`Missing required fields.`},{status:400});let i=await new n.default().addProvider(t,r);return Response.json({provider:i},{status:200})}catch(e){return console.error(`An error occurred while creating provider`,e),Response.json({message:`An error has occurred.`},{status:500})}}}}function C(){return{DELETE:async(e,{params:t})=>{try{let{id:e}=await t;return e?(await new n.default().removeProvider(e),Response.json({message:`Provider deleted successfully.`},{status:200})):Response.json({message:`Provider ID is required.`},{status:400})}catch(e){return console.error(`An error occurred while deleting provider`,e.message),Response.json({message:`An error has occurred.`},{status:500})}},PATCH:async(e,{params:t})=>{try{let{config:r}=await e.json(),{id:i}=await t;if(!i||!r)return Response.json({message:`Missing required fields.`},{status:400});let a=await new n.default().updateProvider(i,r);return Response.json({provider:a},{status:200})}catch(e){return console.error(`An error occurred while updating provider`,e.message),Response.json({message:`An error has occurred.`},{status:500})}}}}function w(){return{POST:async(e,{params:t})=>{try{let{id:r}=await t,i=await e.json();return!i.key||!i.name?Response.json({message:`Key and name must be provided`},{status:400}):(await new n.default().addProviderModel(r,i.type,i),Response.json({message:`Model added successfully`},{status:200}))}catch(e){return console.error(`An error occurred while adding provider model`,e),Response.json({message:`An error has occurred.`},{status:500})}},DELETE:async(e,{params:t})=>{try{let{id:r}=await t,i=await e.json();return i.key?(await new n.default().removeProviderModel(r,i.type,i.key),Response.json({message:`Model added successfully`},{status:200})):Response.json({message:`Key and name must be provided`},{status:400})}catch(e){return console.error(`An error occurred while deleting provider model`,e),Response.json({message:`An error has occurred.`},{status:500})}}}}function T(e){return{GET:async t=>{try{let t=e.getConfiguredMCPServers();return Response.json({servers:t},{status:200})}catch(e){return console.error(`An error occurred while fetching MCP servers`,e),Response.json({message:`An error has occurred.`},{status:500})}},POST:async t=>{try{let{type:n,name:r,config:i}=await t.json();if(!n||!r||!i)return Response.json({message:`Missing required fields.`},{status:400});let a=e.configManager.addMCPServer(n,r,i);return Response.json({server:a},{status:200})}catch(e){return console.error(`An error occurred while creating MCP server`,e),Response.json({message:`An error has occurred.`},{status:500})}}}}function E(e){return{DELETE:async(t,{params:n})=>{try{let{id:t}=await n;return t?(e.configManager.removeMCPServer(t),Response.json({message:`MCP server deleted successfully.`},{status:200})):Response.json({message:`MCP Server ID is required.`},{status:400})}catch(e){return console.error(`An error occurred while deleting MCP server`,e.message),Response.json({message:`An error has occurred.`},{status:500})}},PATCH:async(t,{params:n})=>{try{let{name:r,config:i}=await t.json(),{id:a}=await n;if(!a||!r||!i)return Response.json({message:`Missing required fields.`},{status:400});let o=await e.configManager.updateMCPServer(a,r,i);return Response.json({server:o},{status:200})}catch(e){return console.error(`An error occurred while updating MCP server`,e.message),Response.json({message:`An error has occurred.`},{status:500})}}}}function D(e){return{POST:async(t,{params:n})=>{try{let{enabled:r}=await t.json(),{id:i}=await n;if(!i||typeof r!=`boolean`)return Response.json({message:`Missing required fields.`},{status:400});let a=e.configManager.toggleMCPServer(i,r);return Response.json({server:a},{status:200})}catch(e){return console.error(`An error occurred while toggling MCP server`,e.message),Response.json({message:`An error has occurred.`},{status:500})}}}}var O={tech:{query:[`technology news`,`latest tech`,`AI`,`science and innovation`],links:[`techcrunch.com`,`wired.com`,`theverge.com`]},finance:{query:[`finance news`,`economy`,`stock market`,`investing`],links:[`bloomberg.com`,`cnbc.com`,`marketwatch.com`]},art:{query:[`art news`,`culture`,`modern art`,`cultural events`],links:[`artnews.com`,`hyperallergic.com`,`theartnewspaper.com`]},sports:{query:[`sports news`,`latest sports`,`cricket football tennis`],links:[`espn.com`,`bbc.com/sport`,`skysports.com`]},entertainment:{query:[`entertainment news`,`movies`,`TV shows`,`celebrities`],links:[`hollywoodreporter.com`,`variety.com`,`deadline.com`]}};function k(e={}){let t=e.searxngDomain??`https://search.qwksearch.com`;return{GET:async e=>{let n=new URL(e.url).searchParams,r=n.get(`q`),i=n.get(`cat`)||`general`,o=parseInt(n.get(`page`)||`1`,10),s=n.get(`lang`)||`en-US`,c=n.get(`safesearch`)===`true`,l=n.get(`recency`)||void 0,u=n.get(`publicInstances`)===`true`;if(!r)return Response.json({error:`Query parameter is required`},{status:400});let d=Date.now();try{let e=await(0,a.searchWeb)(r,{category:i,recency:l,safesearch:c,maxRetries:6,privateSearxng:!u&&t,proxy:``,lang:s,page:o});e&&(Array.isArray(e)?e.length>0:e.results&&e.results.length>0)||(e=await(0,a.searchWeb)(r,{category:i,recency:l,safesearch:c,maxRetries:6,privateSearxng:!1,proxy:``,lang:s,page:o}));let n=Date.now()-d;return e?Array.isArray(e)?Response.json({results:e,elapsedTime:n}):Response.json({...e,elapsedTime:n}):Response.json({results:[],suggestions:[],elapsedTime:n})}catch(e){return console.error(`Search error:`,e),Response.json({error:`Search failed`,results:[]},{status:500})}}}}function A(){return{GET:async e=>{try{let t=new URL(e.url).searchParams,n=t.get(`mode`)||`normal`,r=O[t.get(`topic`)||`tech`],i=[];if(n===`normal`){let e=new Set;i=(await Promise.all(r.links.flatMap(e=>r.query.map(async t=>(await(0,a.searchSearxng)(`site:${e} ${t}`,{engines:[`bing news`],pageno:1,language:`en`})).results)))).flat().filter(t=>{let n=t.url?.toLowerCase().trim();return e.has(n)?!1:(e.add(n),!0)}).sort(()=>Math.random()-.5)}else i=(await(0,a.searchSearxng)(`site:${r.links[Math.floor(Math.random()*r.links.length)]} ${r.query[Math.floor(Math.random()*r.query.length)]}`,{engines:[`bing news`],pageno:1,language:`en`})).results;return Response.json({blogs:i},{status:200})}catch(e){return console.error(`An error occurred in discover route: ${e}`),Response.json({message:`An error has occurred`},{status:500})}}}}var j=[`google`,`duckduckgo`,`wikipedia`],M=3,N=3,P=Object.entries(c.default).map(([e,t])=>({domain:e,name:typeof t?.[0]==`string`?t[0]:``,rank:typeof t?.[1]==`number`?t[1]:2**53-1})),F=null;function I(){return F||=new s.default(P,{keys:[{name:`name`,weight:.6},{name:`domain`,weight:.4}],threshold:.1,ignoreLocation:!0,includeScore:!0,minMatchCharLength:3}),F}function L(e){let t=e.split(/\s+/).filter(Boolean),n=t[t.length-1]||``;return n.length<3?[]:I().search(n,{limit:12}).sort((e,t)=>Math.round((e.score??1)*10)-Math.round((t.score??1)*10)||e.item.rank-t.item.rank).slice(0,N).map(({item:e})=>({domain:e.domain,name:e.name,favicon:`https://www.google.com/s2/favicons?domain=${encodeURIComponent(e.domain)}&sz=64`}))}async function R(e,t,n){let r=await(0,o.searchAutocompleteMulti)(e,t,n);if(r.length>0)return r;let i=t.split(/\s+/).filter(Boolean),a=Math.min(M,i.length-1);for(let r=a;r>=1;r--){let a=i.slice(-r).join(` `),s=i.slice(0,-r).join(` `),c=await(0,o.searchAutocompleteMulti)(e,a,n);if(c.length>0){let e=new Set;for(let n of c){let r=s?`${s} ${n}`:n;r.toLowerCase()!==t.toLowerCase()&&e.add(r)}if(e.size>0)return Array.from(e)}}return[]}function z(){return{GET:async e=>{let{searchParams:t}=new URL(e.url),n=t.get(`q`)?.trim(),r=t.get(`locale`)||`en-US`,i=t.get(`backends`),a=parseInt(t.get(`limit`)||`8`,10);if(!n)return Response.json({suggestions:[],domains:[]});let o=i?i.split(`,`).map(e=>e.trim()).filter(Boolean):j;try{let e=await R(o,n,r),t=L(n);return Response.json({suggestions:e.slice(0,a),domains:t})}catch(e){return console.error(`Autocomplete error:`,e),Response.json({suggestions:[],domains:[]},{status:500})}}}}function B(){return{POST:async e=>{let t=await e.json(),r=t.chatHistory.filter(e=>e.role===`user`||e.role===`assistant`).map(e=>({role:e.role,content:String(e.content??``)})),i=await new n.default().loadChatModel(t.chatModel.providerId,t.chatModel.key),a=(await(0,l.default)({chat_history:r,maxQuestions:t.maxQuestions},i)).flatMap(e=>(e.match(/\?/g)||[]).length>1?e.split(/\?/).map(e=>e.trim()).filter(e=>e.length>0).map(e=>e+`?`):[e]);return Response.json({suggestions:a},{status:200})}}}function V(e){return{POST:async t=>{let n;try{n=await t.json()}catch{return Response.json({error:`Invalid JSON input`},{status:500})}n.ip=t.headers?.get?.(`x-forwarded-for`)||t.headers?.get?.(`x-real-ip`)||`unknown`;let i=e.getDB(),a=await e.getUserId(),o=null;return a&&(o=await i.query.user.findFirst({where:(0,r.eq)(e.userSchema.id,a)})),o&&(n.apiKey=o.settings?.providerApiKeys?.find(e=>e.provider==n.provider)?.key),n.apiKey||=n.provider==`groq`&&e.getEnv(`GROQ_API_KEY`),n.apiKey?Response.json({error:`Language generation endpoint is deprecated. Please use /api/agent/chat instead.`},{status:501}):Response.json({error:`API key is required`},{status:500})}}}function H(e){return{POST:async t=>{try{let{text:n,prompt:r}=await t.json();if(!n||typeof n!=`string`)return Response.json({error:`Text is required and must be a string`},{status:400});let i=e.getEnv(`GROQ_API_KEY`);if(!i)return console.error(`GROQ_API_KEY is not configured`),Response.json({error:`AI service is not configured. Please contact the administrator.`},{status:500});let a=e.createGroq({apiKey:i})(`llama-3.3-70b-versatile`),o=r||`Rewrite the following text to improve clarity, grammar, and style while maintaining the original meaning and tone. Only return the rewritten text without any explanation or additional commentary:
|
|
21
21
|
|
|
22
|
-
${n}`,s=(await e.generateText({model:a,prompt:o,temperature:.7})).text.trim();return Response.json({rewrittenText:s})}catch(e){return console.error(`AI rewrite error:`,e),Response.json({error:`Failed to process AI request. Please try again.`},{status:500})}}}}function
|
|
22
|
+
${n}`,s=(await e.generateText({model:a,prompt:o,temperature:.7})).text.trim();return Response.json({rewrittenText:s})}catch(e){return console.error(`AI rewrite error:`,e),Response.json({error:`Failed to process AI request. Please try again.`},{status:500})}}}}function U(e){return{POST:async t=>{let n,r,i;try{let e=await t.json();n=e.text,r=e.voice||e.speaker||`af_heart`,i=e.provider||`kokoro`}catch{return Response.json({error:`Invalid request body`},{status:400})}if(!n||typeof n!=`string`||n.trim().length===0)return Response.json({error:`text is required`},{status:400});let a=await e.getUserId()??t.headers?.get?.(`x-forwarded-for`)?.split(`,`)[0]?.trim()??t.headers?.get?.(`x-real-ip`)??`unknown`,{allowed:o}=e.checkTTSRateLimit(a);if(!o)return Response.json({error:`Daily TTS limit reached (10/day)`,rateLimited:!0},{status:429});try{let t=await e.generateSpeech({text:n.slice(0,5e3),provider:i,voice:r});return new Response(t.audio,{headers:{"Content-Type":t.contentType,"Cache-Control":`public, max-age=86400`,"Content-Disposition":`inline; filename="speech.${t.contentType.includes(`wav`)?`wav`:`mp3`}"`}})}catch(e){console.error(`[TTS] Error:`,e);let t=e instanceof Error?e.message:`TTS generation failed`;return t.includes(`Cloudflare AI binding`)?Response.json({error:`Deepgram provider requires Cloudflare AI binding. Use 'kokoro' provider instead.`},{status:503}):Response.json({error:t},{status:500})}}}}function W(e){return e===`small`||e===`fast`?`@cf/openai/whisper-tiny-en`:e===`medium`||e===`turbo`?`@cf/openai/whisper-large-v3-turbo`:e===`large`?`@cf/openai/whisper-large-v3`:`@cf/openai/whisper-large-v3-turbo`}function G(e){return{POST:async t=>{try{let n=await t.formData(),r=n.get(`file`);if(!r||!(r instanceof File))return Response.json({error:`file is required`},{status:400});let i=W(n.get(`model`)),a;try{a=e.getCloudflareContext().env?.AI}catch{}if(!a)return Response.json({error:`Cloudflare AI binding not available`},{status:503});let o=await r.arrayBuffer(),{text:s}=await a.run(i,{audio:[...new Uint8Array(o)]});return Response.json({text:s,model:i})}catch(e){return console.error(`Transcript error:`,e),Response.json({error:`Failed to transcribe audio`},{status:500})}}}}function K(){return{POST:async e=>{try{let{providerType:t,apiKey:n,onlyFree:r=!0}=await e.json();if(!t)return Response.json({error:`Provider type is required`},{status:400});if(!n)return Response.json({error:`API key is required`},{status:400});let i=d.LANGUAGE_MODELS.find(e=>e.provider.toLowerCase()===t.toLowerCase());if(!i)return Response.json({error:`Provider ${t} not found`},{status:404});let a=await(0,u.testProviderModels)(t,n,i.models,{onlyFree:r,concurrency:3,timeout:15e3});return Response.json(a)}catch(e){return console.error(`[test-models] Error:`,e),Response.json({error:e.message||`Failed to test models`},{status:500})}}}}var q=1440*60*1e3,J=null;function Y(e){return{GET:async t=>{try{let t=Date.now();if(J&&t-J.timestamp<q)return Response.json({...J.result,cached:!0,cacheAge:t-J.timestamp});let n=await e.validateOpenRouterModels();return J={result:n,timestamp:t},Response.json({...n,cached:!1})}catch(e){return console.error(`[validate-openrouter] GET error:`,e),Response.json({error:e.message||`Validation failed`},{status:500})}},POST:async t=>{try{let{concurrency:n=3,timeout:r=15e3}=await t.json().catch(()=>({})),i=await e.validateOpenRouterModels(n,r);return J={result:i,timestamp:Date.now()},Response.json({...i,cached:!1})}catch(e){return console.error(`[validate-openrouter] POST error:`,e),Response.json({error:e.message||`Validation failed`},{status:500})}}}}exports.createAgentsHandler=V,exports.createArticleFollowupsHandler=f,exports.createArticleQAHandler=p,exports.createAutocompleteHandler=z,exports.createChatByIdHandler=h,exports.createChatTitleHandler=v,exports.createChatsHandler=m,exports.createChatsSearchHandler=g,exports.createChatsShareHandler=_,exports.createDiscoverHandler=A,exports.createMCPServerByIdHandler=E,exports.createMCPServerToggleHandler=D,exports.createMCPServersHandler=T,exports.createMessagesHandler=x,exports.createProviderByIdHandler=C,exports.createProviderModelsHandler=w,exports.createProvidersHandler=S,exports.createRewriteHandler=H,exports.createSearchHandler=k,exports.createSuggestionsHandler=B,exports.createTestModelsHandler=K,exports.createTranscriptHandler=G,exports.createValidateOpenRouterHandler=Y,exports.createVoiceHandler=U,exports.describeError=b;
|
package/dist/api.mjs
CHANGED
|
@@ -1,41 +1,43 @@
|
|
|
1
|
-
import e from "
|
|
2
|
-
import
|
|
3
|
-
import l from "
|
|
4
|
-
import
|
|
5
|
-
import {
|
|
6
|
-
import p from "
|
|
7
|
-
import m from "
|
|
8
|
-
import h from "
|
|
9
|
-
import
|
|
10
|
-
import {
|
|
1
|
+
import { generateText as e } from "ai";
|
|
2
|
+
import t from "chat-agent-toolkit/models/registry";
|
|
3
|
+
import { and as n, count as r, eq as i, inArray as a, like as o, max as s, or as c, sql as l } from "drizzle-orm";
|
|
4
|
+
import u from "chat-agent-toolkit/tools/search/titleGeneratorAgent";
|
|
5
|
+
import { searchSearxng as d, searchWeb as f } from "search-web-api/search/public-searxng";
|
|
6
|
+
import { searchAutocompleteMulti as p } from "extract-webpage/suggest-next-words/autocomplete-search-engines";
|
|
7
|
+
import m from "fuse.js";
|
|
8
|
+
import h from "domain-rank/data/domain-rank-merged.json";
|
|
9
|
+
import g from "chat-agent-toolkit/tools/search/suggestionGeneratorAgent";
|
|
10
|
+
import { testProviderModels as _ } from "chat-agent-toolkit/config/model-tester";
|
|
11
|
+
import { LANGUAGE_MODELS as v } from "chat-agent-toolkit/config/language-models-database";
|
|
11
12
|
//#region src/api/handlers/article-followups.ts
|
|
12
|
-
function
|
|
13
|
-
return async (
|
|
13
|
+
function y(n) {
|
|
14
|
+
return async (n) => {
|
|
14
15
|
try {
|
|
15
|
-
let { article:
|
|
16
|
-
if (!
|
|
17
|
-
let
|
|
16
|
+
let { article: r, chatHistory: i = [], maxQuestions: a = 5, chatModel: o } = await n.json();
|
|
17
|
+
if (!r) return Response.json({ error: "Article is required" }, { status: 400 });
|
|
18
|
+
let s = new t(), c;
|
|
18
19
|
try {
|
|
19
|
-
|
|
20
|
+
c = await s.loadChatModel(o?.providerId, o?.key);
|
|
20
21
|
} catch (e) {
|
|
21
22
|
return Response.json({ error: e instanceof Error ? e.message : "Failed to load language model" }, { status: 500 });
|
|
22
23
|
}
|
|
23
|
-
let
|
|
24
|
-
Generate ${
|
|
25
|
-
Return ONLY the questions, one per line, without numbering or bullet points.`,
|
|
26
|
-
${
|
|
24
|
+
let l = i.length > 0 ? `\n\nPrevious questions asked:\n${i.filter((e) => e.role === "user").map((e) => `- ${e.content}`).join("\n")}` : "", u = `You are a helpful AI that generates insightful follow-up questions about articles.
|
|
25
|
+
Generate ${a} thought-provoking questions that would help readers understand the article better.
|
|
26
|
+
Return ONLY the questions, one per line, without numbering or bullet points.`, d = `Article content:
|
|
27
|
+
${r.slice(0, 15e3)}
|
|
27
28
|
|
|
28
|
-
${
|
|
29
|
+
${l}
|
|
29
30
|
|
|
30
|
-
Generate ${
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
31
|
+
Generate ${a} follow-up questions that would help readers dive deeper into this article.`, { text: f } = await e({
|
|
32
|
+
model: c,
|
|
33
|
+
messages: [{
|
|
34
|
+
role: "system",
|
|
35
|
+
content: u
|
|
36
|
+
}, {
|
|
37
|
+
role: "user",
|
|
38
|
+
content: d
|
|
39
|
+
}]
|
|
40
|
+
}), p = f.split("\n").map((e) => e.trim()).filter((e) => e.length > 0).map((e) => e.replace(/^[\d\-\*\.\)]+\s*/, "").trim()).filter((e) => e.length > 10).slice(0, a);
|
|
39
41
|
return Response.json({
|
|
40
42
|
extract: p,
|
|
41
43
|
success: !0
|
|
@@ -50,32 +52,34 @@ Generate ${i} follow-up questions that would help readers dive deeper into this
|
|
|
50
52
|
}
|
|
51
53
|
//#endregion
|
|
52
54
|
//#region src/api/handlers/article-qa.ts
|
|
53
|
-
function
|
|
54
|
-
return async (
|
|
55
|
+
function b(n) {
|
|
56
|
+
return async (n) => {
|
|
55
57
|
try {
|
|
56
|
-
let { article:
|
|
57
|
-
if (!
|
|
58
|
-
let
|
|
58
|
+
let { article: r, question: i, chatHistory: a = [], chatModel: o } = await n.json();
|
|
59
|
+
if (!r || !i) return Response.json({ error: "Article and question are required" }, { status: 400 });
|
|
60
|
+
let s = new t(), c;
|
|
59
61
|
try {
|
|
60
|
-
|
|
62
|
+
c = await s.loadChatModel(o?.providerId, o?.key);
|
|
61
63
|
} catch (e) {
|
|
62
64
|
return Response.json({ error: e instanceof Error ? e.message : "Failed to load language model" }, { status: 500 });
|
|
63
65
|
}
|
|
64
|
-
let
|
|
65
|
-
${
|
|
66
|
+
let l = a.length > 0 ? `\n\nPrevious conversation:\n${a.map((e) => `${e.role === "user" ? "User" : "Assistant"}: ${e.content}`).join("\n")}` : "", u = `Article content:
|
|
67
|
+
${r.slice(0, 15e3)}
|
|
66
68
|
|
|
67
|
-
${
|
|
69
|
+
${l}
|
|
68
70
|
|
|
69
|
-
User question: ${
|
|
71
|
+
User question: ${i}
|
|
70
72
|
|
|
71
|
-
Please provide a helpful answer based on the article content above.`,
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
73
|
+
Please provide a helpful answer based on the article content above.`, { text: d } = await e({
|
|
74
|
+
model: c,
|
|
75
|
+
messages: [{
|
|
76
|
+
role: "system",
|
|
77
|
+
content: "You are a helpful AI assistant that answers questions about articles.\nProvide clear, concise, and accurate answers based on the article content provided.\nIf the answer is not in the article, say so."
|
|
78
|
+
}, {
|
|
79
|
+
role: "user",
|
|
80
|
+
content: u
|
|
81
|
+
}]
|
|
82
|
+
});
|
|
79
83
|
return Response.json({
|
|
80
84
|
content: d,
|
|
81
85
|
success: !0
|
|
@@ -90,35 +94,35 @@ Please provide a helpful answer based on the article content above.`, u = await
|
|
|
90
94
|
}
|
|
91
95
|
//#endregion
|
|
92
96
|
//#region src/api/handlers/chats.ts
|
|
93
|
-
function
|
|
94
|
-
let { chats:
|
|
97
|
+
function x(e) {
|
|
98
|
+
let { chats: t, messages: o } = e.schema;
|
|
95
99
|
return {
|
|
96
|
-
GET: async (
|
|
100
|
+
GET: async (a) => {
|
|
97
101
|
try {
|
|
98
|
-
let
|
|
99
|
-
id:
|
|
100
|
-
title:
|
|
101
|
-
createdAt:
|
|
102
|
-
focusMode:
|
|
103
|
-
userId:
|
|
104
|
-
files:
|
|
105
|
-
messageCount:
|
|
106
|
-
lastMessageAt: o
|
|
107
|
-
}).from(
|
|
102
|
+
let a = e.getDB(), c = await e.requireUserId(), u = await a.select({
|
|
103
|
+
id: t.id,
|
|
104
|
+
title: t.title,
|
|
105
|
+
createdAt: t.createdAt,
|
|
106
|
+
focusMode: t.focusMode,
|
|
107
|
+
userId: t.userId,
|
|
108
|
+
files: t.files,
|
|
109
|
+
messageCount: r(o.id),
|
|
110
|
+
lastMessageAt: s(o.createdAt)
|
|
111
|
+
}).from(t).leftJoin(o, n(i(o.chatId, t.id), i(o.role, "user"))).where(i(t.userId, c)).groupBy(t.id, t.title, t.createdAt, t.focusMode, t.userId, t.files).orderBy(l`${t.createdAt} DESC`);
|
|
108
112
|
return Response.json({ chats: u }, { status: 200 });
|
|
109
113
|
} catch (e) {
|
|
110
114
|
return e instanceof Error && e.message === "Unauthorized" ? Response.json({ message: "Authentication required" }, { status: 401 }) : (console.error("Error in getting chats: ", e), Response.json({ message: "An error has occurred." }, { status: 500 }));
|
|
111
115
|
}
|
|
112
116
|
},
|
|
113
|
-
DELETE: async (
|
|
117
|
+
DELETE: async (n) => {
|
|
114
118
|
try {
|
|
115
|
-
let
|
|
116
|
-
where:
|
|
119
|
+
let n = e.getDB(), r = await e.requireUserId(), s = await n.query.chats.findMany({
|
|
120
|
+
where: i(t.userId, r),
|
|
117
121
|
columns: { id: !0 }
|
|
118
122
|
});
|
|
119
|
-
if (
|
|
120
|
-
let e =
|
|
121
|
-
await
|
|
123
|
+
if (s.length > 0) {
|
|
124
|
+
let e = s.map((e) => e.id);
|
|
125
|
+
await n.delete(o).where(a(o.chatId, e)), await n.delete(t).where(i(t.userId, r));
|
|
122
126
|
}
|
|
123
127
|
return Response.json({ message: "All chats deleted" }, { status: 200 });
|
|
124
128
|
} catch (e) {
|
|
@@ -127,21 +131,21 @@ function b(e) {
|
|
|
127
131
|
}
|
|
128
132
|
};
|
|
129
133
|
}
|
|
130
|
-
function
|
|
131
|
-
let { chats:
|
|
134
|
+
function S(e) {
|
|
135
|
+
let { chats: t, messages: r } = e.schema;
|
|
132
136
|
return {
|
|
133
|
-
GET: async (
|
|
137
|
+
GET: async (n, { params: a }) => {
|
|
134
138
|
try {
|
|
135
|
-
let
|
|
139
|
+
let n = e.getDB(), { id: o } = await a, s;
|
|
136
140
|
try {
|
|
137
141
|
s = await e.requireUserId();
|
|
138
142
|
} catch {
|
|
139
143
|
s = void 0;
|
|
140
144
|
}
|
|
141
|
-
let c = await
|
|
145
|
+
let c = await n.query.chats.findFirst({ where: i(t.id, o) });
|
|
142
146
|
if (!c) return Response.json({ message: "Chat not found" }, { status: 404 });
|
|
143
147
|
if (!(c.userId === s || c.isPublic)) return Response.json({ message: "Unauthorized - this chat is private" }, { status: 403 });
|
|
144
|
-
let l = await
|
|
148
|
+
let l = await n.query.messages.findMany({ where: i(r.chatId, o) });
|
|
145
149
|
return Response.json({
|
|
146
150
|
chat: c,
|
|
147
151
|
messages: l
|
|
@@ -153,37 +157,37 @@ function x(e) {
|
|
|
153
157
|
DELETE: async (a, { params: o }) => {
|
|
154
158
|
try {
|
|
155
159
|
let a = e.getDB(), { id: s } = await o, c = await e.requireUserId();
|
|
156
|
-
return await a.query.chats.findFirst({ where:
|
|
160
|
+
return await a.query.chats.findFirst({ where: n(i(t.id, s), i(t.userId, c)) }) ? (await a.delete(t).where(i(t.id, s)).execute(), await a.delete(r).where(i(r.chatId, s)).execute(), Response.json({ message: "Chat deleted successfully" }, { status: 200 })) : Response.json({ message: "Chat not found" }, { status: 404 });
|
|
157
161
|
} catch (e) {
|
|
158
162
|
return e instanceof Error && e.message === "Unauthorized" ? Response.json({ message: "Authentication required" }, { status: 401 }) : (console.error("Error in deleting chat by id: ", e), Response.json({ message: "An error has occurred." }, { status: 500 }));
|
|
159
163
|
}
|
|
160
164
|
}
|
|
161
165
|
};
|
|
162
166
|
}
|
|
163
|
-
function
|
|
164
|
-
let { chats:
|
|
165
|
-
return { GET: async (
|
|
167
|
+
function C(e) {
|
|
168
|
+
let { chats: t, messages: r } = e.schema;
|
|
169
|
+
return { GET: async (a) => {
|
|
166
170
|
try {
|
|
167
|
-
let
|
|
171
|
+
let s = e.getDB(), u = await e.requireUserId(), { searchParams: d } = new URL(a.url), f = d.get("q");
|
|
168
172
|
if (!f || f.trim().length === 0) return Response.json({ chats: [] }, { status: 200 });
|
|
169
|
-
let p = `%${f.trim()}%`, m = await
|
|
170
|
-
id:
|
|
171
|
-
title:
|
|
172
|
-
createdAt:
|
|
173
|
-
focusMode:
|
|
174
|
-
userId:
|
|
175
|
-
files:
|
|
176
|
-
}).from(
|
|
177
|
-
id:
|
|
178
|
-
title:
|
|
179
|
-
createdAt:
|
|
180
|
-
focusMode:
|
|
181
|
-
userId:
|
|
182
|
-
files:
|
|
183
|
-
}).from(
|
|
184
|
-
chatId:
|
|
185
|
-
count:
|
|
186
|
-
}).from(
|
|
173
|
+
let p = `%${f.trim()}%`, m = await s.select({
|
|
174
|
+
id: t.id,
|
|
175
|
+
title: t.title,
|
|
176
|
+
createdAt: t.createdAt,
|
|
177
|
+
focusMode: t.focusMode,
|
|
178
|
+
userId: t.userId,
|
|
179
|
+
files: t.files
|
|
180
|
+
}).from(t).where(n(i(t.userId, u), o(t.title, p))).orderBy(l`${t.createdAt} DESC`), h = await s.selectDistinct({
|
|
181
|
+
id: t.id,
|
|
182
|
+
title: t.title,
|
|
183
|
+
createdAt: t.createdAt,
|
|
184
|
+
focusMode: t.focusMode,
|
|
185
|
+
userId: t.userId,
|
|
186
|
+
files: t.files
|
|
187
|
+
}).from(r).innerJoin(t, i(r.chatId, t.id)).where(n(i(t.userId, u), c(o(r.content, p)))).orderBy(l`${t.createdAt} DESC`), g = [...m, ...h], _ = Array.from(new Map(g.map((e) => [e.id, e])).values()), v = _.map((e) => e.id), y = v.length ? await s.select({
|
|
188
|
+
chatId: r.chatId,
|
|
189
|
+
count: l`count(*)`
|
|
190
|
+
}).from(r).where(n(l`${r.chatId} IN (${l.join(v.map((e) => l`${e}`), l`, `)})`, i(r.role, "user"))).groupBy(r.chatId) : [], b = new Map(y.map((e) => [e.chatId, Number(e.count)])), x = _.map((e) => ({
|
|
187
191
|
...e,
|
|
188
192
|
messageCount: b.get(e.id) || 0
|
|
189
193
|
}));
|
|
@@ -193,16 +197,16 @@ function S(e) {
|
|
|
193
197
|
}
|
|
194
198
|
} };
|
|
195
199
|
}
|
|
196
|
-
function
|
|
200
|
+
function w(e) {
|
|
197
201
|
let { chats: t } = e.schema;
|
|
198
202
|
return { POST: async (n) => {
|
|
199
203
|
try {
|
|
200
|
-
let
|
|
204
|
+
let r = e.getDB(), { chatId: a } = await n.json();
|
|
201
205
|
if (!a) return Response.json({
|
|
202
206
|
success: !1,
|
|
203
207
|
error: "Chat ID is required"
|
|
204
208
|
}, { status: 400 });
|
|
205
|
-
let o = await e.requireUserId(), s = await
|
|
209
|
+
let o = await e.requireUserId(), s = await r.query.chats.findFirst({ where: i(t.id, a) });
|
|
206
210
|
if (!s) return Response.json({
|
|
207
211
|
success: !1,
|
|
208
212
|
error: "Chat not found"
|
|
@@ -211,7 +215,7 @@ function C(e) {
|
|
|
211
215
|
success: !1,
|
|
212
216
|
error: "Unauthorized"
|
|
213
217
|
}, { status: 403 });
|
|
214
|
-
await
|
|
218
|
+
await r.update(t).set({ isPublic: 1 }).where(i(t.id, a)).execute();
|
|
215
219
|
let c = `${new URL(n.url).origin}/c/${a}`;
|
|
216
220
|
return Response.json({
|
|
217
221
|
success: !0,
|
|
@@ -233,21 +237,21 @@ function C(e) {
|
|
|
233
237
|
}
|
|
234
238
|
//#endregion
|
|
235
239
|
//#region src/api/handlers/chat-title.ts
|
|
236
|
-
function
|
|
237
|
-
let { chats: n } =
|
|
238
|
-
return { POST: async (
|
|
240
|
+
function ee(e) {
|
|
241
|
+
let { chats: n } = e.schema;
|
|
242
|
+
return { POST: async (r) => {
|
|
239
243
|
try {
|
|
240
|
-
let a = await
|
|
244
|
+
let a = await r.json(), o = a.chatHistory.filter((e) => e.role === "user" || e.role === "assistant").map((e) => ({
|
|
241
245
|
role: e.role,
|
|
242
246
|
content: String(e.content ?? "")
|
|
243
247
|
}));
|
|
244
248
|
if (o.length === 0) return Response.json({ message: "No conversation content" }, { status: 400 });
|
|
245
|
-
let s = await new
|
|
249
|
+
let s = await new t().loadChatModel(a.chatModel.providerId, a.chatModel.key), c = await u({ chat_history: o }, s);
|
|
246
250
|
if (!c) return Response.json({ message: "Failed to generate title" }, { status: 500 });
|
|
247
|
-
let
|
|
248
|
-
if (
|
|
249
|
-
let
|
|
250
|
-
|
|
251
|
+
let l = e.getUserId ? await e.getUserId() : null;
|
|
252
|
+
if (l && a.chatId) try {
|
|
253
|
+
let t = e.getDB(), r = await t.query.chats.findFirst({ where: i(n.id, a.chatId) });
|
|
254
|
+
r && r.userId === l && await t.update(n).set({ title: c }).where(i(n.id, a.chatId)).execute();
|
|
251
255
|
} catch (e) {
|
|
252
256
|
console.error("Failed to persist chat title:", e);
|
|
253
257
|
}
|
|
@@ -259,22 +263,22 @@ function w(t) {
|
|
|
259
263
|
}
|
|
260
264
|
//#endregion
|
|
261
265
|
//#region src/api/handlers/messages.ts
|
|
262
|
-
var
|
|
266
|
+
var T = [
|
|
263
267
|
"assistant",
|
|
264
268
|
"user",
|
|
265
269
|
"source",
|
|
266
270
|
"suggestion"
|
|
267
271
|
];
|
|
268
|
-
function
|
|
272
|
+
function E(e) {
|
|
269
273
|
let t = [], n = e;
|
|
270
274
|
for (let e = 0; n != null && e < 5; e++) t.push(n instanceof Error ? n.message : String(n)), n = n instanceof Error ? n.cause : void 0;
|
|
271
275
|
return t.join(" <- caused by: ");
|
|
272
276
|
}
|
|
273
|
-
function
|
|
277
|
+
function D(e) {
|
|
274
278
|
return { POST: async (t) => {
|
|
275
279
|
try {
|
|
276
280
|
let n = e.getDB(), r = await e.requireUserId(), { chatId: i, messageId: a, role: o, suggestions: s, content: c, sources: l } = await t.json();
|
|
277
|
-
return !i || !a || !o ? Response.json({ message: "Missing required fields" }, { status: 400 }) :
|
|
281
|
+
return !i || !a || !o ? Response.json({ message: "Missing required fields" }, { status: 400 }) : T.includes(o) ? (await n.insert(e.messagesSchema).values({
|
|
278
282
|
chatId: i,
|
|
279
283
|
userId: r,
|
|
280
284
|
messageId: a,
|
|
@@ -285,18 +289,18 @@ function E(e) {
|
|
|
285
289
|
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
286
290
|
}), Response.json({ message: "Message saved successfully" }, { status: 200 })) : Response.json({ message: `Invalid role: ${o}` }, { status: 400 });
|
|
287
291
|
} catch (e) {
|
|
288
|
-
return console.error("Error saving message:",
|
|
292
|
+
return console.error("Error saving message:", E(e)), Response.json({ message: "Failed to save message" }, { status: 500 });
|
|
289
293
|
}
|
|
290
294
|
} };
|
|
291
295
|
}
|
|
292
296
|
//#endregion
|
|
293
297
|
//#region src/api/handlers/providers.ts
|
|
294
|
-
function
|
|
298
|
+
function O(e) {
|
|
295
299
|
return {
|
|
296
300
|
GET: async (n) => {
|
|
297
301
|
try {
|
|
298
|
-
let r = new
|
|
299
|
-
i === null && (a = !await
|
|
302
|
+
let r = new t(), i = new URL(n.url).searchParams.get("guest"), a = i === "true";
|
|
303
|
+
i === null && (a = !await e.getSession());
|
|
300
304
|
let o = (await r.getActiveProviders(a)).filter((e) => !e.chatModels.some((e) => e.key === "error"));
|
|
301
305
|
return o.length === 0 ? Response.json({
|
|
302
306
|
providers: [],
|
|
@@ -309,11 +313,11 @@ function D(t) {
|
|
|
309
313
|
return console.error("An error occurred while fetching providers", e), Response.json({ message: "An error has occurred." }, { status: 500 });
|
|
310
314
|
}
|
|
311
315
|
},
|
|
312
|
-
POST: async (
|
|
316
|
+
POST: async (e) => {
|
|
313
317
|
try {
|
|
314
|
-
let { type: n, config: r } = await
|
|
318
|
+
let { type: n, config: r } = await e.json();
|
|
315
319
|
if (!n || !r) return Response.json({ message: "Missing required fields." }, { status: 400 });
|
|
316
|
-
let i = await new
|
|
320
|
+
let i = await new t().addProvider(n, r);
|
|
317
321
|
return Response.json({ provider: i }, { status: 200 });
|
|
318
322
|
} catch (e) {
|
|
319
323
|
return console.error("An error occurred while creating provider", e), Response.json({ message: "An error has occurred." }, { status: 500 });
|
|
@@ -321,21 +325,21 @@ function D(t) {
|
|
|
321
325
|
}
|
|
322
326
|
};
|
|
323
327
|
}
|
|
324
|
-
function
|
|
328
|
+
function k() {
|
|
325
329
|
return {
|
|
326
|
-
DELETE: async (
|
|
330
|
+
DELETE: async (e, { params: n }) => {
|
|
327
331
|
try {
|
|
328
|
-
let { id:
|
|
329
|
-
return
|
|
332
|
+
let { id: e } = await n;
|
|
333
|
+
return e ? (await new t().removeProvider(e), Response.json({ message: "Provider deleted successfully." }, { status: 200 })) : Response.json({ message: "Provider ID is required." }, { status: 400 });
|
|
330
334
|
} catch (e) {
|
|
331
335
|
return console.error("An error occurred while deleting provider", e.message), Response.json({ message: "An error has occurred." }, { status: 500 });
|
|
332
336
|
}
|
|
333
337
|
},
|
|
334
|
-
PATCH: async (
|
|
338
|
+
PATCH: async (e, { params: n }) => {
|
|
335
339
|
try {
|
|
336
|
-
let { config: r } = await
|
|
340
|
+
let { config: r } = await e.json(), { id: i } = await n;
|
|
337
341
|
if (!i || !r) return Response.json({ message: "Missing required fields." }, { status: 400 });
|
|
338
|
-
let a = await new
|
|
342
|
+
let a = await new t().updateProvider(i, r);
|
|
339
343
|
return Response.json({ provider: a }, { status: 200 });
|
|
340
344
|
} catch (e) {
|
|
341
345
|
return console.error("An error occurred while updating provider", e.message), Response.json({ message: "An error has occurred." }, { status: 500 });
|
|
@@ -343,20 +347,20 @@ function O() {
|
|
|
343
347
|
}
|
|
344
348
|
};
|
|
345
349
|
}
|
|
346
|
-
function
|
|
350
|
+
function A() {
|
|
347
351
|
return {
|
|
348
|
-
POST: async (
|
|
352
|
+
POST: async (e, { params: n }) => {
|
|
349
353
|
try {
|
|
350
|
-
let { id: r } = await n, i = await
|
|
351
|
-
return !i.key || !i.name ? Response.json({ message: "Key and name must be provided" }, { status: 400 }) : (await new
|
|
354
|
+
let { id: r } = await n, i = await e.json();
|
|
355
|
+
return !i.key || !i.name ? Response.json({ message: "Key and name must be provided" }, { status: 400 }) : (await new t().addProviderModel(r, i.type, i), Response.json({ message: "Model added successfully" }, { status: 200 }));
|
|
352
356
|
} catch (e) {
|
|
353
357
|
return console.error("An error occurred while adding provider model", e), Response.json({ message: "An error has occurred." }, { status: 500 });
|
|
354
358
|
}
|
|
355
359
|
},
|
|
356
|
-
DELETE: async (
|
|
360
|
+
DELETE: async (e, { params: n }) => {
|
|
357
361
|
try {
|
|
358
|
-
let { id: r } = await n, i = await
|
|
359
|
-
return i.key ? (await new
|
|
362
|
+
let { id: r } = await n, i = await e.json();
|
|
363
|
+
return i.key ? (await new t().removeProviderModel(r, i.type, i.key), Response.json({ message: "Model added successfully" }, { status: 200 })) : Response.json({ message: "Key and name must be provided" }, { status: 400 });
|
|
360
364
|
} catch (e) {
|
|
361
365
|
return console.error("An error occurred while deleting provider model", e), Response.json({ message: "An error has occurred." }, { status: 500 });
|
|
362
366
|
}
|
|
@@ -365,7 +369,7 @@ function k() {
|
|
|
365
369
|
}
|
|
366
370
|
//#endregion
|
|
367
371
|
//#region src/api/handlers/mcpservers.ts
|
|
368
|
-
function
|
|
372
|
+
function j(e) {
|
|
369
373
|
return {
|
|
370
374
|
GET: async (t) => {
|
|
371
375
|
try {
|
|
@@ -387,7 +391,7 @@ function A(e) {
|
|
|
387
391
|
}
|
|
388
392
|
};
|
|
389
393
|
}
|
|
390
|
-
function
|
|
394
|
+
function M(e) {
|
|
391
395
|
return {
|
|
392
396
|
DELETE: async (t, { params: n }) => {
|
|
393
397
|
try {
|
|
@@ -409,7 +413,7 @@ function j(e) {
|
|
|
409
413
|
}
|
|
410
414
|
};
|
|
411
415
|
}
|
|
412
|
-
function
|
|
416
|
+
function N(e) {
|
|
413
417
|
return { POST: async (t, { params: n }) => {
|
|
414
418
|
try {
|
|
415
419
|
let { enabled: r } = await t.json(), { id: i } = await n;
|
|
@@ -423,7 +427,7 @@ function M(e) {
|
|
|
423
427
|
}
|
|
424
428
|
//#endregion
|
|
425
429
|
//#region src/api/handlers/search.ts
|
|
426
|
-
var
|
|
430
|
+
var P = {
|
|
427
431
|
tech: {
|
|
428
432
|
query: [
|
|
429
433
|
"technology news",
|
|
@@ -489,14 +493,14 @@ var N = {
|
|
|
489
493
|
]
|
|
490
494
|
}
|
|
491
495
|
};
|
|
492
|
-
function
|
|
496
|
+
function F(e = {}) {
|
|
493
497
|
let t = e.searxngDomain ?? "https://search.qwksearch.com";
|
|
494
498
|
return { GET: async (e) => {
|
|
495
499
|
let n = new URL(e.url).searchParams, r = n.get("q"), i = n.get("cat") || "general", a = parseInt(n.get("page") || "1", 10), o = n.get("lang") || "en-US", s = n.get("safesearch") === "true", c = n.get("recency") || void 0, l = n.get("publicInstances") === "true";
|
|
496
500
|
if (!r) return Response.json({ error: "Query parameter is required" }, { status: 400 });
|
|
497
501
|
let u = Date.now();
|
|
498
502
|
try {
|
|
499
|
-
let e = await
|
|
503
|
+
let e = await f(r, {
|
|
500
504
|
category: i,
|
|
501
505
|
recency: c,
|
|
502
506
|
safesearch: s,
|
|
@@ -506,7 +510,7 @@ function P(e = {}) {
|
|
|
506
510
|
lang: o,
|
|
507
511
|
page: a
|
|
508
512
|
});
|
|
509
|
-
e && (Array.isArray(e) ? e.length > 0 : e.results && e.results.length > 0) || (e = await
|
|
513
|
+
e && (Array.isArray(e) ? e.length > 0 : e.results && e.results.length > 0) || (e = await f(r, {
|
|
510
514
|
category: i,
|
|
511
515
|
recency: c,
|
|
512
516
|
safesearch: s,
|
|
@@ -536,13 +540,13 @@ function P(e = {}) {
|
|
|
536
540
|
}
|
|
537
541
|
} };
|
|
538
542
|
}
|
|
539
|
-
function
|
|
543
|
+
function I() {
|
|
540
544
|
return { GET: async (e) => {
|
|
541
545
|
try {
|
|
542
|
-
let t = new URL(e.url).searchParams, n = t.get("mode") || "normal", r =
|
|
546
|
+
let t = new URL(e.url).searchParams, n = t.get("mode") || "normal", r = P[t.get("topic") || "tech"], i = [];
|
|
543
547
|
if (n === "normal") {
|
|
544
548
|
let e = /* @__PURE__ */ new Set();
|
|
545
|
-
i = (await Promise.all(r.links.flatMap((e) => r.query.map(async (t) => (await
|
|
549
|
+
i = (await Promise.all(r.links.flatMap((e) => r.query.map(async (t) => (await d(`site:${e} ${t}`, {
|
|
546
550
|
engines: ["bing news"],
|
|
547
551
|
pageno: 1,
|
|
548
552
|
language: "en"
|
|
@@ -550,7 +554,7 @@ function F() {
|
|
|
550
554
|
let n = t.url?.toLowerCase().trim();
|
|
551
555
|
return e.has(n) ? !1 : (e.add(n), !0);
|
|
552
556
|
}).sort(() => Math.random() - .5);
|
|
553
|
-
} else i = (await
|
|
557
|
+
} else i = (await d(`site:${r.links[Math.floor(Math.random() * r.links.length)]} ${r.query[Math.floor(Math.random() * r.query.length)]}`, {
|
|
554
558
|
engines: ["bing news"],
|
|
555
559
|
pageno: 1,
|
|
556
560
|
language: "en"
|
|
@@ -563,17 +567,17 @@ function F() {
|
|
|
563
567
|
}
|
|
564
568
|
//#endregion
|
|
565
569
|
//#region src/api/handlers/autocomplete.ts
|
|
566
|
-
var
|
|
570
|
+
var L = [
|
|
567
571
|
"google",
|
|
568
572
|
"duckduckgo",
|
|
569
573
|
"wikipedia"
|
|
570
|
-
],
|
|
574
|
+
], R = 3, z = 3, B = Object.entries(h).map(([e, t]) => ({
|
|
571
575
|
domain: e,
|
|
572
576
|
name: typeof t?.[0] == "string" ? t[0] : "",
|
|
573
577
|
rank: typeof t?.[1] == "number" ? t[1] : 2 ** 53 - 1
|
|
574
|
-
})),
|
|
575
|
-
function
|
|
576
|
-
return
|
|
578
|
+
})), V = null;
|
|
579
|
+
function H() {
|
|
580
|
+
return V ||= new m(B, {
|
|
577
581
|
keys: [{
|
|
578
582
|
name: "name",
|
|
579
583
|
weight: .6
|
|
@@ -585,22 +589,22 @@ function V() {
|
|
|
585
589
|
ignoreLocation: !0,
|
|
586
590
|
includeScore: !0,
|
|
587
591
|
minMatchCharLength: 3
|
|
588
|
-
}),
|
|
592
|
+
}), V;
|
|
589
593
|
}
|
|
590
|
-
function
|
|
594
|
+
function U(e) {
|
|
591
595
|
let t = e.split(/\s+/).filter(Boolean), n = t[t.length - 1] || "";
|
|
592
|
-
return n.length < 3 ? [] :
|
|
596
|
+
return n.length < 3 ? [] : H().search(n, { limit: 12 }).sort((e, t) => Math.round((e.score ?? 1) * 10) - Math.round((t.score ?? 1) * 10) || e.item.rank - t.item.rank).slice(0, z).map(({ item: e }) => ({
|
|
593
597
|
domain: e.domain,
|
|
594
598
|
name: e.name,
|
|
595
599
|
favicon: `https://www.google.com/s2/favicons?domain=${encodeURIComponent(e.domain)}&sz=64`
|
|
596
600
|
}));
|
|
597
601
|
}
|
|
598
|
-
async function
|
|
599
|
-
let r = await
|
|
602
|
+
async function W(e, t, n) {
|
|
603
|
+
let r = await p(e, t, n);
|
|
600
604
|
if (r.length > 0) return r;
|
|
601
|
-
let i = t.split(/\s+/).filter(Boolean), a = Math.min(
|
|
605
|
+
let i = t.split(/\s+/).filter(Boolean), a = Math.min(R, i.length - 1);
|
|
602
606
|
for (let r = a; r >= 1; r--) {
|
|
603
|
-
let a = i.slice(-r).join(" "), o = i.slice(0, -r).join(" "), s = await
|
|
607
|
+
let a = i.slice(-r).join(" "), o = i.slice(0, -r).join(" "), s = await p(e, a, n);
|
|
604
608
|
if (s.length > 0) {
|
|
605
609
|
let e = /* @__PURE__ */ new Set();
|
|
606
610
|
for (let n of s) {
|
|
@@ -612,16 +616,16 @@ async function U(e, t, n) {
|
|
|
612
616
|
}
|
|
613
617
|
return [];
|
|
614
618
|
}
|
|
615
|
-
function
|
|
619
|
+
function G() {
|
|
616
620
|
return { GET: async (e) => {
|
|
617
621
|
let { searchParams: t } = new URL(e.url), n = t.get("q")?.trim(), r = t.get("locale") || "en-US", i = t.get("backends"), a = parseInt(t.get("limit") || "8", 10);
|
|
618
622
|
if (!n) return Response.json({
|
|
619
623
|
suggestions: [],
|
|
620
624
|
domains: []
|
|
621
625
|
});
|
|
622
|
-
let o = i ? i.split(",").map((e) => e.trim()).filter(Boolean) :
|
|
626
|
+
let o = i ? i.split(",").map((e) => e.trim()).filter(Boolean) : L;
|
|
623
627
|
try {
|
|
624
|
-
let e = await
|
|
628
|
+
let e = await W(o, n, r), t = U(n);
|
|
625
629
|
return Response.json({
|
|
626
630
|
suggestions: e.slice(0, a),
|
|
627
631
|
domains: t
|
|
@@ -636,12 +640,12 @@ function W() {
|
|
|
636
640
|
}
|
|
637
641
|
//#endregion
|
|
638
642
|
//#region src/api/handlers/suggestions.ts
|
|
639
|
-
function
|
|
640
|
-
return { POST: async (
|
|
641
|
-
let n = await
|
|
643
|
+
function K() {
|
|
644
|
+
return { POST: async (e) => {
|
|
645
|
+
let n = await e.json(), r = n.chatHistory.filter((e) => e.role === "user" || e.role === "assistant").map((e) => ({
|
|
642
646
|
role: e.role,
|
|
643
647
|
content: String(e.content ?? "")
|
|
644
|
-
})), i = await new
|
|
648
|
+
})), i = await new t().loadChatModel(n.chatModel.providerId, n.chatModel.key), a = (await g({
|
|
645
649
|
chat_history: r,
|
|
646
650
|
maxQuestions: n.maxQuestions
|
|
647
651
|
}, i)).flatMap((e) => (e.match(/\?/g) || []).length > 1 ? e.split(/\?/).map((e) => e.trim()).filter((e) => e.length > 0).map((e) => e + "?") : [e]);
|
|
@@ -650,7 +654,7 @@ function G() {
|
|
|
650
654
|
}
|
|
651
655
|
//#endregion
|
|
652
656
|
//#region src/api/handlers/agents.ts
|
|
653
|
-
function
|
|
657
|
+
function q(e) {
|
|
654
658
|
return { POST: async (t) => {
|
|
655
659
|
let n;
|
|
656
660
|
try {
|
|
@@ -659,13 +663,13 @@ function K(e) {
|
|
|
659
663
|
return Response.json({ error: "Invalid JSON input" }, { status: 500 });
|
|
660
664
|
}
|
|
661
665
|
n.ip = t.headers?.get?.("x-forwarded-for") || t.headers?.get?.("x-real-ip") || "unknown";
|
|
662
|
-
let
|
|
663
|
-
return a && (o = await
|
|
666
|
+
let r = e.getDB(), a = await e.getUserId(), o = null;
|
|
667
|
+
return a && (o = await r.query.user.findFirst({ where: i(e.userSchema.id, a) })), o && (n.apiKey = o.settings?.providerApiKeys?.find((e) => e.provider == n.provider)?.key), n.apiKey ||= n.provider == "groq" && e.getEnv("GROQ_API_KEY"), n.apiKey ? Response.json({ error: "Language generation endpoint is deprecated. Please use /api/agent/chat instead." }, { status: 501 }) : Response.json({ error: "API key is required" }, { status: 500 });
|
|
664
668
|
} };
|
|
665
669
|
}
|
|
666
670
|
//#endregion
|
|
667
671
|
//#region src/api/handlers/rewrite.ts
|
|
668
|
-
function
|
|
672
|
+
function J(e) {
|
|
669
673
|
return { POST: async (t) => {
|
|
670
674
|
try {
|
|
671
675
|
let { text: n, prompt: r } = await t.json();
|
|
@@ -687,7 +691,7 @@ ${n}`, s = (await e.generateText({
|
|
|
687
691
|
}
|
|
688
692
|
//#endregion
|
|
689
693
|
//#region src/api/handlers/voice.ts
|
|
690
|
-
function
|
|
694
|
+
function Y(e) {
|
|
691
695
|
return { POST: async (t) => {
|
|
692
696
|
let n, r, i;
|
|
693
697
|
try {
|
|
@@ -722,15 +726,15 @@ function J(e) {
|
|
|
722
726
|
}
|
|
723
727
|
//#endregion
|
|
724
728
|
//#region src/api/handlers/transcript.ts
|
|
725
|
-
function
|
|
729
|
+
function X(e) {
|
|
726
730
|
return e === "small" || e === "fast" ? "@cf/openai/whisper-tiny-en" : e === "medium" || e === "turbo" ? "@cf/openai/whisper-large-v3-turbo" : e === "large" ? "@cf/openai/whisper-large-v3" : "@cf/openai/whisper-large-v3-turbo";
|
|
727
731
|
}
|
|
728
|
-
function
|
|
732
|
+
function Z(e) {
|
|
729
733
|
return { POST: async (t) => {
|
|
730
734
|
try {
|
|
731
735
|
let n = await t.formData(), r = n.get("file");
|
|
732
736
|
if (!r || !(r instanceof File)) return Response.json({ error: "file is required" }, { status: 400 });
|
|
733
|
-
let i =
|
|
737
|
+
let i = X(n.get("model")), a;
|
|
734
738
|
try {
|
|
735
739
|
a = e.getCloudflareContext().env?.AI;
|
|
736
740
|
} catch {}
|
|
@@ -747,15 +751,15 @@ function X(e) {
|
|
|
747
751
|
}
|
|
748
752
|
//#endregion
|
|
749
753
|
//#region src/api/handlers/test-models.ts
|
|
750
|
-
function
|
|
754
|
+
function Q() {
|
|
751
755
|
return { POST: async (e) => {
|
|
752
756
|
try {
|
|
753
757
|
let { providerType: t, apiKey: n, onlyFree: r = !0 } = await e.json();
|
|
754
758
|
if (!t) return Response.json({ error: "Provider type is required" }, { status: 400 });
|
|
755
759
|
if (!n) return Response.json({ error: "API key is required" }, { status: 400 });
|
|
756
|
-
let i =
|
|
760
|
+
let i = v.find((e) => e.provider.toLowerCase() === t.toLowerCase());
|
|
757
761
|
if (!i) return Response.json({ error: `Provider ${t} not found` }, { status: 404 });
|
|
758
|
-
let a = await
|
|
762
|
+
let a = await _(t, n, i.models, {
|
|
759
763
|
onlyFree: r,
|
|
760
764
|
concurrency: 3,
|
|
761
765
|
timeout: 15e3
|
|
@@ -768,13 +772,13 @@ function Z() {
|
|
|
768
772
|
}
|
|
769
773
|
//#endregion
|
|
770
774
|
//#region src/api/handlers/validate-openrouter.ts
|
|
771
|
-
var
|
|
772
|
-
function
|
|
775
|
+
var te = 1440 * 60 * 1e3, $ = null;
|
|
776
|
+
function ne(e) {
|
|
773
777
|
return {
|
|
774
778
|
GET: async (t) => {
|
|
775
779
|
try {
|
|
776
780
|
let t = Date.now();
|
|
777
|
-
if ($ && t - $.timestamp <
|
|
781
|
+
if ($ && t - $.timestamp < te) return Response.json({
|
|
778
782
|
...$.result,
|
|
779
783
|
cached: !0,
|
|
780
784
|
cacheAge: t - $.timestamp
|
|
@@ -808,4 +812,4 @@ function te(e) {
|
|
|
808
812
|
};
|
|
809
813
|
}
|
|
810
814
|
//#endregion
|
|
811
|
-
export {
|
|
815
|
+
export { q as createAgentsHandler, y as createArticleFollowupsHandler, b as createArticleQAHandler, G as createAutocompleteHandler, S as createChatByIdHandler, ee as createChatTitleHandler, x as createChatsHandler, C as createChatsSearchHandler, w as createChatsShareHandler, I as createDiscoverHandler, M as createMCPServerByIdHandler, N as createMCPServerToggleHandler, j as createMCPServersHandler, D as createMessagesHandler, k as createProviderByIdHandler, A as createProviderModelsHandler, O as createProvidersHandler, J as createRewriteHandler, F as createSearchHandler, K as createSuggestionsHandler, Q as createTestModelsHandler, Z as createTranscriptHandler, ne as createValidateOpenRouterHandler, Y as createVoiceHandler, E as describeError };
|
package/dist/index.cjs
CHANGED
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
`,"aria-label":j?`Stop listening`:`Voice input`,children:(0,d.jsx)(Q.Mic,{className:`w-5 h-5`})}),(0,d.jsx)(`div`,{className:`absolute bottom-full left-1/2 -translate-x-1/2 mb-2 px-2 py-1 bg-[#1F1E1D] dark:bg-[#EEEEEC] text-[11px] font-medium rounded-[6px] opacity-0 group-hover:opacity-100 transition-opacity whitespace-nowrap pointer-events-none z-50 shadow-sm tracking-wide`,children:(0,d.jsx)(`span`,{className:`text-[#ECECEC] dark:text-[#1F1E1D]`,children:j?`Stop listening`:`Voice input`})})]}),m.length>0&&(0,d.jsxs)(`div`,{className:`relative flex shrink !shrink-0 group`,children:[(0,d.jsx)(`button`,{onClick:e=>{e.stopPropagation(),p()},disabled:t,className:`transition-all duration-200 h-8 w-8 flex items-center justify-center rounded-full active:scale-95 text-text-400 hover:text-text-200 hover:bg-bg-200`,"aria-label":`New chat`,children:(0,d.jsx)(Q.SquarePen,{className:`w-5 h-5`})}),(0,d.jsx)(`div`,{className:`absolute bottom-full left-1/2 -translate-x-1/2 mb-2 px-2 py-1 bg-[#1F1E1D] dark:bg-[#EEEEEC] text-[11px] font-medium rounded-[6px] opacity-0 group-hover:opacity-100 transition-opacity whitespace-nowrap pointer-events-none z-50 shadow-sm tracking-wide`,children:(0,d.jsx)(`span`,{className:`text-[#ECECEC] dark:text-[#1F1E1D]`,children:`New chat`})})]}),(0,d.jsxs)(`div`,{className:`relative flex shrink !shrink-0 group`,children:[t?(0,d.jsx)(`button`,{onClick:e=>{e.stopPropagation(),i()},className:`inline-flex items-center justify-center shrink-0 transition-colors h-8 w-8 rounded-full active:scale-95 bg-red-500 text-white hover:bg-red-600 shadow-md`,type:`button`,"aria-label":`Stop generating`,children:(0,d.jsx)(Q.Stop,{className:`w-3.5 h-3.5 fill-current`})}):(0,d.jsx)(`button`,{onClick:e=>{e.stopPropagation(),fe()},disabled:!me,className:`inline-flex items-center justify-center shrink-0 transition-all duration-200 h-8 w-8 rounded-full active:scale-95
|
|
31
31
|
${me?`bg-accent text-bg-0 hover:bg-accent-hover shadow-md`:`bg-bg-300 text-text-400 cursor-default opacity-50`}
|
|
32
32
|
`,type:`button`,"aria-label":`Send message`,children:(0,d.jsx)(Q.ArrowUp,{className:`w-4 h-4`})}),(0,d.jsx)(`div`,{className:`absolute bottom-full left-1/2 -translate-x-1/2 mb-2 px-2 py-1 bg-[#1F1E1D] dark:bg-[#EEEEEC] text-[11px] font-medium rounded-[6px] opacity-0 group-hover:opacity-100 transition-opacity whitespace-nowrap pointer-events-none z-50 shadow-sm tracking-wide`,children:(0,d.jsx)(`span`,{className:`text-[#ECECEC] dark:text-[#1F1E1D]`,children:t?`Stop generating`:`Send message`})})]})]})]}),(0,d.jsx)(u.AnimatePresence,{children:ne&&W>0&&(0,d.jsx)(u.motion.div,{ref:e=>{e&&v.current&&v.current.contains(e)},initial:{opacity:0,y:ie===`above`?4:-4},animate:{opacity:1,y:0},exit:{opacity:0,y:ie===`above`?4:-4},transition:{duration:.12},className:`absolute left-2 right-2 md:left-0 md:right-0 z-20 rounded-2xl bg-gray-50 dark:bg-[#30302E] border border-bg-300 dark:border-transparent shadow-xl overflow-hidden ${ie===`above`?`bottom-full`:`top-full`}`,onMouseDown:e=>e.preventDefault(),children:(0,d.jsxs)(`ul`,{className:`max-h-72 overflow-y-auto custom-scrollbar py-1`,children:[V.map((e,t)=>(0,d.jsx)(`li`,{children:(0,d.jsxs)(`button`,{type:`button`,onMouseEnter:()=>U(t),onClick:()=>ue(e),className:`w-full text-left px-4 py-1.5 text-[15px] flex items-center gap-3 transition-colors ${t===H?`bg-bg-200 text-text-100`:`text-text-200 hover:bg-bg-100 dark:hover:bg-[#3A3A38]`}`,children:[(0,d.jsx)(`span`,{className:`w-5 h-5 flex items-center justify-center rounded bg-bg-200 dark:bg-[#3A3A38] text-[11px] font-semibold text-text-400 shrink-0`,children:t+1}),(0,d.jsx)(`img`,{src:e.favicon,alt:``,className:`w-4 h-4 rounded-sm shrink-0`}),(0,d.jsx)(`span`,{className:`truncate font-medium`,children:e.name||e.domain}),(0,d.jsx)(`span`,{className:`truncate text-[13px] text-text-400 shrink-0`,children:e.domain})]})},`domain-${e.domain}`)),B.map((e,t)=>{let n=V.length+t;return(0,d.jsx)(`li`,{children:(0,d.jsxs)(`button`,{type:`button`,onMouseEnter:()=>U(n),onClick:()=>le(e),className:`w-full text-left px-4 py-1.5 text-[15px] flex items-center gap-3 transition-colors ${n===H?`bg-bg-200 text-text-100`:`text-text-200 hover:bg-bg-100 dark:hover:bg-[#3A3A38]`}`,children:[(0,d.jsx)(`span`,{className:`w-5 h-5 flex items-center justify-center rounded bg-bg-200 dark:bg-[#3A3A38] text-[11px] font-semibold text-text-400 shrink-0`,children:n+1}),(0,d.jsx)(s.Search,{className:`w-4 h-4 text-text-400 shrink-0`}),(0,d.jsx)(`span`,{className:`truncate`,children:e})]})},`${e}-${t}`)})]})})}),C&&(0,d.jsxs)(`div`,{className:`absolute inset-0 bg-bg-200/90 border-2 border-dashed border-accent rounded-[28px] z-50 flex flex-col items-center justify-center backdrop-blur-sm pointer-events-none`,children:[(0,d.jsx)(Q.Archive,{className:`w-10 h-10 text-accent mb-2 animate-bounce`}),(0,d.jsx)(`p`,{className:`text-accent font-medium`,children:`Drop files to upload`})]})]})};function Bt({...e}){return(0,d.jsx)(S.Root,{"data-slot":`dialog`,...e})}function Vt({...e}){return(0,d.jsx)(S.Trigger,{"data-slot":`dialog-trigger`,...e})}function Ht({...e}){return(0,d.jsx)(S.Portal,{"data-slot":`dialog-portal`,...e})}function Ut({className:e,...t}){return(0,d.jsx)(S.Overlay,{"data-slot":`dialog-overlay`,className:E(`data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50 backdrop-blur-xs`,e),...t})}function Wt({className:e,children:t,hideCloseButton:n=!1,...r}){return(0,d.jsxs)(Ht,{"data-slot":`dialog-portal`,children:[(0,d.jsx)(Ut,{}),(0,d.jsxs)(S.Content,{"data-slot":`dialog-content`,"aria-describedby":r[`aria-describedby`]??void 0,className:E(`z-[9999] bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-2xl border p-6 shadow-lg duration-200`,e),...r,children:[t,!n&&(0,d.jsxs)(S.Close,{className:`ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4`,children:[(0,d.jsx)(s.XIcon,{}),(0,d.jsx)(`span`,{className:`sr-only`,children:`Close`})]})]})]})}function Gt({className:e,...t}){return(0,d.jsx)(S.Title,{"data-slot":`dialog-title`,className:E(`text-lg leading-none font-semibold`,e),...t})}function Kt({className:e,...t}){return(0,d.jsx)(S.Description,{"data-slot":`dialog-description`,className:E(`text-muted-foreground text-sm`,e),...t})}var qt=n.forwardRef(({className:e,...t},n)=>(0,d.jsx)(`span`,{ref:n,className:E(`absolute w-px h-px p-0 -m-px overflow-hidden whitespace-nowrap border-0`,e),style:{clip:`rect(0, 0, 0, 0)`,clipPath:`inset(50%)`},...t}));qt.displayName=`VisuallyHidden`;var Jt=({onClose:e})=>(0,d.jsx)(`div`,{className:`flex items-center justify-between bg-secondary px-4 py-3 border-b border-border`,children:(0,d.jsx)(`button`,{onClick:e,className:`rounded-md p-1 hover:bg-accent transition-colors`,children:(0,d.jsx)(s.X,{className:`h-5 w-5`})})}),Yt=(0,b.cva)(`inline-flex cursor-pointer items-center justify-center gap-2 whitespace-nowrap rounded-2xl text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive`,{variants:{variant:{default:`bg-primary text-primary-foreground hover:bg-primary/90`,destructive:`bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60`,outline:`border-[1.5px] bg-background hover:bg-accent hover:text-accent-foreground dark:bg-card dark:hover:bg-card/50`,secondary:`bg-secondary text-secondary-foreground hover:bg-secondary/80`,ghost:`hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50`,link:`text-primary underline-offset-4 hover:underline`},size:{default:`h-9 px-4 py-2 has-[>svg]:px-3`,sm:`h-8 gap-1.5 px-3 has-[>svg]:px-2.5`,lg:`h-10 px-6 has-[>svg]:px-4`,icon:`size-9`}},defaultVariants:{variant:`default`,size:`default`}});function $({className:e,variant:t,size:n,asChild:r=!1,...i}){return(0,d.jsx)(r?y.Slot:`button`,{"data-slot":`button`,className:E(Yt({variant:t,size:n,className:e})),...i})}var Xt=E(`h-9 w-9 rounded-xl transition-all duration-200`,`hover:bg-muted/80 hover:text-foreground text-muted-foreground`),Zt=({isLoadingAI:e,isLoadingFollowups:t,isLoadingFavorite:n,isFavorited:r,isHighlightMode:i,articleUrl:a,fontScale:o,onAskClick:c,onSuggestClick:l,onCopyClick:u,onFavoriteClick:f,onHighlightToggle:p,onZoomIn:m,onZoomOut:h,onZoomReset:g,onClose:_})=>{let v=m||h,y=Math.round((o??1)*100);return(0,d.jsxs)(`div`,{className:`flex flex-nowrap items-center gap-1 rounded-2xl border border-muted bg-gradient-to-b from-background to-muted/30 p-1 shadow-sm`,children:[(0,d.jsxs)($,{onClick:c,disabled:e,variant:`ghost`,size:`sm`,className:E(`flex items-center gap-2 px-3 h-9 rounded-xl transition-all duration-200`,`hover:bg-muted/80 hover:text-foreground text-muted-foreground`),children:[(0,d.jsx)(s.Bot,{className:`size-4`}),(0,d.jsx)(`span`,{className:`font-medium`,children:e?`...`:`Ask`})]}),(0,d.jsxs)($,{onClick:l,disabled:t,variant:`ghost`,size:`sm`,className:E(`flex items-center gap-2 px-3 h-9 rounded-xl transition-all duration-200`,`hover:bg-muted/80 hover:text-foreground text-muted-foreground`),children:[(0,d.jsx)(s.MessageCircleQuestion,{className:`size-4`}),(0,d.jsx)(`span`,{className:`font-medium`,children:`Suggest`})]}),(0,d.jsx)($,{onClick:u,variant:`ghost`,size:`icon`,className:Xt,title:`Copy article`,children:(0,d.jsx)(s.Clipboard,{className:`size-4`})}),(0,d.jsx)($,{onClick:p,variant:`ghost`,size:`icon`,className:E(`h-9 w-9 rounded-xl transition-all duration-200`,i?`text-yellow-500 bg-yellow-50 dark:bg-yellow-950/30 hover:bg-yellow-100 dark:hover:bg-yellow-950/50`:`hover:bg-muted/80 hover:text-foreground text-muted-foreground`),title:i?`Disable highlighting`:`Enable highlighting`,children:(0,d.jsx)(s.Highlighter,{className:`size-4`})}),(0,d.jsx)($,{onClick:f,disabled:n,variant:`ghost`,size:`icon`,className:E(`h-9 w-9 rounded-xl transition-all duration-200`,r?`text-yellow-500 hover:text-yellow-600 hover:bg-yellow-50 dark:hover:bg-yellow-950/30`:`hover:bg-muted/80 hover:text-foreground text-muted-foreground`),title:r?`Remove from favorites`:`Add to favorites`,children:(0,d.jsx)(s.Star,{className:E(`size-4`,r&&`fill-yellow-400`)})}),a&&(0,d.jsx)($,{asChild:!0,variant:`ghost`,size:`icon`,className:Xt,title:`Open in new tab`,children:(0,d.jsx)(`a`,{href:a,target:`_blank`,rel:`noopener noreferrer`,children:(0,d.jsx)(s.ExternalLink,{className:`size-4`})})}),v&&(0,d.jsxs)(`div`,{className:`ml-auto flex items-center gap-0.5 rounded-xl border border-muted/60 bg-muted/20 px-1`,children:[(0,d.jsx)($,{onClick:h,variant:`ghost`,size:`icon`,className:`h-8 w-8 rounded-lg text-muted-foreground transition-all duration-200 hover:bg-muted/80 hover:text-foreground`,title:`Zoom out`,children:(0,d.jsx)(s.ZoomOut,{className:`size-4`})}),(0,d.jsxs)(`button`,{type:`button`,onClick:g,className:`min-w-[3rem] rounded-md px-1 text-center text-xs font-medium tabular-nums text-muted-foreground transition-colors hover:text-foreground`,title:`Reset zoom`,children:[y,`%`]}),(0,d.jsx)($,{onClick:m,variant:`ghost`,size:`icon`,className:`h-8 w-8 rounded-lg text-muted-foreground transition-all duration-200 hover:bg-muted/80 hover:text-foreground`,title:`Zoom in`,children:(0,d.jsx)(s.ZoomIn,{className:`size-4`})})]}),(0,d.jsx)($,{onClick:_,variant:`ghost`,size:`icon`,className:E(Xt,!v&&`ml-auto`),title:`Close`,children:(0,d.jsx)(s.X,{className:`size-4`})})]})},Qt=({value:e,onChange:t,onSubmit:n})=>(0,d.jsx)(`div`,{className:`relative`,children:(0,d.jsx)(`input`,{value:e,onChange:e=>t(e.target.value),onKeyDown:e=>e.key===`Enter`&&n(),type:`text`,placeholder:`Ask AI any question...`,className:`w-full px-3 py-2 text-sm rounded-md border border-input bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-ring`})}),$t=({questions:e,isLoading:r,error:i,onQuestionClick:a})=>{let o=n.default.useMemo(()=>{let t=[];return e.forEach(e=>{e.includes(`?`)&&e.split(`?`).length>2?e.split(`?`).map(e=>e.trim()).filter(Boolean).forEach(e=>{t.push(e.endsWith(`?`)?e:`${e}?`)}):t.push(e)}),t},[e]);return(0,d.jsxs)(d.Fragment,{children:[o.length>0&&(0,d.jsxs)(`div`,{className:`space-y-3 bg-accent/30 rounded-lg p-4 border border-primary/20`,children:[(0,d.jsx)(`h3`,{className:`text-sm font-bold text-primary mb-2`,children:`💡 Suggested Follow-up Questions`}),(0,d.jsxs)(`div`,{className:`space-y-2`,children:[(0,d.jsx)(`div`,{onClick:()=>a(t.researchAgentUIConfig.defaultSummarizePrompt),className:`cursor-pointer rounded-md p-3 text-sm font-semibold hover:bg-primary/10 bg-background border border-primary/30 transition-all hover:border-primary shadow-sm hover:shadow-md`,children:t.researchAgentUIConfig.defaultSummarizePrompt}),o.map((e,t)=>(0,d.jsx)(`div`,{onClick:()=>a(e),className:`cursor-pointer rounded-md p-3 text-sm font-semibold hover:bg-primary/10 bg-background border border-border transition-all hover:border-primary shadow-sm hover:shadow-md`,dangerouslySetInnerHTML:{__html:e}},t))]})]}),r&&(0,d.jsx)(`div`,{className:`flex justify-center`,children:(0,d.jsx)(`div`,{className:`animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500`})}),i&&(0,d.jsx)(`div`,{className:`bg-red-500 text-white p-2 rounded-md text-sm`,children:i})]})},en=({response:e,isLoading:t,error:n})=>(0,d.jsxs)(d.Fragment,{children:[t&&(0,d.jsx)(`div`,{className:`flex justify-center`,children:(0,d.jsx)(`div`,{className:`animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500`})}),e&&(0,d.jsx)(`div`,{ref:e=>{},className:`bg-muted rounded-lg shadow-md p-4`,dangerouslySetInnerHTML:{__html:e}}),n&&(0,d.jsx)(`div`,{className:`bg-red-500 text-white p-2 rounded-md text-sm`,children:n})]}),tn=({html:e,isHighlightMode:t=!1,fontScale:r=1})=>{let[i,a]=(0,n.useState)(``);return(0,n.useEffect)(()=>{a(C.default.sanitize(e||``,{ADD_TAGS:[`figure`,`figcaption`],ADD_ATTR:[`loading`]}))},[e]),(0,d.jsx)(`div`,{className:[`prose prose-neutral dark:prose-invert max-w-none`,`prose-p:leading-[1.9] prose-li:leading-[1.9] prose-p:my-5 prose-li:my-1.5`,`prose-headings:font-semibold prose-headings:tracking-tight prose-headings:leading-snug`,`prose-h1:mt-8 prose-h2:mt-8 prose-h3:mt-6`,`prose-blockquote:leading-[1.8] prose-blockquote:border-l-2`,`prose-img:rounded-lg prose-img:my-6`,t?`select-text`:``].join(` `),style:{fontSize:`${r}em`,fontFamily:`ui-serif, Georgia, Cambria, "Times New Roman", Times, serif`},dangerouslySetInnerHTML:{__html:i}})},nn=({article:e,isHighlightMode:t,fontScale:n=1})=>(0,d.jsx)(`div`,{className:`border-t border-border pt-6`,children:(0,d.jsxs)(`div`,{children:[(0,d.jsx)(`div`,{className:`flex items-start justify-between mb-2`}),e.cite&&(0,d.jsx)(`div`,{className:`mb-3 text-sm text-muted-foreground`,dangerouslySetInnerHTML:{__html:e.cite}}),(0,d.jsx)(`div`,{className:`mb-3 text-xs text-muted-foreground space-y-1`,children:e.word_count&&(0,d.jsxs)(`p`,{children:[(0,d.jsx)(`span`,{className:`font-semibold`,children:`Words:`}),` `,e.word_count.toLocaleString()]})}),(0,d.jsx)(`div`,{id:`article-content`,children:(0,d.jsx)(tn,{html:e.html||``,isHighlightMode:t,fontScale:n})})]})}),rn=/(?:https?:\/\/)?(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b(?:[-a-zA-Z0-9()@:%_\+.~#?&\/=]*)/g,an=/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g;function on(e){return e.includes(`](`)||e.includes(`)[`)?!1:/\.(com|org|net|io|dev|co|uk|de|fr|it|es|jp|cn|in|br|au|ca|us|gov|edu|mil|int|xyz|info|app|tech|online|site|website|store|shop|blog|news|tv|me|cc|ws|name|mobi|asia|tel|travel|jobs|pro|museum|coop|aero|arpa|biz|cat|jobs|post|tel|xxx|ac|ad|ae|af|ag|ai|al|am|ao|aq|ar|as|at|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cu|cv|cw|cx|cy|cz|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|ss|st|su|sv|sx|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|za|zm|zw)(?:\/|$)/i.test(e)}function sn(e){return/^https?:\/\//i.test(e)?e:`https://${e}`}function cn(e){if(!e||typeof e!=`string`)return e;let t=e,n=[],r;for(an.lastIndex=0;(r=an.exec(t))!==null;){let e=r[0],i=r.index,a=t.substring(0,i),o=t.substring(i+e.length);!a.endsWith(`](`)&&!o.startsWith(`)`)&&n.push({email:e,index:i})}for(let e=n.length-1;e>=0;e--){let{email:r,index:i}=n[e];t=t.substring(0,i)+`[${r}](mailto:${r})`+t.substring(i+r.length)}let i=[],a;for(rn.lastIndex=0;(a=rn.exec(t))!==null;){let e=a[0],n=a.index;if(an.test(e))continue;let r=t.substring(0,n),o=t.substring(n+e.length);if(r.endsWith(`](`)||o.startsWith(`)`)||(r.match(/```/g)||[]).length%2!=0)continue;let s=r.lastIndexOf("`");if(s!==-1){let e=t.substring(s+1).indexOf("`");if(e!==-1&&e>n-s-1)continue}on(e)&&i.push({url:e,index:n})}for(let e=i.length-1;e>=0;e--){let{url:n,index:r}=i[e],a=sn(n);t=t.substring(0,r)+`[${n}](${a})`+t.substring(r+n.length)}return t}function ln(e){return!e||e.startsWith(`http://`)||e.startsWith(`https://`)||e.includes(`://`)?!1:e.startsWith(`/`)||e.startsWith(`#`)}function un(e,t){if(t.startsWith(`#`)){e.preventDefault();let n=t.substring(1),r=document.getElementById(n);r&&r.scrollIntoView({behavior:`smooth`,block:`start`})}}function dn({code:e}){let[t,r]=(0,n.useState)(!1);return(0,d.jsx)(`button`,{onClick:(0,n.useCallback)(async()=>{try{await navigator.clipboard.writeText(e),r(!0),setTimeout(()=>r(!1),2e3)}catch(e){console.error(`Failed to copy:`,e)}},[e]),className:E(`absolute top-3 right-3 p-1.5 rounded-md`,`opacity-0 group-hover:opacity-100 transition-opacity duration-150`,`bg-zinc-200/80 hover:bg-zinc-300 dark:bg-zinc-700/80 dark:hover:bg-zinc-600`,`text-zinc-600 hover:text-zinc-800 dark:text-zinc-400 dark:hover:text-zinc-200`,`focus:outline-none focus:ring-1 focus:ring-zinc-400 dark:focus:ring-zinc-500`),"aria-label":t?`Copied!`:`Copy code`,children:t?(0,d.jsx)(s.Check,{className:`h-4 w-4 text-green-600 dark:text-green-400`}):(0,d.jsx)(s.Copy,{className:`h-4 w-4`})})}function fn({children:e}){let t=(0,n.useRef)(null),[r,i]=(0,n.useState)(``);return(0,n.useEffect)(()=>{if(t.current){let e=t.current.querySelector(`code`);if(e){let t=e.textContent||``;i(t.trim())}}},[e]),(0,d.jsxs)(`div`,{className:`relative group my-5`,children:[(0,d.jsx)(`pre`,{ref:t,className:E(`p-4 rounded-xl overflow-x-auto`,`bg-zinc-100 dark:bg-zinc-900`,`border border-zinc-200 dark:border-zinc-800`,`text-[13px] font-mono leading-relaxed`,`text-zinc-800 dark:text-zinc-200`,`[&_code]:bg-transparent [&_code]:text-inherit [&_code]:p-0`),children:e}),r&&(0,d.jsx)(dn,{code:r})]})}var pn=n.default.memo(({content:e,className:t,isStreaming:n=!1})=>{if(!e)return(0,d.jsx)(`div`,{className:E(`text-muted-foreground text-sm`,t),children:`No content`});let r=cn(e);return(0,d.jsx)(`div`,{className:E(`kortix-markdown`,t),children:(0,d.jsx)(T.Streamdown,{isAnimating:n,components:{h1:({children:e})=>(0,d.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight text-foreground mt-8 mb-4 first:mt-0 pb-2 border-b border-border/40`,children:e}),h2:({children:e})=>(0,d.jsx)(`h2`,{className:`text-xl font-semibold tracking-tight text-foreground mt-8 mb-3 first:mt-0`,children:e}),h3:({children:e})=>(0,d.jsx)(`h3`,{className:`text-lg font-semibold text-foreground mt-6 mb-2 first:mt-0`,children:e}),h4:({children:e})=>(0,d.jsx)(`h4`,{className:`text-base font-semibold text-foreground mt-5 mb-2 first:mt-0`,children:e}),h5:({children:e})=>(0,d.jsx)(`h5`,{className:`text-sm font-semibold text-foreground mt-4 mb-1 first:mt-0`,children:e}),h6:({children:e})=>(0,d.jsx)(`h6`,{className:`text-sm font-medium text-muted-foreground mt-4 mb-1 first:mt-0 uppercase tracking-wide`,children:e}),p:({children:e})=>(0,d.jsx)(`p`,{className:`text-sm text-foreground leading-relaxed my-4 first:mt-0 last:mb-0 [&:has(img)]:my-0`,children:e}),ul:({children:e})=>(0,d.jsx)(`ul`,{className:`my-4 ml-6 list-disc marker:text-muted-foreground/60 space-y-2 first:mt-0 last:mb-0 text-sm`,children:e}),ol:({children:e})=>(0,d.jsx)(`ol`,{className:`my-4 ml-6 list-decimal marker:text-muted-foreground/60 marker:font-medium space-y-2 first:mt-0 last:mb-0 text-sm`,children:e}),li:({children:e})=>(0,d.jsx)(`li`,{className:`text-sm text-foreground leading-relaxed pl-1`,children:e}),a:({href:e,children:t})=>{let n=ln(e),r=e?.startsWith(`#`),i=E(`font-medium text-foreground`,`underline decoration-foreground/30 underline-offset-[3px] decoration-[1px]`,`hover:decoration-foreground/60 transition-colors duration-150`);return r?(0,d.jsx)(`a`,{href:e,onClick:t=>un(t,e),className:i,children:t}):n?(0,d.jsx)(w.default,{href:e||`#`,className:i,children:t}):(0,d.jsx)(`a`,{href:e,target:`_blank`,rel:`noopener noreferrer`,className:i,children:t})},code:({children:e,className:t})=>t?.includes(`language-`)?(0,d.jsx)(`code`,{className:`text-[13px] leading-relaxed text-inherit`,children:e}):(0,d.jsx)(`code`,{className:`px-2 py-1 rounded-md text-[13px] font-mono bg-card dark:bg-[#161618] border border-neutral-200 dark:border-neutral-700/50 text-foreground`,children:e}),pre:({children:e})=>(0,d.jsx)(fn,{children:e}),blockquote:({children:e})=>(0,d.jsx)(`blockquote`,{className:E(`my-5 pl-4 py-1 text-sm`,`border-l-2 border-border`,`text-muted-foreground`,`[&>p]:my-2`),children:e}),hr:()=>(0,d.jsx)(`hr`,{className:`my-8 border-0 h-px bg-border/60`}),table:({children:e})=>(0,d.jsx)(`div`,{className:`my-5 overflow-x-auto rounded-xl border border-border/60`,children:(0,d.jsx)(`table`,{className:`w-full text-sm`,children:e})}),thead:({children:e})=>(0,d.jsx)(`thead`,{className:`bg-muted/50 dark:bg-muted/30 border-b border-border/60`,children:e}),tbody:({children:e})=>(0,d.jsx)(`tbody`,{className:`divide-y divide-border/40`,children:e}),tr:({children:e})=>(0,d.jsx)(`tr`,{className:`transition-colors hover:bg-muted/30`,children:e}),th:({children:e})=>(0,d.jsx)(`th`,{className:`px-4 py-3 text-left text-xs font-semibold text-foreground uppercase tracking-wider`,children:e}),td:({children:e})=>(0,d.jsx)(`td`,{className:`px-4 py-3 text-foreground`,children:e}),img:({src:e,alt:t})=>e?(0,d.jsxs)(`span`,{className:`block my-5`,children:[(0,d.jsx)(`img`,{src:e,alt:t||``,className:E(`max-w-full h-auto rounded-xl`,`border border-border/40`,`shadow-sm`),loading:`lazy`}),t&&(0,d.jsx)(`span`,{className:`block mt-2 text-center text-sm text-muted-foreground`,children:t})]}):null,strong:({children:e})=>(0,d.jsx)(`strong`,{className:`font-semibold text-foreground`,children:e}),em:({children:e})=>(0,d.jsx)(`em`,{className:`italic text-foreground/90`,children:e}),del:({children:e})=>(0,d.jsx)(`del`,{className:`line-through text-muted-foreground decoration-muted-foreground/50`,children:e}),input:({checked:e,...t})=>(0,d.jsx)(`input`,{type:`checkbox`,checked:e,readOnly:!0,className:E(`mr-2 h-4 w-4 rounded border-border`,`accent-secondary cursor-default`,`align-middle relative -top-[1px]`),...t}),div:({children:e,style:t,className:n,...r})=>(0,d.jsx)(`div`,{className:E(`text-sm text-foreground`,n),style:t,...r,children:e}),span:({children:e,style:t,className:n,...r})=>(0,d.jsx)(`span`,{className:E(`text-foreground`,n),style:t,...r,children:e})},children:r})})});pn.displayName=`UnifiedMarkdown`;var mn=e=>{let{isOpen:r,url:i,searchText:a,panelWidth:o,setPanelWidth:s,closePanel:l}=j(),{isAuthenticated:u}=Ie(),{chatModelProvider:f}=K(),m=e.isOpen===void 0?r:e.isOpen,h=e.onClose||l,g=e.url||i,_=e.searchText===void 0?a:e.searchText,[v,y]=(0,n.useState)(null),[b,x]=(0,n.useState)([]),[S,C]=(0,n.useState)(!1),[w,T]=(0,n.useState)(t.researchAgentUIConfig.defaultSummarizePrompt),[E,D]=(0,n.useState)(!1),[O,k]=(0,n.useState)(!1),[A,M]=(0,n.useState)(!1),[N,P]=(0,n.useState)(``),[F,I]=(0,n.useState)(``),[L,R]=(0,n.useState)([]),[z,B]=(0,n.useState)(``),[ee,V]=(0,n.useState)(!1),[te,H]=(0,n.useState)(!1),[U,ne]=(0,n.useState)(!1),[re,ie]=(0,n.useState)(!1),[ae,oe]=(0,n.useState)(o),[se,ce]=(0,n.useState)(!1),[le,ue]=(0,n.useState)(!1),[W,de]=(0,n.useState)(1),fe=(0,n.useRef)(null),pe=.8,me=1.8,he=.1;(0,n.useEffect)(()=>{let e=parseFloat(localStorage.getItem(`articleFontScale`)||``);Number.isNaN(e)||de(Math.min(me,Math.max(pe,e)))},[]);let G=e=>{let t=Math.min(me,Math.max(pe,Math.round(e*100)/100));de(t);try{localStorage.setItem(`articleFontScale`,String(t))}catch(e){console.error(`Error storing article font scale:`,e)}},ge=()=>G(W+he),_e=()=>G(W-he),ve=()=>G(1);(0,n.useEffect)(()=>{let e=()=>{ie(window.innerWidth>=1024)};return e(),window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[]),(0,n.useEffect)(()=>{let e=e=>{if(!se)return;let t=window.innerWidth-e.clientX,n=Math.max(400,Math.min(t,window.innerWidth-100));oe(n),s(n)},t=()=>{ce(!1)};return se&&(document.addEventListener(`mousemove`,e),document.addEventListener(`mouseup`,t),document.body.style.cursor=`ew-resize`,document.body.style.userSelect=`none`),()=>{document.removeEventListener(`mousemove`,e),document.removeEventListener(`mouseup`,t),document.body.style.cursor=``,document.body.style.userSelect=``}},[se,s]),(0,n.useEffect)(()=>{m&&g?(ue(!1),ye()):m||ue(!1)},[m,g]);let ye=async()=>{console.log(`[ArticleExtractPanel] Extracting URL:`,g);try{let e=new URL(g);if([/^https?:\/\/(www\.)?google\.[^/]+\/search/i,/^https?:\/\/(www\.)?bing\.com\/search/i,/^https?:\/\/(www\.)?duckduckgo\.com\/\?/i].some(e=>e.test(g))){p.toast.error(`Cannot extract articles from search result pages`),D(!1),ue(!0);return}(e.pathname===`/`||e.pathname===``)&&(console.error(`[ArticleExtractPanel] URL is domain-only, missing article path:`,g),p.toast.error(`Invalid article URL - only domain provided`))}catch(e){console.error(`[ArticleExtractPanel] Invalid URL format:`,g,e)}D(!0);try{let{data:e}=await(0,c.getArticle)({query:{url:g}}),t=e?.article,n=t?.html?.replace(/<[^>]*>/g,``).trim()||``;t?.error||n.length<20?(document.dispatchEvent(new CustomEvent(`onInvokeChromeAPI`,{detail:{type:`extractURL`,url:g}})),await Promise.race([new Promise(e=>{let t=async n=>{window.removeEventListener(`onExtractionResult`,t);let{data:r}=await(0,c.getArticle)({query:{url:g}}),i=r?.article;i&&(y(i),i.followUpQuestions?.length>0&&R(i.followUpQuestions)),e()};window.addEventListener(`onExtractionResult`,t)}),new Promise(e=>setTimeout(e,1e4))])):(y(t),t?.followUpQuestions&&t.followUpQuestions.length>0&&R(t.followUpQuestions)),u&&be()}catch(e){console.error(`[ArticleExtractPanel] Error extracting URL:`,e),p.toast.error(`Failed to load article`)}finally{D(!1),ue(!0)}},be=async()=>{try{let{data:e}=await(0,c.listFavorites)(),t=e?.favorites?.some(e=>e.url===g);V(!!t)}catch(e){console.error(`Error checking favorite status:`,e)}},xe=async()=>{if(v){H(!0);try{ee?(await(0,c.removeFavorite)({query:{url:g}}),V(!1),p.toast.info(`Removed from favorites`)):(await(0,c.addFavorite)({body:{url:v.url||g,title:v.title,cite:v.cite,author:v.author,author_cite:v.author_cite,date:v.date,source:v.source,word_count:v.word_count,html:v.html}}),V(!0),p.toast.success(`Added to favorites`))}catch(e){console.error(`Error toggling favorite:`,e),p.toast.error(`Failed to toggle favorite`)}finally{H(!1)}}},Se=()=>{if(f?.key&&f?.providerId)return f;try{let e=localStorage.getItem(`chatModelKey`)||``,t=localStorage.getItem(`chatModelProviderId`)||``;if(e&&t)return{key:e,providerId:t}}catch(e){console.error(`Error reading persisted chat model:`,e)}return f},Ce=async e=>{if(!v)return;let n=Se(),r=v.html?.replace(/<[^>]*>?/g,``).slice(0,t.researchAgentUIConfig.maxArticleLength),i=e===`question`,a=i?k:M,o=i?I:B;a(!0),o(``);try{if(i){let e=[_,w].filter(Boolean).join(`
|
|
33
|
-
`);if(!r||r.length===0)throw Error(`Article content is empty`);let{data:t,error:i}=await(0,c.articleQa)({body:{article:r,question:e,chatHistory:b.slice(-5),chatModel:n}});if(i){let e=i.details||i.error||i.message||`Article QA failed`;throw Error(e)}let a=t?.content||``;P(a),x(e=>[...e,{role:`user`,content:w,time:new Date().toISOString()},{role:`assistant`,content:a,time:new Date().toISOString()}]);try{await(0,c.updateArticle)({body:{url:g,question:w,answer:a}})}catch(e){console.error(`Error storing Q&A in cache:`,e)}}else{let e=parseInt(localStorage.getItem(`maxFollowupQuestions`)||`4`);if(!r||r.length===0)throw Error(`Article content is empty`);let{data:t,error:i}=await(0,c.articleFollowups)({body:{article:r,chatHistory:b.slice(-5),maxQuestions:e,chatModel:n}});if(i){let e=i.details||i.error||i.message||`Article followups failed`;throw Error(e)}let a=t?.extract||[];R(a);try{await(0,c.updateArticle)({body:{url:g,followUpQuestions:a}})}catch(e){console.error(`Error storing follow-up questions in cache:`,e)}}}catch(e){console.error(`Error calling language API:`,e),o(e instanceof Error||typeof e==`object`&&e&&`message`in e?e.message:`Failed to get AI response`)}finally{a(!1)}},we=e=>{T(e),Ce(`question`)},Te=async()=>{if(!v)return;let e=`${N}\n\n\n${v.cite||``}\n\n\n${v.html}`;try{await navigator.clipboard.writeText(e),C(!0),setTimeout(()=>C(!1),2e3)}catch(e){console.error(`Failed to copy to clipboard:`,e)}},Ee=()=>(0,d.jsxs)(`div`,{className:`flex h-full flex-col bg-background shadow-xl`,children:[(0,d.jsx)(`div`,{className:`shrink-0 border-b border-border bg-background/95 px-4 py-3 backdrop-blur supports-[backdrop-filter]:bg-background/80`,children:(0,d.jsx)(Zt,{isLoadingAI:O,isLoadingFollowups:A,isLoadingFavorite:te,isFavorited:ee,isHighlightMode:U,articleUrl:v?.url||g,fontScale:W,onAskClick:()=>Ce(`question`),onSuggestClick:()=>Ce(`suggest-followups`),onCopyClick:Te,onFavoriteClick:xe,onHighlightToggle:()=>ne(!U),onZoomIn:ge,onZoomOut:_e,onZoomReset:ve,onClose:h})}),(0,d.jsx)(`div`,{className:`flex-1 overflow-y-auto`,children:(0,d.jsxs)(`div`,{className:`p-4 space-y-6`,children:[(0,d.jsxs)(`div`,{className:`space-y-4`,children:[S&&(0,d.jsx)(`div`,{className:`bg-blue-500 text-white text-sm font-medium px-3 py-2 rounded-md shadow-lg`,children:`Copied!`}),(0,d.jsx)(Qt,{value:w,onChange:T,onSubmit:()=>Ce(`question`)}),(0,d.jsx)($t,{questions:L,isLoading:A,error:z,onQuestionClick:we}),b.length>0&&(0,d.jsx)(`div`,{className:`space-y-4`,children:b.map((e,t)=>(0,d.jsx)(`div`,{className:`space-y-2`,children:e.role===`user`?(0,d.jsxs)(`div`,{className:`bg-primary/10 border border-primary/20 rounded-lg p-3`,children:[(0,d.jsx)(`div`,{className:`text-xs font-semibold text-primary mb-1`,children:`Your Question`}),(0,d.jsx)(`div`,{className:`text-sm text-foreground`,children:e.content})]}):(0,d.jsxs)(`div`,{className:`bg-muted rounded-lg shadow-md p-4`,children:[(0,d.jsx)(`div`,{className:`text-xs font-semibold text-muted-foreground mb-2`,children:`AI Response`}),(0,d.jsx)(`div`,{className:`text-sm`,dangerouslySetInnerHTML:{__html:e.content}})]})},t))}),(O||N&&b.length===0)&&(0,d.jsx)(en,{response:N,isLoading:O,error:F}),F&&!O&&(0,d.jsx)(`div`,{className:`bg-red-500 text-white p-2 rounded-md text-sm`,children:F})]}),v&&(0,d.jsx)(nn,{article:v,isHighlightMode:U,fontScale:W})]})})]});return!m||!le?null:re?(0,d.jsxs)(`div`,{className:`fixed top-0 right-0 h-screen z-40 transition-all duration-300`,style:{width:`${ae}px`},children:[(0,d.jsx)(`div`,{ref:fe,onMouseDown:()=>ce(!0),className:`absolute left-0 top-0 bottom-0 w-1 cursor-ew-resize hover:bg-primary bg-transparent transition-colors z-50`,style:{touchAction:`none`},children:(0,d.jsx)(`div`,{className:`absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 w-1 h-12 rounded-full bg-muted-foreground opacity-50 hover:opacity-100 transition-opacity`})}),Ee()]}):(0,d.jsx)(Bt,{open:m,onOpenChange:e=>!e&&h(),children:(0,d.jsxs)(Wt,{className:`pointer-events-auto fixed inset-0 !top-0 !left-0 !translate-x-0 !translate-y-0 h-full w-full max-w-none p-0 m-0 rounded-none border-0 overflow-hidden data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right`,hideCloseButton:!0,children:[(0,d.jsx)(qt,{children:(0,d.jsx)(Gt,{children:`Article Details`})}),(0,d.jsx)(`div`,{className:`h-full overflow-y-auto`,children:Ee()})]})})},hn=()=>{let{sections:e,chatTurns:r,loading:i,messageAppeared:a,newChat:o,chatId:s}=K(),{isOpen:c,panelWidth:l}=j(),{isAuthenticated:u}=Ie(),[f,p]=(0,n.useState)(!1),m=(0,n.useRef)(null),h=(0,n.useRef)(null),g=(0,n.useRef)(!1);return(0,n.useEffect)(()=>{let e=()=>{p(window.innerWidth>=1024)};return e(),window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[]),(0,n.useEffect)(()=>{if(r.length===1&&(document.title=`${r[0].content.substring(0,30)} - ${t.researchAgentUIConfig.appName}`),r[r.length-1]?.role===`user`){g.current=!0,h.current?.scrollIntoView({behavior:`auto`}),setTimeout(()=>{g.current=!1},100);return}},[r]),(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)(`div`,{className:`flex flex-col min-h-full transition-all duration-300`,style:f&&c?{width:`calc(100% - ${l}px)`}:{},children:[(0,d.jsxs)(`div`,{className:`flex-1 flex flex-col space-y-3 pb-48 ${f&&!c?`px-0 max-w-[800px] mx-auto w-full`:`px-4 lg:px-8`}`,children:[e.map((t,r)=>{let i=r===e.length-1;return(0,d.jsxs)(n.Fragment,{children:[(0,d.jsx)(_t,{section:t,sectionIndex:r,dividerRef:i?m:void 0,isLast:i}),!i&&(0,d.jsx)(`div`,{className:`h-px w-full bg-light-secondary dark:bg-dark-secondary`})]},t.userMessage.messageId)}),i&&!a&&(0,d.jsx)(`div`,{className:`flex items-center justify-center`,children:(0,d.jsx)(`div`,{style:{height:`200px`,width:`100%`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:(0,d.jsx)(x.default,{autoRandomize:!0,onSphereClick:()=>console.log(`Sphere clicked`),className:`my-custom-class`})})}),(0,d.jsx)(`div`,{ref:h,className:`h-0`})]}),(0,d.jsx)(`div`,{className:`sticky bottom-[60px] md:bottom-0 z-40 bg-gradient-to-t from-background via-background to-transparent pt-4 pb-2`,children:(0,d.jsx)(zt,{})})]}),(0,d.jsx)(mn,{})]})};function gn({radius:e=60,opacityDecay:t=.025,backgroundColor:r=`transparent`,color:i,colorGenerator:a}){let o=(0,n.useRef)(null),s=(0,n.useRef)({x:0,y:0}),c=(0,n.useRef)([]),l=()=>[Math.floor(Math.random()*130+10),Math.floor(.5*Math.random()*50),Math.floor(.5*Math.random()*255)],u=()=>i||a?.()||l();return(0,n.useEffect)(()=>{let n=o.current;if(!n)return;let i=n.getContext(`2d`);if(!i)return;let a=()=>{n.width=window.innerWidth,n.height=window.innerHeight};a();let l=()=>{i.globalCompositeOperation=`source-over`,r===`transparent`?i.clearRect(0,0,n.width,n.height):(i.fillStyle=r,i.fillRect(0,0,n.width,n.height)),i.globalCompositeOperation=`lighter`;let a={col:u(),x:s.current.x,y:s.current.y,grdblur:i.createRadialGradient(s.current.x,s.current.y,0,s.current.x,s.current.y,e),alpha:1};c.current.push(a);let o=[];for(let n=0;n<c.current.length;n++){let r=c.current[n];r.grdblur.addColorStop(0,`rgba(${r.col[0]},${r.col[1]},${r.col[2]},0.95)`),r.grdblur.addColorStop(.2,`rgba(${r.col[0]},${r.col[1]},${r.col[2]},0.7)`),r.grdblur.addColorStop(.5,`rgba(${r.col[0]},${r.col[1]},${r.col[2]},0.3)`),r.grdblur.addColorStop(1,`rgba(${r.col[0]},${r.col[1]},${r.col[2]},0)`),i.beginPath(),i.fillStyle=r.grdblur,i.globalAlpha=r.alpha,i.arc(r.x,r.y,e,0,Math.PI*2),i.fill(),r.alpha-=t,r.alpha<=0&&o.push(n)}for(let e=o.length-1;e>=0;e--)c.current.splice(o[e],1);i.globalAlpha=1,requestAnimationFrame(l)},d=e=>{s.current.x=e.pageX,s.current.y=e.pageY},f=e=>{s.current.x=e.touches[0].pageX,s.current.y=e.touches[0].pageY};return window.addEventListener(`mousemove`,d),window.addEventListener(`touchmove`,f,{passive:!0}),window.addEventListener(`resize`,a),l(),()=>{window.removeEventListener(`mousemove`,d),window.removeEventListener(`touchmove`,f),window.removeEventListener(`resize`,a)}},[e,t,r,i,a]),(0,d.jsx)(`div`,{className:`relative w-full h-screen overflow-hidden pointer-events-none`,children:(0,d.jsx)(`canvas`,{ref:o,className:`absolute inset-0`,style:{background:`transparent`}})})}var _n=`qwksearch_pinned_chats`;function vn(e){let t=e.messages?.[e.messages.length-1],n=t&&`createdAt`in t?t.createdAt:void 0;if(n){let e=new Date(n).getTime();if(!Number.isNaN(e))return new Date(e).toISOString()}return e.createdAt}function yn(){if(typeof window>`u`)return[];try{let e=localStorage.getItem(_n);return e?JSON.parse(e):[]}catch{return[]}}function bn(e){typeof window>`u`||localStorage.setItem(_n,JSON.stringify(e))}function xn(){let[e,t]=(0,n.useState)([]),[r,i]=(0,n.useState)(!0),[a,o]=(0,n.useState)(!1),[s,l]=(0,n.useState)(null),[u,d]=(0,n.useState)(!1),[f,m]=(0,n.useState)(!1),[h,g]=(0,n.useState)(!1),[_,v]=(0,n.useState)([]),[y,b]=(0,n.useState)(``),[x,S]=(0,n.useState)([]),[C,w]=(0,n.useState)(!1),{isAuthenticated:T,isLoading:E}=Ie(),{incognito:D,setIncognito:O}=K();(0,n.useEffect)(()=>{v(yn())},[]);let k=(0,n.useCallback)((e,t)=>{e.preventDefault(),e.stopPropagation(),v(e=>{let n=e.includes(t)?e.filter(e=>e!==t):[...e,t];return bn(n),n})},[]),A=(0,n.useMemo)(()=>[...e].sort((e,t)=>{let n=_.includes(e.id),r=_.includes(t.id);return n&&!r?-1:!n&&r?1:0}),[e,_]),j=(0,n.useMemo)(()=>y.trim()?x:A,[y,x,A]),M=(0,n.useCallback)(async()=>{if(!E){i(!0);try{if(T){let{data:e,error:n}=await(0,c.listChats)();if(n&&n.status===401){let e=ge().map(e=>({...e,messageCount:e.messages?.filter(e=>e.role===`user`).length??0,lastMessageAt:vn(e)}));t(e);return}if(n)throw Error(`Failed to fetch chats: ${n.message}`);t(Array.isArray(e?.chats)?e.chats:[])}else{let e=ge().map(e=>({...e,messageCount:e.messages?.filter(e=>e.role===`user`).length??0}));t(e)}}catch(e){console.error(`Failed to fetch chat history:`,e),t([]),p.toast.error(`Failed to load chat history`)}finally{i(!1)}}},[T,E]);(0,n.useEffect)(()=>{M()},[M]);let N=(e,t)=>{e.preventDefault(),e.stopPropagation(),l(t),o(!0)},P=async()=>{if(s){d(!0);try{if(T){let{error:e}=await(0,c.deleteChatById)({path:{id:s}});if(e)throw Error(`Failed to delete chat: ${e.message}`)}else ye(s);t(e=>e.filter(e=>e.id!==s)),p.toast.success(`Chat deleted`)}catch(e){p.toast.error(e.message||`Failed to delete chat`)}finally{o(!1),l(null),d(!1)}}},F=()=>{m(!0)},I=async()=>{g(!0);try{if(T){let{error:e}=await(0,c.deleteAllChats)();if(e)throw Error(`Failed to clear history: ${e.message}`)}else be();t([]),p.toast.success(`All history cleared`)}catch(e){p.toast.error(e.message||`Failed to clear history`)}finally{m(!1),g(!1)}},L=()=>{O(!D),p.toast.success(D?`Private mode off`:`Private mode on — messages won't be saved`)},R=(0,n.useCallback)(async e=>{if(!e.trim()){S([]),w(!1);return}w(!0);try{if(T){let{data:t,error:n}=await(0,c.searchChats)({query:{q:e}});if(n)throw Error(`Failed to search chats: ${n.message}`);S(Array.isArray(t?.chats)?t.chats:[])}else{let t=ge().filter(t=>{let n=t.title.toLowerCase().includes(e.toLowerCase()),r=t.messages?.some(t=>`content`in t&&t.content?.toLowerCase().includes(e.toLowerCase()));return n||r});S(t.map(e=>({...e,messageCount:e.messages?.filter(e=>e.role===`user`).length??0,lastMessageAt:vn(e)})))}}catch(e){console.error(`Failed to search chat history:`,e),S([]),p.toast.error(`Failed to search chat history`)}finally{w(!1)}},[T]);return(0,n.useEffect)(()=>{let e=setTimeout(()=>{R(y)},300);return()=>clearTimeout(e)},[y,R]),{chats:e,sortedChats:A,displayChats:j,loading:r,pinnedIds:_,togglePin:k,incognito:D,toggleIncognito:L,searchQuery:y,searchResults:x,searching:C,handleSearchChange:(0,n.useCallback)(e=>{b(e)},[]),deleteDialogOpen:a,setDeleteDialogOpen:o,chatToDelete:s,setChatToDelete:l,deleting:u,handleDeleteClick:N,handleConfirmDelete:P,clearAllDialogOpen:f,setClearAllDialogOpen:m,clearingAll:h,handleClearAllClick:F,handleConfirmClearAll:I}}function Sn({incognito:e,onToggleIncognito:t,showClearAll:n,onClearAll:r,searchQuery:i,onSearchChange:a}){return(0,d.jsxs)(`div`,{className:`mb-2 pb-2 border-b border-border space-y-2`,children:[(0,d.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,d.jsx)(`p`,{className:`text-xs font-medium text-muted-foreground/80 uppercase tracking-wide`,children:`Chat History`}),(0,d.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,d.jsxs)(`button`,{onClick:t,className:`flex items-center gap-1 px-2 py-1 text-xs rounded-lg transition-colors duration-200 ${e?`text-primary bg-primary/10`:`text-muted-foreground hover:text-foreground hover:bg-secondary`}`,title:e?`Private mode on`:`Private mode`,children:[(0,d.jsx)(s.Lock,{size:12}),(0,d.jsx)(`span`,{children:`Private`})]}),n&&(0,d.jsxs)(`button`,{onClick:r,className:`flex items-center gap-1 px-2 py-1 text-xs text-muted-foreground hover:text-red-500 hover:bg-red-500/10 rounded-lg transition-colors duration-200`,title:`Clear all history`,children:[(0,d.jsx)(s.Trash2,{size:12}),(0,d.jsx)(`span`,{children:`Clear All`})]})]})]}),(0,d.jsxs)(`div`,{className:`relative`,children:[(0,d.jsx)(s.Search,{className:`absolute left-2 top-1/2 -translate-y-1/2 text-muted-foreground`,size:14}),(0,d.jsx)(`input`,{type:`text`,placeholder:`Search chats...`,value:i,onChange:e=>a(e.target.value),className:`w-full pl-7 pr-7 py-1.5 text-sm bg-secondary/50 border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 placeholder:text-muted-foreground/50`}),i&&(0,d.jsx)(`button`,{onClick:()=>a(``),className:`absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground`,children:(0,d.jsx)(s.X,{size:14})})]})]})}function Cn({chat:e,isPinned:t,onTogglePin:n,onDelete:r}){let i=e.messageCount??0;return(0,d.jsxs)(`div`,{className:`group flex items-center gap-1 px-2 py-1 rounded-lg hover:bg-secondary transition-colors duration-200`,children:[(0,d.jsxs)(w.default,{href:`/c/${e.id}`,className:`flex-1 min-w-0 flex items-center gap-1.5`,children:[(0,d.jsxs)(`span`,{className:`flex items-center gap-1 shrink-0`,children:[i>0&&(0,d.jsxs)(ht,{className:`px-1.5 py-0 text-[10px] font-medium bg-zinc-200 text-zinc-700 hover:bg-zinc-200 dark:bg-zinc-700 dark:text-zinc-300 dark:hover:bg-zinc-700 border-0 rounded-md`,children:[i,`Q`]}),(0,d.jsx)(ht,{className:`px-1.5 py-0 text-[10px] font-medium bg-zinc-100 text-zinc-500 hover:bg-zinc-100 dark:bg-zinc-800 dark:text-zinc-400 dark:hover:bg-zinc-800 border-0 rounded-md`,children:O(new Date,e.createdAt)})]}),(0,d.jsxs)(`p`,{className:`text-xs text-popover-foreground truncate`,children:[t&&(0,d.jsx)(s.Pin,{size:10,className:`inline mr-1 text-primary`}),e.title]})]}),(0,d.jsx)(`button`,{onClick:t=>n(t,e.id),className:`p-1.5 rounded-lg transition-all duration-200 ${t?`opacity-100 text-primary hover:bg-primary/10`:`opacity-0 group-hover:opacity-100 text-muted-foreground hover:text-primary hover:bg-primary/10`}`,title:t?`Unpin chat`:`Pin chat`,children:(0,d.jsx)(s.Pin,{size:14})}),(0,d.jsx)(`button`,{onClick:t=>r(t,e.id),className:`opacity-0 group-hover:opacity-100 p-1.5 rounded-lg hover:bg-red-500/10 text-muted-foreground hover:text-red-500 transition-all duration-200`,title:`Delete chat`,children:(0,d.jsx)(s.Trash,{size:14})})]})}function wn({open:e,onOpenChange:t,title:n,description:r,confirmLabel:i,loadingLabel:a,loading:o,onConfirm:s}){return(0,d.jsx)(Bt,{open:e,onOpenChange:e=>{!e&&!o&&t(!1)},children:(0,d.jsxs)(Wt,{className:`w-full max-w-md transform rounded-2xl bg-light-secondary dark:bg-dark-secondary border border-light-200 dark:border-dark-200 p-6 text-left align-middle shadow-xl`,children:[(0,d.jsx)(Gt,{className:`text-lg font-medium leading-6 dark:text-white`,children:n}),(0,d.jsx)(Kt,{className:`text-sm dark:text-white/70 text-black/70 mt-2`,children:r}),(0,d.jsxs)(`div`,{className:`flex flex-row items-end justify-end space-x-4 mt-6`,children:[(0,d.jsx)(`button`,{onClick:()=>{o||t(!1)},className:`text-black/50 dark:text-white/50 text-sm hover:text-black/70 hover:dark:text-white/70 transition duration-200`,children:`Cancel`}),(0,d.jsx)(`button`,{onClick:s,disabled:o,className:`text-red-400 text-sm hover:text-red-500 transition duration-200 disabled:opacity-50`,children:o?a:i})]})]})})}function Tn({deleteDialogOpen:e,setDeleteDialogOpen:t,chatToDelete:n,setChatToDelete:r,deleting:i,onConfirmDelete:a,clearAllDialogOpen:o,setClearAllDialogOpen:s,clearingAll:c,onConfirmClearAll:l}){return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(wn,{open:e,onOpenChange:e=>{t(e),e||r(null)},title:`Delete Confirmation`,description:`Are you sure you want to delete this chat?`,confirmLabel:`Delete`,loadingLabel:`Deleting...`,loading:i,onConfirm:a}),(0,d.jsx)(wn,{open:o,onOpenChange:s,title:`Clear All History`,description:`Are you sure you want to delete all your chat history? This action cannot be undone.`,confirmLabel:`Clear All`,loadingLabel:`Clearing...`,loading:c,onConfirm:l})]})}var En={Today:(0,d.jsx)(s.Sun,{size:12}),Yesterday:(0,d.jsx)(s.Clock,{size:12}),"This Week":(0,d.jsx)(s.CalendarDays,{size:12}),Older:(0,d.jsx)(s.Archive,{size:12})};function Dn(e){let t=new Date,n=new Date(t.getFullYear(),t.getMonth(),t.getDate()),r=new Date(n.getTime()-864e5),i=new Date(n.getTime()-6*864e5),a={Today:[],Yesterday:[],"This Week":[],Older:[]};for(let t of e){let e=new Date(t.createdAt);e>=n?a.Today.push(t):e>=r?a.Yesterday.push(t):e>=i?a[`This Week`].push(t):a.Older.push(t)}return[`Today`,`Yesterday`,`This Week`,`Older`].filter(e=>a[e].length>0).map(e=>({label:e,chats:a[e]}))}var On=({showLabel:e=!1})=>{let t=xn();return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)(Bt,{children:[(0,d.jsxs)(Vt,{className:e?`inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs text-muted-foreground bg-secondary hover:bg-secondary/80 hover:text-foreground transition-colors duration-150`:`p-2 text-muted-foreground rounded-2xl bg-background/60 backdrop-blur-md hover:bg-secondary/80 transition duration-200 hover:text-foreground border border-border/30`,children:[(0,d.jsx)(s.History,{size:e?14:18}),e&&(0,d.jsx)(`span`,{children:`History`})]}),(0,d.jsxs)(Wt,{className:`max-w-[420px] p-3`,children:[(0,d.jsx)(Gt,{className:`sr-only`,children:`Chat History`}),(0,d.jsx)(Sn,{incognito:t.incognito,onToggleIncognito:t.toggleIncognito,showClearAll:t.chats.length>0&&!t.loading,onClearAll:t.handleClearAllClick,searchQuery:t.searchQuery,onSearchChange:t.handleSearchChange}),t.loading||t.searching?(0,d.jsx)(`div`,{className:`flex items-center justify-center py-8`,children:(0,d.jsxs)(`svg`,{"aria-hidden":`true`,className:`w-6 h-6 text-light-200 fill-light-secondary dark:text-[#202020] animate-spin dark:fill-[#ffffff3b]`,viewBox:`0 0 100 101`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,d.jsx)(`path`,{d:`M100 50.5908C100.003 78.2051 78.1951 100.003 50.5908 100C22.9765 99.9972 0.997224 78.018 1 50.4037C1.00281 22.7993 22.8108 0.997224 50.4251 1C78.0395 1.00281 100.018 22.8108 100 50.4251ZM9.08164 50.594C9.06312 73.3997 27.7909 92.1272 50.5966 92.1457C73.4023 92.1642 92.1298 73.4365 92.1483 50.6308C92.1669 27.8251 73.4392 9.0973 50.6335 9.07878C27.8278 9.06026 9.10003 27.787 9.08164 50.594Z`,fill:`currentColor`}),(0,d.jsx)(`path`,{d:`M93.9676 39.0409C96.393 38.4037 97.8624 35.9116 96.9801 33.5533C95.1945 28.8227 92.871 24.3692 90.0681 20.348C85.6237 14.1775 79.4473 9.36872 72.0454 6.45794C64.6435 3.54717 56.3134 2.65431 48.3133 3.89319C45.869 4.27179 44.3768 6.77534 45.014 9.20079C45.6512 11.6262 48.1343 13.0956 50.5786 12.717C56.5073 11.8281 62.5542 12.5399 68.0406 14.7911C73.527 17.0422 78.2187 20.7487 81.5841 25.4923C83.7976 28.5886 85.4467 32.059 86.4416 35.7474C87.1273 38.1189 89.5423 39.6781 91.9676 39.0409Z`,fill:`currentFill`})]})}):t.searchQuery.trim()&&t.displayChats.length===0?(0,d.jsx)(`div`,{className:`flex items-center justify-center py-8`,children:(0,d.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No matching chats found.`})}):t.chats.length===0?(0,d.jsx)(`div`,{className:`flex items-center justify-center py-8`,children:(0,d.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No chats found.`})}):(0,d.jsx)(`div`,{className:`space-y-1 max-h-[500px] overflow-y-auto`,children:t.searchQuery.trim()?t.displayChats.map(e=>(0,d.jsx)(Cn,{chat:e,isPinned:t.pinnedIds.includes(e.id),onTogglePin:t.togglePin,onDelete:t.handleDeleteClick},e.id)):Dn(t.displayChats).map(({label:e,chats:n})=>(0,d.jsxs)(`div`,{children:[(0,d.jsxs)(`div`,{className:`flex items-center gap-1.5 px-3 py-1.5 text-xs font-semibold text-muted-foreground/70 uppercase tracking-wider`,children:[En[e],e]}),n.map(e=>(0,d.jsx)(Cn,{chat:e,isPinned:t.pinnedIds.includes(e.id),onTogglePin:t.togglePin,onDelete:t.handleDeleteClick},e.id))]},e))}),t.chats.length>0&&(0,d.jsx)(`div`,{className:`mt-2 pt-2 border-t border-border`,children:(0,d.jsx)(w.default,{href:`/library`,className:`block text-center text-xs text-primary hover:underline`,children:`View all chats`})})]})]}),(0,d.jsx)(Tn,{deleteDialogOpen:t.deleteDialogOpen,setDeleteDialogOpen:t.setDeleteDialogOpen,chatToDelete:t.chatToDelete,setChatToDelete:t.setChatToDelete,deleting:t.deleting,onConfirmDelete:t.handleConfirmDelete,clearAllDialogOpen:t.clearAllDialogOpen,setClearAllDialogOpen:t.setClearAllDialogOpen,clearingAll:t.clearingAll,onConfirmClearAll:t.handleConfirmClearAll})]})};function kn(e){let t=new Date(e).getTime();if(Number.isNaN(t))return``;let n=Math.round((Date.now()-t)/1e3);if(n<5)return`just now`;if(n<60)return`${n} sec ago`;let r=Math.round(n/60);if(r<60)return`${r} min ago`;let i=Math.round(r/60);if(i<24)return`${i} hr ago`;let a=Math.round(i/24);if(a<7)return`${a} day${a===1?``:`s`} ago`;let o=Math.round(a/7);if(o<5)return`${o} week${o===1?``:`s`} ago`;let s=Math.round(a/30);if(s<12)return`${s} month${s===1?``:`s`} ago`;let c=Math.round(a/365);return`${c} year${c===1?``:`s`} ago`}var An=e=>new Date(e.lastMessageAt||e.createdAt).getTime();function jn(){let{chats:e,loading:t}=xn(),n=[...e].sort((e,t)=>An(t)-An(e)).slice(0,5);if(t||n.length===0)return null;let r=kn(n[0].lastMessageAt||n[0].createdAt);return(0,d.jsxs)(`div`,{className:`flex flex-row items-center justify-center gap-2 flex-wrap`,children:[(0,d.jsx)(On,{showLabel:!0}),n.map(e=>(0,d.jsx)(w.default,{href:`/c/${e.id}`,className:`px-3 py-1 rounded-full text-xs text-muted-foreground bg-secondary hover:bg-secondary/80 hover:text-foreground transition-colors duration-150 truncate max-w-[160px]`,title:e.title,children:e.title},e.id)),r&&(0,d.jsx)(`span`,{className:`text-xs text-muted-foreground/70 whitespace-nowrap`,children:r})]})}function Mn({listFooterLinks:e=[],optionShowIcons:t=!0,optionBackgroundColor:r=`bg-black/40`}){let[i,a]=(0,n.useState)(!1),o=(0,n.useRef)(null);(0,n.useEffect)(()=>{if(!i)return;let e=e=>{o.current&&!o.current.contains(e.target)&&a(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[i]);let c=()=>e.map(({url:e,text:n,icon:r})=>{let i=r?s[r]:null,a=e.startsWith(`http`),o=a?{target:`_blank`,rel:`noopener noreferrer`}:{},c=(0,d.jsxs)(d.Fragment,{children:[t&&i&&(0,d.jsx)(i,{size:14}),(0,d.jsx)(`span`,{className:`font-semibold tracking-wide text-md`,style:{fontVariant:`small-caps`},children:n}),(0,d.jsx)(`span`,{className:`absolute bottom-0 left-0 w-0 h-0.5 bg-current transition-all duration-300 group-hover:w-full group-hover:shadow-[0_0_8px_rgba(255,255,255,0.6)]`})]});return a?(0,d.jsx)(`a`,{href:e,...o,className:`relative group inline-flex items-center gap-1 hover:text-white hover:drop-shadow-[0_0_8px_rgba(255,255,255,0.8)] transition-all duration-300 whitespace-nowrap`,children:c},e):(0,d.jsx)(w.default,{href:e,className:`relative group inline-flex items-center gap-1 hover:text-white hover:drop-shadow-[0_0_8px_rgba(255,255,255,0.8)] transition-all duration-300 whitespace-nowrap`,children:c},e)}),l=s.Info;return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(`div`,{className:`hidden md:flex absolute bottom-2 left-1/2 -translate-x-1/2 text-slate-200 text-xs z-20 ${r} rounded-lg px-2 py-1 shadow-lg hover:shadow-xl hover:-translate-y-1 transition-all duration-300 flex-wrap items-center justify-center gap-x-6 max-w-[90vw]`,children:(0,d.jsx)(`div`,{className:`max-w-4xl mx-auto grid grid-cols-3 gap-2`,children:c()})}),(0,d.jsxs)(`div`,{ref:o,className:`md:hidden fixed top-[calc(8px+env(safe-area-inset-top,0px))] right-2 z-30`,children:[i&&(0,d.jsx)(`div`,{className:`absolute top-full right-0 mt-2 text-slate-200 text-xs ${r} rounded-lg px-3 py-2 shadow-lg flex flex-col items-start gap-2 backdrop-blur-sm`,children:c()}),(0,d.jsx)(`button`,{type:`button`,onClick:()=>a(e=>!e),"aria-label":i?`Hide links`:`Show links`,"aria-expanded":i,className:`flex items-center justify-center h-8 w-8 rounded-full text-slate-200 ${r} shadow-lg backdrop-blur-sm hover:text-white transition-all duration-300`,children:l?(0,d.jsx)(l,{size:16}):`i`})]})]})}function Nn(){let e=`hyZbH3n.mp4,iOeZcCk.mp4,dUZlxYE.mp4,GpWeP6E.gif,LuKUsLE.png,w7X11Dd.png,MHmVtCr.png,HmnUAee.png,vKP22VU.png,l1lsV39.png,Ku8F2qc.png,KUEXtwm.png,vvKFPmY.png,5p8eaEf.png,VAKuJcG.png,sTMPtQW.png,m0gHbZZ.png,cKu7dWQ.png,ogfefYD.png,ey5vAae.png,twuLrvk.png,ELILiYt.png,9el5qpP.png,Up6xTkk.png,W1XKBo0.png,1Y6xvW0.png,JXOytMz.png,DNiI6pp.png,XDv5s6p.jpeg,eRwiRJ9.jpeg,DRAfJoc.jpeg,ASVRQ1G.jpeg,35svwUT.jpeg,81xLiVI.jpeg,6kod2Em.jpeg,eU0C8zt.jpeg,Bv0PBY8.jpeg,DQNbjIZ.jpeg,2uACPqZ.jpeg,XEKltMF.jpeg,WHgLfBm.jpeg,QFYM0Fw.jpeg,K12HCao.jpeg,oN8rtsE.jpeg,9fGnrns.jpeg,2ONJJeW.jpeg,DO23Va7.jpeg,QaKeoXk.jpeg,QU5oCBR.jpeg,MhlYZmh.jpeg,ylL1ToB.jpeg,AWWsCv8.jpeg,Tk9Tzzj.jpeg`.split(`,`);return`https://i.imgur.com/`+e[Math.floor(Math.random()*e.length)]}function Pn(){let{sendMessage:e}=K(),[r,i]=(0,n.useState)(null),[a,o]=(0,n.useState)(null),[s,c]=(0,n.useState)(!1),[l,u]=(0,n.useState)({os:``});(0,n.useEffect)(()=>{if(localStorage.getItem(`showBackgroundArt`)===`false`)return;i(Nn());let e=setInterval(()=>{let e=Nn();o(e),c(!0),setTimeout(()=>{i(e),c(!1),o(null)},1e3)},2e4);return()=>clearInterval(e)},[]),(0,n.useEffect)(()=>{if(typeof window<`u`){let e=window.navigator.userAgent.toLowerCase();e.includes(`win`)?u({os:`Windows`}):e.includes(`mac`)?u({os:`MacOS`}):u({os:`Other`})}},[]);let f=e=>e.endsWith(`.webm`)||e.endsWith(`.mp4`),p=(e,t)=>f(e)?(0,d.jsx)(`video`,{src:e,autoPlay:!0,loop:!0,muted:!0,playsInline:!0,className:`absolute inset-0 w-full h-full object-cover transition-opacity duration-1000 ${t}`},e):(0,d.jsx)(`img`,{src:e,alt:``,className:`absolute inset-0 w-full h-full object-cover transition-opacity duration-1000 ${t}`},e);return(0,d.jsxs)(`div`,{className:`relative min-h-screen w-full`,children:[(0,d.jsxs)(`div`,{className:`fixed inset-0 z-0`,children:[r&&p(r,s?`opacity-0`:`opacity-30`),a&&p(a,s?`opacity-30`:`opacity-0`),(0,d.jsx)(gn,{})]}),(0,d.jsx)(`div`,{className:`relative z-10`,children:(0,d.jsxs)(`div`,{className:`flex flex-col items-center justify-end md:justify-center min-h-[calc(100dvh-64px)] md:min-h-screen max-w-screen-sm mx-auto p-2 pb-1 md:pb-2`,children:[(0,d.jsx)(`div`,{style:{height:`200px`,width:`100%`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:(0,d.jsx)(x.default,{autoRandomize:!0,onSphereClick:()=>console.log(`Sphere clicked`),className:`my-custom-class`})}),(0,d.jsxs)(`p`,{className:`text-lg text-gray-500 text-center justify-center mt-4`,children:[(0,d.jsx)(`a`,{"aria-label":`Chrome Web Store`,className:`download-chrome download-btn text-center justify-center`,target:`_blank`,href:t.researchAgentUIConfig.downloadChromeUrl}),(0,d.jsx)(`a`,{"aria-label":`Microsoft Store`,className:`download-windows download-btn text-center justify-center`,target:`_blank`,href:l.os==`Windows`?`ms-windows-store://pdp/?productid=${t.researchAgentUIConfig.downloadWindowsStoreId}`:`https://apps.microsoft.com/detail/${t.researchAgentUIConfig.downloadWindowsStoreId}?rtc=1`})]}),(0,d.jsxs)(`div`,{className:`w-full max-w-2xl mt-8 space-y-2`,children:[(0,d.jsx)(jn,{}),(0,d.jsx)(zt,{})]})]})}),(0,d.jsx)(Mn,{listFooterLinks:t.researchAgentUIConfig.footerLinks})]})}var Fn=()=>(0,d.jsxs)(`svg`,{"aria-hidden":`true`,className:`w-8 h-8 text-border fill-secondary animate-spin`,viewBox:`0 0 100 101`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,d.jsx)(`path`,{d:`M100 50.5908C100.003 78.2051 78.1951 100.003 50.5908 100C22.9765 99.9972 0.997224 78.018 1 50.4037C1.00281 22.7993 22.8108 0.997224 50.4251 1C78.0395 1.00281 100.018 22.8108 100 50.4251ZM9.08164 50.594C9.06312 73.3997 27.7909 92.1272 50.5966 92.1457C73.4023 92.1642 92.1298 73.4365 92.1483 50.6308C92.1669 27.8251 73.4392 9.0973 50.6335 9.07878C27.8278 9.06026 9.10003 27.787 9.08164 50.594Z`,fill:`currentColor`}),(0,d.jsx)(`path`,{d:`M93.9676 39.0409C96.393 38.4037 97.8624 35.9116 96.9801 33.5533C95.1945 28.8227 92.871 24.3692 90.0681 20.348C85.6237 14.1775 79.4473 9.36872 72.0454 6.45794C64.6435 3.54717 56.3134 2.65431 48.3133 3.89319C45.869 4.27179 44.3768 6.77534 45.014 9.20079C45.6512 11.6262 48.1343 13.0956 50.5786 12.717C56.5073 11.8281 62.5542 12.5399 68.0406 14.7911C73.527 17.0422 78.2187 20.7487 81.5841 25.4923C83.7976 28.5886 85.4467 32.059 86.4416 35.7474C87.1273 38.1189 89.5423 39.6781 91.9676 39.0409Z`,fill:`currentFill`})]});function In(){return(0,d.jsx)(`div`,{className:`flex min-h-screen flex-col items-center justify-center p-8`,children:(0,d.jsxs)(`div`,{className:`max-w-2xl w-full space-y-6 bg-light-secondary dark:bg-dark-secondary rounded-lg p-8 border border-black/10 dark:border-white/10`,children:[(0,d.jsxs)(`div`,{className:`space-y-2`,children:[(0,d.jsx)(`h1`,{className:`text-2xl font-semibold text-black dark:text-white`,children:`⚠️ Configuration Required`}),(0,d.jsx)(`p`,{className:`text-black/70 dark:text-white/70`,children:`No AI model providers are configured. Add at least one API key to continue.`})]}),(0,d.jsxs)(`div`,{className:`space-y-4`,children:[(0,d.jsx)(`h2`,{className:`text-lg font-medium text-black dark:text-white`,children:`Quick Setup:`}),(0,d.jsxs)(`div`,{className:`space-y-3 text-sm`,children:[(0,d.jsxs)(`div`,{className:`bg-black/5 dark:bg-white/5 rounded p-4`,children:[(0,d.jsx)(`p`,{className:`font-medium text-black dark:text-white mb-2`,children:`1. Create environment file:`}),(0,d.jsx)(`code`,{className:`block bg-black/10 dark:bg-white/10 rounded p-2 text-xs overflow-x-auto`,children:`apps/qwksearch-web/.env.local`})]}),(0,d.jsxs)(`div`,{className:`bg-black/5 dark:bg-white/5 rounded p-4`,children:[(0,d.jsx)(`p`,{className:`font-medium text-black dark:text-white mb-2`,children:`2. Add required variables:`}),(0,d.jsx)(`pre`,{className:`block bg-black/10 dark:bg-white/10 rounded p-3 text-xs overflow-x-auto text-black/80 dark:text-white/80`,children:`# Database
|
|
33
|
+
`);if(!r||r.length===0)throw Error(`Article content is empty`);let{data:t,error:i}=await(0,c.articleQa)({body:{article:r,question:e,chatHistory:b.slice(-5),chatModel:n}});if(i){let e=i.details||i.error||i.message||`Article QA failed`;throw Error(e)}let a=t?.content||``;P(a),x(e=>[...e,{role:`user`,content:w,time:new Date().toISOString()},{role:`assistant`,content:a,time:new Date().toISOString()}]);try{await(0,c.updateArticle)({body:{url:g,question:w,answer:a}})}catch(e){console.error(`Error storing Q&A in cache:`,e)}}else{let e=parseInt(localStorage.getItem(`maxFollowupQuestions`)||`4`);if(!r||r.length===0)throw Error(`Article content is empty`);let{data:t,error:i}=await(0,c.articleFollowups)({body:{article:r,chatHistory:b.slice(-5),maxQuestions:e,chatModel:n}});if(i){let e=i.details||i.error||i.message||`Article followups failed`;throw Error(e)}let a=t?.extract||[];R(a);try{await(0,c.updateArticle)({body:{url:g,followUpQuestions:a}})}catch(e){console.error(`Error storing follow-up questions in cache:`,e)}}}catch(e){console.error(`Error calling language API:`,e),o(e instanceof Error||typeof e==`object`&&e&&`message`in e?e.message:`Failed to get AI response`)}finally{a(!1)}},we=e=>{T(e),Ce(`question`)},Te=async()=>{if(!v)return;let e=`${N}\n\n\n${v.cite||``}\n\n\n${v.html}`;try{await navigator.clipboard.writeText(e),C(!0),setTimeout(()=>C(!1),2e3)}catch(e){console.error(`Failed to copy to clipboard:`,e)}},Ee=()=>(0,d.jsxs)(`div`,{className:`flex h-full flex-col bg-background shadow-xl`,children:[(0,d.jsx)(`div`,{className:`shrink-0 border-b border-border bg-background/95 px-4 py-3 backdrop-blur supports-[backdrop-filter]:bg-background/80`,children:(0,d.jsx)(Zt,{isLoadingAI:O,isLoadingFollowups:A,isLoadingFavorite:te,isFavorited:ee,isHighlightMode:U,articleUrl:v?.url||g,fontScale:W,onAskClick:()=>Ce(`question`),onSuggestClick:()=>Ce(`suggest-followups`),onCopyClick:Te,onFavoriteClick:xe,onHighlightToggle:()=>ne(!U),onZoomIn:ge,onZoomOut:_e,onZoomReset:ve,onClose:h})}),(0,d.jsx)(`div`,{className:`flex-1 overflow-y-auto`,children:(0,d.jsxs)(`div`,{className:`p-4 space-y-6`,children:[(0,d.jsxs)(`div`,{className:`space-y-4`,children:[S&&(0,d.jsx)(`div`,{className:`bg-blue-500 text-white text-sm font-medium px-3 py-2 rounded-md shadow-lg`,children:`Copied!`}),(0,d.jsx)(Qt,{value:w,onChange:T,onSubmit:()=>Ce(`question`)}),(0,d.jsx)($t,{questions:L,isLoading:A,error:z,onQuestionClick:we}),b.length>0&&(0,d.jsx)(`div`,{className:`space-y-4`,children:b.map((e,t)=>(0,d.jsx)(`div`,{className:`space-y-2`,children:e.role===`user`?(0,d.jsxs)(`div`,{className:`bg-primary/10 border border-primary/20 rounded-lg p-3`,children:[(0,d.jsx)(`div`,{className:`text-xs font-semibold text-primary mb-1`,children:`Your Question`}),(0,d.jsx)(`div`,{className:`text-sm text-foreground`,children:e.content})]}):(0,d.jsxs)(`div`,{className:`bg-muted rounded-lg shadow-md p-4`,children:[(0,d.jsx)(`div`,{className:`text-xs font-semibold text-muted-foreground mb-2`,children:`AI Response`}),(0,d.jsx)(`div`,{className:`text-sm`,dangerouslySetInnerHTML:{__html:e.content}})]})},t))}),(O||N&&b.length===0)&&(0,d.jsx)(en,{response:N,isLoading:O,error:F}),F&&!O&&(0,d.jsx)(`div`,{className:`bg-red-500 text-white p-2 rounded-md text-sm`,children:F})]}),v&&(0,d.jsx)(nn,{article:v,isHighlightMode:U,fontScale:W})]})})]});return!m||!le?null:re?(0,d.jsxs)(`div`,{className:`fixed top-0 right-0 h-screen z-40 transition-all duration-300`,style:{width:`${ae}px`},children:[(0,d.jsx)(`div`,{ref:fe,onMouseDown:()=>ce(!0),className:`absolute left-0 top-0 bottom-0 w-1 cursor-ew-resize hover:bg-primary bg-transparent transition-colors z-50`,style:{touchAction:`none`},children:(0,d.jsx)(`div`,{className:`absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 w-1 h-12 rounded-full bg-muted-foreground opacity-50 hover:opacity-100 transition-opacity`})}),Ee()]}):(0,d.jsx)(Bt,{open:m,onOpenChange:e=>!e&&h(),children:(0,d.jsxs)(Wt,{className:`pointer-events-auto fixed inset-0 !top-0 !left-0 !translate-x-0 !translate-y-0 h-full w-full max-w-none p-0 m-0 rounded-none border-0 overflow-hidden data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right`,hideCloseButton:!0,children:[(0,d.jsx)(qt,{children:(0,d.jsx)(Gt,{children:`Article Details`})}),(0,d.jsx)(`div`,{className:`h-full overflow-y-auto`,children:Ee()})]})})},hn=()=>{let{sections:e,chatTurns:r,loading:i,messageAppeared:a,newChat:o,chatId:s}=K(),{isOpen:c,panelWidth:l}=j(),{isAuthenticated:u}=Ie(),[f,p]=(0,n.useState)(!1),m=(0,n.useRef)(null),h=(0,n.useRef)(null),g=(0,n.useRef)(!1);return(0,n.useEffect)(()=>{let e=()=>{p(window.innerWidth>=1024)};return e(),window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[]),(0,n.useEffect)(()=>{if(r.length===1&&(document.title=`${r[0].content.substring(0,30)} - ${t.researchAgentUIConfig.appName}`),r[r.length-1]?.role===`user`){g.current=!0,h.current?.scrollIntoView({behavior:`auto`}),setTimeout(()=>{g.current=!1},100);return}},[r]),(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)(`div`,{className:`flex flex-col min-h-full transition-all duration-300`,style:f&&c?{width:`calc(100% - ${l}px)`}:{},children:[(0,d.jsxs)(`div`,{className:`flex-1 flex flex-col space-y-3 pb-48 ${f&&!c?`px-0 max-w-[800px] mx-auto w-full`:`px-4 lg:px-8`}`,children:[e.map((t,r)=>{let i=r===e.length-1;return(0,d.jsxs)(n.Fragment,{children:[(0,d.jsx)(_t,{section:t,sectionIndex:r,dividerRef:i?m:void 0,isLast:i}),!i&&(0,d.jsx)(`div`,{className:`h-px w-full bg-light-secondary dark:bg-dark-secondary`})]},t.userMessage.messageId)}),i&&!a&&(0,d.jsx)(`div`,{className:`flex items-center justify-center`,children:(0,d.jsx)(`div`,{style:{height:`200px`,width:`100%`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:(0,d.jsx)(x.default,{autoRandomize:!0,onSphereClick:()=>console.log(`Sphere clicked`),className:`my-custom-class`})})}),(0,d.jsx)(`div`,{ref:h,className:`h-0`})]}),(0,d.jsx)(`div`,{className:`sticky bottom-[60px] md:bottom-0 z-40 bg-gradient-to-t from-background via-background to-transparent pt-4 pb-2`,children:(0,d.jsx)(zt,{})})]}),(0,d.jsx)(mn,{})]})};function gn({radius:e=60,opacityDecay:t=.025,backgroundColor:r=`transparent`,color:i,colorGenerator:a}){let o=(0,n.useRef)(null),s=(0,n.useRef)({x:0,y:0}),c=(0,n.useRef)([]),l=()=>[Math.floor(Math.random()*130+10),Math.floor(.5*Math.random()*50),Math.floor(.5*Math.random()*255)],u=()=>i||a?.()||l();return(0,n.useEffect)(()=>{let n=o.current;if(!n)return;let i=n.getContext(`2d`);if(!i)return;let a=()=>{n.width=window.innerWidth,n.height=window.innerHeight};a();let l=()=>{i.globalCompositeOperation=`source-over`,r===`transparent`?i.clearRect(0,0,n.width,n.height):(i.fillStyle=r,i.fillRect(0,0,n.width,n.height)),i.globalCompositeOperation=`lighter`;let a={col:u(),x:s.current.x,y:s.current.y,grdblur:i.createRadialGradient(s.current.x,s.current.y,0,s.current.x,s.current.y,e),alpha:1};c.current.push(a);let o=[];for(let n=0;n<c.current.length;n++){let r=c.current[n];r.grdblur.addColorStop(0,`rgba(${r.col[0]},${r.col[1]},${r.col[2]},0.95)`),r.grdblur.addColorStop(.2,`rgba(${r.col[0]},${r.col[1]},${r.col[2]},0.7)`),r.grdblur.addColorStop(.5,`rgba(${r.col[0]},${r.col[1]},${r.col[2]},0.3)`),r.grdblur.addColorStop(1,`rgba(${r.col[0]},${r.col[1]},${r.col[2]},0)`),i.beginPath(),i.fillStyle=r.grdblur,i.globalAlpha=r.alpha,i.arc(r.x,r.y,e,0,Math.PI*2),i.fill(),r.alpha-=t,r.alpha<=0&&o.push(n)}for(let e=o.length-1;e>=0;e--)c.current.splice(o[e],1);i.globalAlpha=1,requestAnimationFrame(l)},d=e=>{s.current.x=e.pageX,s.current.y=e.pageY},f=e=>{s.current.x=e.touches[0].pageX,s.current.y=e.touches[0].pageY};return window.addEventListener(`mousemove`,d),window.addEventListener(`touchmove`,f,{passive:!0}),window.addEventListener(`resize`,a),l(),()=>{window.removeEventListener(`mousemove`,d),window.removeEventListener(`touchmove`,f),window.removeEventListener(`resize`,a)}},[e,t,r,i,a]),(0,d.jsx)(`div`,{className:`relative w-full h-screen overflow-hidden pointer-events-none`,children:(0,d.jsx)(`canvas`,{ref:o,className:`absolute inset-0`,style:{background:`transparent`}})})}var _n=`qwksearch_pinned_chats`;function vn(e){let t=e.messages?.[e.messages.length-1],n=t&&`createdAt`in t?t.createdAt:void 0;if(n){let e=new Date(n).getTime();if(!Number.isNaN(e))return new Date(e).toISOString()}return e.createdAt}function yn(){if(typeof window>`u`)return[];try{let e=localStorage.getItem(_n);return e?JSON.parse(e):[]}catch{return[]}}function bn(e){typeof window>`u`||localStorage.setItem(_n,JSON.stringify(e))}function xn(){let[e,t]=(0,n.useState)([]),[r,i]=(0,n.useState)(!0),[a,o]=(0,n.useState)(!1),[s,l]=(0,n.useState)(null),[u,d]=(0,n.useState)(!1),[f,m]=(0,n.useState)(!1),[h,g]=(0,n.useState)(!1),[_,v]=(0,n.useState)([]),[y,b]=(0,n.useState)(``),[x,S]=(0,n.useState)([]),[C,w]=(0,n.useState)(!1),{isAuthenticated:T,isLoading:E}=Ie(),{incognito:D,setIncognito:O}=K();(0,n.useEffect)(()=>{v(yn())},[]);let k=(0,n.useCallback)((e,t)=>{e.preventDefault(),e.stopPropagation(),v(e=>{let n=e.includes(t)?e.filter(e=>e!==t):[...e,t];return bn(n),n})},[]),A=(0,n.useMemo)(()=>[...e].sort((e,t)=>{let n=_.includes(e.id),r=_.includes(t.id);return n&&!r?-1:!n&&r?1:0}),[e,_]),j=(0,n.useMemo)(()=>y.trim()?x:A,[y,x,A]),M=(0,n.useCallback)(async()=>{if(!E){i(!0);try{if(T){let{data:e,error:n}=await(0,c.listChats)();if(n&&n.status===401){let e=ge().map(e=>({...e,messageCount:e.messages?.filter(e=>e.role===`user`).length??0,lastMessageAt:vn(e)}));t(e);return}if(n)throw Error(`Failed to fetch chats: ${n.message}`);t(Array.isArray(e?.chats)?e.chats:[])}else{let e=ge().map(e=>({...e,messageCount:e.messages?.filter(e=>e.role===`user`).length??0}));t(e)}}catch(e){console.error(`Failed to fetch chat history:`,e),t([]),p.toast.error(`Failed to load chat history`)}finally{i(!1)}}},[T,E]);(0,n.useEffect)(()=>{M()},[M]);let N=(e,t)=>{e.preventDefault(),e.stopPropagation(),l(t),o(!0)},P=async()=>{if(s){d(!0);try{if(T){let{error:e}=await(0,c.deleteChatById)({path:{id:s}});if(e)throw Error(`Failed to delete chat: ${e.message}`)}else ye(s);t(e=>e.filter(e=>e.id!==s)),p.toast.success(`Chat deleted`)}catch(e){p.toast.error(e.message||`Failed to delete chat`)}finally{o(!1),l(null),d(!1)}}},F=()=>{m(!0)},I=async()=>{g(!0);try{if(T){let{error:e}=await(0,c.deleteAllChats)();if(e)throw Error(`Failed to clear history: ${e.message}`)}else be();t([]),p.toast.success(`All history cleared`)}catch(e){p.toast.error(e.message||`Failed to clear history`)}finally{m(!1),g(!1)}},L=()=>{O(!D),p.toast.success(D?`Private mode off`:`Private mode on — messages won't be saved`)},R=(0,n.useCallback)(async e=>{if(!e.trim()){S([]),w(!1);return}w(!0);try{if(T){let{data:t,error:n}=await(0,c.searchChats)({query:{q:e}});if(n)throw Error(`Failed to search chats: ${n.message}`);S(Array.isArray(t?.chats)?t.chats:[])}else{let t=ge().filter(t=>{let n=t.title.toLowerCase().includes(e.toLowerCase()),r=t.messages?.some(t=>`content`in t&&t.content?.toLowerCase().includes(e.toLowerCase()));return n||r});S(t.map(e=>({...e,messageCount:e.messages?.filter(e=>e.role===`user`).length??0,lastMessageAt:vn(e)})))}}catch(e){console.error(`Failed to search chat history:`,e),S([]),p.toast.error(`Failed to search chat history`)}finally{w(!1)}},[T]);return(0,n.useEffect)(()=>{let e=setTimeout(()=>{R(y)},300);return()=>clearTimeout(e)},[y,R]),{chats:e,sortedChats:A,displayChats:j,loading:r,pinnedIds:_,togglePin:k,incognito:D,toggleIncognito:L,searchQuery:y,searchResults:x,searching:C,handleSearchChange:(0,n.useCallback)(e=>{b(e)},[]),deleteDialogOpen:a,setDeleteDialogOpen:o,chatToDelete:s,setChatToDelete:l,deleting:u,handleDeleteClick:N,handleConfirmDelete:P,clearAllDialogOpen:f,setClearAllDialogOpen:m,clearingAll:h,handleClearAllClick:F,handleConfirmClearAll:I}}function Sn({incognito:e,onToggleIncognito:t,showClearAll:n,onClearAll:r,searchQuery:i,onSearchChange:a}){return(0,d.jsxs)(`div`,{className:`mb-2 pb-2 border-b border-border space-y-2`,children:[(0,d.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,d.jsx)(`p`,{className:`text-xs font-medium text-muted-foreground/80 uppercase tracking-wide`,children:`Chat History`}),(0,d.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,d.jsxs)(`button`,{onClick:t,className:`flex items-center gap-1 px-2 py-1 text-xs rounded-lg transition-colors duration-200 ${e?`text-primary bg-primary/10`:`text-muted-foreground hover:text-foreground hover:bg-secondary`}`,title:e?`Private mode on`:`Private mode`,children:[(0,d.jsx)(s.Lock,{size:12}),(0,d.jsx)(`span`,{children:`Private`})]}),n&&(0,d.jsxs)(`button`,{onClick:r,className:`flex items-center gap-1 px-2 py-1 text-xs text-muted-foreground hover:text-red-500 hover:bg-red-500/10 rounded-lg transition-colors duration-200`,title:`Clear all history`,children:[(0,d.jsx)(s.Trash2,{size:12}),(0,d.jsx)(`span`,{children:`Clear All`})]})]})]}),(0,d.jsxs)(`div`,{className:`relative`,children:[(0,d.jsx)(s.Search,{className:`absolute left-2 top-1/2 -translate-y-1/2 text-muted-foreground`,size:14}),(0,d.jsx)(`input`,{type:`text`,placeholder:`Search chats...`,value:i,onChange:e=>a(e.target.value),className:`w-full pl-7 pr-7 py-1.5 text-sm bg-secondary/50 border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 placeholder:text-muted-foreground/50`}),i&&(0,d.jsx)(`button`,{onClick:()=>a(``),className:`absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground`,children:(0,d.jsx)(s.X,{size:14})})]})]})}function Cn({chat:e,isPinned:t,onTogglePin:n,onDelete:r}){let i=e.messageCount??0;return(0,d.jsxs)(`div`,{className:`group flex items-center gap-1 px-2 py-1 rounded-lg hover:bg-secondary transition-colors duration-200`,children:[(0,d.jsxs)(w.default,{href:`/c/${e.id}`,className:`flex-1 min-w-0 flex items-center gap-1.5`,children:[(0,d.jsxs)(`span`,{className:`flex items-center gap-1 shrink-0`,children:[i>0&&(0,d.jsxs)(ht,{className:`px-1.5 py-0 text-[10px] font-medium bg-zinc-200 text-zinc-700 hover:bg-zinc-200 dark:bg-zinc-700 dark:text-zinc-300 dark:hover:bg-zinc-700 border-0 rounded-md`,children:[i,`Q`]}),(0,d.jsx)(ht,{className:`px-1.5 py-0 text-[10px] font-medium bg-zinc-100 text-zinc-500 hover:bg-zinc-100 dark:bg-zinc-800 dark:text-zinc-400 dark:hover:bg-zinc-800 border-0 rounded-md`,children:O(new Date,e.createdAt)})]}),(0,d.jsxs)(`p`,{className:`text-xs text-popover-foreground truncate`,children:[t&&(0,d.jsx)(s.Pin,{size:10,className:`inline mr-1 text-primary`}),e.title]})]}),(0,d.jsx)(`button`,{onClick:t=>n(t,e.id),className:`p-1.5 rounded-lg transition-all duration-200 ${t?`opacity-100 text-primary hover:bg-primary/10`:`opacity-0 group-hover:opacity-100 text-muted-foreground hover:text-primary hover:bg-primary/10`}`,title:t?`Unpin chat`:`Pin chat`,children:(0,d.jsx)(s.Pin,{size:14})}),(0,d.jsx)(`button`,{onClick:t=>r(t,e.id),className:`opacity-0 group-hover:opacity-100 p-1.5 rounded-lg hover:bg-red-500/10 text-muted-foreground hover:text-red-500 transition-all duration-200`,title:`Delete chat`,children:(0,d.jsx)(s.Trash,{size:14})})]})}function wn({open:e,onOpenChange:t,title:n,description:r,confirmLabel:i,loadingLabel:a,loading:o,onConfirm:s}){return(0,d.jsx)(Bt,{open:e,onOpenChange:e=>{!e&&!o&&t(!1)},children:(0,d.jsxs)(Wt,{className:`w-full max-w-md transform rounded-2xl bg-light-secondary dark:bg-dark-secondary border border-light-200 dark:border-dark-200 p-6 text-left align-middle shadow-xl`,children:[(0,d.jsx)(Gt,{className:`text-lg font-medium leading-6 dark:text-white`,children:n}),(0,d.jsx)(Kt,{className:`text-sm dark:text-white/70 text-black/70 mt-2`,children:r}),(0,d.jsxs)(`div`,{className:`flex flex-row items-end justify-end space-x-4 mt-6`,children:[(0,d.jsx)(`button`,{onClick:()=>{o||t(!1)},className:`text-black/50 dark:text-white/50 text-sm hover:text-black/70 hover:dark:text-white/70 transition duration-200`,children:`Cancel`}),(0,d.jsx)(`button`,{onClick:s,disabled:o,className:`text-red-400 text-sm hover:text-red-500 transition duration-200 disabled:opacity-50`,children:o?a:i})]})]})})}function Tn({deleteDialogOpen:e,setDeleteDialogOpen:t,chatToDelete:n,setChatToDelete:r,deleting:i,onConfirmDelete:a,clearAllDialogOpen:o,setClearAllDialogOpen:s,clearingAll:c,onConfirmClearAll:l}){return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(wn,{open:e,onOpenChange:e=>{t(e),e||r(null)},title:`Delete Confirmation`,description:`Are you sure you want to delete this chat?`,confirmLabel:`Delete`,loadingLabel:`Deleting...`,loading:i,onConfirm:a}),(0,d.jsx)(wn,{open:o,onOpenChange:s,title:`Clear All History`,description:`Are you sure you want to delete all your chat history? This action cannot be undone.`,confirmLabel:`Clear All`,loadingLabel:`Clearing...`,loading:c,onConfirm:l})]})}var En={Today:(0,d.jsx)(s.Sun,{size:12}),Yesterday:(0,d.jsx)(s.Clock,{size:12}),"This Week":(0,d.jsx)(s.CalendarDays,{size:12}),Older:(0,d.jsx)(s.Archive,{size:12})};function Dn(e){let t=new Date,n=new Date(t.getFullYear(),t.getMonth(),t.getDate()),r=new Date(n.getTime()-864e5),i=new Date(n.getTime()-6*864e5),a={Today:[],Yesterday:[],"This Week":[],Older:[]};for(let t of e){let e=new Date(t.createdAt);e>=n?a.Today.push(t):e>=r?a.Yesterday.push(t):e>=i?a[`This Week`].push(t):a.Older.push(t)}return[`Today`,`Yesterday`,`This Week`,`Older`].filter(e=>a[e].length>0).map(e=>({label:e,chats:a[e]}))}var On=({showLabel:e=!1})=>{let t=xn();return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)(Bt,{children:[(0,d.jsxs)(Vt,{className:e?`inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs text-muted-foreground bg-secondary hover:bg-secondary/80 hover:text-foreground transition-colors duration-150`:`p-2 text-muted-foreground rounded-2xl bg-background/60 backdrop-blur-md hover:bg-secondary/80 transition duration-200 hover:text-foreground border border-border/30`,children:[(0,d.jsx)(s.History,{size:e?14:18}),e&&(0,d.jsx)(`span`,{children:`History`})]}),(0,d.jsxs)(Wt,{className:`max-w-[420px] p-3`,children:[(0,d.jsx)(Gt,{className:`sr-only`,children:`Chat History`}),(0,d.jsx)(Sn,{incognito:t.incognito,onToggleIncognito:t.toggleIncognito,showClearAll:t.chats.length>0&&!t.loading,onClearAll:t.handleClearAllClick,searchQuery:t.searchQuery,onSearchChange:t.handleSearchChange}),t.loading||t.searching?(0,d.jsx)(`div`,{className:`flex items-center justify-center py-8`,children:(0,d.jsxs)(`svg`,{"aria-hidden":`true`,className:`w-6 h-6 text-light-200 fill-light-secondary dark:text-[#202020] animate-spin dark:fill-[#ffffff3b]`,viewBox:`0 0 100 101`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,d.jsx)(`path`,{d:`M100 50.5908C100.003 78.2051 78.1951 100.003 50.5908 100C22.9765 99.9972 0.997224 78.018 1 50.4037C1.00281 22.7993 22.8108 0.997224 50.4251 1C78.0395 1.00281 100.018 22.8108 100 50.4251ZM9.08164 50.594C9.06312 73.3997 27.7909 92.1272 50.5966 92.1457C73.4023 92.1642 92.1298 73.4365 92.1483 50.6308C92.1669 27.8251 73.4392 9.0973 50.6335 9.07878C27.8278 9.06026 9.10003 27.787 9.08164 50.594Z`,fill:`currentColor`}),(0,d.jsx)(`path`,{d:`M93.9676 39.0409C96.393 38.4037 97.8624 35.9116 96.9801 33.5533C95.1945 28.8227 92.871 24.3692 90.0681 20.348C85.6237 14.1775 79.4473 9.36872 72.0454 6.45794C64.6435 3.54717 56.3134 2.65431 48.3133 3.89319C45.869 4.27179 44.3768 6.77534 45.014 9.20079C45.6512 11.6262 48.1343 13.0956 50.5786 12.717C56.5073 11.8281 62.5542 12.5399 68.0406 14.7911C73.527 17.0422 78.2187 20.7487 81.5841 25.4923C83.7976 28.5886 85.4467 32.059 86.4416 35.7474C87.1273 38.1189 89.5423 39.6781 91.9676 39.0409Z`,fill:`currentFill`})]})}):t.searchQuery.trim()&&t.displayChats.length===0?(0,d.jsx)(`div`,{className:`flex items-center justify-center py-8`,children:(0,d.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No matching chats found.`})}):t.chats.length===0?(0,d.jsx)(`div`,{className:`flex items-center justify-center py-8`,children:(0,d.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No chats found.`})}):(0,d.jsx)(`div`,{className:`space-y-1 max-h-[500px] overflow-y-auto`,children:t.searchQuery.trim()?t.displayChats.map(e=>(0,d.jsx)(Cn,{chat:e,isPinned:t.pinnedIds.includes(e.id),onTogglePin:t.togglePin,onDelete:t.handleDeleteClick},e.id)):Dn(t.displayChats).map(({label:e,chats:n})=>(0,d.jsxs)(`div`,{children:[(0,d.jsxs)(`div`,{className:`flex items-center gap-1.5 px-3 py-1.5 text-xs font-semibold text-muted-foreground/70 uppercase tracking-wider`,children:[En[e],e]}),n.map(e=>(0,d.jsx)(Cn,{chat:e,isPinned:t.pinnedIds.includes(e.id),onTogglePin:t.togglePin,onDelete:t.handleDeleteClick},e.id))]},e))}),t.chats.length>0&&(0,d.jsx)(`div`,{className:`mt-2 pt-2 border-t border-border`,children:(0,d.jsx)(w.default,{href:`/library`,className:`block text-center text-xs text-primary hover:underline`,children:`View all chats`})})]})]}),(0,d.jsx)(Tn,{deleteDialogOpen:t.deleteDialogOpen,setDeleteDialogOpen:t.setDeleteDialogOpen,chatToDelete:t.chatToDelete,setChatToDelete:t.setChatToDelete,deleting:t.deleting,onConfirmDelete:t.handleConfirmDelete,clearAllDialogOpen:t.clearAllDialogOpen,setClearAllDialogOpen:t.setClearAllDialogOpen,clearingAll:t.clearingAll,onConfirmClearAll:t.handleConfirmClearAll})]})};function kn(e){let t=new Date(e).getTime();if(Number.isNaN(t))return``;let n=Math.round((Date.now()-t)/1e3);if(n<5)return`just now`;if(n<60)return`${n} sec ago`;let r=Math.round(n/60);if(r<60)return`${r} min ago`;let i=Math.round(r/60);if(i<24)return`${i} hr ago`;let a=Math.round(i/24);if(a<7)return`${a} day${a===1?``:`s`} ago`;let o=Math.round(a/7);if(o<5)return`${o} week${o===1?``:`s`} ago`;let s=Math.round(a/30);if(s<12)return`${s} month${s===1?``:`s`} ago`;let c=Math.round(a/365);return`${c} year${c===1?``:`s`} ago`}var An=e=>new Date(e.lastMessageAt||e.createdAt).getTime();function jn(){let{chats:e,loading:t}=xn(),n=[...e].sort((e,t)=>An(t)-An(e)).slice(0,5);return t||n.length===0?null:(0,d.jsxs)(`div`,{className:`flex flex-row items-center justify-center gap-2 flex-wrap`,children:[(0,d.jsx)(On,{showLabel:!0}),n.map(e=>{let t=kn(e.lastMessageAt||e.createdAt);return(0,d.jsxs)(w.default,{href:`/c/${e.id}`,className:`flex items-center gap-1.5 px-3 py-1 rounded-full text-xs text-muted-foreground bg-secondary hover:bg-secondary/80 hover:text-foreground transition-colors duration-150 max-w-[220px]`,title:e.title,children:[(0,d.jsx)(`span`,{className:`truncate`,children:e.title}),t&&(0,d.jsx)(`span`,{className:`italic text-muted-foreground/70 whitespace-nowrap`,children:t})]},e.id)})]})}function Mn({listFooterLinks:e=[],optionShowIcons:t=!0,optionBackgroundColor:r=`bg-black/40`}){let[i,a]=(0,n.useState)(!1),o=(0,n.useRef)(null);(0,n.useEffect)(()=>{if(!i)return;let e=e=>{o.current&&!o.current.contains(e.target)&&a(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[i]);let c=()=>e.map(({url:e,text:n,icon:r})=>{let i=r?s[r]:null,a=e.startsWith(`http`),o=a?{target:`_blank`,rel:`noopener noreferrer`}:{},c=(0,d.jsxs)(d.Fragment,{children:[t&&i&&(0,d.jsx)(i,{size:14}),(0,d.jsx)(`span`,{className:`font-semibold tracking-wide text-md`,style:{fontVariant:`small-caps`},children:n}),(0,d.jsx)(`span`,{className:`absolute bottom-0 left-0 w-0 h-0.5 bg-current transition-all duration-300 group-hover:w-full group-hover:shadow-[0_0_8px_rgba(255,255,255,0.6)]`})]});return a?(0,d.jsx)(`a`,{href:e,...o,className:`relative group inline-flex items-center gap-1 hover:text-white hover:drop-shadow-[0_0_8px_rgba(255,255,255,0.8)] transition-all duration-300 whitespace-nowrap`,children:c},e):(0,d.jsx)(w.default,{href:e,className:`relative group inline-flex items-center gap-1 hover:text-white hover:drop-shadow-[0_0_8px_rgba(255,255,255,0.8)] transition-all duration-300 whitespace-nowrap`,children:c},e)}),l=s.Info;return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(`div`,{className:`hidden md:flex absolute bottom-2 left-1/2 -translate-x-1/2 text-slate-200 text-xs z-20 ${r} rounded-lg px-2 py-1 shadow-lg hover:shadow-xl hover:-translate-y-1 transition-all duration-300 flex-wrap items-center justify-center gap-x-6 max-w-[90vw]`,children:(0,d.jsx)(`div`,{className:`max-w-4xl mx-auto grid grid-cols-3 gap-2`,children:c()})}),(0,d.jsxs)(`div`,{ref:o,className:`md:hidden fixed top-[calc(8px+env(safe-area-inset-top,0px))] right-2 z-30`,children:[i&&(0,d.jsx)(`div`,{className:`absolute top-full right-0 mt-2 text-slate-200 text-xs ${r} rounded-lg px-3 py-2 shadow-lg flex flex-col items-start gap-2 backdrop-blur-sm`,children:c()}),(0,d.jsx)(`button`,{type:`button`,onClick:()=>a(e=>!e),"aria-label":i?`Hide links`:`Show links`,"aria-expanded":i,className:`flex items-center justify-center h-8 w-8 rounded-full text-slate-200 ${r} shadow-lg backdrop-blur-sm hover:text-white transition-all duration-300`,children:l?(0,d.jsx)(l,{size:16}):`i`})]})]})}function Nn(){let e=`hyZbH3n.mp4,iOeZcCk.mp4,dUZlxYE.mp4,GpWeP6E.gif,LuKUsLE.png,w7X11Dd.png,MHmVtCr.png,HmnUAee.png,vKP22VU.png,l1lsV39.png,Ku8F2qc.png,KUEXtwm.png,vvKFPmY.png,5p8eaEf.png,VAKuJcG.png,sTMPtQW.png,m0gHbZZ.png,cKu7dWQ.png,ogfefYD.png,ey5vAae.png,twuLrvk.png,ELILiYt.png,9el5qpP.png,Up6xTkk.png,W1XKBo0.png,1Y6xvW0.png,JXOytMz.png,DNiI6pp.png,XDv5s6p.jpeg,eRwiRJ9.jpeg,DRAfJoc.jpeg,ASVRQ1G.jpeg,35svwUT.jpeg,81xLiVI.jpeg,6kod2Em.jpeg,eU0C8zt.jpeg,Bv0PBY8.jpeg,DQNbjIZ.jpeg,2uACPqZ.jpeg,XEKltMF.jpeg,WHgLfBm.jpeg,QFYM0Fw.jpeg,K12HCao.jpeg,oN8rtsE.jpeg,9fGnrns.jpeg,2ONJJeW.jpeg,DO23Va7.jpeg,QaKeoXk.jpeg,QU5oCBR.jpeg,MhlYZmh.jpeg,ylL1ToB.jpeg,AWWsCv8.jpeg,Tk9Tzzj.jpeg`.split(`,`);return`https://i.imgur.com/`+e[Math.floor(Math.random()*e.length)]}function Pn(){let{sendMessage:e}=K(),[r,i]=(0,n.useState)(null),[a,o]=(0,n.useState)(null),[s,c]=(0,n.useState)(!1),[l,u]=(0,n.useState)({os:``});(0,n.useEffect)(()=>{if(localStorage.getItem(`showBackgroundArt`)===`false`)return;i(Nn());let e=setInterval(()=>{let e=Nn();o(e),c(!0),setTimeout(()=>{i(e),c(!1),o(null)},1e3)},2e4);return()=>clearInterval(e)},[]),(0,n.useEffect)(()=>{if(typeof window<`u`){let e=window.navigator.userAgent.toLowerCase();e.includes(`win`)?u({os:`Windows`}):e.includes(`mac`)?u({os:`MacOS`}):u({os:`Other`})}},[]);let f=e=>e.endsWith(`.webm`)||e.endsWith(`.mp4`),p=(e,t)=>f(e)?(0,d.jsx)(`video`,{src:e,autoPlay:!0,loop:!0,muted:!0,playsInline:!0,className:`absolute inset-0 w-full h-full object-cover transition-opacity duration-1000 ${t}`},e):(0,d.jsx)(`img`,{src:e,alt:``,className:`absolute inset-0 w-full h-full object-cover transition-opacity duration-1000 ${t}`},e);return(0,d.jsxs)(`div`,{className:`relative min-h-screen w-full`,children:[(0,d.jsxs)(`div`,{className:`fixed inset-0 z-0`,children:[r&&p(r,s?`opacity-0`:`opacity-30`),a&&p(a,s?`opacity-30`:`opacity-0`),(0,d.jsx)(gn,{})]}),(0,d.jsx)(`div`,{className:`relative z-10`,children:(0,d.jsxs)(`div`,{className:`flex flex-col items-center justify-end md:justify-center min-h-[calc(100dvh-64px)] md:min-h-screen max-w-screen-sm mx-auto p-2 pb-1 md:pb-2`,children:[(0,d.jsx)(`div`,{style:{height:`200px`,width:`100%`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:(0,d.jsx)(x.default,{autoRandomize:!0,onSphereClick:()=>console.log(`Sphere clicked`),className:`my-custom-class`})}),(0,d.jsxs)(`p`,{className:`text-lg text-gray-500 text-center justify-center mt-4`,children:[(0,d.jsx)(`a`,{"aria-label":`Chrome Web Store`,className:`download-chrome download-btn text-center justify-center`,target:`_blank`,href:t.researchAgentUIConfig.downloadChromeUrl}),(0,d.jsx)(`a`,{"aria-label":`Microsoft Store`,className:`download-windows download-btn text-center justify-center`,target:`_blank`,href:l.os==`Windows`?`ms-windows-store://pdp/?productid=${t.researchAgentUIConfig.downloadWindowsStoreId}`:`https://apps.microsoft.com/detail/${t.researchAgentUIConfig.downloadWindowsStoreId}?rtc=1`})]}),(0,d.jsxs)(`div`,{className:`w-full max-w-2xl mt-8 space-y-2`,children:[(0,d.jsx)(jn,{}),(0,d.jsx)(zt,{})]})]})}),(0,d.jsx)(Mn,{listFooterLinks:t.researchAgentUIConfig.footerLinks})]})}var Fn=()=>(0,d.jsxs)(`svg`,{"aria-hidden":`true`,className:`w-8 h-8 text-border fill-secondary animate-spin`,viewBox:`0 0 100 101`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,d.jsx)(`path`,{d:`M100 50.5908C100.003 78.2051 78.1951 100.003 50.5908 100C22.9765 99.9972 0.997224 78.018 1 50.4037C1.00281 22.7993 22.8108 0.997224 50.4251 1C78.0395 1.00281 100.018 22.8108 100 50.4251ZM9.08164 50.594C9.06312 73.3997 27.7909 92.1272 50.5966 92.1457C73.4023 92.1642 92.1298 73.4365 92.1483 50.6308C92.1669 27.8251 73.4392 9.0973 50.6335 9.07878C27.8278 9.06026 9.10003 27.787 9.08164 50.594Z`,fill:`currentColor`}),(0,d.jsx)(`path`,{d:`M93.9676 39.0409C96.393 38.4037 97.8624 35.9116 96.9801 33.5533C95.1945 28.8227 92.871 24.3692 90.0681 20.348C85.6237 14.1775 79.4473 9.36872 72.0454 6.45794C64.6435 3.54717 56.3134 2.65431 48.3133 3.89319C45.869 4.27179 44.3768 6.77534 45.014 9.20079C45.6512 11.6262 48.1343 13.0956 50.5786 12.717C56.5073 11.8281 62.5542 12.5399 68.0406 14.7911C73.527 17.0422 78.2187 20.7487 81.5841 25.4923C83.7976 28.5886 85.4467 32.059 86.4416 35.7474C87.1273 38.1189 89.5423 39.6781 91.9676 39.0409Z`,fill:`currentFill`})]});function In(){return(0,d.jsx)(`div`,{className:`flex min-h-screen flex-col items-center justify-center p-8`,children:(0,d.jsxs)(`div`,{className:`max-w-2xl w-full space-y-6 bg-light-secondary dark:bg-dark-secondary rounded-lg p-8 border border-black/10 dark:border-white/10`,children:[(0,d.jsxs)(`div`,{className:`space-y-2`,children:[(0,d.jsx)(`h1`,{className:`text-2xl font-semibold text-black dark:text-white`,children:`⚠️ Configuration Required`}),(0,d.jsx)(`p`,{className:`text-black/70 dark:text-white/70`,children:`No AI model providers are configured. Add at least one API key to continue.`})]}),(0,d.jsxs)(`div`,{className:`space-y-4`,children:[(0,d.jsx)(`h2`,{className:`text-lg font-medium text-black dark:text-white`,children:`Quick Setup:`}),(0,d.jsxs)(`div`,{className:`space-y-3 text-sm`,children:[(0,d.jsxs)(`div`,{className:`bg-black/5 dark:bg-white/5 rounded p-4`,children:[(0,d.jsx)(`p`,{className:`font-medium text-black dark:text-white mb-2`,children:`1. Create environment file:`}),(0,d.jsx)(`code`,{className:`block bg-black/10 dark:bg-white/10 rounded p-2 text-xs overflow-x-auto`,children:`apps/qwksearch-web/.env.local`})]}),(0,d.jsxs)(`div`,{className:`bg-black/5 dark:bg-white/5 rounded p-4`,children:[(0,d.jsx)(`p`,{className:`font-medium text-black dark:text-white mb-2`,children:`2. Add required variables:`}),(0,d.jsx)(`pre`,{className:`block bg-black/10 dark:bg-white/10 rounded p-3 text-xs overflow-x-auto text-black/80 dark:text-white/80`,children:`# Database
|
|
34
34
|
DATABASE_URL=file:./data/qwksearch.db
|
|
35
35
|
|
|
36
36
|
# Auth (generate: openssl rand -base64 32)
|
package/dist/index.mjs
CHANGED
|
@@ -5716,23 +5716,23 @@ function xi(e) {
|
|
|
5716
5716
|
var Si = (e) => new Date(e.lastMessageAt || e.createdAt).getTime();
|
|
5717
5717
|
function Ci() {
|
|
5718
5718
|
let { chats: e, loading: t } = pi(), n = [...e].sort((e, t) => Si(t) - Si(e)).slice(0, 5);
|
|
5719
|
-
|
|
5720
|
-
let r = xi(n[0].lastMessageAt || n[0].createdAt);
|
|
5721
|
-
return /* @__PURE__ */ G("div", {
|
|
5719
|
+
return t || n.length === 0 ? null : /* @__PURE__ */ G("div", {
|
|
5722
5720
|
className: "flex flex-row items-center justify-center gap-2 flex-wrap",
|
|
5723
|
-
children: [
|
|
5724
|
-
|
|
5725
|
-
|
|
5721
|
+
children: [/* @__PURE__ */ W(bi, { showLabel: !0 }), n.map((e) => {
|
|
5722
|
+
let t = xi(e.lastMessageAt || e.createdAt);
|
|
5723
|
+
return /* @__PURE__ */ G(St, {
|
|
5726
5724
|
href: `/c/${e.id}`,
|
|
5727
|
-
className: "px-3 py-1 rounded-full text-xs text-muted-foreground bg-secondary hover:bg-secondary/80 hover:text-foreground transition-colors duration-150
|
|
5725
|
+
className: "flex items-center gap-1.5 px-3 py-1 rounded-full text-xs text-muted-foreground bg-secondary hover:bg-secondary/80 hover:text-foreground transition-colors duration-150 max-w-[220px]",
|
|
5728
5726
|
title: e.title,
|
|
5729
|
-
children:
|
|
5730
|
-
|
|
5731
|
-
|
|
5732
|
-
|
|
5733
|
-
|
|
5734
|
-
|
|
5735
|
-
|
|
5727
|
+
children: [/* @__PURE__ */ W("span", {
|
|
5728
|
+
className: "truncate",
|
|
5729
|
+
children: e.title
|
|
5730
|
+
}), t && /* @__PURE__ */ W("span", {
|
|
5731
|
+
className: "italic text-muted-foreground/70 whitespace-nowrap",
|
|
5732
|
+
children: t
|
|
5733
|
+
})]
|
|
5734
|
+
}, e.id);
|
|
5735
|
+
})]
|
|
5736
5736
|
});
|
|
5737
5737
|
}
|
|
5738
5738
|
//#endregion
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "research-agent-ui",
|
|
3
3
|
"description": "Chat research agent UI: conversation window, article reader, search config, file uploads, and chat history",
|
|
4
|
-
"version": "0.1.
|
|
4
|
+
"version": "0.1.85",
|
|
5
5
|
"author": "vtempest",
|
|
6
6
|
"repository": {
|
|
7
7
|
"type": "git",
|
|
@@ -65,19 +65,20 @@
|
|
|
65
65
|
"@radix-ui/react-slot": "^1.2.5",
|
|
66
66
|
"@radix-ui/react-tooltip": "^1.2.9",
|
|
67
67
|
"@ricky0123/vad-web": "^0.0.30",
|
|
68
|
-
"
|
|
69
|
-
"
|
|
68
|
+
"ai": "^5.0.0",
|
|
69
|
+
"chat-agent-toolkit": "^1.2.109",
|
|
70
|
+
"domain-rank": "^0.1.98",
|
|
70
71
|
"drizzle-orm": "^0.45.2",
|
|
71
72
|
"fuse.js": "^7.1.0",
|
|
72
73
|
"class-variance-authority": "^0.7.1",
|
|
73
74
|
"clsx": "^2.1.1",
|
|
74
75
|
"dompurify": "^3.4.9",
|
|
75
|
-
"extract-webpage": "^1.2.
|
|
76
|
-
"search-web-api": "^1.0.
|
|
76
|
+
"extract-webpage": "^1.2.109",
|
|
77
|
+
"search-web-api": "^1.0.67",
|
|
77
78
|
"framer-motion": "^12.40.0",
|
|
78
79
|
"grab-url": "^1.6.22",
|
|
79
80
|
"kokoro-js": "^1.2.1",
|
|
80
|
-
"qwksearch-api-client": "^0.9.
|
|
81
|
+
"qwksearch-api-client": "^0.9.56",
|
|
81
82
|
"html2canvas": "^1.4.1",
|
|
82
83
|
"lucide-react": "^1.17.0",
|
|
83
84
|
"markdown-to-jsx": "^9.8.2",
|