research-agent-ui 0.1.294 → 0.1.295
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/{ArticleExtractPanel-D_y16YHG.js → ArticleExtractPanel-BPNXuezE.js} +1 -1
- package/dist/{ArticleExtractPanel-25tRTnpl.cjs → ArticleExtractPanel-DAPLUpyx.cjs} +1 -1
- package/dist/{ChatConversationThread-BoNH0wvs.cjs → ChatConversationThread-D1RR0Bcx.cjs} +2 -2
- package/dist/{ChatConversationThread-BIJ8aNug.js → ChatConversationThread-DMPdu2sr.js} +2 -2
- package/dist/api.cjs +6 -6
- package/dist/api.mjs +304 -66
- package/dist/index.cjs +1 -1
- package/dist/index.mjs +1 -1
- package/dist/{src-GPr1ceY8.js → src-BqV2Vwpv.js} +912 -702
- package/dist/src-Ckb1ciEL.cjs +34 -0
- package/dist/workspace.cjs +1 -1
- package/dist/workspace.mjs +1 -1
- package/package.json +14 -14
- package/dist/src-ebmQu_if.cjs +0 -34
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { i as e, n as t, o as n, t as r } from "./dialog-Cufn2u50.js";
|
|
2
2
|
import { a as i, c as a, u as o } from "./tooltip-Bl3IdX-I.js";
|
|
3
|
-
import { D as s, E as ee, O as te, S as ne, T as re, w as ie } from "./src-
|
|
3
|
+
import { D as s, E as ee, O as te, S as ne, T as re, w as ie } from "./src-BqV2Vwpv.js";
|
|
4
4
|
import { researchAgentUIConfig as ae } from "./config.mjs";
|
|
5
5
|
import * as c from "react";
|
|
6
6
|
import { useEffect as l, useRef as u, useState as d } from "react";
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./rolldown-runtime-BocRIvOZ.cjs"),t=require("./dialog-7GDz0sWx.cjs"),n=require("./tooltip-DmUO6ZUz.cjs"),r=require("./src-
|
|
1
|
+
const e=require("./rolldown-runtime-BocRIvOZ.cjs"),t=require("./dialog-7GDz0sWx.cjs"),n=require("./tooltip-DmUO6ZUz.cjs"),r=require("./src-Ckb1ciEL.cjs"),i=require("./config.cjs");let a=require("react");a=e.t(a,1);let o=require("react/jsx-runtime"),s=require("sonner"),c=require("qwksearch-api-client");var l=a.forwardRef(({className:e,...n},r)=>(0,o.jsx)(`span`,{ref:r,className:t.o(`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%)`},...n}));l.displayName=`VisuallyHidden`;function u(e){return e instanceof Error&&e.name===`AbortError`}async function ee(e,t){if(t.share)try{return await t.share(e),`shared`}catch(e){if(u(e))return`cancelled`}return await t.writeText(e.url),`copied`}var d=e=>{let{isOpen:u,url:d,searchText:te,suggestQuestions:f,panelWidth:ne,setPanelWidth:p,closePanel:re}=n.a(),{isAuthenticated:ie}=n.c(),{chatModelProvider:m}=n.u(),h=e.isOpen===void 0?u:e.isOpen,g=e.onClose||re,_=e.url||d,ae=e.searchText===void 0?te:e.searchText,[v,y]=(0,a.useState)(null),[b,oe]=(0,a.useState)([]),[se,x]=(0,a.useState)(!1),[ce,S]=(0,a.useState)(!1),[C,w]=(0,a.useState)(i.researchAgentUIConfig.defaultSummarizePrompt),[le,T]=(0,a.useState)(!1),[E,ue]=(0,a.useState)(!1),[D,de]=(0,a.useState)(!1),[O,fe]=(0,a.useState)(``),[k,pe]=(0,a.useState)(``),[me,A]=(0,a.useState)([]),[he,ge]=(0,a.useState)(``),[j,M]=(0,a.useState)(!1),[_e,N]=(0,a.useState)(!1),[P,F]=(0,a.useState)(!1),[I,ve]=(0,a.useState)(!1),[ye,be]=(0,a.useState)(ne),[L,R]=(0,a.useState)(!1),[xe,z]=(0,a.useState)(!1),[B,V]=(0,a.useState)(1),Se=(0,a.useRef)(null),H=(0,a.useRef)({}),U=.5,W=1.8,G=.1;(0,a.useEffect)(()=>{let e=parseFloat(localStorage.getItem(`articleFontScale`)||``);Number.isNaN(e)||V(Math.min(W,Math.max(U,e)))},[]);let K=e=>{let t=Math.min(W,Math.max(U,Math.round(e*100)/100));V(t);try{localStorage.setItem(`articleFontScale`,String(t))}catch(e){console.error(`Error storing article font scale:`,e)}},q=()=>K(B+G),J=()=>K(B-G),Y=()=>K(1);(0,a.useEffect)(()=>{let e=()=>{ve(window.innerWidth>=1024)};return e(),window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[]),(0,a.useEffect)(()=>{let e=e=>{if(!L)return;let t=window.innerWidth-e.clientX,n=Math.max(400,Math.min(t,window.innerWidth-100));be(n),p(n)},t=()=>{R(!1)};return L&&(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=``}},[L,p]),(0,a.useEffect)(()=>{h&&_?(z(!1),Ce()):h||z(!1)},[h,_]);let Ce=async()=>{console.log(`[ArticleExtractPanel] Extracting URL:`,_);try{let e=new URL(_);if([/^https?:\/\/(www\.)?google\.[^/]+\/search/i,/^https?:\/\/(www\.)?bing\.com\/search/i,/^https?:\/\/(www\.)?duckduckgo\.com\/\?/i].some(e=>e.test(_))){s.toast.error(`Cannot extract articles from search result pages`),T(!1),z(!0);return}(e.pathname===`/`||e.pathname===``)&&(console.error(`[ArticleExtractPanel] URL is domain-only, missing article path:`,_),s.toast.error(`Invalid article URL - only domain provided`))}catch(e){console.error(`[ArticleExtractPanel] Invalid URL format:`,_,e)}T(!0);try{let{data:e}=await(0,c.getArticle)({query:{url:_}}),t=e?.article,n=t?.html?.replace(/<[^>]*>/g,``).trim()||``;t?.error||n.length<20?(document.dispatchEvent(new CustomEvent(`onInvokeChromeAPI`,{detail:{type:`extractURL`,url:_}})),await Promise.race([new Promise(e=>{let t=async n=>{window.removeEventListener(`onExtractionResult`,t);let{data:r}=await(0,c.getArticle)({query:{url:_}}),i=r?.article;i&&(y(i),i.followUpQuestions?.length>0?A(i.followUpQuestions):f&&(A([]),Z(`suggest-followups`,{source:i}))),e()};window.addEventListener(`onExtractionResult`,t)}),new Promise(e=>setTimeout(e,1e4))])):(y(t),t?.followUpQuestions&&t.followUpQuestions.length>0?A(t.followUpQuestions):f&&t&&(A([]),Z(`suggest-followups`,{source:t}))),ie&&we()}catch(e){console.error(`[ArticleExtractPanel] Error extracting URL:`,e),s.toast.error(`Failed to load article`)}finally{T(!1),z(!0)}},we=async()=>{try{let{data:e}=await(0,c.listFavorites)(),t=e?.favorites?.some(e=>e.url===_);M(!!t)}catch(e){console.error(`Error checking favorite status:`,e)}},X=async()=>{if(v){N(!0);try{j?(await(0,c.removeFavorite)({query:{url:_}}),M(!1),s.toast.info(`Removed from favorites`)):(await(0,c.addFavorite)({body:{url:v.url||_,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}}),M(!0),s.toast.success(`Added to favorites`))}catch(e){console.error(`Error toggling favorite:`,e),s.toast.error(`Failed to toggle favorite`)}finally{N(!1)}}},Te=()=>{if(m?.key&&m?.providerId)return m;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 m},Z=async(e,{source:t=v,question:n=C}={})=>{if(!t)return;let r=Te(),a=t.html?.replace(/<[^>]*>?/g,``).slice(0,i.researchAgentUIConfig.maxArticleLength),o=e===`question`,s=o?ue:de,l=o?pe:ge;s(!0),l(``);try{if(o){let e=[ae,n].filter(Boolean).join(`
|
|
2
2
|
`);if(!a||a.length===0)throw Error(`Article content is empty`);let{data:t,error:i}=await(0,c.articleQa)({body:{article:a,question:e,chatHistory:b.slice(-5),chatModel:r}});if(i){let e=i.details||i.error||i.message||`Article QA failed`;throw Error(e)}let o=t?.content||``;fe(o),oe(e=>[...e,{role:`user`,content:n,time:new Date().toISOString()},{role:`assistant`,content:o,time:new Date().toISOString()}]);try{await(0,c.updateArticle)({body:{url:_,question:n,answer:o}})}catch(e){console.error(`Error storing Q&A in cache:`,e)}}else{let e=parseInt(localStorage.getItem(`maxFollowupQuestions`)||`4`);if(!a||a.length===0)throw Error(`Article content is empty`);let{data:t,error:n}=await(0,c.articleFollowups)({body:{article:a,chatHistory:b.slice(-5),maxQuestions:e,chatModel:r}});if(n){let e=n.details||n.error||n.message||`Article followups failed`;throw Error(e)}let i=t?.extract||[];A(i);try{await(0,c.updateArticle)({body:{url:_,followUpQuestions:i}})}catch(e){console.error(`Error storing follow-up questions in cache:`,e)}}}catch(e){console.error(`Error calling language API:`,e),l(e instanceof Error||typeof e==`object`&&e&&`message`in e?e.message:`Failed to get AI response`)}finally{s(!1)}},Ee=e=>{w(e),Z(`question`,{question:e})},Q=async()=>{if(!v)return;let e=`${O}\n\n\n${v.cite||``}\n\n\n${v.html}`;try{await navigator.clipboard.writeText(e),x(!0),setTimeout(()=>x(!1),2e3)}catch(e){console.error(`Failed to copy to clipboard:`,e)}},De=async()=>{let e=v?.url||_;if(e)try{await ee({title:v?.title,text:v?.cite,url:e},{share:typeof navigator<`u`&&navigator.share?e=>navigator.share(e):void 0,writeText:e=>navigator.clipboard.writeText(e)})===`copied`&&(S(!0),setTimeout(()=>S(!1),2e3))}catch(e){console.error(`Failed to share article:`,e)}};H.current={ask:()=>Z(`question`),suggest:()=>Z(`suggest-followups`),copy:Q,highlight:()=>F(e=>!e),favorite:X,open:()=>{let e=v?.url||_;e&&window.open(e,`_blank`,`noopener,noreferrer`)},zoomIn:q,zoomOut:J,zoomReset:Y,close:g},(0,a.useEffect)(()=>{if(!h)return;let e=e=>/^[a-z]$/.test(e)?`Key${e.toUpperCase()}`:/^[0-9]$/.test(e)?`Digit${e}`:e===`-`?`Minus`:e===`=`?`Equal`:e,t={};Object.keys(r.D).forEach(n=>{let{alt:i,key:a}=r.D[n];i&&(t[e(a.toLowerCase())]=n)});let n=e=>{if(e.key===`Escape`){H.current.close?.();return}if(!e.altKey||e.ctrlKey||e.metaKey)return;let n=e.target;if(n&&(n.tagName===`INPUT`||n.tagName===`TEXTAREA`||n.isContentEditable))return;let r=t[e.code];if(!r)return;let i=H.current[r];i&&(e.preventDefault(),i())};return window.addEventListener(`keydown`,n),()=>window.removeEventListener(`keydown`,n)},[h]);let $=()=>(0,o.jsxs)(`div`,{className:`flex h-full flex-col bg-background shadow-xl`,children:[(0,o.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,o.jsx)(r.O,{isLoadingAI:E,isLoadingFollowups:D,isLoadingFavorite:_e,isFavorited:j,isHighlightMode:P,articleUrl:v?.url||_,fontScale:B,onAskClick:()=>Z(`question`),onSuggestClick:()=>Z(`suggest-followups`),onCopyClick:Q,onShareClick:De,onFavoriteClick:X,onHighlightToggle:()=>F(!P),onZoomIn:q,onZoomOut:J,onZoomReset:Y,onClose:g})}),(0,o.jsx)(`div`,{className:`flex-1 overflow-y-auto`,children:(0,o.jsxs)(`div`,{className:`p-4 space-y-6`,children:[(0,o.jsxs)(`div`,{className:`space-y-4`,children:[se&&(0,o.jsx)(`div`,{className:`bg-blue-500 text-white text-sm font-medium px-3 py-2 rounded-md shadow-lg`,children:`Copied!`}),ce&&(0,o.jsx)(`div`,{className:`bg-blue-500 text-white text-sm font-medium px-3 py-2 rounded-md shadow-lg`,children:`Link copied!`}),(0,o.jsx)(r.E,{value:C,onChange:w,onSubmit:()=>Z(`question`)}),(0,o.jsx)(r.T,{questions:me,isLoading:D,error:he,onQuestionClick:Ee}),b.length>0&&(0,o.jsx)(`div`,{className:`space-y-4`,children:b.map((e,t)=>(0,o.jsx)(`div`,{className:`space-y-2`,children:e.role===`user`?(0,o.jsxs)(`div`,{className:`bg-primary/10 border border-primary/20 rounded-lg p-3`,children:[(0,o.jsx)(`div`,{className:`text-xs font-semibold text-primary mb-1`,children:`Your Question`}),(0,o.jsx)(`div`,{className:`text-sm text-foreground`,children:e.content})]}):(0,o.jsxs)(`div`,{className:`bg-muted rounded-lg shadow-md p-4`,children:[(0,o.jsx)(`div`,{className:`text-xs font-semibold text-muted-foreground mb-2`,children:`AI Response`}),(0,o.jsx)(`div`,{className:`text-sm`,dangerouslySetInnerHTML:{__html:e.content}})]})},t))}),(E||O&&b.length===0)&&(0,o.jsx)(r.w,{response:O,isLoading:E,error:k}),k&&!E&&(0,o.jsx)(`div`,{className:`bg-red-500 text-white p-2 rounded-md text-sm`,children:k})]}),v&&(0,o.jsx)(r.S,{article:v,isHighlightMode:P,fontScale:B})]})})]});return!h||!xe?null:I?(0,o.jsxs)(`div`,{className:`fixed top-0 right-0 h-screen z-40 transition-all duration-300`,style:{width:`${ye}px`},children:[(0,o.jsx)(`div`,{ref:Se,onMouseDown:()=>R(!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,o.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`})}),$()]}):(0,o.jsx)(t.t,{open:h,onOpenChange:e=>!e&&g(),children:(0,o.jsxs)(t.n,{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,o.jsx)(l,{children:(0,o.jsx)(t.i,{children:`Article Details`})}),(0,o.jsx)(`div`,{className:`h-full overflow-y-auto`,children:$()})]})})};exports.default=d;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const e=require("./rolldown-runtime-BocRIvOZ.cjs"),t=require("./dialog-7GDz0sWx.cjs"),n=require("./tooltip-DmUO6ZUz.cjs"),r=require("./src-
|
|
1
|
+
const e=require("./rolldown-runtime-BocRIvOZ.cjs"),t=require("./dialog-7GDz0sWx.cjs"),n=require("./tooltip-DmUO6ZUz.cjs"),r=require("./src-Ckb1ciEL.cjs"),i=require("./config.cjs");let a=require("react");a=e.t(a,1);let o=require("react/jsx-runtime"),s=require("motion/react"),c=require("lucide-react"),l=require("qwksearch-api-client"),u=require("quantum-sphere-loading-icon/react");u=e.t(u,1);let d=require("markdown-to-jsx");d=e.t(d,1);let f=require("extract-webpage/html-to-content/html-utils"),p=require("@radix-ui/react-popover");p=e.t(p,1);let m=require("grab-url/animations");m=e.t(m,1);var h=(0,a.memo)(({blur:e=0,inactiveZone:n=.7,proximity:r=0,spread:i=20,variant:c=`default`,glow:l=!1,className:u,movementDuration:d=2,borderWidth:f=1,disabled:p=!0})=>{let m=(0,a.useRef)(null),h=(0,a.useRef)({x:0,y:0}),g=(0,a.useRef)(0),_=(0,a.useCallback)(e=>{m.current&&(g.current&&cancelAnimationFrame(g.current),g.current=requestAnimationFrame(()=>{let t=m.current;if(!t)return;let{left:i,top:a,width:o,height:c}=t.getBoundingClientRect(),l=e?.x??h.current.x,u=e?.y??h.current.y;e&&(h.current={x:l,y:u});let f=[i+o*.5,a+c*.5];if(Math.hypot(l-f[0],u-f[1])<.5*Math.min(o,c)*n){t.style.setProperty(`--active`,`0`);return}let p=l>i-r&&l<i+o+r&&u>a-r&&u<a+c+r;if(t.style.setProperty(`--active`,p?`1`:`0`),!p)return;let g=parseFloat(t.style.getPropertyValue(`--start`))||0,_=g+((180*Math.atan2(u-f[1],l-f[0])/Math.PI+90-g+180)%360-180);(0,s.animate)(g,_,{duration:d,ease:[.16,1,.3,1],onUpdate:e=>{t.style.setProperty(`--start`,String(e))}})}))},[n,r,d]);return(0,a.useEffect)(()=>{if(p)return;let e=()=>_(),t=e=>_(e);return window.addEventListener(`scroll`,e,{passive:!0}),document.body.addEventListener(`pointermove`,t,{passive:!0}),()=>{g.current&&cancelAnimationFrame(g.current),window.removeEventListener(`scroll`,e),document.body.removeEventListener(`pointermove`,t)}},[_,p]),(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)(`div`,{className:t.o(`pointer-events-none absolute -inset-px hidden rounded-[inherit] border opacity-0 transition-opacity`,l&&`opacity-100`,c===`white`&&`border-white`,p&&`!block`)}),(0,o.jsx)(`div`,{ref:m,style:{"--blur":`${e}px`,"--spread":i,"--start":`0`,"--active":`0`,"--glowingeffect-border-width":`${f}px`,"--repeating-conic-gradient-times":`5`,"--gradient":c===`white`?`repeating-conic-gradient(
|
|
2
2
|
from 236.84deg at 50% 50%,
|
|
3
3
|
var(--black),
|
|
4
4
|
var(--black) calc(25% / var(--repeating-conic-gradient-times))
|
|
@@ -14,4 +14,4 @@ const e=require("./rolldown-runtime-BocRIvOZ.cjs"),t=require("./dialog-7GDz0sWx.
|
|
|
14
14
|
#4c7894 calc(75% / var(--repeating-conic-gradient-times)),
|
|
15
15
|
#dd7bbb calc(100% / var(--repeating-conic-gradient-times))
|
|
16
16
|
)`},className:t.o(`pointer-events-none absolute inset-0 rounded-[inherit] opacity-100 transition-opacity`,l&&`opacity-100`,e>0&&`blur-[var(--blur)] `,u,p&&`!hidden`),children:(0,o.jsx)(`div`,{className:t.o(`glow`,`rounded-[inherit]`,`after:content-[""] after:rounded-[inherit] after:absolute after:inset-[calc(-1*var(--glowingeffect-border-width))]`,`after:[border:var(--glowingeffect-border-width)_solid_transparent]`,`after:[background:var(--gradient)] after:[background-attachment:fixed]`,`after:opacity-[var(--active)] after:transition-opacity after:duration-300`,`after:[mask-clip:padding-box,border-box]`,`after:[mask-composite:intersect]`,`after:[mask-image:linear-gradient(#0000,#0000),conic-gradient(from_calc((var(--start)-var(--spread))*1deg),#00000000_0deg,#fff,#00000000_calc(var(--spread)*2deg))]`)})})]})});h.displayName=`GlowingEffect`;function g(e){try{let t=new URL(e);return t.protocol===`https:`||t.protocol===`http:`}catch{return!1}}function _(e){return e.iframe_src&&g(e.iframe_src)?{type:`inline`,src:e.iframe_src}:{type:`external`,url:e.url||``}}function v(e){return{pageContent:e.snippet||e.content||``,metadata:{title:e.title||``,source:e.source||``,thumbnail:e.thumbnail||``,url:e.url||``,...e.img_src&&{img_src:e.img_src},...e.iframe_src&&{iframe_src:e.iframe_src}}}}var y=r.J.filter(e=>[`general`,`news`,`videos`,`images`,`science`,`files`].includes(e.code)),b=({sources:e,query:r})=>{let[i,s]=(0,a.useState)(`general`),[u,d]=(0,a.useState)(e),[p,m]=(0,a.useState)(!1),[g,b]=(0,a.useState)(!1),[x,S]=(0,a.useState)(1),[C,w]=(0,a.useState)(!0),[T,E]=(0,a.useState)(!1),[D,O]=(0,a.useState)(!1),[k,A]=(0,a.useState)(null),j=(0,a.useRef)(null),M=(0,a.useRef)(!1),N=(0,a.useRef)(!1),{openPanel:P,isOpen:F}=n.a();(0,a.useEffect)(()=>{let e=()=>{O(localStorage.getItem(`searchResultGlow`)===`true`)};return e(),window.addEventListener(`client-config-changed`,e),window.addEventListener(`storage`,e),()=>{window.removeEventListener(`client-config-changed`,e),window.removeEventListener(`storage`,e)}},[]);let[I,L]=(0,a.useState)({});(0,a.useEffect)(()=>{let e=()=>{E(window.innerWidth>=1024)};return e(),window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[]),(0,a.useEffect)(()=>{d(e),s(`general`),S(1),w(!0),L({}),R(e)},[e]);let R=(0,a.useCallback)(async e=>{let t=e.filter(e=>e.metadata.url&&e.metadata.url!==`File`&&!e.metadata.iframe_src);for(let e of t)try{let{data:t}=await(0,l.getArticle)({query:{url:e.metadata.url}});t?.cached&&t?.article?.html&&L(t=>({...t,[e.metadata.url]:`loaded`}))}catch{}},[]);(0,a.useEffect)(()=>{if(typeof window<`u`){let e=new URLSearchParams(window.location.search).get(`extract`);e&&(P(decodeURIComponent(e),``),N.current=!1)}},[P]),(0,a.useEffect)(()=>{N.current=!1},[e]),(0,a.useEffect)(()=>{M.current&&!F&&(N.current=!0),M.current=F},[F]),(0,a.useEffect)(()=>{if(T&&u&&u.length>0&&!F&&!N.current){let e=u[0];e?.metadata?.url&&P(e.metadata.url,``)}},[u,T]);let z=async(e,t)=>{e.preventDefault(),N.current=!1,L(e=>({...e,[t]:`loading`})),P(t,``);try{await(0,l.getArticle)({query:{url:t}}),L(e=>({...e,[t]:`loaded`}))}catch{L(e=>({...e,[t]:`loaded`}))}},B=(0,a.useCallback)(async()=>{if(!r||g||!C)return;b(!0);let e=x+1,{data:t}=await(0,l.agentSearch)({query:{q:r,cat:i,page:e}}),n=t?.results??[];if(n.length===0){w(!1),b(!1);return}let a=n.map(e=>{if(e.url)try{let t=new URL(e.url);(t.pathname===`/`||t.pathname===``)&&console.warn(`[MessageSources] Search result URL is domain-only:`,e.url,`Title:`,e.title)}catch{console.error(`[MessageSources] Invalid URL in search result:`,e.url)}return v(e)});d(e=>[...e,...a]),S(e),b(!1)},[r,i,x,g,C]),V=async e=>{if(e!==i&&r){s(e),m(!0),S(1),w(!0);try{let{data:t}=await(0,l.agentSearch)({query:{q:r,cat:e,page:1}}),n=(t?.results??[]).map(e=>{if(e.url)try{let t=new URL(e.url);(t.pathname===`/`||t.pathname===``)&&console.warn(`[MessageSources] Category search result URL is domain-only:`,e.url,`Title:`,e.title)}catch{console.error(`[MessageSources] Invalid URL in category search result:`,e.url)}return v(e)});d(n)}catch(e){console.error(`Error searching:`,e)}finally{m(!1)}}};(0,a.useEffect)(()=>{let e=j.current;if(!e)return;let t=()=>{let{scrollTop:t,scrollHeight:n,clientHeight:r}=e;n-t-r<100&&B()};return e.addEventListener(`scroll`,t),()=>e.removeEventListener(`scroll`,t)},[B]);let H=(e,t)=>{let n=i===`images`,r=i===`videos`,a=e.metadata.img_src||e.metadata.thumbnail;if(n&&a)return(0,o.jsx)(`div`,{className:`relative rounded-lg group`,children:(0,o.jsxs)(`a`,{className:`relative block overflow-hidden rounded-lg cursor-pointer`,href:e.metadata.url,onClick:t=>z(t,e.metadata.url),children:[(0,o.jsx)(`img`,{src:a,alt:e.metadata.title,className:`w-full h-auto object-cover rounded-lg hover:scale-105 transition-transform duration-200`,loading:`lazy`}),(0,o.jsxs)(`div`,{className:`absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/70 to-transparent p-2 opacity-0 group-hover:opacity-100 transition-opacity duration-200`,children:[(0,o.jsx)(`p`,{className:`text-xs text-white line-clamp-2`,children:(0,f.convertURLSafeHTMLToHTML)(e.metadata.title)}),(0,o.jsx)(`p`,{className:`text-[10px] text-white/70 truncate mt-0.5`,children:e.metadata.source})]})]})},t);if(r&&a){let n=_(e.metadata),r=(0,o.jsxs)(`div`,{className:`relative`,children:[(0,o.jsx)(`img`,{src:a,alt:e.metadata.title,className:`w-full h-24 object-cover`}),(0,o.jsx)(`div`,{className:`absolute inset-0 flex items-center justify-center`,children:(0,o.jsx)(`div`,{className:`w-10 h-10 bg-black/60 rounded-full flex items-center justify-center`,children:(0,o.jsx)(c.Video,{size:18,className:`text-white ml-0.5`})})})]}),i=(0,o.jsx)(`p`,{className:`text-xs line-clamp-2 p-2 text-muted-foreground`,children:(0,f.convertURLSafeHTMLToHTML)(e.metadata.title)});return(0,o.jsxs)(`div`,{className:`relative rounded-xl`,children:[(0,o.jsx)(h,{spread:40,glow:!0,disabled:!D,proximity:64,inactiveZone:.01,borderWidth:2}),n.type===`inline`?(0,o.jsxs)(`button`,{type:`button`,className:`relative w-full text-left bg-card text-card-foreground border border-border rounded-xl overflow-hidden flex flex-col cursor-pointer shadow-sm hover:shadow-md transition-all duration-200`,onClick:()=>A({src:n.src,title:e.metadata.title}),children:[r,i]}):(0,o.jsxs)(`a`,{className:`relative bg-card text-card-foreground border border-border rounded-xl overflow-hidden flex flex-col cursor-pointer shadow-sm hover:shadow-md transition-all duration-200`,href:n.url,target:`_blank`,rel:`noopener noreferrer`,children:[r,i]})]},t)}let s=I[e.metadata.url];return(0,o.jsxs)(`div`,{className:`relative rounded-xl group h-full`,children:[(0,o.jsx)(h,{spread:40,glow:!0,disabled:!D,proximity:64,inactiveZone:.01,borderWidth:2}),(0,o.jsxs)(`div`,{className:`relative bg-card text-card-foreground border border-border rounded-xl p-2.5 flex flex-col font-medium cursor-pointer shadow-sm hover:shadow-md transition-all duration-200 h-full`,onClick:t=>z(t,e.metadata.url),children:[s&&(0,o.jsx)(`div`,{className:`absolute top-1.5 left-1.5 p-1 rounded-md bg-background/80 backdrop-blur-sm z-[5]`,children:s===`loading`?(0,o.jsx)(c.Loader2,{size:14,className:`text-primary animate-spin`}):(0,o.jsx)(c.FileText,{size:14,className:`text-green-500`})}),(0,o.jsx)(`a`,{href:e.metadata.url,target:`_blank`,rel:`noopener noreferrer`,onClick:e=>e.stopPropagation(),className:`absolute top-1.5 right-1.5 p-1 rounded-md bg-secondary/50 opacity-0 group-hover:opacity-100 transition-opacity hover:bg-secondary z-10`,title:`Open in new tab`,children:(0,o.jsx)(c.ExternalLink,{size:12,className:`text-muted-foreground`})}),(0,o.jsxs)(`p`,{className:`text-xs line-clamp-4 text-muted-foreground`,children:[(0,o.jsxs)(`span`,{className:`inline-flex items-center gap-1 font-semibold text-foreground/70 align-middle`,children:[e.metadata.url===`File`?(0,o.jsx)(`span`,{className:`inline-flex items-center justify-center w-3.5 h-3.5 rounded-full bg-secondary flex-shrink-0`,children:(0,o.jsx)(c.File,{size:10,className:`text-muted-foreground`})}):(0,o.jsx)(`img`,{src:`https://s2.googleusercontent.com/s2/favicons?domain_url=${e.metadata.url}`,width:20,height:20,alt:`favicon`,className:`inline rounded h-5 w-5 flex-shrink-0`}),e.metadata.source]}),` `,(0,o.jsx)(`span`,{className:`align-middle`,children:(0,f.convertURLSafeHTMLToHTML)(e.metadata.title)})]})]})]},t)};return(0,o.jsxs)(o.Fragment,{children:[r&&(0,o.jsx)(`div`,{className:`flex items-center gap-1 mb-3 overflow-x-auto pb-1`,children:y.map(e=>(0,o.jsxs)(`button`,{onClick:()=>V(e.code),disabled:p,className:t.o(`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-sm font-medium transition-all duration-200 whitespace-nowrap`,i===e.code?`bg-primary text-primary-foreground`:`bg-secondary/50 text-muted-foreground hover:bg-secondary hover:text-foreground`),children:[(0,o.jsx)(e.icon,{className:`w-4 h-4 flex-shrink-0`}),(0,o.jsx)(`span`,{children:e.name})]},e.code))}),(0,o.jsx)(`div`,{ref:j,className:t.o(`overflow-y-auto pb-2 pr-1`,i===`images`?`max-h-[400px] lg:max-h-[500px]`:`max-h-[180px] lg:max-h-[280px]`),children:p?(0,o.jsx)(`div`,{className:`flex items-center justify-center py-8`,children:(0,o.jsx)(c.Loader2,{className:`w-6 h-6 animate-spin text-muted-foreground`})}):u.length>0?(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)(`div`,{className:t.o(i===`images`?`columns-2 sm:columns-3 lg:columns-4 gap-2 [&>div]:mb-2 [&>div]:break-inside-avoid`:t.o(`grid gap-3 auto-rows-fr`,F&&T?`grid-cols-2`:`grid-cols-3`)),children:u.map((e,t)=>H(e,t))}),g&&(0,o.jsx)(`div`,{className:`flex items-center justify-center py-4`,children:(0,o.jsx)(c.Loader2,{className:`w-5 h-5 animate-spin text-muted-foreground`})}),!C&&u.length>0&&(0,o.jsx)(`div`,{className:`flex items-center justify-center py-4 text-muted-foreground text-xs`,children:`No more results`})]}):(0,o.jsx)(`div`,{className:`flex items-center justify-center py-8 text-muted-foreground text-sm`,children:`No results found`})}),(0,o.jsx)(t.t,{open:k!==null,onOpenChange:e=>!e&&A(null),children:(0,o.jsxs)(t.n,{className:`max-w-3xl p-0 overflow-hidden gap-0`,children:[(0,o.jsx)(t.i,{className:`sr-only`,children:k?.title||`Video player`}),k&&(0,o.jsx)(`iframe`,{src:k.src,title:k.title||`Video player`,className:`w-full aspect-video`,allow:`accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture`,allowFullScreen:!0})]})})]})},x={extract:`Extract`,arxiv:`ArXiv`,"google scholar":`Scholar`,pubmed:`PubMed`,wolframalpha:`Wolfram`,youtube:`YouTube`,Web:`Web`};function S(e){return e?x[e]??e:`Web`}function C({queries:e,loading:n}){let r=e.filter(e=>e.status===`done`).length,i=e.length,a=n&&e.some(e=>e.status===`running`);return n?(0,o.jsxs)(`div`,{className:`rounded-xl border border-border bg-secondary/20 overflow-hidden text-sm`,children:[(0,o.jsxs)(`div`,{className:`flex items-center justify-between px-3 py-2 border-b border-border/50`,children:[(0,o.jsxs)(`div`,{className:`flex items-center gap-2 text-muted-foreground`,children:[a?(0,o.jsx)(c.Loader2,{className:`w-3.5 h-3.5 animate-spin`}):(0,o.jsx)(c.Search,{className:`w-3.5 h-3.5`}),(0,o.jsx)(`span`,{className:`font-medium text-foreground`,children:a?`Running analysis…`:`Analysis complete`})]}),i>0&&(0,o.jsxs)(`span`,{className:`text-xs text-muted-foreground tabular-nums`,children:[r,`/`,i,` searches`]})]}),e.length>0&&(0,o.jsx)(`div`,{className:`divide-y divide-border/40`,children:e.map((e,n)=>(0,o.jsxs)(`div`,{className:`flex items-center gap-2.5 px-3 py-2`,children:[e.status===`running`?(0,o.jsx)(c.Loader2,{className:`w-3.5 h-3.5 text-muted-foreground animate-spin flex-shrink-0`}):(0,o.jsx)(c.Search,{className:t.o(`w-3.5 h-3.5 flex-shrink-0`,e.status===`done`?`text-muted-foreground`:`text-muted-foreground/40`)}),(0,o.jsxs)(`div`,{className:`flex items-baseline gap-1.5 min-w-0 flex-1`,children:[(0,o.jsxs)(`span`,{className:`text-xs text-muted-foreground whitespace-nowrap flex-shrink-0`,children:[S(e.category),` ·`]}),(0,o.jsx)(`span`,{className:`text-foreground/80 truncate`,children:e.query})]})]},n))})]}):null}var w=({href:e,children:t,sources:r})=>{let{openPanel:i}=n.a(),s=(0,a.useMemo)(()=>!r||!e?null:r.find(t=>t.metadata?.url===e)??null,[r,e]),c=(0,a.useMemo)(()=>{try{return new URL(e).hostname.replace(`www.`,``)}catch{return s?.metadata?.source||``}},[e,s]),l=s?.metadata?.title||``,u=`https://s2.googleusercontent.com/s2/favicons?domain_url=${e}`;return(0,o.jsxs)(n.t,{children:[(0,o.jsx)(n.r,{asChild:!0,children:(0,o.jsx)(`a`,{href:e,onClick:t=>{t.preventDefault(),i(e,``)},className:`bg-light-secondary dark:bg-dark-secondary px-1 rounded ml-1 no-underline text-xs text-black/70 dark:text-white/70 relative cursor-pointer hover:bg-black/10 dark:hover:bg-white/20 transition-colors`,children:t})}),(0,o.jsx)(n.n,{side:`top`,className:`max-w-72 p-2.5`,children:(0,o.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,o.jsx)(`img`,{src:u,alt:``,width:16,height:16,className:`rounded flex-shrink-0 mt-0.5`}),(0,o.jsxs)(`div`,{className:`min-w-0`,children:[(0,o.jsx)(`p`,{className:`text-xs font-medium leading-snug line-clamp-2`,children:l||c}),l&&(0,o.jsx)(`p`,{className:`text-[10px] opacity-70 truncate mt-0.5`,children:c})]})]})})]})},T=({content:e,thinkingEnded:t})=>{let[n,r]=(0,a.useState)(!0);return(0,a.useEffect)(()=>{r(!t)},[t]),(0,o.jsxs)(`div`,{className:`my-4 bg-secondary/50 rounded-xl border border-border overflow-hidden`,children:[(0,o.jsxs)(`button`,{onClick:()=>r(!n),className:`w-full flex items-center justify-between px-4 py-1 text-foreground/90 hover:bg-secondary transition duration-200`,children:[(0,o.jsxs)(`div`,{className:`flex items-center space-x-2`,children:[(0,o.jsx)(c.BrainCircuit,{size:20,className:`text-accent-foreground`}),(0,o.jsx)(`p`,{className:`font-medium text-sm`,children:`Thinking Process`})]}),n?(0,o.jsx)(c.ChevronUp,{size:18,className:`text-muted-foreground`}):(0,o.jsx)(c.ChevronDown,{size:18,className:`text-muted-foreground`})]}),n&&(0,o.jsx)(`div`,{className:`px-4 py-3 text-foreground/80 text-sm border-t border-border bg-muted/50 whitespace-pre-wrap`,children:e})]})},E=({children:e,thinkingEnded:t})=>(0,o.jsx)(T,{content:e,thinkingEnded:t}),D=[`png`,`jpg`,`jpeg`,`gif`,`webp`,`svg`,`bmp`,`avif`],O=e=>{let t=(e||``).toLowerCase();return D.includes(t)?(0,o.jsx)(c.Image,{size:15}):t===`url`?(0,o.jsx)(c.Link2,{size:15}):(0,o.jsx)(c.FileText,{size:15})},k=({file:e})=>{let{deleteAttachedFile:r}=n.u(),[i,s]=(0,a.useState)(!1),[l,u]=(0,a.useState)(!1);return(0,o.jsxs)(o.Fragment,{children:[(0,o.jsxs)(`div`,{className:`group inline-flex max-w-full items-center gap-2 rounded-lg border border-border bg-secondary/40 py-1.5 pl-2.5 pr-1.5 text-sm`,children:[(0,o.jsx)(`span`,{className:`text-muted-foreground`,children:O(e.fileExtension)}),(0,o.jsx)(`span`,{className:`min-w-0 truncate font-medium text-foreground`,title:e.fileName,children:e.fileName}),e.fileExtension&&e.fileExtension!==`url`&&(0,o.jsx)(`span`,{className:`hidden shrink-0 text-[10px] font-semibold uppercase tracking-wider text-muted-foreground sm:inline`,children:e.fileExtension}),(0,o.jsx)(`button`,{type:`button`,"aria-label":`Delete ${e.fileName}`,onClick:()=>s(!0),className:`shrink-0 rounded-md p-1 text-muted-foreground transition-colors hover:bg-red-500/10 hover:text-red-500`,children:(0,o.jsx)(c.Trash2,{size:14})})]}),(0,o.jsx)(t.t,{open:i,onOpenChange:e=>{l||s(e)},children:(0,o.jsxs)(t.n,{className:`w-full max-w-md rounded-2xl`,children:[(0,o.jsx)(t.i,{className:`text-lg font-medium leading-6`,children:`Delete file`}),(0,o.jsxs)(t.r,{className:`text-sm text-muted-foreground`,children:[`Are you sure you want to delete`,` `,(0,o.jsx)(`span`,{className:`font-medium text-foreground`,children:e.fileName}),`? This removes it from the conversation and permanently deletes the upload.`]}),(0,o.jsxs)(`div`,{className:`mt-6 flex flex-row items-center justify-end gap-4`,children:[(0,o.jsx)(`button`,{type:`button`,onClick:()=>!l&&s(!1),className:`text-sm text-muted-foreground transition-colors hover:text-foreground`,children:`Cancel`}),(0,o.jsxs)(`button`,{type:`button`,onClick:async()=>{u(!0);try{await r(e.fileId),s(!1)}finally{u(!1)}},disabled:l,className:`inline-flex items-center gap-1.5 text-sm text-red-500 transition-colors hover:text-red-600 disabled:opacity-60`,children:[l&&(0,o.jsx)(c.Loader2,{size:14,className:`animate-spin`}),`Delete`]})]})]})})]})},A=({files:e})=>!e||e.length===0?null:(0,o.jsx)(`div`,{className:`ml-10 mt-2 flex flex-wrap gap-2`,children:e.map(e=>(0,o.jsx)(k,{file:e},e.fileId))}),j=({section:e,isExpanded:r,setIsExpanded:i,isEditing:s,setIsEditing:l,editText:u,setEditText:d,handleEditSubmit:f,copiedUserMsg:p,handleCopyUserMsg:m})=>{let h=(0,a.useRef)(null);return(0,o.jsxs)(`div`,{className:`w-full pt-8 break-words`,children:[(0,o.jsxs)(`button`,{onClick:()=>i(!r),className:`flex items-center gap-3 group text-left w-full`,children:[(0,o.jsx)(`div`,{className:`flex-shrink-0 p-1.5 rounded-lg bg-secondary/50 group-hover:bg-secondary transition-colors duration-200`,children:r?(0,o.jsx)(c.ChevronDown,{size:18,className:`text-muted-foreground group-hover:text-foreground transition-colors`}):(0,o.jsx)(c.ChevronRight,{size:18,className:`text-muted-foreground group-hover:text-foreground transition-colors`})}),(0,o.jsx)(`h2`,{className:`text-foreground font-medium text-lg lg:text-3xl lg:w-9/12 group-hover:text-foreground/80 transition-colors line-clamp-3 lg:line-clamp-none`,children:e.userMessage.content})]}),(0,o.jsxs)(`div`,{className:`flex items-center gap-0.5 mt-1 ml-10`,children:[(()=>{let n=t.s(e.userMessage.createdAt);return n?(0,o.jsx)(`time`,{dateTime:new Date(e.userMessage.createdAt).toISOString(),className:`mr-1.5 text-xs text-muted-foreground tabular-nums select-none`,children:n}):null})(),(0,o.jsxs)(n.t,{children:[(0,o.jsx)(n.r,{asChild:!0,children:(0,o.jsx)(`button`,{onClick:m,className:`p-1.5 text-muted-foreground rounded-lg hover:bg-secondary transition-all duration-200 hover:text-foreground`,children:(0,o.jsx)(`span`,{className:t.o(`flex items-center transition-all duration-300`,p?`scale-110`:`scale-100`),children:p?(0,o.jsx)(c.Check,{size:14,className:`text-green-500`}):(0,o.jsx)(c.ClipboardList,{size:14})})})}),(0,o.jsx)(n.n,{side:`bottom`,children:p?`Copied!`:`Copy prompt`})]}),(0,o.jsxs)(n.t,{children:[(0,o.jsx)(n.r,{asChild:!0,children:(0,o.jsx)(`button`,{onClick:()=>{d(e.userMessage.content),l(!0),setTimeout(()=>h.current?.focus(),50)},className:`p-1.5 text-muted-foreground rounded-lg hover:bg-secondary transition-all duration-200 hover:text-foreground`,children:(0,o.jsx)(c.Pencil,{size:14})})}),(0,o.jsx)(n.n,{side:`bottom`,children:`Edit & resubmit`})]})]}),(0,o.jsx)(A,{files:e.userMessage.files}),s&&(0,o.jsxs)(`div`,{className:`mt-3 ml-10 flex flex-col gap-2`,children:[(0,o.jsx)(`textarea`,{ref:h,value:u,onChange:e=>d(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),f()),e.key===`Escape`&&l(!1)},rows:3,className:`w-full rounded-xl border border-border bg-background p-3 text-sm resize-none focus:outline-none focus:ring-2 focus:ring-primary/30 transition-colors`}),(0,o.jsxs)(`div`,{className:`flex gap-2 justify-end`,children:[(0,o.jsx)(`button`,{onClick:()=>l(!1),className:`px-3 py-1.5 text-sm text-muted-foreground rounded-lg hover:bg-secondary transition-colors duration-200`,children:`Cancel`}),(0,o.jsx)(`button`,{onClick:f,disabled:!u.trim(),className:`px-3 py-1.5 text-sm bg-primary text-primary-foreground rounded-lg hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed transition-colors duration-200`,children:`Resubmit`})]})]})]})},M=({section:e,initialMessage:t})=>{let[r,i]=(0,a.useState)(!1);return(0,o.jsxs)(n.t,{children:[(0,o.jsx)(n.r,{asChild:!0,children:(0,o.jsx)(`button`,{onClick:()=>{let n=`${t}${e?.sourceMessage?.sources&&e.sourceMessage.sources.length>0&&`\n\nCitations:\n${e.sourceMessage.sources?.map((e,t)=>`[${t+1}] ${e.metadata.url}`).join(`
|
|
17
|
-
`)}`}`;navigator.clipboard.writeText(n),i(!0),setTimeout(()=>i(!1),1e3)},className:`p-2 text-muted-foreground rounded-full backdrop-blur-md bg-white/10 dark:bg-black/10 hover:bg-white/20 dark:hover:bg-black/20 transition duration-200 hover:text-foreground`,children:r?(0,o.jsx)(c.Check,{size:18}):(0,o.jsx)(c.ClipboardList,{size:18})})}),(0,o.jsx)(n.n,{side:`bottom`,children:r?`Copied!`:`Copy`})]})};function N({...e}){return(0,o.jsx)(p.Root,{"data-slot":`popover`,...e})}function P({...e}){return(0,o.jsx)(p.Trigger,{"data-slot":`popover-trigger`,...e})}function F({className:e,align:n=`center`,sideOffset:r=4,container:i,...a}){return(0,o.jsx)(p.Portal,{container:i,children:(0,o.jsx)(p.Content,{"data-slot":`popover-content`,align:n,sideOffset:r,className:t.o(`bg-popover text-popover-foreground 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 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-2xl border p-4 shadow-md outline-hidden`,e),...a})})}var I=({messageId:e})=>{let{rewrite:i,chatModelProvider:s,setChatModelProvider:u}=n.u(),[d,f]=(0,a.useState)([]),[p,m]=(0,a.useState)(!0),[h,g]=(0,a.useState)(``),[_,v]=(0,a.useState)(!1);(0,a.useEffect)(()=>{_&&(async()=>{try{m(!0);let{data:e}=await(0,l.listProviders)();f(e?.providers??[])}catch(e){console.error(`Error loading providers:`,e)}finally{m(!1)}})()},[_]);let y=(0,a.useMemo)(()=>{if(!s?.providerId)return d;let e=d.findIndex(e=>e.id===s.providerId);return e===-1?d:[d[e],...d.filter((t,n)=>n!==e)]},[d,s]).map(e=>({...e,chatModels:(e.chatModels??[]).filter(t=>t.name.toLowerCase().includes(h.toLowerCase())||e.name.toLowerCase().includes(h.toLowerCase()))})).filter(e=>e.chatModels.length>0),b=(0,a.useMemo)(()=>{if(!s.key)return`Rewrite`;for(let e of d){let t=e.chatModels.find(e=>e.key===s.key);if(t)return t.name}return s.key},[d,s.key]),x=(t,n)=>{u({providerId:t,key:n}),localStorage.setItem(`chatModelProviderId`,t),localStorage.setItem(`chatModelKey`,n),v(!1),i(e)};return(0,o.jsxs)(N,{open:_,onOpenChange:v,children:[(0,o.jsxs)(n.t,{children:[(0,o.jsx)(n.r,{asChild:!0,children:(0,o.jsx)(P,{asChild:!0,children:(0,o.jsx)(`button`,{className:`p-2 text-muted-foreground rounded-full backdrop-blur-md bg-white/10 dark:bg-black/10 hover:bg-white/20 dark:hover:bg-black/20 transition duration-200 hover:text-foreground`,children:(0,o.jsx)(c.ArrowLeftRight,{size:18})})})}),(0,o.jsxs)(n.n,{side:`bottom`,children:[`Rewrite with `,b]})]}),(0,o.jsx)(F,{className:`w-[280px] p-0`,align:`start`,side:`top`,sideOffset:8,children:(0,o.jsxs)(`div`,{className:`bg-white dark:bg-[#212121] max-h-[400px] border rounded-2xl border-[#DDDDDD] dark:border-[#30302E] w-full flex flex-col shadow-2xl overflow-hidden`,children:[(0,o.jsx)(`div`,{className:`p-3 border-b border-[#EEEEEE] dark:border-[#30302E]`,children:(0,o.jsxs)(`div`,{className:`relative`,children:[(0,o.jsx)(c.Search,{size:14,className:`absolute left-3 top-1/2 -translate-y-1/2 text-text-400 dark:text-[#999999]`}),(0,o.jsx)(`input`,{type:`text`,placeholder:`Search models...`,value:h,onChange:e=>g(e.target.value),className:`w-full pl-9 pr-3 py-2 text-[13px] bg-bg-100 dark:bg-[#30302E] border border-bg-300 dark:border-[#404040] rounded-lg text-text-100 dark:text-[#ECECEC] placeholder:text-text-400 dark:placeholder:text-[#999999] focus:outline-none focus:ring-2 focus:ring-sky-500/20 focus:border-sky-500/30 transition-all`})]})}),(0,o.jsx)(`div`,{className:`max-h-[320px] overflow-y-auto`,children:p?(0,o.jsx)(`div`,{className:`flex items-center justify-center py-12`,children:(0,o.jsx)(r.tt.Loader2,{className:`animate-spin text-text-400 dark:text-[#999999]`,size:20})}):y.length===0?(0,o.jsx)(`div`,{className:`text-center py-12 px-4 text-text-400 dark:text-[#999999] text-sm`,children:h?`No models found`:`No chat models configured`}):(0,o.jsx)(`div`,{className:`flex flex-col`,children:y.map((e,n)=>(0,o.jsxs)(`div`,{children:[(0,o.jsx)(`div`,{className:`px-4 py-2 sticky top-0 bg-white dark:bg-[#212121] border-b border-[#EEEEEE]/50 dark:border-[#30302E]/50`,children:(0,o.jsx)(`p`,{className:`text-[11px] text-text-400 dark:text-[#999999] uppercase tracking-wider font-medium`,children:e.name})}),(0,o.jsx)(`div`,{className:`flex flex-col px-1.5 py-1.5 space-y-0.5`,children:e.chatModels.map(n=>(0,o.jsxs)(`button`,{onClick:()=>x(e.id,n.key),type:`button`,className:t.o(`px-3 py-2 flex items-center justify-between text-start duration-200 cursor-pointer transition rounded-xl group`,s?.providerId===e.id&&s?.key===n.key?`bg-sky-50 dark:bg-sky-500/10`:`hover:bg-bg-100 dark:hover:bg-[#30302E]`),children:[(0,o.jsxs)(`div`,{className:`flex items-center space-x-2.5 min-w-0 flex-1`,children:[(0,o.jsx)(c.Cpu,{size:14,className:t.o(`shrink-0`,s?.providerId===e.id&&s?.key===n.key?`text-sky-500`:`text-text-400 dark:text-[#999999] group-hover:text-text-300 dark:group-hover:text-[#B4B4B4]`)}),(0,o.jsx)(`p`,{className:t.o(`text-[13px] truncate`,s?.providerId===e.id&&s?.key===n.key?`text-sky-600 dark:text-sky-400 font-medium`:`text-text-200 dark:text-[#ECECEC] group-hover:text-text-100 dark:group-hover:text-white`),children:n.name})]}),s?.providerId===e.id&&s?.key===n.key&&(0,o.jsx)(r.tt.Check,{className:`w-4 h-4 text-sky-500 shrink-0`})]},n.key))}),n<y.length-1&&(0,o.jsx)(`div`,{className:`h-px bg-[#EEEEEE] dark:bg-[#30302E] mx-2`})]},e.id))})})]})})]})},L=({section:e,speechStatus:t,isLoadingTTS:i=!1,start:a,stop:s,handleOpenInLLM:l})=>e.assistantMessage?(0,o.jsx)(`div`,{className:`flex flex-row items-center justify-end w-full text-foreground py-4 -mx-2`,children:(0,o.jsxs)(`div`,{className:`flex flex-row items-center space-x-1`,children:[(0,o.jsx)(I,{messageId:e.assistantMessage.messageId}),(0,o.jsx)(M,{initialMessage:e.assistantMessage.content,section:e}),(0,o.jsxs)(n.t,{children:[(0,o.jsx)(n.r,{asChild:!0,children:(0,o.jsx)(`button`,{onClick:()=>{t===`started`?s():a()},disabled:i,className:`p-2 text-muted-foreground rounded-full backdrop-blur-md bg-white/10 dark:bg-black/10 hover:bg-white/20 dark:hover:bg-black/20 transition duration-200 hover:text-foreground disabled:opacity-50 disabled:cursor-not-allowed`,children:i?(0,o.jsx)(c.Loader2,{size:18,className:`animate-spin`}):t===`started`?(0,o.jsx)(c.StopCircle,{size:18}):(0,o.jsx)(c.Volume2,{size:18})})}),(0,o.jsx)(n.n,{side:`bottom`,children:i?`Loading TTS...`:t===`started`?`Stop`:`Read aloud`})]}),(0,o.jsxs)(r.Y,{children:[(0,o.jsxs)(n.t,{children:[(0,o.jsx)(n.r,{asChild:!0,children:(0,o.jsx)(r.Q,{asChild:!0,children:(0,o.jsx)(`button`,{className:`p-2 text-muted-foreground rounded-full backdrop-blur-md bg-white/10 dark:bg-black/10 hover:bg-white/20 dark:hover:bg-black/20 transition duration-200 hover:text-foreground`,children:(0,o.jsx)(c.Download,{size:18})})})}),(0,o.jsx)(n.n,{side:`bottom`,children:`Export`})]}),(0,o.jsxs)(r.X,{align:`end`,side:`top`,children:[(0,o.jsxs)(r.Z,{onClick:()=>r.G(e.userMessage.content,e.assistantMessage.content),children:[(0,o.jsx)(c.FileText,{size:16}),`Markdown`]}),(0,o.jsxs)(r.Z,{onClick:()=>r.K(e.userMessage.content,e.assistantMessage.content),children:[(0,o.jsx)(c.FileType,{size:16}),`PDF`]}),(0,o.jsxs)(r.Z,{onClick:()=>r.W(e.userMessage.content,e.assistantMessage.content),children:[(0,o.jsx)(c.FileDown,{size:16}),`DOCX`]}),(0,o.jsxs)(r.Z,{onClick:()=>r.q(e.userMessage.content,e.assistantMessage.content),children:[(0,o.jsx)(c.FileSpreadsheet,{size:16}),`Google Docs`]})]})]}),(0,o.jsxs)(r.Y,{children:[(0,o.jsxs)(n.t,{children:[(0,o.jsx)(n.r,{asChild:!0,children:(0,o.jsx)(r.Q,{asChild:!0,children:(0,o.jsx)(`button`,{className:`p-2 text-muted-foreground rounded-full backdrop-blur-md bg-white/10 dark:bg-black/10 hover:bg-white/20 dark:hover:bg-black/20 transition duration-200 hover:text-foreground`,children:(0,o.jsx)(c.ExternalLink,{size:18})})})}),(0,o.jsx)(n.n,{side:`bottom`,children:`Open in LLM`})]}),(0,o.jsxs)(r.X,{align:`end`,side:`top`,children:[(0,o.jsx)(r.Z,{onClick:()=>l(`qwksearch`),children:`QwkSearch`}),(0,o.jsx)(r.Z,{onClick:()=>l(`claude`),children:`Claude`}),(0,o.jsx)(r.Z,{onClick:()=>l(`perplexity`),children:`Perplexity`}),(0,o.jsx)(r.Z,{onClick:()=>l(`gemini`),children:`Google Gemini`}),(0,o.jsx)(r.Z,{onClick:()=>l(`chatgpt`),children:`ChatGPT`})]})]})]})}):null,R=({section:e,isLast:t,loading:n,sendMessage:i})=>{let s=(0,a.useRef)([]);return(0,a.useEffect)(()=>{e.suggestions&&e.suggestions.length>0&&(s.current=e.suggestions.slice(0,5))},[e.suggestions]),(0,a.useEffect)(()=>{let e=e=>{let t=e.target;if(t.tagName===`INPUT`||t.tagName===`TEXTAREA`||t.isContentEditable)return;let n=e.key,r=parseInt(n);r>=1&&r<=5&&s.current.length>=r&&(e.preventDefault(),i(s.current[r-1]))};if(t&&s.current.length>0)return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[t,i]),!e.suggestions||e.suggestions.length===0||!e.assistantMessage?null:(0,o.jsx)(`div`,{className:`mt-8 pt-6 border-t border-border/50`,children:(0,o.jsx)(`div`,{className:`space-y-2`,children:e.suggestions?.slice(0,5).map((e,t)=>(0,o.jsx)(`button`,{onClick:()=>i(e),className:`group w-full px-4 py-4 text-left transition-all duration-200 cursor-pointer rounded-lg border border-border/50 hover:border-primary/30 hover:bg-accent/50 hover:shadow-sm`,children:(0,o.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,o.jsx)(r.V,{variant:`secondary`,className:`flex-shrink-0 h-6 w-6 p-0 flex items-center justify-center rounded-full text-sm font-semibold`,children:t+1}),(0,o.jsx)(`p`,{className:`flex-1 text-base font-medium text-muted-foreground group-hover:text-primary transition-colors duration-200 leading-relaxed`,children:e}),(0,o.jsx)(c.Plus,{size:18,className:`text-muted-foreground/60 group-hover:text-primary transition-colors duration-200 flex-shrink-0`})]})},t))})})},z=({section:e,dividerRef:i,isLast:s})=>{let{loading:c,sendMessage:l}=n.u(),[u,f]=(0,a.useState)(!0),[p,m]=(0,a.useState)(!1),[h,g]=(0,a.useState)(!1),[_,v]=(0,a.useState)(e.userMessage.content),y=()=>{navigator.clipboard.writeText(e.userMessage.content),m(!0),setTimeout(()=>m(!1),1500)},x=()=>{_.trim()&&(l(_.trim()),g(!1))},S=e.parsedAssistantMessage||``,T=e.speechMessage||``,D=e.thinkingEnded,{speechStatus:O,start:k,stop:A,isLoading:M}=r.d(T,{enableInterrupt:!0}),N=t=>{if(!e.assistantMessage)return;let n=`${e.userMessage.content}\n\n${e.assistantMessage.content}`;navigator.clipboard.writeText(n);let r={qwksearch:`https://qwksearch.com/?q=`,claude:`https://claude.ai/new?q=`,perplexity:`https://www.perplexity.ai/?q=`,gemini:`https://gemini.google.com/?q=`,chatgpt:`https://chat.openai.com/?q=`}[t];r&&window.open(`${r}${encodeURIComponent(n)}`,`_blank`)},P={overrides:{think:{component:E,props:{thinkingEnded:D}},citation:{component:w,props:{sources:e.sourceMessage?.sources||[]}},table:{component:({children:e,...t})=>(0,o.jsx)(`div`,{className:`not-prose -mx-2 my-4 max-w-full overflow-x-auto sm:mx-0`,children:(0,o.jsx)(`table`,{...t,className:`w-max min-w-full border-collapse text-sm`,children:e})})}}};return(0,o.jsxs)(`div`,{className:`space-y-3`,children:[(0,o.jsx)(j,{section:e,isExpanded:u,setIsExpanded:f,isEditing:h,setIsEditing:g,editText:_,setEditText:v,handleEditSubmit:x,copiedUserMsg:p,handleCopyUserMsg:y}),(0,o.jsx)(`div`,{className:t.o(`flex flex-col space-y-3 overflow-hidden transition-all duration-300 ease-in-out`,u?`max-h-[100000px] opacity-100`:`max-h-0 opacity-0`),children:(0,o.jsxs)(`div`,{ref:i,className:`flex flex-col space-y-6 w-full`,children:[e.searchingMessage&&e.searchingMessage.queries.length>0&&(0,o.jsx)(C,{queries:e.searchingMessage.queries,loading:c&&s}),e.sourceMessage&&e.sourceMessage.sources.length>0&&(0,o.jsx)(`div`,{className:`flex flex-col space-y-2`,children:(0,o.jsx)(b,{sources:e.sourceMessage.sources,query:e.userMessage.content})}),(0,o.jsx)(`div`,{className:`flex min-w-0 flex-col space-y-2`,children:e.assistantMessage&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)(d.default,{className:t.o(`prose prose-lg prose-h1:mb-3 prose-h2:mb-2 prose-h2:mt-6 prose-h2:font-[800] prose-h3:mt-4 prose-h3:mb-1.5 prose-h3:font-[600] dark:prose-invert prose-p:leading-loose prose-pre:p-0 font-[400]`,`min-w-0 max-w-none break-words text-foreground font-inter`),options:P,children:S}),c&&s?null:(0,o.jsx)(L,{section:e,speechStatus:O,isLoadingTTS:M,start:k,stop:A,handleOpenInLLM:N}),(0,o.jsx)(R,{section:e,isLast:s,loading:c,sendMessage:l})]})})]})})]})},B=[`default`,`circle`,`pinwheel`,`circle-filled`,`ellipsis`,`ring`,`bars`,`infinite`],V=`M12 12c-2-2.67-4-4-6-4a4 4 0 1 0 0 8c2 0 4-1.33 6-4Zm0 0c2 2.67 4 4 6 4a4 4 0 0 0 0-8c-2 0-4 1.33-6 4Z`,H={transformBox:`view-box`,transformOrigin:`center`},U=[[12,2,12,6],[16.24,7.76,19.07,4.93],[18,12,22,12],[16.24,16.24,19.07,19.07],[12,18,12,22],[4.93,19.07,7.76,16.24],[2,12,6,12],[4.93,4.93,7.76,7.76]],W=e=>{switch(e){case`circle`:return(0,o.jsx)(`g`,{className:`animate-spin`,style:H,children:(0,o.jsx)(`path`,{d:`M21 12a9 9 0 1 1-6.219-8.56`})});case`pinwheel`:return(0,o.jsxs)(`g`,{className:`animate-spin`,style:H,children:[(0,o.jsx)(`path`,{d:`M22 12a1 1 0 0 1-10 0 1 1 0 0 0-10 0`}),(0,o.jsx)(`path`,{d:`M7 20.7a1 1 0 1 1 5-8.7 1 1 0 1 0 5-8.6`}),(0,o.jsx)(`path`,{d:`M7 3.3a1 1 0 1 1 5 8.6 1 1 0 1 0 5 8.6`}),(0,o.jsx)(`circle`,{cx:`12`,cy:`12`,r:`10`})]});case`circle-filled`:return(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)(`circle`,{cx:`12`,cy:`12`,r:`9`,opacity:`0.2`}),(0,o.jsx)(`g`,{className:`animate-spin`,style:H,children:(0,o.jsx)(`path`,{d:`M21 12a9 9 0 0 0-9-9`})})]});case`ellipsis`:return(0,o.jsx)(`g`,{fill:`currentColor`,stroke:`none`,children:[4,12,20].map((e,t)=>(0,o.jsx)(`circle`,{cx:e,cy:`12`,r:`2.5`,children:(0,o.jsx)(`animate`,{attributeName:`cy`,values:`12;7.5;12`,keyTimes:`0;0.5;1`,dur:`1.2s`,begin:`${t*.16}s`,repeatCount:`indefinite`})},e))});case`ring`:return(0,o.jsx)(o.Fragment,{children:[0,-.8].map(e=>(0,o.jsxs)(`circle`,{cx:`12`,cy:`12`,r:`2`,children:[(0,o.jsx)(`animate`,{attributeName:`r`,values:`2;11`,dur:`1.6s`,begin:`${e}s`,repeatCount:`indefinite`}),(0,o.jsx)(`animate`,{attributeName:`opacity`,values:`1;0`,dur:`1.6s`,begin:`${e}s`,repeatCount:`indefinite`})]},e))});case`bars`:return(0,o.jsx)(`g`,{fill:`currentColor`,stroke:`none`,children:[2.5,10,17.5].map((e,t)=>(0,o.jsxs)(`rect`,{x:e,y:`8`,width:`4`,height:`8`,rx:`1.5`,children:[(0,o.jsx)(`animate`,{attributeName:`height`,values:`8;18;8`,keyTimes:`0;0.5;1`,dur:`1.1s`,begin:`${t*.18}s`,repeatCount:`indefinite`}),(0,o.jsx)(`animate`,{attributeName:`y`,values:`8;3;8`,keyTimes:`0;0.5;1`,dur:`1.1s`,begin:`${t*.18}s`,repeatCount:`indefinite`})]},e))});case`infinite`:return(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)(`path`,{d:V,opacity:`0.2`}),(0,o.jsx)(`path`,{d:V,pathLength:`100`,strokeDasharray:`25 75`,children:(0,o.jsx)(`animate`,{attributeName:`stroke-dashoffset`,values:`100;0`,dur:`1.5s`,repeatCount:`indefinite`})})]});default:return(0,o.jsx)(`g`,{className:`animate-spin`,style:H,children:U.map(([e,t,n,r],i)=>(0,o.jsx)(`line`,{x1:e,y1:t,x2:n,y2:r,opacity:1-i*.1},`${e}-${t}`))})}},G=({variant:e=`default`,size:n=24,className:r,...i})=>(0,o.jsx)(`svg`,{"aria-hidden":`true`,xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 24 24`,width:n,height:n,fill:`none`,stroke:`currentColor`,strokeWidth:2,strokeLinecap:`round`,strokeLinejoin:`round`,className:t.o(`shrink-0`,r),...i,children:W(e)}),K=`quantumSphere`,q=`spinner:`,J=new Set([`loadingSpokes`,`loadingCircleNotch`,`loadingPinwheel`,`loadingCircleTrack`,`loadingDotsBounce`,`loadingPulseRing`,`loadingEqualizerBars`,`loadingInfiniteDash`]),Y=Object.fromEntries(Object.entries(m).filter(([e,t])=>typeof t==`function`&&e.startsWith(`loading`)&&!J.has(e))),X=[K,...B.map(e=>`${q}${e}`),...Object.keys(Y).sort()],Z;function Q(){let e=X.filter(e=>e!==Z),t=e.length>0?e:X;return Z=t[Math.floor(Math.random()*t.length)],Z}function $(e){if(!e.startsWith(`spinner:`))return;let t=e.slice(8);return B.find(e=>e===t)}function ee(e,t){let n=Y[e];return n?n({size:t,raw:!0}):``}var te=({size:e=140,className:n})=>{let[r,i]=(0,a.useState)(null);(0,a.useEffect)(()=>{i(Q())},[]);let s=r?$(r):void 0;return(0,o.jsx)(`div`,{role:`status`,"aria-label":`Loading`,className:t.o(`flex items-center justify-center w-full h-[200px]`,n),children:r===`quantumSphere`?(0,o.jsx)(u.default,{autoRandomize:!0}):s?(0,o.jsx)(G,{variant:s,size:e,className:`text-muted-foreground`}):r?(0,o.jsx)(`div`,{className:`flex items-center justify-center`,dangerouslySetInnerHTML:{__html:ee(r,e)}}):null})},ne=(0,a.lazy)(()=>Promise.resolve().then(()=>require("./ArticleExtractPanel-25tRTnpl.cjs"))),re=()=>{let{sections:e,chatTurns:t,loading:s,messageAppeared:c,newChat:l,chatId:u}=n.u(),{isOpen:d,panelWidth:f}=n.a(),{isAuthenticated:p}=n.c(),[m,h]=(0,a.useState)(!1);(0,a.useEffect)(()=>{d&&h(!0)},[d]);let[g,_]=(0,a.useState)(!1),v=(0,a.useRef)(null),y=(0,a.useRef)(null),b=(0,a.useRef)(!1);(0,a.useEffect)(()=>{let e=()=>{_(window.innerWidth>=1024)};return e(),window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[]),(0,a.useEffect)(()=>{t.length===1&&(document.title=`${t[0].content.substring(0,30)} - ${i.researchAgentUIConfig.appName}`),t[t.length-1]?.role===`user`&&(b.current=!0,y.current?.scrollIntoView({behavior:`auto`}),setTimeout(()=>{b.current=!1},100))},[t]);let x=g&&d?{width:`calc(100% - ${f}px)`}:{};return(0,o.jsxs)(o.Fragment,{children:[(0,o.jsxs)(`div`,{className:`flex flex-col min-h-full transition-all duration-300`,style:x,children:[(0,o.jsxs)(`div`,{className:`flex-1 flex flex-col space-y-3 pb-48 ${g&&!d?`px-0 max-w-[800px] mx-auto w-full`:`px-4 lg:px-8`}`,children:[e.map((t,n)=>{let r=n===e.length-1;return(0,o.jsxs)(a.Fragment,{children:[(0,o.jsx)(z,{section:t,sectionIndex:n,dividerRef:r?v:void 0,isLast:r}),!r&&(0,o.jsx)(`div`,{className:`h-px w-full bg-light-secondary dark:bg-dark-secondary`})]},t.userMessage.messageId)}),s&&!c&&(0,o.jsx)(te,{}),(0,o.jsx)(`div`,{ref:y,className:`h-0`})]}),(0,o.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,o.jsx)(r.U,{})})]}),(m||d)&&(0,o.jsx)(a.Suspense,{fallback:null,children:(0,o.jsx)(ne,{})})]})};exports.default=re;
|
|
17
|
+
`)}`}`;navigator.clipboard.writeText(n),i(!0),setTimeout(()=>i(!1),1e3)},className:`p-2 text-muted-foreground rounded-full backdrop-blur-md bg-white/10 dark:bg-black/10 hover:bg-white/20 dark:hover:bg-black/20 transition duration-200 hover:text-foreground`,children:r?(0,o.jsx)(c.Check,{size:18}):(0,o.jsx)(c.ClipboardList,{size:18})})}),(0,o.jsx)(n.n,{side:`bottom`,children:r?`Copied!`:`Copy`})]})};function N({...e}){return(0,o.jsx)(p.Root,{"data-slot":`popover`,...e})}function P({...e}){return(0,o.jsx)(p.Trigger,{"data-slot":`popover-trigger`,...e})}function F({className:e,align:n=`center`,sideOffset:r=4,container:i,...a}){return(0,o.jsx)(p.Portal,{container:i,children:(0,o.jsx)(p.Content,{"data-slot":`popover-content`,align:n,sideOffset:r,className:t.o(`bg-popover text-popover-foreground 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 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-2xl border p-4 shadow-md outline-hidden`,e),...a})})}var I=({messageId:e})=>{let{rewrite:i,chatModelProvider:s,setChatModelProvider:u}=n.u(),[d,f]=(0,a.useState)([]),[p,m]=(0,a.useState)(!0),[h,g]=(0,a.useState)(``),[_,v]=(0,a.useState)(!1);(0,a.useEffect)(()=>{_&&(async()=>{try{m(!0);let{data:e}=await(0,l.listProviders)();f(e?.providers??[])}catch(e){console.error(`Error loading providers:`,e)}finally{m(!1)}})()},[_]);let y=(0,a.useMemo)(()=>{if(!s?.providerId)return d;let e=d.findIndex(e=>e.id===s.providerId);return e===-1?d:[d[e],...d.filter((t,n)=>n!==e)]},[d,s]).map(e=>({...e,chatModels:(e.chatModels??[]).filter(t=>t.name.toLowerCase().includes(h.toLowerCase())||e.name.toLowerCase().includes(h.toLowerCase()))})).filter(e=>e.chatModels.length>0),b=(0,a.useMemo)(()=>{if(!s.key)return`Rewrite`;for(let e of d){let t=e.chatModels.find(e=>e.key===s.key);if(t)return t.name}return s.key},[d,s.key]),x=(t,n)=>{u({providerId:t,key:n}),localStorage.setItem(`chatModelProviderId`,t),localStorage.setItem(`chatModelKey`,n),v(!1),i(e)};return(0,o.jsxs)(N,{open:_,onOpenChange:v,children:[(0,o.jsxs)(n.t,{children:[(0,o.jsx)(n.r,{asChild:!0,children:(0,o.jsx)(P,{asChild:!0,children:(0,o.jsx)(`button`,{className:`p-2 text-muted-foreground rounded-full backdrop-blur-md bg-white/10 dark:bg-black/10 hover:bg-white/20 dark:hover:bg-black/20 transition duration-200 hover:text-foreground`,children:(0,o.jsx)(c.ArrowLeftRight,{size:18})})})}),(0,o.jsxs)(n.n,{side:`bottom`,children:[`Rewrite with `,b]})]}),(0,o.jsx)(F,{className:`w-[280px] p-0`,align:`start`,side:`top`,sideOffset:8,children:(0,o.jsxs)(`div`,{className:`bg-white dark:bg-[#212121] max-h-[400px] border rounded-2xl border-[#DDDDDD] dark:border-[#30302E] w-full flex flex-col shadow-2xl overflow-hidden`,children:[(0,o.jsx)(`div`,{className:`p-3 border-b border-[#EEEEEE] dark:border-[#30302E]`,children:(0,o.jsxs)(`div`,{className:`relative`,children:[(0,o.jsx)(c.Search,{size:14,className:`absolute left-3 top-1/2 -translate-y-1/2 text-text-400 dark:text-[#999999]`}),(0,o.jsx)(`input`,{type:`text`,placeholder:`Search models...`,value:h,onChange:e=>g(e.target.value),className:`w-full pl-9 pr-3 py-2 text-[13px] bg-bg-100 dark:bg-[#30302E] border border-bg-300 dark:border-[#404040] rounded-lg text-text-100 dark:text-[#ECECEC] placeholder:text-text-400 dark:placeholder:text-[#999999] focus:outline-none focus:ring-2 focus:ring-sky-500/20 focus:border-sky-500/30 transition-all`})]})}),(0,o.jsx)(`div`,{className:`max-h-[320px] overflow-y-auto`,children:p?(0,o.jsx)(`div`,{className:`flex items-center justify-center py-12`,children:(0,o.jsx)(r.tt.Loader2,{className:`animate-spin text-text-400 dark:text-[#999999]`,size:20})}):y.length===0?(0,o.jsx)(`div`,{className:`text-center py-12 px-4 text-text-400 dark:text-[#999999] text-sm`,children:h?`No models found`:`No chat models configured`}):(0,o.jsx)(`div`,{className:`flex flex-col`,children:y.map((e,n)=>(0,o.jsxs)(`div`,{children:[(0,o.jsx)(`div`,{className:`px-4 py-2 sticky top-0 bg-white dark:bg-[#212121] border-b border-[#EEEEEE]/50 dark:border-[#30302E]/50`,children:(0,o.jsx)(`p`,{className:`text-[11px] text-text-400 dark:text-[#999999] uppercase tracking-wider font-medium`,children:e.name})}),(0,o.jsx)(`div`,{className:`flex flex-col px-1.5 py-1.5 space-y-0.5`,children:e.chatModels.map(n=>(0,o.jsxs)(`button`,{onClick:()=>x(e.id,n.key),type:`button`,className:t.o(`px-3 py-2 flex items-center justify-between text-start duration-200 cursor-pointer transition rounded-xl group`,s?.providerId===e.id&&s?.key===n.key?`bg-sky-50 dark:bg-sky-500/10`:`hover:bg-bg-100 dark:hover:bg-[#30302E]`),children:[(0,o.jsxs)(`div`,{className:`flex items-center space-x-2.5 min-w-0 flex-1`,children:[(0,o.jsx)(c.Cpu,{size:14,className:t.o(`shrink-0`,s?.providerId===e.id&&s?.key===n.key?`text-sky-500`:`text-text-400 dark:text-[#999999] group-hover:text-text-300 dark:group-hover:text-[#B4B4B4]`)}),(0,o.jsx)(`p`,{className:t.o(`text-[13px] truncate`,s?.providerId===e.id&&s?.key===n.key?`text-sky-600 dark:text-sky-400 font-medium`:`text-text-200 dark:text-[#ECECEC] group-hover:text-text-100 dark:group-hover:text-white`),children:n.name})]}),s?.providerId===e.id&&s?.key===n.key&&(0,o.jsx)(r.tt.Check,{className:`w-4 h-4 text-sky-500 shrink-0`})]},n.key))}),n<y.length-1&&(0,o.jsx)(`div`,{className:`h-px bg-[#EEEEEE] dark:bg-[#30302E] mx-2`})]},e.id))})})]})})]})},L=({section:e,speechStatus:t,isLoadingTTS:i=!1,start:a,stop:s,handleOpenInLLM:l})=>e.assistantMessage?(0,o.jsx)(`div`,{className:`flex flex-row items-center justify-end w-full text-foreground py-4 -mx-2`,children:(0,o.jsxs)(`div`,{className:`flex flex-row items-center space-x-1`,children:[(0,o.jsx)(I,{messageId:e.assistantMessage.messageId}),(0,o.jsx)(M,{initialMessage:e.assistantMessage.content,section:e}),(0,o.jsxs)(n.t,{children:[(0,o.jsx)(n.r,{asChild:!0,children:(0,o.jsx)(`button`,{onClick:()=>{t===`started`?s():a()},disabled:i,className:`p-2 text-muted-foreground rounded-full backdrop-blur-md bg-white/10 dark:bg-black/10 hover:bg-white/20 dark:hover:bg-black/20 transition duration-200 hover:text-foreground disabled:opacity-50 disabled:cursor-not-allowed`,children:i?(0,o.jsx)(c.Loader2,{size:18,className:`animate-spin`}):t===`started`?(0,o.jsx)(c.StopCircle,{size:18}):(0,o.jsx)(c.Volume2,{size:18})})}),(0,o.jsx)(n.n,{side:`bottom`,children:i?`Loading TTS...`:t===`started`?`Stop`:`Read aloud`})]}),(0,o.jsxs)(r.Y,{children:[(0,o.jsxs)(n.t,{children:[(0,o.jsx)(n.r,{asChild:!0,children:(0,o.jsx)(r.Q,{asChild:!0,children:(0,o.jsx)(`button`,{className:`p-2 text-muted-foreground rounded-full backdrop-blur-md bg-white/10 dark:bg-black/10 hover:bg-white/20 dark:hover:bg-black/20 transition duration-200 hover:text-foreground`,children:(0,o.jsx)(c.Download,{size:18})})})}),(0,o.jsx)(n.n,{side:`bottom`,children:`Export`})]}),(0,o.jsxs)(r.X,{align:`end`,side:`top`,children:[(0,o.jsxs)(r.Z,{onClick:()=>r.G(e.userMessage.content,e.assistantMessage.content),children:[(0,o.jsx)(c.FileText,{size:16}),`Markdown`]}),(0,o.jsxs)(r.Z,{onClick:()=>r.K(e.userMessage.content,e.assistantMessage.content),children:[(0,o.jsx)(c.FileType,{size:16}),`PDF`]}),(0,o.jsxs)(r.Z,{onClick:()=>r.W(e.userMessage.content,e.assistantMessage.content),children:[(0,o.jsx)(c.FileDown,{size:16}),`DOCX`]}),(0,o.jsxs)(r.Z,{onClick:()=>r.q(e.userMessage.content,e.assistantMessage.content),children:[(0,o.jsx)(c.FileSpreadsheet,{size:16}),`Google Docs`]})]})]}),(0,o.jsxs)(r.Y,{children:[(0,o.jsxs)(n.t,{children:[(0,o.jsx)(n.r,{asChild:!0,children:(0,o.jsx)(r.Q,{asChild:!0,children:(0,o.jsx)(`button`,{className:`p-2 text-muted-foreground rounded-full backdrop-blur-md bg-white/10 dark:bg-black/10 hover:bg-white/20 dark:hover:bg-black/20 transition duration-200 hover:text-foreground`,children:(0,o.jsx)(c.ExternalLink,{size:18})})})}),(0,o.jsx)(n.n,{side:`bottom`,children:`Open in LLM`})]}),(0,o.jsxs)(r.X,{align:`end`,side:`top`,children:[(0,o.jsx)(r.Z,{onClick:()=>l(`qwksearch`),children:`QwkSearch`}),(0,o.jsx)(r.Z,{onClick:()=>l(`claude`),children:`Claude`}),(0,o.jsx)(r.Z,{onClick:()=>l(`perplexity`),children:`Perplexity`}),(0,o.jsx)(r.Z,{onClick:()=>l(`gemini`),children:`Google Gemini`}),(0,o.jsx)(r.Z,{onClick:()=>l(`chatgpt`),children:`ChatGPT`})]})]})]})}):null,R=({section:e,isLast:t,loading:n,sendMessage:i})=>{let s=(0,a.useRef)([]);return(0,a.useEffect)(()=>{e.suggestions&&e.suggestions.length>0&&(s.current=e.suggestions.slice(0,5))},[e.suggestions]),(0,a.useEffect)(()=>{let e=e=>{let t=e.target;if(t.tagName===`INPUT`||t.tagName===`TEXTAREA`||t.isContentEditable)return;let n=e.key,r=parseInt(n);r>=1&&r<=5&&s.current.length>=r&&(e.preventDefault(),i(s.current[r-1]))};if(t&&s.current.length>0)return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[t,i]),!e.suggestions||e.suggestions.length===0||!e.assistantMessage?null:(0,o.jsx)(`div`,{className:`mt-8 pt-6 border-t border-border/50`,children:(0,o.jsx)(`div`,{className:`space-y-2`,children:e.suggestions?.slice(0,5).map((e,t)=>(0,o.jsx)(`button`,{onClick:()=>i(e),className:`group w-full px-4 py-4 text-left transition-all duration-200 cursor-pointer rounded-lg border border-border/50 hover:border-primary/30 hover:bg-accent/50 hover:shadow-sm`,children:(0,o.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,o.jsx)(r.V,{variant:`secondary`,className:`flex-shrink-0 h-6 w-6 p-0 flex items-center justify-center rounded-full text-sm font-semibold`,children:t+1}),(0,o.jsx)(`p`,{className:`flex-1 text-base font-medium text-muted-foreground group-hover:text-primary transition-colors duration-200 leading-relaxed`,children:e}),(0,o.jsx)(c.Plus,{size:18,className:`text-muted-foreground/60 group-hover:text-primary transition-colors duration-200 flex-shrink-0`})]})},t))})})},z=({section:e,dividerRef:i,isLast:s})=>{let{loading:c,sendMessage:l}=n.u(),[u,f]=(0,a.useState)(!0),[p,m]=(0,a.useState)(!1),[h,g]=(0,a.useState)(!1),[_,v]=(0,a.useState)(e.userMessage.content),y=()=>{navigator.clipboard.writeText(e.userMessage.content),m(!0),setTimeout(()=>m(!1),1500)},x=()=>{_.trim()&&(l(_.trim()),g(!1))},S=e.parsedAssistantMessage||``,T=e.speechMessage||``,D=e.thinkingEnded,{speechStatus:O,start:k,stop:A,isLoading:M}=r.d(T,{enableInterrupt:!0}),N=t=>{if(!e.assistantMessage)return;let n=`${e.userMessage.content}\n\n${e.assistantMessage.content}`;navigator.clipboard.writeText(n);let r={qwksearch:`https://qwksearch.com/?q=`,claude:`https://claude.ai/new?q=`,perplexity:`https://www.perplexity.ai/?q=`,gemini:`https://gemini.google.com/?q=`,chatgpt:`https://chat.openai.com/?q=`}[t];r&&window.open(`${r}${encodeURIComponent(n)}`,`_blank`)},P={overrides:{think:{component:E,props:{thinkingEnded:D}},citation:{component:w,props:{sources:e.sourceMessage?.sources||[]}},table:{component:({children:e,...t})=>(0,o.jsx)(`div`,{className:`not-prose -mx-2 my-4 max-w-full overflow-x-auto sm:mx-0`,children:(0,o.jsx)(`table`,{...t,className:`w-max min-w-full border-collapse text-sm`,children:e})})}}};return(0,o.jsxs)(`div`,{className:`space-y-3`,children:[(0,o.jsx)(j,{section:e,isExpanded:u,setIsExpanded:f,isEditing:h,setIsEditing:g,editText:_,setEditText:v,handleEditSubmit:x,copiedUserMsg:p,handleCopyUserMsg:y}),(0,o.jsx)(`div`,{className:t.o(`flex flex-col space-y-3 overflow-hidden transition-all duration-300 ease-in-out`,u?`max-h-[100000px] opacity-100`:`max-h-0 opacity-0`),children:(0,o.jsxs)(`div`,{ref:i,className:`flex flex-col space-y-6 w-full`,children:[e.searchingMessage&&e.searchingMessage.queries.length>0&&(0,o.jsx)(C,{queries:e.searchingMessage.queries,loading:c&&s}),e.sourceMessage&&e.sourceMessage.sources.length>0&&(0,o.jsx)(`div`,{className:`flex flex-col space-y-2`,children:(0,o.jsx)(b,{sources:e.sourceMessage.sources,query:e.userMessage.content})}),(0,o.jsx)(`div`,{className:`flex min-w-0 flex-col space-y-2`,children:e.assistantMessage&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)(d.default,{className:t.o(`prose prose-lg prose-h1:mb-3 prose-h2:mb-2 prose-h2:mt-6 prose-h2:font-[800] prose-h3:mt-4 prose-h3:mb-1.5 prose-h3:font-[600] dark:prose-invert prose-p:leading-loose prose-pre:p-0 font-[400]`,`min-w-0 max-w-none break-words text-foreground font-inter`),options:P,children:S}),c&&s?null:(0,o.jsx)(L,{section:e,speechStatus:O,isLoadingTTS:M,start:k,stop:A,handleOpenInLLM:N}),(0,o.jsx)(R,{section:e,isLast:s,loading:c,sendMessage:l})]})})]})})]})},B=[`default`,`circle`,`pinwheel`,`circle-filled`,`ellipsis`,`ring`,`bars`,`infinite`],V=`M12 12c-2-2.67-4-4-6-4a4 4 0 1 0 0 8c2 0 4-1.33 6-4Zm0 0c2 2.67 4 4 6 4a4 4 0 0 0 0-8c-2 0-4 1.33-6 4Z`,H={transformBox:`view-box`,transformOrigin:`center`},U=[[12,2,12,6],[16.24,7.76,19.07,4.93],[18,12,22,12],[16.24,16.24,19.07,19.07],[12,18,12,22],[4.93,19.07,7.76,16.24],[2,12,6,12],[4.93,4.93,7.76,7.76]],W=e=>{switch(e){case`circle`:return(0,o.jsx)(`g`,{className:`animate-spin`,style:H,children:(0,o.jsx)(`path`,{d:`M21 12a9 9 0 1 1-6.219-8.56`})});case`pinwheel`:return(0,o.jsxs)(`g`,{className:`animate-spin`,style:H,children:[(0,o.jsx)(`path`,{d:`M22 12a1 1 0 0 1-10 0 1 1 0 0 0-10 0`}),(0,o.jsx)(`path`,{d:`M7 20.7a1 1 0 1 1 5-8.7 1 1 0 1 0 5-8.6`}),(0,o.jsx)(`path`,{d:`M7 3.3a1 1 0 1 1 5 8.6 1 1 0 1 0 5 8.6`}),(0,o.jsx)(`circle`,{cx:`12`,cy:`12`,r:`10`})]});case`circle-filled`:return(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)(`circle`,{cx:`12`,cy:`12`,r:`9`,opacity:`0.2`}),(0,o.jsx)(`g`,{className:`animate-spin`,style:H,children:(0,o.jsx)(`path`,{d:`M21 12a9 9 0 0 0-9-9`})})]});case`ellipsis`:return(0,o.jsx)(`g`,{fill:`currentColor`,stroke:`none`,children:[4,12,20].map((e,t)=>(0,o.jsx)(`circle`,{cx:e,cy:`12`,r:`2.5`,children:(0,o.jsx)(`animate`,{attributeName:`cy`,values:`12;7.5;12`,keyTimes:`0;0.5;1`,dur:`1.2s`,begin:`${t*.16}s`,repeatCount:`indefinite`})},e))});case`ring`:return(0,o.jsx)(o.Fragment,{children:[0,-.8].map(e=>(0,o.jsxs)(`circle`,{cx:`12`,cy:`12`,r:`2`,children:[(0,o.jsx)(`animate`,{attributeName:`r`,values:`2;11`,dur:`1.6s`,begin:`${e}s`,repeatCount:`indefinite`}),(0,o.jsx)(`animate`,{attributeName:`opacity`,values:`1;0`,dur:`1.6s`,begin:`${e}s`,repeatCount:`indefinite`})]},e))});case`bars`:return(0,o.jsx)(`g`,{fill:`currentColor`,stroke:`none`,children:[2.5,10,17.5].map((e,t)=>(0,o.jsxs)(`rect`,{x:e,y:`8`,width:`4`,height:`8`,rx:`1.5`,children:[(0,o.jsx)(`animate`,{attributeName:`height`,values:`8;18;8`,keyTimes:`0;0.5;1`,dur:`1.1s`,begin:`${t*.18}s`,repeatCount:`indefinite`}),(0,o.jsx)(`animate`,{attributeName:`y`,values:`8;3;8`,keyTimes:`0;0.5;1`,dur:`1.1s`,begin:`${t*.18}s`,repeatCount:`indefinite`})]},e))});case`infinite`:return(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)(`path`,{d:V,opacity:`0.2`}),(0,o.jsx)(`path`,{d:V,pathLength:`100`,strokeDasharray:`25 75`,children:(0,o.jsx)(`animate`,{attributeName:`stroke-dashoffset`,values:`100;0`,dur:`1.5s`,repeatCount:`indefinite`})})]});default:return(0,o.jsx)(`g`,{className:`animate-spin`,style:H,children:U.map(([e,t,n,r],i)=>(0,o.jsx)(`line`,{x1:e,y1:t,x2:n,y2:r,opacity:1-i*.1},`${e}-${t}`))})}},G=({variant:e=`default`,size:n=24,className:r,...i})=>(0,o.jsx)(`svg`,{"aria-hidden":`true`,xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 24 24`,width:n,height:n,fill:`none`,stroke:`currentColor`,strokeWidth:2,strokeLinecap:`round`,strokeLinejoin:`round`,className:t.o(`shrink-0`,r),...i,children:W(e)}),K=`quantumSphere`,q=`spinner:`,J=new Set([`loadingSpokes`,`loadingCircleNotch`,`loadingPinwheel`,`loadingCircleTrack`,`loadingDotsBounce`,`loadingPulseRing`,`loadingEqualizerBars`,`loadingInfiniteDash`]),Y=Object.fromEntries(Object.entries(m).filter(([e,t])=>typeof t==`function`&&e.startsWith(`loading`)&&!J.has(e))),X=[K,...B.map(e=>`${q}${e}`),...Object.keys(Y).sort()],Z;function Q(){let e=X.filter(e=>e!==Z),t=e.length>0?e:X;return Z=t[Math.floor(Math.random()*t.length)],Z}function $(e){if(!e.startsWith(`spinner:`))return;let t=e.slice(8);return B.find(e=>e===t)}function ee(e,t){let n=Y[e];return n?n({size:t,raw:!0}):``}var te=({size:e=140,className:n})=>{let[r,i]=(0,a.useState)(null);(0,a.useEffect)(()=>{i(Q())},[]);let s=r?$(r):void 0;return(0,o.jsx)(`div`,{role:`status`,"aria-label":`Loading`,className:t.o(`flex items-center justify-center w-full h-[200px]`,n),children:r===`quantumSphere`?(0,o.jsx)(u.default,{autoRandomize:!0}):s?(0,o.jsx)(G,{variant:s,size:e,className:`text-muted-foreground`}):r?(0,o.jsx)(`div`,{className:`flex items-center justify-center`,dangerouslySetInnerHTML:{__html:ee(r,e)}}):null})},ne=(0,a.lazy)(()=>Promise.resolve().then(()=>require("./ArticleExtractPanel-DAPLUpyx.cjs"))),re=()=>{let{sections:e,chatTurns:t,loading:s,messageAppeared:c,newChat:l,chatId:u}=n.u(),{isOpen:d,panelWidth:f}=n.a(),{isAuthenticated:p}=n.c(),[m,h]=(0,a.useState)(!1);(0,a.useEffect)(()=>{d&&h(!0)},[d]);let[g,_]=(0,a.useState)(!1),v=(0,a.useRef)(null),y=(0,a.useRef)(null),b=(0,a.useRef)(!1);(0,a.useEffect)(()=>{let e=()=>{_(window.innerWidth>=1024)};return e(),window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[]),(0,a.useEffect)(()=>{t.length===1&&(document.title=`${t[0].content.substring(0,30)} - ${i.researchAgentUIConfig.appName}`),t[t.length-1]?.role===`user`&&(b.current=!0,y.current?.scrollIntoView({behavior:`auto`}),setTimeout(()=>{b.current=!1},100))},[t]);let x=g&&d?{width:`calc(100% - ${f}px)`}:{};return(0,o.jsxs)(o.Fragment,{children:[(0,o.jsxs)(`div`,{className:`flex flex-col min-h-full transition-all duration-300`,style:x,children:[(0,o.jsxs)(`div`,{className:`flex-1 flex flex-col space-y-3 pb-48 ${g&&!d?`px-0 max-w-[800px] mx-auto w-full`:`px-4 lg:px-8`}`,children:[e.map((t,n)=>{let r=n===e.length-1;return(0,o.jsxs)(a.Fragment,{children:[(0,o.jsx)(z,{section:t,sectionIndex:n,dividerRef:r?v:void 0,isLast:r}),!r&&(0,o.jsx)(`div`,{className:`h-px w-full bg-light-secondary dark:bg-dark-secondary`})]},t.userMessage.messageId)}),s&&!c&&(0,o.jsx)(te,{}),(0,o.jsx)(`div`,{ref:y,className:`h-0`})]}),(0,o.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,o.jsx)(r.U,{})})]}),(m||d)&&(0,o.jsx)(a.Suspense,{fallback:null,children:(0,o.jsx)(ne,{})})]})};exports.default=re;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { i as e, n as t, o as n, r, s as i, t as a } from "./dialog-Cufn2u50.js";
|
|
2
2
|
import { a as o, c as s, n as c, r as l, t as u, u as d } from "./tooltip-Bl3IdX-I.js";
|
|
3
|
-
import { G as f, J as p, K as m, Q as h, U as g, V as _, W as v, X as y, Y as b, Z as x, d as S, q as C, tt as w } from "./src-
|
|
3
|
+
import { G as f, J as p, K as m, Q as h, U as g, V as _, W as v, X as y, Y as b, Z as x, d as S, q as C, tt as w } from "./src-BqV2Vwpv.js";
|
|
4
4
|
import { researchAgentUIConfig as T } from "./config.mjs";
|
|
5
5
|
import { Fragment as E, Suspense as D, lazy as O, memo as k, useCallback as A, useEffect as j, useMemo as M, useRef as N, useState as P } from "react";
|
|
6
6
|
import { Fragment as F, jsx as I, jsxs as L } from "react/jsx-runtime";
|
|
@@ -1378,7 +1378,7 @@ var it = ({ size: e = 140, className: t }) => {
|
|
|
1378
1378
|
dangerouslySetInnerHTML: { __html: rt(r, e) }
|
|
1379
1379
|
}) : null
|
|
1380
1380
|
});
|
|
1381
|
-
}, at = O(() => import("./ArticleExtractPanel-
|
|
1381
|
+
}, at = O(() => import("./ArticleExtractPanel-BPNXuezE.js")), ot = () => {
|
|
1382
1382
|
let { sections: e, chatTurns: t, loading: n, messageAppeared: r, newChat: i, chatId: a } = d(), { isOpen: c, panelWidth: l } = o(), { isAuthenticated: u } = s(), [f, p] = P(!1);
|
|
1383
1383
|
j(() => {
|
|
1384
1384
|
c && p(!0);
|
package/dist/api.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./rolldown-runtime-BocRIvOZ.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("chat-agent-toolkit/tools/search/suggestionGeneratorAgent");
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./rolldown-runtime-BocRIvOZ.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("fuse.js");o=e.t(o,1);let s=require("tldts"),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
2
|
`)}`:``,u=`You are a helpful AI that generates insightful follow-up questions about articles.
|
|
3
3
|
Generate ${a} thought-provoking questions that would help readers understand the article better.
|
|
4
4
|
Return ONLY the questions, one per line, without numbering or bullet points.`,d=`Article content:
|
|
@@ -7,7 +7,7 @@ ${r.slice(0,15e3)}
|
|
|
7
7
|
${l}
|
|
8
8
|
|
|
9
9
|
Generate ${a} follow-up questions that would help readers dive deeper into this article.`,{text:f}=await(0,t.generateText)({model:c,instructions:u,prompt: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
|
|
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{title:r=``,content:i,maxTips:a=4,chatModel:o}=await e.json();if(!i)return Response.json({error:`Content 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=`You are a helpful AI that surfaces short, useful tips about a page the reader currently has open.
|
|
11
11
|
Generate ${a} concise tips (each a single sentence) highlighting the most useful takeaways or things worth noticing on the page.
|
|
12
12
|
Return ONLY the tips, one per line, without numbering or bullet points.`,u=`Page title: ${r}
|
|
13
13
|
|
|
@@ -15,7 +15,7 @@ Page content:
|
|
|
15
15
|
${i.slice(0,15e3)}
|
|
16
16
|
|
|
17
17
|
Generate ${a} short tips about this page.`,{text:d}=await(0,t.generateText)({model:c,instructions:l,prompt:u}),f=d.split(`
|
|
18
|
-
`).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({tips:f,success:!0})}catch(e){return console.error(`Error generating page tips:`,e),Response.json({error:`An error occurred while generating page tips`,details:e instanceof Error?e.message:String(e)},{status:500})}}}function
|
|
18
|
+
`).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({tips:f,success:!0})}catch(e){return console.error(`Error generating page tips:`,e),Response.json({error:`An error occurred while generating page tips`,details:e instanceof Error?e.message:String(e)},{status:500})}}}function m(e){return async e=>{try{let{title:r=``,content:i,maxTopics:a=4,chatModel:o}=await e.json();if(!i)return Response.json({error:`Content 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=`You are a helpful AI that suggests related searches for a reader based on a page they currently have open.
|
|
19
19
|
Generate ${a} short search queries (each a few words, phrased the way someone would type it into a search box) that dig deeper into topics related to the page.
|
|
20
20
|
Return ONLY the search queries, one per line, without numbering or bullet points.`,u=`Page title: ${r}
|
|
21
21
|
|
|
@@ -23,7 +23,7 @@ Page content:
|
|
|
23
23
|
${i.slice(0,15e3)}
|
|
24
24
|
|
|
25
25
|
Generate ${a} short related search queries for this page.`,{text:d}=await(0,t.generateText)({model:c,instructions:l,prompt:u}),f=d.split(`
|
|
26
|
-
`).map(e=>e.trim()).filter(e=>e.length>0).map(e=>e.replace(/^[\d\-\*\.\)]+\s*/,``).trim()).filter(e=>e.length>2).slice(0,a);return Response.json({topics:f,success:!0})}catch(e){return console.error(`Error generating topic searches:`,e),Response.json({error:`An error occurred while generating topic searches`,details:e instanceof Error?e.message:String(e)},{status:500})}}}function
|
|
26
|
+
`).map(e=>e.trim()).filter(e=>e.length>0).map(e=>e.replace(/^[\d\-\*\.\)]+\s*/,``).trim()).filter(e=>e.length>2).slice(0,a);return Response.json({topics:f,success:!0})}catch(e){return console.error(`Error generating topic searches:`,e),Response.json({error:`An error occurred while generating topic searches`,details:e instanceof Error?e.message:String(e)},{status:500})}}}function h(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(`
|
|
27
27
|
`)}`:``,u=`Article content:
|
|
28
28
|
${r.slice(0,15e3)}
|
|
29
29
|
|
|
@@ -33,6 +33,6 @@ User question: ${i}
|
|
|
33
33
|
|
|
34
34
|
Please provide a helpful answer based on the article content above.`,{text:d}=await(0,t.generateText)({model:c,instructions:`You are a helpful AI assistant that answers questions about articles.
|
|
35
35
|
Provide clear, concise, and accurate answers based on the article content provided.
|
|
36
|
-
If the answer is not in the article, say so.`,prompt: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=Number.isFinite(o)&&o>0?o:1,c=n.get(`lang`)||`en-US`,l=n.get(`safesearch`)===`true`,u=n.get(`recency`)||void 0,d=n.get(`publicInstances`)===`true`;if(!r)return Response.json({error:`Query parameter is required`},{status:400});let f=Date.now();try{let e=await(0,a.searchWeb)(r,{category:i,recency:u,safesearch:l,maxRetries:6,privateSearxng:!d&&t,proxy:``,lang:c,page:s});e&&(Array.isArray(e)?e.length>0:e.results&&e.results.length>0)||(e=await(0,a.searchWeb)(r,{category:i,recency:u,safesearch:l,maxRetries:6,privateSearxng:!1,proxy:``,lang:c,page:s}));let n=Date.now()-f;return e?Array.isArray(e)?Response.json({results:e,elapsedTime:n}):Response.json({...e,elapsedTime:n}):Response.json({results:[],suggestions:[],elapsedTime:n})}catch(e){let t=e instanceof Error?e.message:String(e);return console.error(`Search error for q="${r}" cat="${i}" page=${s}: ${t}`,e instanceof Error?e.stack:void 0),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)&&(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})}}}}function j(){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,o.default)({chat_history:r,maxQuestions:t.maxQuestions,promptTemplate:t.promptTemplate},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 M(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.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})}}}var N=`llama-3.3-70b-versatile`;function P(e){return e instanceof Error?e.message:typeof e==`string`?e:String(e)}async function F(e,t){let n=[];if(t&&e.loadChatModel)try{return await e.loadChatModel(t)}catch(e){n.push(P(e))}let r=e.getEnv(`GROQ_API_KEY`);if(r)return e.createGroq({apiKey:r})(N);if(e.loadChatModel)try{return await e.loadChatModel()}catch(e){n.push(P(e))}throw Error(n.length?`AI service is not configured: ${n.join(`; `)}`:`AI service is not configured. Please contact the administrator.`)}function I(e){return{POST:async t=>{try{let{text:n,prompt:r,stream:i,chatModel:a}=await t.json();if(!n||typeof n!=`string`)return Response.json({error:`Text is required and must be a string`},{status:400});let o;try{o=await F(e,a)}catch(e){let t=P(e);return console.error(`AI rewrite has no usable model:`,t),Response.json({error:t},{status:500})}let s=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:
|
|
36
|
+
If the answer is not in the article, say so.`,prompt: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 g(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 _(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 v(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 ee(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 te(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 ne=[`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 re(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}):ne.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 ie(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 ae(){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 b(){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 oe(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 se(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 ce(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 le={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 x(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=Number.isFinite(o)&&o>0?o:1,c=n.get(`lang`)||`en-US`,l=n.get(`safesearch`)===`true`,u=n.get(`recency`)||void 0,d=n.get(`publicInstances`)===`true`;if(!r)return Response.json({error:`Query parameter is required`},{status:400});let f=Date.now();try{let e=await(0,a.searchWeb)(r,{category:i,recency:u,safesearch:l,maxRetries:6,privateSearxng:!d&&t,proxy:``,lang:c,page:s});e&&(Array.isArray(e)?e.length>0:e.results&&e.results.length>0)||(e=await(0,a.searchWeb)(r,{category:i,recency:u,safesearch:l,maxRetries:6,privateSearxng:!1,proxy:``,lang:c,page:s}));let n=Date.now()-f;return e?Array.isArray(e)?Response.json({results:e,elapsedTime:n}):Response.json({...e,elapsedTime:n}):Response.json({results:[],suggestions:[],elapsedTime:n})}catch(e){let t=e instanceof Error?e.message:String(e);return console.error(`Search error for q="${r}" cat="${i}" page=${s}: ${t}`,e instanceof Error?e.stack:void 0),Response.json({error:`Search failed`,results:[]},{status:500})}}}}function S(){return{GET:async e=>{try{let t=new URL(e.url).searchParams,n=t.get(`mode`)||`normal`,r=le[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)&&(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})}}}}async function C(e,t,n={}){let r=t.fetch??fetch,i=new AbortController,a=setTimeout(()=>i.abort(Error(`Timed out after ${t.timeoutMs??3e3}ms`)),t.timeoutMs??3e3),o=()=>i.abort(t.signal?.reason);t.signal?.aborted&&o(),t.signal?.addEventListener(`abort`,o,{once:!0});try{let t=await r(e,{headers:{"User-Agent":`Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36`,...n},signal:i.signal});if(!t.ok)throw Error(`HTTP ${t.status} from ${new URL(e).hostname}`);return await t.text()}finally{clearTimeout(a),t.signal?.removeEventListener(`abort`,o)}}function w(e){let t=JSON.parse(e);return Array.isArray(t)&&Array.isArray(t[1])?t[1].filter(e=>typeof e==`string`):[]}var ue={amp:`&`,lt:`<`,gt:`>`,quot:`"`,apos:`'`,nbsp:` `};function de(e){return e.replace(/<[^>]*>/g,``).replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi,(e,t)=>{if(t[0]===`#`){let n=t[1]===`x`||t[1]===`X`?parseInt(t.slice(2),16):parseInt(t.slice(1),10);return Number.isFinite(n)?String.fromCodePoint(n):e}return ue[t.toLowerCase()]??e}).trim()}function T(e=`en-US`){return e.split(/[-_]/)[0].toLowerCase()}var fe=async(e,t={})=>{let n=new URLSearchParams({ie:`utf-8`,json:`1`,prod:`pc`,wd:e}),r=JSON.parse(await C(`https://www.baidu.com/sugrec?${n}`,t));return Array.isArray(r?.g)?r.g.map(e=>e.q):[]},pe=async(e,t={})=>w(await C(`https://api.bing.com/osjson.aspx?${new URLSearchParams({query:e,mkt:t.locale??`en-US`})}`,t)),E=async(e,t={})=>w(await C(`https://search.brave.com/api/suggest?${new URLSearchParams({q:e})}`,t,{Cookie:`country=all`})),D=async(e,t={})=>{let n=(t.locale??`en-US`).toLowerCase().split(/[-_]/).reverse().join(`-`);return w(await C(`https://duckduckgo.com/ac/?type=list&${new URLSearchParams({q:e,kl:n})}`,t))},O={de:`google.de`,fr:`google.fr`,es:`google.es`,it:`google.it`,nl:`google.nl`,pt:`google.pt`,ru:`google.ru`,ja:`google.co.jp`,zh:`google.com.hk`,ko:`google.co.kr`},k=async(e,t={})=>{let n=T(t.locale),r=new URLSearchParams({q:e,client:`gws-wiz`,hl:n}),i=await C(`https://${O[n]??`google.com`}/complete/search?${r}`,t),a=i.indexOf(`[`),o=i.lastIndexOf(`]`)+1;if(a<0||o<=a)return[];let s=JSON.parse(i.slice(a,o));return Array.isArray(s?.[0])?s[0].map(e=>typeof e?.[0]==`string`?de(e[0]):``).filter(Boolean):[]},A=async(e,t={})=>{let n=new URLSearchParams({q:e,locale:(t.locale??`en-US`).replace(`-`,`_`),version:`2`}),r=JSON.parse(await C(`https://api.qwant.com/v3/suggest?${n}`,t));return r?.status===`success`&&Array.isArray(r?.data?.items)?r.data.items.map(e=>e.value):[]},j={da:`dansk`,de:`deutsch`,en:`english`,es:`espanol`,fr:`francais`,nb:`norsk`,nl:`nederlands`,pl:`polski`,pt:`portugues`,sv:`svenska`},M=async(e,t={})=>w(await C(`https://www.startpage.com/suggestions?${new URLSearchParams({q:e,format:`opensearch`,segment:`startpage.defaultffx`,lui:j[T(t.locale)]??`english`})}`,t)),N=new Set([`en`,`de`,`fr`,`es`,`it`,`nl`,`pt`,`ru`,`ja`,`zh`,`ar`,`ko`]),P={baidu:fe,bing:pe,brave:E,duckduckgo:D,google:k,qwant:A,startpage:M,wikipedia:async(e,t={})=>{let n=T(t.locale),r=new URLSearchParams({action:`opensearch`,format:`json`,formatversion:`2`,search:e,namespace:`0`,limit:`10`});return w(await C(`https://${`${N.has(n)?n:`en`}.wikipedia.org`}/w/api.php?${r}`,t))},yandex:async(e,t={})=>w(await C(`https://suggest.yandex.com/suggest-ff.cgi?${new URLSearchParams({part:e})}`,t))};Object.keys(P);function F(e){return Object.prototype.hasOwnProperty.call(P,e)}var I=`google`,L=3;function R(e){let t=e?.trim().toLowerCase();return t===`ddg`?`duckduckgo`:t&&F(t)?t:I}async function z(e,t={}){let n=R(t.engine);try{return await P[n](e,t)}catch(e){return t.signal?.aborted||console.error(`Autocomplete engine '${n}' failed:`,e),[]}}async function B(e,t={}){let n=e=>Array.from(new Set(e)),r=await z(e,t);if(r.length>0)return n(r);let i=e.split(/\s+/).filter(Boolean),a=Math.min(L,i.length-1);for(let n=a;n>=1;n--){if(t.signal?.aborted)return[];let r=i.slice(-n).join(` `),a=i.slice(0,-n).join(` `),o=await z(r,t),s=new Set;for(let t of o){let n=a?`${a} ${t}`:t;n.toLowerCase()!==e.toLowerCase()&&s.add(n)}if(s.size>0)return Array.from(s)}return[]}var me=3,V=null;function he(){if(!V){let e=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}));V=new o.default(e,{keys:[{name:`name`,weight:.6},{name:`domain`,weight:.4}],threshold:.1,ignoreLocation:!0,includeScore:!0,minMatchCharLength:3})}return V}function H(e,t,n){return{domain:e,name:t,favicon:`https://www.google.com/s2/favicons?domain=${encodeURIComponent(e)}&sz=64`,rank:n}}function ge(e){let t=(0,s.parse)(e);return t.domain&&t.isIcann?t.hostname:null}function _e(e){let t=e.split(/\s+/).filter(Boolean),n=t[t.length-1]||``;if(n.length<3)return[];let r=he().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).map(({item:e})=>H(e.domain,e.name,e.rank)),i=ge(n);return i&&!r.some(e=>e.domain===i)&&r.unshift(H(i,``,2**53-1)),r.slice(0,me)}function ve(e={}){return{GET:async t=>{let{searchParams:n}=new URL(t.url),r=n.get(`q`)?.trim(),i=n.get(`locale`)||`en-US`,a=parseInt(n.get(`limit`)||String(e.defaultLimit??8),10),o=n.get(`engine`)||n.get(`backends`)?.split(`,`)[0]||e.engine;if(!r)return Response.json({suggestions:[],domains:[]});try{let e=await B(r,{engine:R(o),locale:i,signal:t.signal}),n=_e(r);return Response.json({suggestions:e.slice(0,a),domains:n})}catch(e){return console.error(`Autocomplete error:`,e),Response.json({suggestions:[],domains:[]},{status:500})}}}}function ye(){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,promptTemplate:t.promptTemplate},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 be(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.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})}}}var xe=`llama-3.3-70b-versatile`;function U(e){return e instanceof Error?e.message:typeof e==`string`?e:String(e)}async function Se(e,t){let n=[];if(t&&e.loadChatModel)try{return await e.loadChatModel(t)}catch(e){n.push(U(e))}let r=e.getEnv(`GROQ_API_KEY`);if(r)return e.createGroq({apiKey:r})(xe);if(e.loadChatModel)try{return await e.loadChatModel()}catch(e){n.push(U(e))}throw Error(n.length?`AI service is not configured: ${n.join(`; `)}`:`AI service is not configured. Please contact the administrator.`)}function Ce(e){return{POST:async t=>{try{let{text:n,prompt:r,stream:i,chatModel:a}=await t.json();if(!n||typeof n!=`string`)return Response.json({error:`Text is required and must be a string`},{status:400});let o;try{o=await Se(e,a)}catch(e){let t=U(e);return console.error(`AI rewrite has no usable model:`,t),Response.json({error:t},{status:500})}let s=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:
|
|
37
37
|
|
|
38
|
-
${n}`;if(i&&e.streamText){let{textStream:t}=e.streamText({model:o,prompt:s,temperature:.7}),n=t[Symbol.asyncIterator](),r=await n.next(),i=new ReadableStream({async start(e){let t=new TextEncoder;try{for(r.done||e.enqueue(t.encode(r.value));;){let r=await n.next();if(r.done)break;e.enqueue(t.encode(r.value))}e.close()}catch(t){console.error(`AI rewrite stream error:`,t),e.error(t)}}});return new Response(i,{headers:{"Content-Type":`text/plain; charset=utf-8`,"Cache-Control":`no-store`,"X-Accel-Buffering":`no`}})}let c=(await e.generateText({model:o,prompt:s,temperature:.7})).text.trim();return Response.json({rewrittenText:c})}catch(e){let t=
|
|
38
|
+
${n}`;if(i&&e.streamText){let{textStream:t}=e.streamText({model:o,prompt:s,temperature:.7}),n=t[Symbol.asyncIterator](),r=await n.next(),i=new ReadableStream({async start(e){let t=new TextEncoder;try{for(r.done||e.enqueue(t.encode(r.value));;){let r=await n.next();if(r.done)break;e.enqueue(t.encode(r.value))}e.close()}catch(t){console.error(`AI rewrite stream error:`,t),e.error(t)}}});return new Response(i,{headers:{"Content-Type":`text/plain; charset=utf-8`,"Cache-Control":`no-store`,"X-Accel-Buffering":`no`}})}let c=(await e.generateText({model:o,prompt:s,temperature:.7})).text.trim();return Response.json({rewrittenText:c})}catch(e){let t=U(e);return console.error(`AI rewrite error:`,e),Response.json({error:`Failed to process AI request: ${t}`,details:t},{status:500})}}}}function we(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})}}}}var W=[`small`,`fast`,`medium`,`turbo`,`large`],G=`turbo`;function K(e){return typeof e==`string`&&W.includes(e)}function q(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`}async function J(e,t,n){let r=q(n),i;try{i=e.getCloudflareContext().env?.AI}catch{}if(!i)return{ok:!1,reason:`ai_unavailable`};let a=await t.arrayBuffer(),{text:o}=await i.run(r,{audio:[...new Uint8Array(a)]});return{ok:!0,text:o,model:r}}function Te(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=await J(e,r,n.get(`model`));return i.ok?Response.json({text:i.text,model:i.model}):Response.json({error:`Cloudflare AI binding not available`},{status:503})}catch(e){return console.error(`Transcript error:`,e),Response.json({error:`Failed to transcribe audio`},{status:500})}}}}var Y=[`json`];function X(e,t,n,r=null,i=null){return Response.json({error:{message:t,type:n,param:r,code:i}},{status:e})}async function Z(e,t){let n=await e.authorize(t);if(n.authorized)return null;let{status:r,message:i}=n;return X(r??401,i,`authentication_error`,null,`invalid_api_key`)}function Q(){return{object:`list`,data:W.map(e=>({id:e,object:`model`,created:0,owned_by:`qwksearch`}))}}function Ee(e){return{GET:async t=>await Z(e,t)||Response.json(Q())}}function De(e){return{POST:async t=>{let n=await Z(e,t);if(n)return n;let r;try{r=await t.formData()}catch{return X(400,"Request body must be multipart/form-data with a `file` field.",`invalid_request_error`,null,`invalid_body`)}let i=r.get(`file`);if(!i||!(i instanceof File))return X(400,"`file` is required.",`invalid_request_error`,`file`,`missing_file`);if(i.size===0)return X(400,"`file` is empty.",`invalid_request_error`,`file`,`empty_file`);let a=r.get(`model`),o=a===null||a===``?G:a;if(!K(o))return X(400,`Unsupported model. Use one of: ${W.join(`, `)}.`,`invalid_request_error`,`model`,`model_not_found`);let s=r.get(`response_format`);if(s!==null&&s!==``&&s!==`json`)return X(400,`Unsupported response_format. Only ${Y.join(`, `)} is supported.`,`invalid_request_error`,`response_format`,`unsupported_response_format`);try{let t=await J(e,i,o);return t.ok?Response.json({text:t.text}):X(503,`Transcription is not available right now.`,`server_error`,null,`ai_unavailable`)}catch(e){return console.error(`[v1/audio/transcriptions] Workers AI failed:`,e instanceof Error?e.name:typeof e),X(500,`Failed to transcribe audio.`,`server_error`,null,`transcription_failed`)}}}}function Oe(){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 ke=864e5,$=null;function Ae(e){return{GET:async t=>{try{let t=Date.now();if($&&t-$.timestamp<ke)return Response.json({...$.result,cached:!0,cacheAge:t-$.timestamp});let n=await e.validateOpenRouterModels();return $={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 $={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.DEFAULT_TRANSCRIPTION_MODEL=G,exports.SUPPORTED_RESPONSE_FORMATS=Y,exports.TRANSCRIPTION_MODELS=W,exports.createAgentsHandler=be,exports.createArticleFollowupsHandler=f,exports.createArticleQAHandler=h,exports.createAutocompleteHandler=ve,exports.createChatByIdHandler=_,exports.createChatTitleHandler=te,exports.createChatsHandler=g,exports.createChatsSearchHandler=v,exports.createChatsShareHandler=ee,exports.createDiscoverHandler=S,exports.createMCPServerByIdHandler=se,exports.createMCPServerToggleHandler=ce,exports.createMCPServersHandler=oe,exports.createMessagesHandler=re,exports.createOpenAIModelsHandler=Ee,exports.createOpenAITranscriptionHandler=De,exports.createPageTipsHandler=p,exports.createProviderByIdHandler=ae,exports.createProviderModelsHandler=b,exports.createProvidersHandler=ie,exports.createRewriteHandler=Ce,exports.createSearchHandler=x,exports.createSuggestionsHandler=ye,exports.createTestModelsHandler=Oe,exports.createTopicSearchesHandler=m,exports.createTranscriptHandler=Te,exports.createValidateOpenRouterHandler=Ae,exports.createVoiceHandler=we,exports.describeError=y,exports.getWhisperModel=q,exports.isTranscriptionModel=K,exports.listTranscriptionModels=Q,exports.openAIError=X,exports.transcribeAudio=J;
|