PageSourceSearch

https://smry.ai/_next/static/chunks/0vxva863vq4lc.js?dpl=5cb6504fd3cb

js smry.ai collected 2026-09-24 10:06:43 UTC 405,706 bytes, 84 lines download raw bytes

1!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{};e._posthogReleaseId=e._posthogReleaseId||"01a0d2c8-6b7d-0000-f70a-d8c4c3e4bcf2";var n=(new e.Error).stack;n&&(e._posthogChunkIds=e._posthogChunkIds||{},e._posthogChunkIds[n]="7cee1efb-ca00-5f7e-b3c2-b8354ddc8b36")}catch(e){}}();(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,382357,e=>{"use strict";var t=e.i(843476),r=e.i(271645),a=e.i(174080),n=e.i(192875),i=e.i(948148),s=e.i(623426),o=e.i(82061),l=e.i(809299),u=e.i(916107),c=e.i(542272),d=e.i(172213),p=e.i(987368),h=e.i(198447),m=e.i(43014),f=e.i(353177),g=e.i(21139);e.i(25755);var v=e.i(604392),y=e.i(640777);function b(e,t=[]){return{id:e.id,title:e.title??"New Chat",createdAt:e.created_at??new Date().toISOString(),updatedAt:e.updated_at??new Date().toISOString(),isPinned:(e.is_pinned??0)!==0,articleUrl:e.article_url??void 0,articleTitle:e.article_title??void 0,articleDomain:e.article_domain??void 0,messages:t,lastAssistantPreview:e.last_assistant_preview??void 0,userMessageCount:e.user_message_count??void 0}}function x(e){let t=[];try{t=e.parts?JSON.parse(e.parts):[]}catch{t=e.content?[{type:"text",text:e.content}]:[]}return{id:e.id,role:e.role??"user",parts:t}}function w(e){return e.parts.map(e=>"text"in e&&"string"==typeof e.text?e.text:"").join("")}async function _(e,t,r,a,{touchThread:n=!0}={}){let i=await e.getAll("SELECT * FROM chat_messages WHERE thread_id = ? AND user_id = ?",[t,a]);if(0===r.length&&i.length>0)return void console.warn("[chat] refusing to diff an empty transcript against stored rows",{existingRows:i.length,threadId:t});let s=new Map(i.map(e=>[e.id,e])),o=new Set(r.map(e=>e.id)),l=function(e,t){let r=new Map,a=e.map(e=>{let r=Date.parse(t.get(e.id)?.created_at??"");return Number.isNaN(r)?null:r});for(let t=0;t<e.length;t++){if(null!==a[t])continue;let n=a[t-1],i=a.slice(t+1).find(e=>null!==e);a[t]=null!=i?Math.min(i,(n??i-2)+1):Math.max(Date.now(),(n??0)+1),r.set(e[t].id,new Date(a[t]).toISOString())}return r}(r,s);
1await e.writeTransaction(async e=>{let u=!1;for(let n of r){let r=JSON.stringify(n.parts),i=s.get(n.id);i?i.parts!==r&&(await e.execute(`UPDATE chat_messages SET content = ?, parts = ?
2           WHERE id = ? AND user_id = ?`,[w(n),r,n.id,a]),u=!0):(await e.execute(`INSERT INTO chat_messages (id, user_id, thread_id, role, content, parts, created_at)
3           VALUES (?, ?, ?, ?, ?, ?, ?)`,[n.id,a,t,n.role,w(n),r,l.get(n.id)]),u=!0)}for(let t of i)o.has(t.id)||(await e.execute("DELETE FROM chat_messages WHERE id = ? AND user_id = ?",[t.id,a]),u=!0);n&&u&&await e.execute("UPDATE chat_threads SET updated_at = ? WHERE id = ? AND user_id = ?",[new Date().toISOString(),t,a])})}let k="\n…[content truncated for storage]",S="\n…[thought truncated for storage]",E=new Set(["output-available","output-error"]);function C(e){return"object"==typeof e&&null!==e&&"text"===e.type&&"string"==typeof e.text}function j(e){return"object"==typeof e&&null!==e&&"reasoning"===e.type&&"string"==typeof e.text}function I(e){if(e.text.length<=12e3)return{type:"reasoning",text:e.text};let t=12e3-S.length;return{type:"reasoning",text:M(e.text,t)+S}}function T(e){if("object"!=typeof e||null===e)return!1;let{type:t,state:r,toolCallId:a}=e;return"string"==typeof t&&(t.startsWith("tool-")||"dynamic-tool"===t)&&"string"==typeof r&&E.has(r)&&"string"==typeof a}function N(e){return"user"===e||"assistant"===e}function R(e,t,r){if("string"==typeof e&&e.length>0)return e;let a=`msg-${t}`;for(;r.has(a);)a=`${a}x`;return a}function A(e){let t=new Set;for(let r of e){let e=r?.id;"string"==typeof e&&e.length>0&&t.add(e)}return t}function z(e){if("object"!=typeof e||null===e)return e;let t=e.content;if("string"!=typeof t||t.length<=2e3)return e;let r=2e3-k.length;return{...e,content:M(t,r)+k}}function M(e,t){if(e.length<=t)return e;let r=e.slice(0,t),a=r.charCodeAt(r.length-1);return a>=55296&&a<=56319&&(r=r.slice(0,-1)),r}var O=e.i(411091),P=e.i(846696),$=e.i(802822),D=e.i(792540),U=e.i(439120);function L(e){try{return(0,y.normalizeCacheUrl)(e)}catch{return e}}async function F({source:e,surface:t,defaultStatus:r,captureArticle:a,savedKeys:n,savingKeys:i,setSaving:s,upsertItem:o,trackSaved:l,notifySaved:u,notifyFailed:c,logFailure:d=e=>{(0,h.reportClientError)("[research-source-save] Could not save source:","[research-source-save] Could not save source:",e)}}){let p=L(e.url);if(n.has(p)||i.has(p))return"skipped";s(p,!0);try{return await o({url:e.url,title:e.title,domain:e.domain,defaultTr
3iageStatus:r,source:"reader"},{captureArticle:a}),l(e,t),u(),"saved"}catch(e){return d(e),c(),"failed"}finally{s(p,!1)}}var Z=e.i(613176),B=e.i(101616),H=e.i(504778);function q({articleUrl:e}){return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(B.StreamSubscriptionGate,{options:(0,H.libraryChatStream)()}),(0,t.jsx)(B.StreamSubscriptionGate,{options:(0,H.chatIndexStream)()}),e?(0,t.jsx)(B.StreamSubscriptionGate,{options:(0,H.chatStream)((0,y.normalizeCacheUrl)(e))}):null]})}let V=(0,r.createContext)(null);function W(){let e=(0,r.useContext)(V),{userId:t}=(0,n.useAuth)();return e?{...e,snapshot:e.snapshot?.owner===t?e.snapshot:null}:null}function G({request:e,publish:a}){let{userId:s}=(0,n.useAuth)(),o=(0,i.useTranslations)("chat"),w=function(e,t,a){let{threads:n,isLoaded:i,createThread:s,updateThread:o,deleteThread:l,setActiveThreadId:w,activeThreadId:k,activeThreadMessagesReady:S}=function(e=!1,t,a,n={}){let i=n.enabled??!0,s=(0,u.useIsClient)(),o=(0,c.usePowerSyncOptional)(),{authLoaded:l,isSignedIn:p,ownerKey:w}=(0,m.useLibraryOwner)(),k=(0,d.useSyncSchemaMutation)(),S=w?(0,g.getLibraryOwnerUserId)(w)??"":null,[E,C]=(0,r.useState)(a??null),j=w?.startsWith("anonymous:")===!0||l&&p&&e,[I,T]=(0,r.useState)([]),[N,R]=(0,r.useState)({}),A=(0,r.useRef)(new Map),z=(0,r.useRef)(new Map),M=(0,r.useMemo)(()=>t?(0,y.normalizeCacheUrl)(t):t,[t]),{data:O,isLoading:P}=(0,v.useQuery)(i&&null!==S?`SELECT t.*,
4       (SELECT COUNT(*) FROM chat_messages m
5          WHERE m.thread_id = t.id AND m.user_id = t.user_id AND m.role = 'user') AS user_message_count,
6       (SELECT m.content FROM chat_messages m WHERE m.thread_id = t.id AND m.role = 'assistant'
7          AND m.user_id = t.user_id
8          ORDER BY m.created_at DESC LIMIT 1) AS last_assistant_preview
9     FROM chat_threads t WHERE t.user_id = ? ORDER BY t.updated_at DESC LIMIT 500`:c.DISABLED_QUERY,i&&null!==S?[S]:[]),$=i&&!!E,{data:D,isLoading:U,isFetching:L}=(0,v.useQuery)($&&null!==S?"SELECT * FROM chat_messages WHERE thread_id = ? AND user_id = ? ORDER BY created_at":c.DISABLED_QUERY,$&&null!==S?[E,S]:[]),F=!$||!U&&!L,Z=(0,r.useMemo)(()=>{let e=O.map(e=>{let t=N[e.id]??(e.id===E&&F?D.map(x):[]);return b(e,t)});if(0===I.length)return e;let t=[...I,...e];return t.sort((e,t)=>new Date(t.updatedAt).getTime()-new Date(e.updatedAt).getTime()),t},[O,N,E,F,D,I]),B=(0,r.useRef)(Z);(0,r.useLayoutEffect)(()=>{B.current=Z},[Z]);let H=(0,r.useCallback)(async(e,t)=>k(async r=>{r===e&&await t(r)}),[k]),q=(0,r.useCallback)((e,t)=>{if(!o||null===S)return;if(""===S)return void H(S,r=>_(o,e,t,r)).catch(e=>(0,h.reportClientError)("[chat] guest message write failed","[chat] guest message write failed",e));let r=A.current.get(e);r&&clearTimeout(r.timer);let a=setTimeout(()=>{A.current.delete(e),H(S,r=>_(o,e,t,r)).catch(e=>(0,h.reportClientError)("[chat] message write failed","[chat] message write failed",e))},1e3);A.current.set(e,{messages:t,ownerUserId:S,timer:a})},[o,S,H]),V=(0,r.useCallback)(async()=>{if(!o)return;let e=[...A.current.entries()];for(let[t,{messages:r,ownerUserId:a,timer:n}]of(A.current.clear(),e))clearTimeout(n),await H(a,e=>_(o,t,r,e)).catch(e=>(0,h.reportClientError)("[chat] flush failed","[chat] flush failed",e))},[o,H]);(0,u.useExternalSync)(()=>{let e=()=>void V();return window.addEventListener("beforeunload",e),document.addEventListener("visibilitychange",e),()=>{window.removeEventListener("beforeunload",e),document.removeEventListener("visibilitychange",e),e()}},[V]);let W=(0,r.useCallback)((e,t,r,a)=>{let n=new Date().toISOString(),i={id:a??crypto.randomUUID(),title:e||"New Chat",createdAt:n,updatedAt:n,isPinned:!1,articleUrl:t?.articleUrl?(0,y.normalizeCacheUrl)(t.articleUrl):t?.articleUrl,articleTitle:t?.articleTitle,articleDomain:t?.articleDomain,messages:r||[]};return j&&o&&null!==S?(R(e=>({...e,[i.id]:i.messages})),C(i.id),z.current.set(i.id,{title:i.title,isPinned:!1,articleUrl:i.articleUrl??null,articleTitle:i.articleTitle??null,articleDomain:i.articleDomain??null}),H(S,async e=>{await o.execute(`INSERT OR IGNORE INTO chat_threads
10             (id, user_id, article_url, article_title, article_domain, title, is_pinned, created_at, updated_at)
11           VALUES (?, ?, ?, ?, ?, ?, 0, ?, ?)`,[i.id,e,i.articleUrl??null,i.articleTitle??null,i.articleDomain??null,i.title,n,n]),i.messages.length>0&&await _(o,i.id,i.messages,e,{touchThread:!1})}).catch(e=>(0,h.reportClientError)("[chat] thread create failed","[chat] thread create failed",e))):(T(e=>[i,...e]),C(i.id)),i},[o,S,j,H]),G=(0,r.useCallback)((e,t)=>{let r=new Date().toISOString(),a=void 0!==t.articleUrl&&t.articleUrl?{...t,articleUrl:(0,y.normalizeCacheUrl)(t.articleUrl)}:t;if(I.some(t=>t.id===e)||!o)return void T(t=>{let n=t.find(t=>
11t.id===e);return!n||Object.entries(a).every(([e,t])=>JSON.stringify(n[e])===JSON.stringify(t))?t:t.map(t=>t.id===e?{...t,...a,updatedAt:r}:t)});a.messages&&(R(t=>({...t,[e]:a.messages})),q(e,a.messages));let n=B.current.find(t=>t.id===e),i={title:n?.title,isPinned:n?.isPinned,articleUrl:n?n.articleUrl??null:void 0,articleTitle:n?n.articleTitle??null:void 0,articleDomain:n?n.articleDomain??null:void 0,...z.current.get(e)},s={...i},l=[],u=[];void 0!==a.title&&a.title!==i.title&&(l.push("title = ?"),u.push(a.title),s.title=a.title),void 0!==a.isPinned&&a.isPinned!==i.isPinned&&(l.push("is_pinned = ?"),u.push(+!!a.isPinned),s.isPinned=a.isPinned),void 0!==a.articleUrl&&(a.articleUrl??null)!==i.articleUrl&&(l.push("article_url = ?"),u.push(a.articleUrl??null),s.articleUrl=a.articleUrl??null),void 0!==a.articleTitle&&(a.articleTitle??null)!==i.articleTitle&&(l.push("article_title = ?"),u.push(a.articleTitle??null),s.articleTitle=a.articleTitle??null),void 0!==a.articleDomain&&(a.articleDomain??null)!==i.articleDomain&&(l.push("article_domain = ?"),u.push(a.articleDomain??null),s.articleDomain=a.articleDomain??null),0===l.length||(l.push("updated_at = ?"),u.push(r,e),z.current.set(e,s),null===S||H(S,async e=>{await o.execute(`UPDATE chat_threads SET ${l.join(", ")} WHERE id = ? AND user_id = ?`,[...u,e])}).catch(e=>(0,h.reportClientError)("[chat] thread update failed","[chat] thread update failed",e)))},[o,I,S,H,q]),Y=(0,r.useCallback)(e=>{let t=A.current.get(e);t&&(clearTimeout(t.timer),A.current.delete(e)),z.current.delete(e),T(t=>t.filter(t=>t.id!==e)),R(t=>{let{[e]:r,...a}=t;return a}),E===e&&C(null),o&&null!==S&&H(S,async()=>{await o.writeTransaction(async t=>{await t.execute("DELETE FROM chat_messages WHERE thread_id = ? AND user_id = ?",[e,S]),await t.execute("DELETE FROM chat_threads WHERE id = ? AND user_id = ?",[e,S])})}).catch(e=>(0,h.reportClientError)("[chat] thread delete failed","[chat] thread delete failed",e))},[E,o,S,H]),J=(0,r.useCallback)(e=>{let t=B.current.find(t=>t.id===e);t&&G(e,{isPinned:!t.isPinned})},[G]),K=(0,r.useCallback)((e,t)=>G(e,{title:t}),[G]),Q=(0,r.useCallback)(()=>{for(let{timer:e}of A.current.values())clearTimeout(e);A.current.clear(),z.current.clear(),T([]),R({}),C(null),o&&null!==S&&H(S,async()=>{await o.writeTransaction(async e=>{await e.execute("DELETE FROM chat_messages WHERE user_id = ?",[S]),await e.execute("DELETE FROM chat_threads WHERE user_id = ?",[S])})}).catch(e=>(0,h.reportClientError)("[chat] clear failed","[chat] clear failed",e))},[o,S,H]),X=(0,r.useCallback)(async e=>{if(!o||null===S)return[];let t=e.replaceAll("\\","\\\\").replaceAll("%","\\%").replaceAll("_","\\_"),r=`%${t}%`;return(await o.getAll(`SELECT DISTINCT t.* FROM chat_threads t
12         LEFT JOIN chat_messages m ON m.thread_id = t.id AND m.user_id = t.user_id
13         WHERE t.user_id = ? AND (t.title LIKE ? ESCAPE '\\' OR m.content LIKE ? ESCAPE '\\')
14         ORDER BY t.updated_at DESC LIMIT 50`,[S,r,r])).map(e=>b(e))},[o,S]),ee=(0,r.useCallback)(async(e,t=!1)=>{let r=I.find(t=>t.id===e);if(r)return r;if(!o||null===S)return null;let[a]=await o.getAll("SELECT * FROM chat_threads WHERE id = ? AND user_id = ? LIMIT 1",[e,S]);return a?b(a,(await o.getAll("SELECT * FROM chat_messages WHERE thread_id = ? AND user_id = ? ORDER BY created_at",[e,S])).map(x)):null},[o,I,S]),et=(0,r.useCallback)(e=>{let t=e?(0,y.normalizeCacheUrl)(e):e;return B.current.find(e=>e.articleUrl===t)||null},[]),er=(0,r.useMemo)(()=>{let e=new Set,t=Z.filter(t=>!e.has(t.id)&&(e.add(t.id),!0)),r=t.filter(e=>e.isPinned),a=t.filter(e=>!e.isPinned);if(M){let e=[],t=new Map;for(let r of a)if(r.articleUrl===M)e.push(r);else{let e=r.articleUrl||"__no_article__",a=t.get(e);a?a.push(r):t.set(e,[r])}e.sort((e,t)=>new Date(t.updatedAt).getTime()-new Date(e.updatedAt).getTime());let n=[];for(let a of(r.length>0&&n.push({label:"Pinned",threads:r}),e.length>0&&n.push({label:"This Article",threads:e}),Array.from(t.entries()).map(([e,t])=>{t.sort((e,t)=>new Date(t.updatedAt).getTime()-new Date(e.updatedAt).getTime());let r=t[0];return{label:r.articleTitle||r.articleDomain||"Other",threads:t,mostRecent:new Date(t[0].updatedAt).getTime()}}).sort((e,t)=>
14t.mostRecent-e.mostRecent)))n.push({label:a.label,threads:a.threads});return n}if(!s)return[];let n=new Date,i=new Date(n.getFullYear(),n.getMonth(),n.getDate()),o=new Date(i.getTime()-864e5),l=new Date(i.getTime()-6048e5),u=new Date(i.getTime()-2592e6),c=[{label:"Pinned",threads:r},{label:"Today",threads:[]},{label:"Yesterday",threads:[]},{label:"Last 7 Days",threads:[]},{label:"Last 30 Days",threads:[]},{label:"Older",threads:[]}];return a.forEach(e=>{let t=new Date(e.updatedAt);t>=i?c[1].threads.push(e):t>=o?c[2].threads.push(e):t>=l?c[3].threads.push(e):t>=u?c[4].threads.push(e):c[5].threads.push(e)}),c.filter(e=>e.threads.length>0)},[Z,M,s]),ea=Z.find(e=>e.id===E)||null;return{threads:Z,activeThread:ea,activeThreadId:E,activeThreadMessagesReady:F,setActiveThreadId:C,groupedThreads:er,isLoaded:!i||null!==o&&(0,f.isAccountDataReadSettled)({authLoaded:l,isSignedIn:!!p,hasDatabase:null!==o,queryLoading:P}),createThread:W,updateThread:G,deleteThread:Y,togglePin:J,renameThread:K,clearAllThreads:Q,flushToServer:V,findThreadByArticleUrl:et,loadMore:(0,r.useCallback)(async()=>{},[]),hasMore:!1,isLoadingMore:!1,searchThreads:X,getThreadWithMessages:ee}}(e,a?.articleUrl,t);(0,u.useExternalSync)(()=>{w(t)},[t,w]);let E=(0,p.useLatestRef)(n),M=(0,r.useRef)(new Set);return(0,u.useExternalSync)(()=>{for(let e of n)M.current.delete(e.id)},[n]),{threads:(0,r.useMemo)(()=>n.map(e=>({id:e.id,title:e.title,messages:function(e){if(!Array.isArray(e))return[];let t=A(e),r=[];return e.forEach((e,a)=>{if("object"!=typeof e||null===e)return;let{id:n,role:i,metadata:s,parts:o,content:l}=e;if(!N(i))return;let u=[];if(Array.isArray(o))for(let e of o)C(e)?u.push(e):j(e)&&e.text.trim()?u.push(I(e)):T(e)&&u.push(e);else u.push({type:"text",text:"string"==typeof l?l:""});r.push({id:R(n,a,t),role:i,...void 0!==s?{metadata:s}:{},parts:u})}),r}(e.messages),createdAt:Date.parse(e.createdAt),updatedAt:Date.parse(e.updatedAt),articleUrl:e.articleUrl,articleTitle:e.articleTitle,articleDomain:e.articleDomain})),[n]),ready:i,activeThreadReady:k===t&&S,upsert:(0,r.useCallback)(e=>{var t;let r,n,i=(r=A(t=e.messages),n=[],t.forEach((e,t)=>{if(!N(e.role))return;let a=[];for(let t of e.parts)C(t)?a.push({type:"text",text:t.text}):j(t)&&t.text.trim()?a.push(I({type:"reasoning",text:t.text})):T(t)&&a.push(function(e){let t=e.output;if("object"!=typeof t||null===t)return e;let r=t.webPage,a=z(r),n=t.pages,i=Array.isArray(n)?n.map(z):n,s=Array.isArray(n)&&Array.isArray(i)&&i.some((e,t)=>e!==n[t]);return a!==r||s?{...e,output:{...t,...a!==r?{webPage:a}:{},...s?{pages:i}:{}}}:e}(t));n.push({id:R(e.id,t,r),role:e.role,...void 0!==e.metadata?{metadata:e.metadata}:{},parts:a})}),n);if(E.current.some(t=>t.id===e.id)){M.current.delete(e.id),o(e.id,{...a,title:e.title,messages:i});return}M.current.has(e.id)||(M.current.add(e.id),s(e.title,a,i,e.id))},[s,a,E,o]),remove:l}}(e.canPersist,e.activeThreadId,e.metadata),k=(0,O.useLibraryAggregates)(),S=(0,l.useChatModelSelection)(e.isPremium),E=function({enabled:e=!0,failedMessage:t,savedMessage:a,surface:n}){let{items:i,isLoaded:s,upsertItem:o}=(0,D.useLibrary)({enabled:e}),{preferences:l}=(0,U.useReadLaterPreferences)(),{trackArticle:u}=(0,$.useAnalytics)(),[c,d]=(0,r.useState)(()=>new Set),p=(0,r.useRef)(new Set),h=(0,r.useMemo)(()=>new Set(i.map(e=>L(e.url))),[i]),m=(0,r.useCallback)((e,t)=>{let r=new Set(p.current);t?r.add(e):r.delete(e),p.current=r,d(r)},[]);return{getSaveState:(0,r.useCallback)(e=>(function({source:e,isLoaded:t,savedKeys:r,savingKeys:a}){let n=L(e.url);return r.has(n)?"saved":a.has(n)?"saving":t?"idle":"loading"})({source:e,isLoaded:s,savedKeys:h,savingKeys:c}),[s,h,c]),saveSource:(0,r.useCallback)(async e=>{await F({source:e,surface:n,defaultStatus:l.defaultSaveStatus,captureArticle:!0,savedKeys:h,savingKeys:p.current,setSaving:m,upsertItem:o,trackSaved:(e,t)=>{u("library_status_changed",e.url,{surface:t,active_view:t,previous_status:"none",next_status:l.defaultSaveStatus,action_source:"chat_research_source"})},notifySaved:()=>P.toast.success(a),notifyFailed:()=>P.toast.error(t)})},[t,l.defaultSaveStatus,h,a,m,n,u,o])}}({enabled:e.researchSources,surface:"local_chat",failedMessage:o("sourceSaveError"),savedMessage:o("sourceSaveSuccess")});(0,u.useExternalLayoutSync)(()=>{a({request:e,owner:s,threads:w,libraryEmpty:k.isLoaded&&0===k.counts.all,model:S,sources:E})}
14,[a,e,s,w.threads,w.ready,w.activeThreadReady,w.upsert,w.remove,k.isLoaded,k.counts.all,S.selection,S.setSelection,E.getSaveState,E.saveSource]),(0,u.useExternalLayoutSync)(()=>()=>a(null),[a]);let M=w.threads.find(t=>t.id===e.activeThreadId)?.articleUrl??e.metadata?.articleUrl;return(0,t.jsx)(q,{articleUrl:M})}let Y=[],J=()=>{},K=()=>"loading",Q=async()=>{};e.s(["RemyDataBridge",0,function(){let e=(0,r.useContext)(V),n=(0,c.usePowerSyncOptional)(),i=(0,d.useSyncSchemaReady)();return e?(0,t.jsxs)(t.Fragment,{children:[e.menu?(0,a.createPortal)((0,t.jsx)(Z.AppMenuButton,{surface:"chat"}),e.menu):null,n&&i&&e.request?(0,t.jsx)(G,{request:e.request,publish:e.publish}):null]}):null},"RemyDataProvider",0,function({children:e}){let[a,n]=(0,r.useState)(null),[i,s]=(0,r.useState)(null),[o,l]=(0,r.useState)(null),u=(0,r.useMemo)(()=>({request:a,setRequest:n,snapshot:i,publish:s,menu:o,setMenu:l}),[a,i,o]);return(0,t.jsx)(V.Provider,{value:u,children:e})},"RemyMenuSlot",0,function(){let e=(0,r.useContext)(V),a=e?.setMenu,n=(0,r.useCallback)(e=>a?.(e),[a]);return e?(0,t.jsx)("div",{ref:n,className:"contents"}):(0,t.jsx)(Z.AppMenuButton,{surface:"chat"})},"useRemyChatStorage",0,function(e,t,a){let i=W(),{userId:c}=(0,n.useAuth)(),d=i.snapshot?.request.activeThreadId===e&&i.snapshot.request.metadata===t?i.snapshot:null,[p]=(0,o.default)(l.CHAT_MODEL_SELECTION_STORAGE_KEY,s.AUTO_MODEL_ID),[h,m]=(0,r.useState)(null),f=h&&h.owner===c?h.selection:null,g=(0,s.normalizeChatModelSelection)(f??d?.model.selection??p,a),v=(0,r.useCallback)(e=>m({owner:c,selection:e}),[c]),y=d?.model.selection,b=d?.model.setSelection;return(0,u.useExternalSync)(()=>{null!==f&&b&&(y===f?m(null):b(f))},[f,y,b]),{setRequest:i.setRequest,threads:d?.threads.threads??Y,threadsReady:d?.threads.ready??!1,activeThreadReady:d?.threads.activeThreadReady??!1,upsertThread:d?.threads.upsert??J,removeThread:d?.threads.remove??J,getResearchSourceSaveState:d?.sources.getSaveState??K,saveResearchSource:d?.sources.saveSource??Q,libraryEmpty:d?.libraryEmpty??!1,modelSelection:g,setModelSelection:v}},"useRemyData",0,W],382357)},50582,e=>{"use strict";var t,r,a,n,i,s,o,l,u,c,d,p,h,m,f,g,v,y,b,x,w,_,k,S,E,C,j,I,T,N,R,A,z,M,O,P,$,D,U,L,F,Z,B,H,q,V,W,G,Y,J,K,Q,X,ee,et,er,ea,en=e.i(843476),ei=e.i(382357),es=e.i(756733),eo=e.i(845129),el=e.i(835903),eu=e.i(9143),ec=e.i(948148),ed=e.i(475254);let ep=(0,ed.default)("arrow-up-left",[["path",{d:"M7 17V7h10",key:"11bw93"}],["path",{d:"M17 17 7 7",key:"2786uv"}]]);var eh=e.i(810980),em=e.i(394908);let ef=(0,ed.default)("folder-open",[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]]),eg=(0,ed.default)("newspaper",[["path",{d:"M15 18h-5",key:"95g1m2"}],["path",{d:"M18 14h-8",key:"sponae"}],["path",{d:"M4 22h16a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2H8a2 2 0 0 0-2 2v16a2 2 0 0 1-4 0v-9a2 2 0 0 1 2-2h2",key:"39pd36"}],["rect",{width:"8",height:"4",x:"10",y:"6",rx:"1",key:"aywv1n"}]]),ev=(0,ed.default)("scan-search",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["path",{d:"m16 16-1.9-1.9",key:"1dq9hf"}]]),ey=(0,ed.default)("search",[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]]);var eb=e.i(127341);let ex=[{id:"explore",prompts:["discover","recommend","video","podcast","perspective"]},{id:"learn",prompts:["summarize","explain","quiz","pdf","study"]},{id:"research",prompts:["topic","claim","compare","brief","readingList"]},{id:"find",prompts:["saved","highlights","notes","history","revisit"],account:!0},{id:"catchUp",prompts:["updates","unread","coverage","changes","health"],account:!0},{id:"organize",prompts:["tags","collections","follow","monitor","newsletters"],account:!0}],ew={explore:em.Compass,learn:eh.BookOpen,research:ev,find:ey,catchUp:eg,organize:ef};function e_({hasSource:e=!1,hasHighlights:t=!1,signedIn:r,libraryEmpty:a=!1,onDraft:n}){let i=(0,ec.useTranslations)("remySuggestions");return(0,en.jsx)("div",{className:"@container w-full min-w-0",children:(0,en.jsxs)(eb.Tabs,{defaultValue:e?"learn":"explore",className:"gap-0 rounded-[14px] bg-card p-2 shadow-hairline",children:[(0,en.jsx)(eb.TabsList,{activateOnFocus:!0,variant:"button","aria-label":i("categoriesLabel"),className:"grid w-full grid-cols-2 items-stretch gap-1 rounded-[10px] bg-muted/40 p-1 @min-[20rem]:grid-cols-3 @min-[36rem]:flex @min-[36rem]:flex-wrap",children:ex.map(({id:e})=>{let t=ew[e];return(0,en.jsxs)(eb.TabsTab,{value:e,className:"min-h-11 min-w-0 gap-1.5 whitespace-normal rounded-lg px-2 text-[13px] data-active:bg-card data-active:shadow-hairline dark:data-active:bg-foreground
14/[0.06]",children:[(0,en.jsx)(t,{className:"size-3.5",strokeWidth:1.5,"aria-hidden":"true"}),i(`${e}.label`)]},e)})}),ex.map(s=>(0,en.jsxs)(eb.TabsPanel,{value:s.id,className:"mt-2 rounded-[10px]",children:[(0,en.jsx)("p",{className:"px-3 pb-2 pt-3 text-xs leading-5 text-muted-foreground",children:i(`${s.id}.description`)}),(0,en.jsx)("div",{className:"flex flex-col",children:(function(e,{hasSource:t=!1,hasHighlights:r=!1}={}){return t&&"learn"===e.id?["takeaways","argument","assumptions","quizSource",r?"sourceHighlights":"studySource"]:t&&"research"===e.id?["checkSource","counterargument","compareSource","briefSource","readNext"]:e.prompts})(s,{hasSource:e,hasHighlights:t}).map(e=>(0,en.jsxs)("button",{type:"button",onClick:()=>n(i(`prompts.${e}`)),className:"group/prompt flex min-h-12 w-full touch-manipulation items-center gap-3 rounded-[10px] px-3 py-2 text-start text-sm leading-5 text-foreground transition-colors hover:bg-accent/35 focus-visible:bg-accent/35 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring motion-reduce:transition-none",children:[(0,en.jsx)("span",{className:"min-w-0 flex-1 text-pretty",children:i(`prompts.${e}`)}),(0,en.jsx)("span",{className:"flex size-7 shrink-0 items-center justify-center rounded-lg text-muted-foreground/60 transition-colors group-hover/prompt:bg-background group-hover/prompt:text-foreground group-focus-visible/prompt:bg-background group-focus-visible/prompt:text-foreground motion-reduce:transition-none",children:(0,en.jsx)(ep,{className:"size-4",strokeWidth:1.5,"aria-hidden":"true"})})]},e))}),(0,en.jsx)("p",{className:"mx-3 mt-2 pb-1 pt-3 text-xs leading-5 text-muted-foreground",children:i("account"in s&&!r?"accountHint":"find"===s.id&&a?"emptyLibraryHint":"draftHint")})]},s.id))]})})}var ek=e.i(271645),eS=e.i(200093),eE=e.i(647163);function eC({compact:e=!1,onDraft:t,signedIn:r,libraryEmpty:a=!1}){let n=(0,ek.useId)(),i=(0,ec.useTranslations)("remySuggestions");return(0,en.jsx)("section",{"aria-labelledby":n,className:(0,eE.cn)("mx-auto flex min-h-0 w-full max-w-[46.5rem] flex-1 flex-col overflow-y-auto px-5 py-6",!e&&"sm:px-8"),children:(0,en.jsxs)("div",{className:"my-auto w-full shrink-0 py-2",children:[(0,en.jsxs)("div",{className:"mb-5 px-1",children:[(0,en.jsxs)("div",{className:"mb-3 flex items-center gap-3",children:[(0,en.jsx)(eS.RemyIcon,{className:"size-6 shrink-0 text-muted-foreground","aria-hidden":"true"}),(0,en.jsx)("h1",{id:n,className:(0,eE.cn)("text-balance text-xl font-medium tracking-tight text-foreground",!e&&"sm:text-2xl"),children:i("title")})]}),(0,en.jsx)("p",{className:"max-w-md text-pretty text-sm leading-6 text-muted-foreground",children:i("description")})]}),(0,en.jsx)(e_,{signedIn:r,libraryEmpty:a,onDraft:t})]})})}var ej=e.i(546110),eI=e.i(658938),eT=e.i(43014),eN=e.i(198447),eR=e.i(714766),eA=ek;class ez extends eA.Component{state={hasError:!1};static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(e,t){(0,eN.reportClientError)("Ad renderer failure in components/ads/error-boundary.tsx",e,t)}render(){return this.state.hasError?this.props.fallback:this.props.children}}var eM=e.i(401727),eO=e.i(384034),eP=e.i(916107),e$=e.i(242030);let eD="chat_below_response";function eU({enabled:e,articleUrl:t,question:r,answer:a,turnKey:n,isPremium:i}){let[s,o]=(0,ek.useState)(!1),[l,u]=(0,ek.useState)(null);(0,eP.useExternalSync)(()=>{let e,t=!0;return(0,eO.initPostHogClient)().then(r=>{if(!t||!r)return;let a=()=>{t&&o(!0===r.getFeatureFlag?.("remy-chat-ads-kill"))};e=r.onFeatureFlags?.(a),r.reloadFeatureFlags?.(),a()}).catch(e=>{(0,eN.reportClientError)("Chat ad kill-switch lookup failed in components/ads/chat-ad.tsx; card stays on",e)}),()=>{t=!1,e?.()}},[]);let c=function({enabled:e,articleUrl:t,question:r,answer:a,turnKey:n,isPremium:i}){let s=(0,e$.useContextAd)({enabled:e,isPremium:i,url:t||"https://smry.ai/chat",title:"",textContent:"",placementSurface:"chat",adRenderer:"gravity",chat:{question:r.slice(0,2e3),answer:a.slice(0,4e3),turnKey:n}}),o=(0,ek.useCallback)(()=>s.fireImpression(s.ad??void 0,eD),[s]),l=(0,ek.useCallback)(()=>s.fireClick(s.ad??void 0,eD),[s]),u=(0,ek.useCallback)(()=>s.fireFeedback(s.ad??void 0,eD),[s]);return{ad:s.ad,placement:eD,fireImpression:o,onClick:l,dismiss:u}}({enabled:e&&!s,articleUrl:t,question:r,answer:a,turnKey:n,isPremium:i}),d=c.dismiss,p=(0,ek.useCallback)(()=>{d(),u(n)},[d,n]);if(!c.ad||l===n)return null;let h=(0,en.jsx)(eR.ContextAd,{ad:c.ad,variant:"inline",placement:c.placement,onVisible:c.fireImpression,onClick:c.onClick,onDismiss:p});return(0,en.jsxs)("aside",{"data-chat-ad":"",className:"mt-3 w-full min-w-0 rounded-lg border border-border/60 bg-muted/20 px-3 py-2",children:[(0,en.jsx)("p",{className:"mb-1 text-[11px] text-muted-foreground
14/60",children:"Sponsored"}),c.ad.leadForm?h:(0,en.jsx)(ez,{fallback:h,children:(0,en.jsx)(eM.GravityRenderedAd,{ad:c.ad,placement:c.placement,onVisible:c.fireImpression,onClick:c.onClick,onDismiss:p})})]})}var eL=e.i(247167),eF="vercel.ai.error",eZ=Symbol.for(eF),eB=class e extends(r=Error,t=eZ,r){constructor({name:e,message:r,cause:a}){super(r),this[t]=!0,this.name=e,this.cause=a}static isInstance(t){return e.hasMarker(t,eF)}static hasMarker(e,t){let r=Symbol.for(t);return null!=e&&"object"==typeof e&&r in e&&"boolean"==typeof e[r]&&!0===e[r]}},eH="AI_APICallError",eq=`vercel.ai.error.${eH}`,eV=Symbol.for(eq),eW=class extends(n=eB,a=eV,n){constructor({message:e,url:t,requestBodyValues:r,statusCode:n,responseHeaders:i,responseBody:s,cause:o,isRetryable:l=null!=n&&(408===n||409===n||429===n||n>=500),data:u}){super({name:eH,message:e,cause:o}),this[a]=!0,this.url=t,this.requestBodyValues=r,this.statusCode=n,this.responseHeaders=i,this.responseBody=s,this.isRetryable=l,this.data=u}static isInstance(e){return eB.hasMarker(e,eq)}},eG="AI_EmptyResponseBodyError",eY=`vercel.ai.error.${eG}`,eJ=Symbol.for(eY),eK=class extends(s=eB,i=eJ,s){constructor({message:e="Empty response body"}={}){super({name:eG,message:e}),this[i]=!0}static isInstance(e){return eB.hasMarker(e,eY)}};function eQ(e){return null==e?"unknown error":"string"==typeof e?e:e instanceof Error?e.toString():JSON.stringify(e)}var eX="AI_InvalidArgumentError",e0=`vercel.ai.error.${eX}`,e1=Symbol.for(e0),e2=class extends(l=eB,o=e1,l){constructor({message:e,cause:t,argument:r}){super({name:eX,message:e,cause:t}),this[o]=!0,this.argument=r}static isInstance(e){return eB.hasMarker(e,e0)}},e5=Symbol.for("vercel.ai.error.AI_InvalidPromptError");Symbol.for("vercel.ai.error.AI_InvalidResponseDataError");var e4="AI_JSONParseError",e3=`vercel.ai.error.${e4}`,e9=Symbol.for(e3),e6=class extends(c=eB,u=e9,c){constructor({text:e,cause:t}){super({name:e4,message:`JSON parsing failed: Text: ${e}.
15Error message: ${eQ(t)}`,cause:t}),this[u]=!0,this.text=e}static isInstance(e){return eB.hasMarker(e,e3)}},e8=Symbol.for("vercel.ai.error.AI_LoadAPIKeyError");Symbol.for("vercel.ai.error.AI_LoadSettingError");Symbol.for("vercel.ai.error.AI_NoContentGeneratedError");var e7="AI_NoSuchModelError",te=`vercel.ai.error.${e7}`,tt=Symbol.for(te),tr=class extends(p=eB,d=tt,p){constructor({errorName:e=e7,modelId:t,modelType:r,message:a=`No such ${r}: ${t}`}){super({name:e,message:a}),this[d]=!0,this.modelId=t,this.modelType=r}static isInstance(e){return eB.hasMarker(e,te)}},ta=Symbol.for("vercel.ai.error.AI_NoSuchProviderReferenceError");Symbol.for("vercel.ai.error.AI_TooManyEmbeddingValuesForCallError");var tn="AI_TypeValidationError",ti=`vercel.ai.error.${tn}`,ts=Symbol.for(ti),to=class e extends(m=eB,h=ts,m){constructor({value:e,cause:t,context:r}){let a="Type validation failed";if((null==r?void 0:r.field)&&(a+=` for ${r.field}`),(null==r?void 0:r.entityName)||(null==r?void 0:r.entityId)){a+=" (";const e=[];r.entityName&&e.push(r.entityName),r.entityId&&e.push(`id: "${r.entityId}"`),a+=e.join(", "),a+=")"}super({name:tn,message:`${a}: Value: ${JSON.stringify(e)}.
16Error message: ${eQ(t)}`,cause:t}),this[h]=!0,this.value=e,this.context=r}static isInstance(e){return eB.hasMarker(e,ti)}static wrap({value:t,cause:r,context:a}){var n,i,s;return e.isInstance(r)&&r.value===t&&(null==(n=r.context)?void 0:n.field)===(null==a?void 0:a.field)&&(null==(i=r.context)?void 0:i.entityName)===(null==a?void 0:a.entityName)&&(null==(s=r.context)?void 0:s.entityId)===(null==a?void 0:a.entityId)?r:new e({value:t,cause:r,context:a})}},tl=Symbol.for("vercel.ai.error.AI_UnsupportedFunctionalityError");function tu(e,t,r){function a(r,a){var n;for(let i in Object.defineProperty(r,"_zod",{value:r._zod??{},enumerable:!1}),(n=r._zod).traits??(n.traits=new Set),r._zod.traits.add(e),t(r,a),s.prototype)i in r||Object.defineProperty(r,i,{value:s.prototype[i].bind(r)});r._zod.constr=s,r._zod.def=a}let n=r?.Parent??Object;class i extends n{}function s(e){var t;let n=r?.Parent?new i:this;for(let r of(a(n,e),(t=n._zod).deferred??(t.deferred=[]),n._zod.deferred))r();return n}return Object.defineProperty(i,"name",{value:e}),Object.defineProperty(s,"init",{value:a}),Object.defineProperty(s,Symbol.hasInstance,{value:t=>!!r?.Parent&&t instanceof r.Parent||t?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}Object.freeze({status:"aborted"}),Symbol("zod_brand");
16class tc extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}let td={};function tp(e){return e&&Object.assign(td,e),td}function th(e){let t=Object.values(e).filter(e=>"number"==typeof e);return Object.entries(e).filter(([e,r])=>-1===t.indexOf(+e)).map(([e,t])=>t)}function tm(e,t){return"bigint"==typeof t?t.toString():t}function tf(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function tg(e){return null==e}function tv(e){let t=+!!e.startsWith("^"),r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function ty(e,t){let r=(e.toString().split(".")[1]||"").length,a=(t.toString().split(".")[1]||"").length,n=r>a?r:a;return Number.parseInt(e.toFixed(n).replace(".",""))%Number.parseInt(t.toFixed(n).replace(".",""))/10**n}function tb(e,t,r){Object.defineProperty(e,t,{get(){{let a=r();return e[t]=a,a}},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function tx(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function tw(e){return JSON.stringify(e)}let t_=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function tk(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}let tS=tf(()=>{if("u">typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return Function(""),!0}catch(e){return!1}});function tE(e){if(!1===tk(e))return!1;let t=e.constructor;if(void 0===t)return!0;let r=t.prototype;return!1!==tk(r)&&!1!==Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")}let tC=new Set(["string","number","symbol"]),tj=new Set(["string","number","bigint","boolean","symbol","undefined"]);function tI(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function tT(e,t,r){let a=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(a._zod.parent=e),a}function tN(e){if(!e)return{};if("string"==typeof e)return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");e.error=e.message}return(delete e.message,"string"==typeof e.error)?{...e,error:()=>e.error}:e}function tR(e){return"bigint"==typeof e?e.toString()+"n":"string"==typeof e?`"${e}"`:`${e}`}function tA(e){return Object.keys(e).filter(t=>"optional"===e[t]._zod.optin&&"optional"===e[t]._zod.optout)}let tz={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-0x80000000,0x7fffffff],uint32:[0,0xffffffff],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},tM={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function tO(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function tP(e,t){return t.map(t=>(t.path??(t.path=[]),t.path.unshift(e),t))}function t$(e){return"string"==typeof e?e:e?.message}function tD(e,t,r){let a={...e,path:e.path??[]};return e.message||(a.message=t$(e.inst?._zod.def?.error?.(e))??t$(t?.error?.(e))??t$(r.customError?.(e))??t$(r.localeError?.(e))??"Invalid input"),delete a.inst,delete a.continue,t?.reportInput||delete a.input,a}function tU(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function tL(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function tF(...e){let[t,r,a]=e;return"string"==typeof t?{message:t,code:"custom",input:r,inst:a}:{...t}}e.s(["BIGINT_FORMAT_RANGES",0,tM,"Class",0,class{constructor(...e){}},"NUMBER_FORMAT_RANGES",0,tz,"aborted",0,tO,"allowsEval",0,tS,"assert",0,function(e){},"assertEqual",0,function(e){return e},"assertIs",0,function(e){},"assertNever",0,function(e){throw Error()},"assertNotEqual",0,function(e){return e},"assignProp",0,tx,"cached",0,tf,"captureStackTrace",0,t_,"cleanEnum",0,function(e){return Object.entries(e).filter(([e,t])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])},"cleanRegex",0,tv,"clone",0,tT,"createTransparentProxy",0,function(e){let t;return new Proxy({},{get:(r,a,n)=>(t??(t=e()),Reflect.get(t,a,n)),set:(r,a,n,i)=>(t??(t=e()),Reflect.set(t,a,n,i)),has:(r,a)=>(t??(t=e()),Reflect.has(t,a)),deleteProperty:(r,a)=>(t??(t=e()),Reflect.deleteProperty(t,a)),ownKeys:r=>(t??(t=e()),Reflect.ownKeys(t)),getOwnPropertyDescriptor:(r,a)=>(t??(t=e()),Reflect.getOwnPropertyDescriptor(t,a)),defineProperty:(r,a,n)=>(t??(t=e()),Reflect.defineProperty(t,a,n))})},"defineLazy",0,tb,"esc",0,tw,"escapeRegex",0,tI,"extend",0,function(e,t){if(!tE(t))throw Error("Invalid input to extend: expected a plain object");let r={...e._zod.def,get shape(){let r={...e._zod.def.shape,...t};return tx(this,"shape",r),r},checks:[]};return tT(e,r)},"finalizeIssue",0,tD,"floatSafeRemainder",0,ty,"getElementAtPath",0,function(e,t){return t?t.reduce((e,t)=>
16e?.[t],e):e},"getEnumValues",0,th,"getLengthableOrigin",0,tL,"getParsedType",0,e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch)return"promise";if("u">typeof Map&&e instanceof Map)return"map";if("u">typeof Set&&e instanceof Set)return"set";if("u">typeof Date&&e instanceof Date)return"date";if("u">typeof File&&e instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${t}`)}},"getSizableOrigin",0,tU,"isObject",0,tk,"isPlainObject",0,tE,"issue",0,tF,"joinValues",0,function(e,t="|"){return e.map(e=>tR(e)).join(t)},"jsonStringifyReplacer",0,tm,"merge",0,function(e,t){return tT(e,{...e._zod.def,get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return tx(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})},"normalizeParams",0,tN,"nullish",0,tg,"numKeys",0,function(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t},"omit",0,function(e,t){let r={...e._zod.def.shape},a=e._zod.def;for(let e in t){if(!(e in a.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return tT(e,{...e._zod.def,shape:r,checks:[]})},"optionalKeys",0,tA,"partial",0,function(e,t,r){let a=t._zod.def.shape,n={...a};if(r)for(let t in r){if(!(t in a))throw Error(`Unrecognized key: "${t}"`);r[t]&&(n[t]=e?new e({type:"optional",innerType:a[t]}):a[t])}else for(let t in a)n[t]=e?new e({type:"optional",innerType:a[t]}):a[t];return tT(t,{...t._zod.def,shape:n,checks:[]})},"pick",0,function(e,t){let r={},a=e._zod.def;for(let e in t){if(!(e in a.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&(r[e]=a.shape[e])}return tT(e,{...e._zod.def,shape:r,checks:[]})},"prefixIssues",0,tP,"primitiveTypes",0,tj,"promiseAllObject",0,function(e){let t=Object.keys(e);return Promise.all(t.map(t=>e[t])).then(e=>{let r={};for(let a=0;a<t.length;a++)r[t[a]]=e[a];return r})},"propertyKeyTypes",0,tC,"randomString",0,function(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let a=0;a<e;a++)r+=t[Math.floor(Math.random()*t.length)];return r},"required",0,function(e,t,r){let a=t._zod.def.shape,n={...a};if(r)for(let t in r){if(!(t in n))throw Error(`Unrecognized key: "${t}"`);r[t]&&(n[t]=new e({type:"nonoptional",innerType:a[t]}))}else for(let t in a)n[t]=new e({type:"nonoptional",innerType:a[t]});return tT(t,{...t._zod.def,shape:n,checks:[]})},"stringifyPrimitive",0,tR,"unwrapMessage",0,t$],922143);let tZ=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get:()=>JSON.stringify(t,tm,2),enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},tB=tu("$ZodError",tZ),tH=tu("$ZodError",tZ,{Parent:Error}),tq=e=>(t,r,a)=>{let n=a?{...a,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},n);if(i instanceof Promise)throw new tc;return i.issues.length?{success:!1,error:new(e??tB)(i.issues.map(e=>tD(e,n,tp())))}:{success:!0,data:i.value}},tV=tq(tH),tW=e=>async(t,r,a)=>{let n=a?Object.assign(a,{async:!0}):{async:!0},i=t._zod.run({value:r,issues:[]},n);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(e=>tD(e,n,tp())))}:{success:!0,data:i.value}},tG=tW(tH),tY=tu("ZodError",(e,t)=>{tB.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:t=>{let r,a,n;return r=t||function(e){return e.message},a={_errors:[]},(n=e=>{for(let t of e.issues)if("invalid_union"===t.code&&t.errors.length)t.errors.map(e=>n({issues:e}));else if("invalid_key"===t.code)n({issues:t.issues});else if("invalid_element"===t.code)n({issues:t.issues});else if(0===t.path.length)a._errors.push(r(t));else{let e=a,n=0;for(;n<t.path.length;){let a=t.path[n];n===t.path.length-1?(e[a]=e[a]||{_errors:[]}
16,e[a]._errors.push(r(t))):e[a]=e[a]||{_errors:[]},e=e[a],n++}}})(e),a}},flatten:{value:t=>(function(e,t=e=>e.message){let r={},a=[];for(let n of e.issues)n.path.length>0?(r[n.path[0]]=r[n.path[0]]||[],r[n.path[0]].push(t(n))):a.push(t(n));return{formErrors:a,fieldErrors:r}})(e,t)},addIssue:{value:t=>e.issues.push(t)},addIssues:{value:t=>e.issues.push(...t)},isEmpty:{get:()=>0===e.issues.length}})},{Parent:Error}),tJ=(e,t,r,a)=>{let n=r?Object.assign(r,{async:!1}):{async:!1},i=e._zod.run({value:t,issues:[]},n);if(i instanceof Promise)throw new tc;if(i.issues.length){let e=new(a?.Err??tY)(i.issues.map(e=>tD(e,n,tp())));throw t_(e,a?.callee),e}return i.value},tK=async(e,t,r,a)=>{let n=r?Object.assign(r,{async:!0}):{async:!0},i=e._zod.run({value:t,issues:[]},n);if(i instanceof Promise&&(i=await i),i.issues.length){let e=new(a?.Err??tY)(i.issues.map(e=>tD(e,n,tp())));throw t_(e,a?.callee),e}return i.value},tQ=tq(tY),tX=tW(tY);Symbol("ZodOutput"),Symbol("ZodInput");class t0{constructor(){this._map=new Map,this._idmap=new Map}add(e,...t){let r=t[0];if(this._map.set(e,r),r&&"object"==typeof r&&"id"in r){if(this._idmap.has(r.id))throw Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let r={...this.get(t)??{}};return delete r.id,{...r,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}}let t1=new t0;class t2{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??t1,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,t={path:[],schemaPath:[]}){var r;let a=e._zod.def,n=this.seen.get(e);if(n)return n.count++,t.schemaPath.includes(e)&&(n.cycle=t.path),n.schema;let i={schema:{},count:1,cycle:void 0,path:t.path};this.seen.set(e,i);let s=e._zod.toJSONSchema?.();if(s)i.schema=s;else{let r={...t,schemaPath:[...t.schemaPath,e],path:t.path},n=e._zod.parent;if(n)i.ref=n,this.process(n,r),this.seen.get(n).isParent=!0;else{let t=i.schema;switch(a.type){case"string":{t.type="string";let{minimum:r,maximum:a,format:n,patterns:s,contentEncoding:o}=e._zod.bag;if("number"==typeof r&&(t.minLength=r),"number"==typeof a&&(t.maxLength=a),n&&(t.format=({guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""})[n]??n,""===t.format&&delete t.format),o&&(t.contentEncoding=o),s&&s.size>0){let e=[...s];1===e.length?t.pattern=e[0].source:e.length>1&&(i.schema.allOf=[...e.map(e=>({..."draft-7"===this.target?{type:"string"}:{},pattern:e.source}))])}break}case"number":{let{minimum:r,maximum:a,format:n,multipleOf:i,exclusiveMaximum:s,exclusiveMinimum:o}=e._zod.bag;"string"==typeof n&&n.includes("int")?t.type="integer":t.type="number","number"==typeof o&&(t.exclusiveMinimum=o),"number"==typeof r&&(t.minimum=r,"number"==typeof o&&(o>=r?delete t.minimum:delete t.exclusiveMinimum)),"number"==typeof s&&(t.exclusiveMaximum=s),"number"==typeof a&&(t.maximum=a,"number"==typeof s&&(s<=a?delete t.maximum:delete t.exclusiveMaximum)),"number"==typeof i&&(t.multipleOf=i);break}case"boolean":case"success":t.type="boolean";break;case"bigint":if("throw"===this.unrepresentable)throw Error("BigInt cannot be represented in JSON Schema");break;case"symbol":if("throw"===this.unrepresentable)throw Error("Symbols cannot be represented in JSON Schema");break;case"null":t.type="null";break;case"any":case"unknown":break;case"undefined":if("throw"===this.unrepresentable)throw Error("Undefined cannot be represented in JSON Schema");break;case"void":if("throw"===this.unrepresentable)throw Error("Void cannot be represented in JSON Schema");break;case"never":t.not={};break;case"date":if("throw"===this.unrepresentable)throw Error("Date cannot be represented in JSON Schema");break;case"array":{let{minimum:n,maximum:i}=e._zod.bag;"number"==typeof n&&(t.minItems=n),"number"==typeof i&&(t.maxItems=i),t.type="array",t.items=this.process(a.element,{...r,path:[...r.path,"items"]});break}case"object":{t.type="object",t.properties={};let e=a.shape;for(let a in e)t.properties[a]=this.process(e[a],{...r,path:[...r.path,"properties",a]});let n=new Set([...new Set(Object.keys(e))].filter(e=>{let t=a.shape[e]._zod;return"input"===this.io?void 0===t.optin:void 0===t.optout}));n.size>
160&&(t.required=Array.from(n)),a.catchall?._zod.def.type==="never"?t.additionalProperties=!1:a.catchall?a.catchall&&(t.additionalProperties=this.process(a.catchall,{...r,path:[...r.path,"additionalProperties"]})):"output"===this.io&&(t.additionalProperties=!1);break}case"union":t.anyOf=a.options.map((e,t)=>this.process(e,{...r,path:[...r.path,"anyOf",t]}));break;case"intersection":{let e=this.process(a.left,{...r,path:[...r.path,"allOf",0]}),n=this.process(a.right,{...r,path:[...r.path,"allOf",1]}),i=e=>"allOf"in e&&1===Object.keys(e).length;t.allOf=[...i(e)?e.allOf:[e],...i(n)?n.allOf:[n]];break}case"tuple":{t.type="array";let n=a.items.map((e,t)=>this.process(e,{...r,path:[...r.path,"prefixItems",t]}));if("draft-2020-12"===this.target?t.prefixItems=n:t.items=n,a.rest){let e=this.process(a.rest,{...r,path:[...r.path,"items"]});"draft-2020-12"===this.target?t.items=e:t.additionalItems=e}a.rest&&(t.items=this.process(a.rest,{...r,path:[...r.path,"items"]}));let{minimum:i,maximum:s}=e._zod.bag;"number"==typeof i&&(t.minItems=i),"number"==typeof s&&(t.maxItems=s);break}case"record":t.type="object",t.propertyNames=this.process(a.keyType,{...r,path:[...r.path,"propertyNames"]}),t.additionalProperties=this.process(a.valueType,{...r,path:[...r.path,"additionalProperties"]});break;case"map":if("throw"===this.unrepresentable)throw Error("Map cannot be represented in JSON Schema");break;case"set":if("throw"===this.unrepresentable)throw Error("Set cannot be represented in JSON Schema");break;case"enum":{let e=th(a.entries);e.every(e=>"number"==typeof e)&&(t.type="number"),e.every(e=>"string"==typeof e)&&(t.type="string"),t.enum=e;break}case"literal":{let e=[];for(let t of a.values)if(void 0===t){if("throw"===this.unrepresentable)throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if("bigint"==typeof t)if("throw"===this.unrepresentable)throw Error("BigInt literals cannot be represented in JSON Schema");else e.push(Number(t));else e.push(t);if(0===e.length);else if(1===e.length){let r=e[0];t.type=null===r?"null":typeof r,t.const=r}else e.every(e=>"number"==typeof e)&&(t.type="number"),e.every(e=>"string"==typeof e)&&(t.type="string"),e.every(e=>"boolean"==typeof e)&&(t.type="string"),e.every(e=>null===e)&&(t.type="null"),t.enum=e;break}case"file":{let r={type:"string",format:"binary",contentEncoding:"binary"},{minimum:a,maximum:n,mime:i}=e._zod.bag;void 0!==a&&(r.minLength=a),void 0!==n&&(r.maxLength=n),i?1===i.length?(r.contentMediaType=i[0],Object.assign(t,r)):t.anyOf=i.map(e=>({...r,contentMediaType:e})):Object.assign(t,r);break}case"transform":if("throw"===this.unrepresentable)throw Error("Transforms cannot be represented in JSON Schema");break;case"nullable":t.anyOf=[this.process(a.innerType,r),{type:"null"}];break;case"nonoptional":case"promise":case"optional":this.process(a.innerType,r),i.ref=a.innerType;break;case"default":this.process(a.innerType,r),i.ref=a.innerType,t.default=JSON.parse(JSON.stringify(a.defaultValue));break;case"prefault":this.process(a.innerType,r),i.ref=a.innerType,"input"===this.io&&(t._prefault=JSON.parse(JSON.stringify(a.defaultValue)));break;case"catch":{let e;this.process(a.innerType,r),i.ref=a.innerType;try{e=a.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}t.default=e;break}case"nan":if("throw"===this.unrepresentable)throw Error("NaN cannot be represented in JSON Schema");break;case"template_literal":{let r=e._zod.pattern;if(!r)throw Error("Pattern not found in template literal");t.type="string",t.pattern=r.source;break}case"pipe":{let e="input"===this.io?"transform"===a.in._zod.def.type?a.out:a.in:a.out;this.process(e,r),i.ref=e;break}case"readonly":this.process(a.innerType,r),i.ref=a.innerType,t.readOnly=!0;break;case"lazy":{let t=e._zod.innerType;this.process(t,r),i.ref=t;break}case"custom":if("throw"===this.unrepresentable)throw Error("Custom types cannot be represented in JSON Schema")}}}let o=this.metadataRegistry.get(e);return o&&Object.assign(i.schema,o),"input"===this.io&&function e(t,r){let a=r??{seen:new Set};if(a.seen.has(t))return!1;a.seen.add(t);let n=t._zod.def;switch(n.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":case"custom"
16:case"success":case"catch":return!1;case"array":return e(n.element,a);case"object":for(let t in n.shape)if(e(n.shape[t],a))return!0;return!1;case"union":for(let t of n.options)if(e(t,a))return!0;return!1;case"intersection":return e(n.left,a)||e(n.right,a);case"tuple":for(let t of n.items)if(e(t,a))return!0;if(n.rest&&e(n.rest,a))return!0;return!1;case"record":case"map":return e(n.keyType,a)||e(n.valueType,a);case"set":return e(n.valueType,a);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":case"default":case"prefault":return e(n.innerType,a);case"lazy":return e(n.getter(),a);case"transform":return!0;case"pipe":return e(n.in,a)||e(n.out,a)}throw Error(`Unknown schema type: ${n.type}`)}(e)&&(delete i.schema.examples,delete i.schema.default),"input"===this.io&&i.schema._prefault&&((r=i.schema).default??(r.default=i.schema._prefault)),delete i.schema._prefault,this.seen.get(e).schema}emit(e,t){let r={cycles:t?.cycles??"ref",reused:t?.reused??"inline",external:t?.external??void 0},a=this.seen.get(e);if(!a)throw Error("Unprocessed schema. This is a bug in Zod.");let n=e=>{let t="draft-2020-12"===this.target?"$defs":"definitions";if(r.external){let a=r.external.registry.get(e[0])?.id,n=r.external.uri??(e=>e);if(a)return{ref:n(a)};let i=e[1].defId??e[1].schema.id??`schema${this.counter++}`;return e[1].defId=i,{defId:i,ref:`${n("__shared")}#/${t}/${i}`}}if(e[1]===a)return{ref:"#"};let n=`#/${t}/`,i=e[1].schema.id??`__schema${this.counter++}`;return{defId:i,ref:n+i}},i=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:r,defId:a}=n(e);t.def={...t.schema},a&&(t.defId=a);let i=t.schema;for(let e in i)delete i[e];i.$ref=r};if("throw"===r.cycles)for(let e of this.seen.entries()){let t=e[1];if(t.cycle)throw Error(`Cycle detected: #/${t.cycle?.join("/")}/<root>
17
18Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let t of this.seen.entries()){let a=t[1];if(e===t[0]){i(t);continue}if(r.external){let a=r.external.registry.get(t[0])?.id;if(e!==t[0]&&a){i(t);continue}}if(this.metadataRegistry.get(t[0])?.id||a.cycle||a.count>1&&"ref"===r.reused){i(t);continue}}let s=(e,t)=>{let r=this.seen.get(e),a=r.def??r.schema,n={...a};if(null===r.ref)return;let i=r.ref;if(r.ref=null,i){s(i,t);let e=this.seen.get(i).schema;e.$ref&&"draft-7"===t.target?(a.allOf=a.allOf??[],a.allOf.push(e)):(Object.assign(a,e),Object.assign(a,n))}r.isParent||this.override({zodSchema:e,jsonSchema:a,path:r.path??[]})};for(let e of[...this.seen.entries()].reverse())s(e[0],{target:this.target});let o={};if("draft-2020-12"===this.target?o.$schema="https://json-schema.org/draft/2020-12/schema":"draft-7"===this.target?o.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),r.external?.uri){let t=r.external.registry.get(e)?.id;if(!t)throw Error("Schema is missing an `id` property");o.$id=r.external.uri(t)}Object.assign(o,a.def);let l=r.external?.defs??{};for(let e of this.seen.entries()){let t=e[1];t.def&&t.defId&&(l[t.defId]=t.def)}r.external||Object.keys(l).length>0&&("draft-2020-12"===this.target?o.$defs=l:o.definitions=l);try{return JSON.parse(JSON.stringify(o))}catch(e){throw Error("Error converting schema to JSON.")}}}class t5 extends Error{constructor(e,t){super(e),this.name="ParseError",this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}}function t4(e){}function t3(e,t,r){return 100===r&&97===e.charCodeAt(t+1)&&116===e.charCodeAt(t+2)&&97===e.charCodeAt(t+3)&&58===e.charCodeAt(t+4)}function t9(e,t,r){return 101===r&&118===e.charCodeAt(t+1)&&101===e.charCodeAt(t+2)&&110===e.charCodeAt(t+3)&&116===e.charCodeAt(t+4)&&58===e.charCodeAt(t+5)}class t6 extends TransformStream{constructor({onError:e,onRetry:t,onComment:r,maxBufferSize:a}={}){let n;super({start(i){n=function(e){if("function"==typeof e)throw TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:t=t4,onError:r=t4,onRetry:a=t4,onComment:n,maxBufferSize:i}=e,s=[],o=0,l=!0,u,c="",d=0,p,h=!1;function m(){void 0!==i&&(o+c.length<=i||(h=!0,s.length=0,o=0,u=void 0,c="",d=0,p=void 0,r(new t5(`Buffered data exceeded max buffer size of ${i} characters`,{type:"max-buffer-size-exceeded"}))))}function f(e){let r=0;if(-1===e.indexOf("\r")){let a=e.indexOf(`
19`,r);for(;-1!==a;){if(r===a){d>0&&t({id:u,event:p,data:c}),u=void 0,c="",d=0,p=void 0,r=a+1,a=e.indexOf(`
20`,r);continue}let n=e.charCodeAt(r);if(t3(e,r,n)){let n=32===e.charCodeAt(r+5)?r+6:r+5,i=e.slice(n,a);if(0===d&&10===e.charCodeAt(a+1)){t({id:u,event:p,data:i}),u=void 0,c="",p=void 0,r=a+2,a=e.indexOf(`
21`,r);continue}c=0===d?i:`${c}
22${i}`,d++}else t9(e,r,n)?p=e.slice(32===e.charCodeAt(r+6)?r+7:r+6,a)||void 0:g(e,r,a);r=a+1,a=e.indexOf(`
23`,r)}return e.slice(r)}for(;r<e.length;){let t=e.indexOf("\r",r),a=e.indexOf(`
24`,r),n=-1;
24if(-1!==t&&-1!==a?n=t<a?t:a:-1!==t?n=t===e.length-1?-1:t:-1!==a&&(n=a),-1===n)break;g(e,r,n),r=n+1,13===e.charCodeAt(r-1)&&10===e.charCodeAt(r)&&r++}return e.slice(r)}function g(e,r,a){if(r===a)return void(d>0&&t({id:u,event:p,data:c}),u=void 0,c="",d=0,p=void 0);let i=e.charCodeAt(r);if(t3(e,r,i)){let t=32===e.charCodeAt(r+5)?r+6:r+5,n=e.slice(t,a);c=0===d?n:`${c}
25${n}`,d++;return}if(t9(e,r,i)){p=e.slice(32===e.charCodeAt(r+6)?r+7:r+6,a)||void 0;return}if(105===i&&100===e.charCodeAt(r+1)&&58===e.charCodeAt(r+2)){let t=e.slice(32===e.charCodeAt(r+3)?r+4:r+3,a);t.includes("\0")||(u=t);return}if(58===i){n&&n(e.slice(r,a).slice(32===e.charCodeAt(r+1)?2:1));return}let s=e.slice(r,a),o=s.indexOf(":");if(-1===o)return void v(s,"",s);let l=s.slice(0,o),h=32===s.charCodeAt(o+1)?2:1;v(l,s.slice(o+h),s)}function v(e,t,n){switch(e){case"event":p=t||void 0;break;case"data":c=0===d?t:`${c}
26${t}`,d++;break;case"id":t.includes("\0")||(u=t);break;case"retry":/^\d+$/.test(t)?a(parseInt(t,10)):r(new t5(`Invalid \`retry\` value: "${t}"`,{type:"invalid-retry",value:t,line:n}));break;default:r(new t5(`Unknown field "${e.length>20?`${e.slice(0,20)}\u2026`:e}"`,{type:"unknown-field",field:e,value:t,line:n}))}}return{feed:function(e){if(h)throw Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(l&&(l=!1,239===e.charCodeAt(0)&&187===e.charCodeAt(1)&&191===e.charCodeAt(2)&&(e=e.slice(3))),0===s.length){let t=f(e);""!==t&&(s.push(t),o=t.length),m();return}if(-1===e.indexOf(`
27`)&&-1===e.indexOf("\r")){s.push(e),o+=e.length,m();return}s.push(e);let t=s.join("");s.length=0,o=0;let r=f(t);""!==r&&(s.push(r),o=r.length),m()},reset:function(e={}){if(e.consume&&s.length>0){let e=s.join("");g(e,0,e.length)}l=!0,u=void 0,c="",d=0,p=void 0,s.length=0,o=0,h=!1}}}({onEvent:e=>{i.enqueue(e)},onError(t){"function"==typeof e&&e(t),("terminate"===e||"max-buffer-size-exceeded"===t.type)&&i.error(t)},onRetry:t,onComment:r,maxBufferSize:a})},transform(e){n.feed(e)}})}}let t8=Symbol.for("workflow-serialize"),t7=Symbol.for("workflow-deserialize");function re(...e){return e.reduce((e,t)=>({...e,...null!=t?t:{}}),{})}async function rt(e,t){if(null==e)return Promise.resolve();let r=null==t?void 0:t.abortSignal;return new Promise((t,a)=>{if(null==r?void 0:r.aborted)return void a(rr());let n=setTimeout(()=>{i(),t()},e),i=()=>{clearTimeout(n),null==r||r.removeEventListener("abort",s)},s=()=>{i(),a(rr())};null==r||r.addEventListener("abort",s)})}function rr(){return new DOMException("Delay was aborted","AbortError")}var ra=new TextDecoder;async function rn(e){return"string"==typeof e?e:e instanceof ArrayBuffer||ArrayBuffer.isView(e)?ra.decode(e):"u">typeof Blob&&e instanceof Blob?e.text():String(e)}async function ri(e,{highWaterMark:t=1048576,pollIntervalMs:r=20,abortSignal:a}={}){for(var n;1===e.readyState&&(null!=(n=e.bufferedAmount)?n:0)>t;){if((null==a?void 0:a.aborted)===!0)return;await rt(r)}}var{btoa:rs,atob:ro}=globalThis;function rl(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCodePoint(e[r]);return rs(t)}function ru(e){return Object.fromEntries([...e.headers])}function rc(e=globalThis){var t,r,a;return e.window?"runtime/browser":(null==(t=e.navigator)?void 0:t.userAgent)?`runtime/${e.navigator.userAgent.toLowerCase()}`:(null==(a=null==(r=e.process)?void 0:r.versions)?void 0:a.node)?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function rd(e){return(e instanceof Error||e instanceof DOMException)&&("AbortError"===e.name||"ResponseAborted"===e.name||"TimeoutError"===e.name)}var rp=["fetch failed","failed to fetch"],rh=new Set(["ConnectionRefused","ConnectionClosed","FailedToOpenSocket","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE","UND_ERR_SOCKET","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CONNECT_TIMEOUT"]);function rm({error:e,url:t,requestBodyValues:r}){if(rd(e))return e;if(e instanceof TypeError&&rp.includes(e.message.toLowerCase())){let a=e.cause;if(null!=a)return new eW({message:`Cannot connect to API: ${a.message}`,cause:a,url:t,requestBodyValues:r,isRetryable:!0})}let a=function(e){let t=new Set,r=e;for(;r instanceof Error&&!t.has(r);){t.add(r);let e=r;if("string"==typeof e.code&&rh.has(e.code))return e;r=r.cause}}
27(e);return null!=a?new eW(eW.isInstance(e)?{message:e.message,cause:e.cause,url:e.url,requestBodyValues:e.requestBodyValues,statusCode:e.statusCode,responseHeaders:e.responseHeaders,responseBody:e.responseBody,data:e.data,isRetryable:!0}:{message:`Cannot connect to API: ${e instanceof Error?e.message:a.message}`,cause:e,url:t,requestBodyValues:r,isRetryable:!0}):e}var rf="5.0.36";function rg(e){if(null==e)return{};let t={};if(e instanceof Headers)e.forEach((e,r)=>{t[r.toLowerCase()]=e});else for(let[r,a]of(Array.isArray(e)||(e=Object.entries(e)),e))null!=a&&(t[r.toLowerCase()]=a);return t}function rv(e,...t){let r=new Headers(rg(e)),a=r.get("user-agent")||"";return r.set("user-agent",[a,...t].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}async function ry(e){var t;try{await (null==(t=e.body)?void 0:t.cancel())}catch(e){}}var rb="AI_DownloadError",rx=`vercel.ai.error.${rb}`,rw=Symbol.for(rx),r_=class extends(g=eB,f=rw,g){constructor({url:e,statusCode:t,statusText:r,cause:a,message:n=null==a?`Failed to download ${e}: ${t} ${r}`:`Failed to download ${e}: ${a}`}){super({name:rb,message:n,cause:a}),this[f]=!0,this.url=e,this.statusCode=t,this.statusText=r}static isInstance(e){return eB.hasMarker(e,rx)}};function rk(e,t){try{return new URL(e).origin===new URL(t).origin}catch(e){return!1}}function rS(e){let t=e.split(".");return 4===t.length&&t.every(e=>{let t=Number(e);return Number.isInteger(t)&&t>=0&&t<=255&&String(t)===e})}function rE(e){let[t,r,a]=e.split(".").map(Number);return 0===t||10===t||100===t&&r>=64&&r<=127||127===t||169===t&&254===r||172===t&&r>=16&&r<=31||192===t&&0===r&&0===a||192===t&&0===r&&2===a||192===t&&168===r||198===t&&(18===r||19===r)||198===t&&51===r&&100===a||203===t&&0===r&&113===a||t>=224||!1}function rC(e){let t=function(e){let t=e.toLowerCase(),r=t.indexOf("%");-1!==r&&(t=t.slice(0,r));let a=t.split("::");if(a.length>2)return null;let n=e=>{if(""===e)return[];let t=[],r=e.split(":");for(let e=0;e<r.length;e++){let a=r[e];if(a.includes(".")){if(e!==r.length-1||!rS(a))return null;let[n,i,s,o]=a.split(".").map(Number);t.push(n<<8|i,s<<8|o);continue}if(!/^[0-9a-f]{1,4}$/.test(a))return null;t.push(parseInt(a,16))}return t},i=n(a[0]);if(null===i)return null;if(2===a.length){let e=n(a[1]);if(null===e)return null;let t=8-i.length-e.length;return t<0?null:[...i,...Array(t).fill(0),...e]}return 8===i.length?i:null}(e);if(null===t)return!0;let r=e=>t.slice(0,e).every(e=>0===e);if(r(7)&&(0===t[7]||1===t[7])||(65024&t[0])==64512||(65472&t[0])==65152||(65472&t[0])==65216||(65280&t[0])==65280||8193===t[0]&&3512===t[1]||16383===t[0]&&(61440&t[1])==0)return!0;if(r(6)||r(5)&&65535===t[5]||r(4)&&65535===t[4]&&0===t[5]||100===t[0]&&65435===t[1]&&0===t[2]&&0===t[3]&&0===t[4]&&0===t[5]||100===t[0]&&65435===t[1]&&1===t[2]){let e=t[6]>>8&255,r=255&t[6],a=t[7]>>8&255,n=255&t[7];return rE(`${e}.${r}.${a}.${n}`)}return!1}var rj=globalThis.fetch,rI=function(e){if("function"!=typeof e)return!1;let t=Function.prototype.toString.call(e);return t.includes("internal/deps/undici")||t.includes("lazy loading of undici")}(rj);async function rT(){var e,t;let r;return(null==(e=null==(r=globalThis.process)?void 0:r.release)?void 0:e.name)==="node"&&(null==(t=r.versions)?void 0:t.bun)==null&&rI&&globalThis.fetch===rj?null!=v?v:v=Promise.resolve().then(rN):globalThis.fetch}function rN(){let{createRequire:e}=rR("node:module"),{lookup:t}=rR("node:dns"),{Agent:r,fetch:a}=e(function e(){let t=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;let t=Error("Capture current module path");Error.captureStackTrace(t,e);let[r]=t.stack,a=null==r?void 0:r.getFileName();if(null==a)throw Error("Unable to determine the current module path");return a}finally{Error.prepareStackTrace=t}}())("undici"),n=new r({connect:{lookup:(e,r,a)=>{t(e,{...r,all:!0},(t,n)=>{if(t)return void a(t);try{let[t]=n;if(null==t)throw Error(`Hostname ${e} did not resolve to an address`);for(let{address:t,family:r}of n)!function({address:e,family:t,hostname:r}){if(4===t?!rS(e)||rE(e):6!==t||rC(e))throw new r_({url:r,message:`Hostname ${r} resolved to disallowed IP address ${e}`})}({address:t,family:r,hostname:e});!0===r.all?a(null,n):a(null,t.address,t.family)}catch(e){a(e instanceof Error?e:Error(String(e)))}})}}});return(e,t)=>a(e,{...t,dispatcher:n})}function rR(e){var t;let r=globalThis.process,a=null==(t=null==r?void 0:r.getBuiltinModule)?void 0:t.call(r,e);if(null==a)throw Error(`Node.js built-in module ${e} is unavailable`);return a}var rA=["connection","keep-alive","te","trailer","transfer-encoding","upgrade","host","forwarded","proxy-authorization","via","x-forwarded-for","x-forwarded-host","x-forwarded-proto","x-real-ip","metadata","metadata-flavor","x-aws-ec2-metadata-token","x-metadata-token","cookie","set-cookie"],rz=new Set([301,302,303,307,308]);async function rM({url:e,headers:t,abortSignal:r,maxRedirects:a=10,fetch:n,trustedOrigin:i}){let s=void 0===t?void 0:function(e){let t=new Headers(e);for(let e of rA)t.delete(e);return t}(t),o=e=>{let t={signal:r,redirect:e};return void 0!==s&&(t.headers=new Headers(s)),t},l=e;for(let t=0;t<=a;t++){let t=void 0!==i&&rk(l,i);t||function(e){let t;try{t=new URL(e)}catch(t){throw new r_({url:e,message:`Invalid URL: ${e}`})}if("data:"===t.protocol)return;if("http:"!==t.protocol&&"https:"!==t.protocol)throw new r_({url:e,message:`URL scheme must be http, https, or data, got ${t.protocol}`});let r=t.hostname.toLowerCase().replace(/\.+$/,"");if(!r)throw new r_({url:e,message:"URL must have a hostname"});if("localhost"===r||r.endsWith(".local")||r.endsWith(".localhost"))throw new r_({url:e,message:`URL with hostname ${r} is not allowed`});
27if(r.startsWith("[")&&r.endsWith("]")){if(rC(r.slice(1,-1)))throw new r_({url:e,message:`URL with IPv6 address ${r} is not allowed`});return}if(rS(r)&&rE(r))throw new r_({url:e,message:`URL with IP address ${r} is not allowed`})}(l);let r=null!=n?n:t?globalThis.fetch:await rT(),a=await r(l,o("manual"));if("opaqueredirect"===a.type){if(!function(e=globalThis){return null!=e.window}())throw new r_({url:e,message:`Redirect from ${l} could not be validated and was blocked`});return await r(l,o("follow"))}let u=a.headers.get("location");if(rz.has(a.status)&&u){await ry(a);let e=new URL(u,l).toString();if(void 0!==s&&!rk(e,l)){let e=s.get("user-agent");s=new Headers(null==e?void 0:{"user-agent":e})}l=e;continue}return a}throw new r_({url:e,message:`Too many redirects (max ${a})`})}async function rO({response:e,url:t,maxBytes:r=0x80000000}){let a=e.headers.get("content-length");if(null!=a){let n=parseInt(a,10);if(!isNaN(n)&&n>r)throw await ry(e),new r_({url:t,message:`Download of ${t} exceeded maximum size of ${r} bytes (Content-Length: ${n}).`})}let n=e.body;if(null==n)return new Uint8Array(0);let i=n.getReader(),s=[],o=0;try{for(;;){let{done:e,value:a}=await i.read();if(e)break;if((o+=a.length)>r)throw new r_({url:t,message:`Download of ${t} exceeded maximum size of ${r} bytes.`});s.push(a)}}finally{try{await i.cancel()}catch(e){}finally{i.releaseLock()}}let l=new Uint8Array(o),u=0;
27for(let e of s)l.set(e,u),u+=e.length;return l}var rP=({prefix:e,size:t=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:a="-"}={})=>{let n=()=>{let e=r.length,a=Array(t);for(let n=0;n<t;n++)a[n]=r[Math.random()*e|0];return a.join("")};if(null==e)return n;if(r.includes(a))throw new e2({argument:"separator",message:`The separator "${a}" must not be part of the alphabet "${r}".`});return()=>`${e}${a}${n()}`},r$=rP(),rD=async({url:e,headers:t={},successfulResponseHandler:r,failedResponseHandler:a,abortSignal:n,fetch:i,validateUrl:s,credentialedOrigin:o,trustedOrigin:l})=>{try{let u=null!=i?i:globalThis.fetch,c=void 0===o||rk(e,o)?t:{},d=rv(c,`ai-sdk/provider-utils/${rf}`,rc()),p=s?await rM({url:e,headers:d,abortSignal:n,fetch:i,trustedOrigin:l}):await u(e,{method:"GET",headers:d,signal:n}),h=ru(p);if(!p.ok){let t;try{t=await a({response:p,url:e,requestBodyValues:{}})}catch(t){if(rd(t)||eW.isInstance(t))throw t;throw new eW({message:"Failed to process error response",cause:t,statusCode:p.status,url:e,responseHeaders:h,requestBodyValues:{}})}throw t.value}try{return await r({response:p,url:e,requestBodyValues:{}})}catch(t){if(t instanceof Error&&(rd(t)||eW.isInstance(t)))throw t;throw new eW({message:"Failed to process successful response",cause:t,statusCode:p.status,url:e,responseHeaders:h,requestBodyValues:{}})}}catch(t){throw rm({error:t,url:e,requestBodyValues:{}})}};function rU(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)}function rL({settingValue:e,environmentVariableName:t}){return"string"==typeof e?e:null!=e||void 0===eL.default?void 0:null!=(e=eL.default.env[t])&&"string"==typeof e?e:void 0}function rF(e){return null!=e&&Number.isSafeInteger(e)&&e>=0}var rZ=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,rB=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function rH(e){let t=JSON.parse(e);return null===t||"object"!=typeof t||!1===rZ.test(e)&&!1===rB.test(e)?t:function(e){let t=[e];for(;t.length;){let e=t;for(let r of(t=[],e)){if(Object.prototype.hasOwnProperty.call(r,"__proto__")||Object.prototype.hasOwnProperty.call(r,"constructor")&&null!==r.constructor&&"object"==typeof r.constructor&&Object.prototype.hasOwnProperty.call(r.constructor,"prototype"))throw SyntaxError("Object contains forbidden prototype property");for(let e in r){let a=r[e];a&&"object"==typeof a&&t.push(a)}}}return e}(t)}function rq(e){let{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch(t){return rH(e)}try{return rH(e)}finally{Error.stackTraceLimit=t}}function rV(e){if("object"===e.type||Array.isArray(e.type)&&e.type.includes("object")){let{additionalProperties:t}=e;e.additionalProperties=null!=t&&"boolean"!=typeof t&&rW(t);let{properties:r}=e;if(null!=r)for(let e of Object.keys(r))r[e]=rW(r[e])}null!=e.items&&(e.items=Array.isArray(e.items)?e.items.map(rW):rW(e.items)),null!=e.anyOf&&(e.anyOf=e.anyOf.map(rW)),null!=e.allOf&&(e.allOf=e.allOf.map(rW)),null!=e.oneOf&&(e.oneOf=e.oneOf.map(rW));let{definitions:t}=e;if(null!=t)for(let e of Object.keys(t))t[e]=rW(t[e]);return e}function rW(e){return"boolean"==typeof e?e:rV(e)}var rG=Symbol("Let zodToJsonSchema decide on which parser to use"),rY={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"};function rJ(e,t){return ao(e.type._def,t)}var rK=void 0,rQ=/^[cC][^\s-]{8,}$/,rX=/^[0-9a-z]+$/,r0=/^[0-9A-HJKMNP-TV-Z]{26}$/,r1=/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,r2=()=>(void 0===rK&&(rK=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),rK),r5=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,r4=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,r3=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,r9=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,r6=/^[a-zA-Z0-9_-]{21}$/,r8=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;function r7(e,t){let r={type:"string"};if(e.checks)for(let a of e.checks)switch(a.kind){case"min":r.minLength="number"==typeof r.minLength?Math.max(r.minLength,a.value):a.value;break;case"max":r.maxLength="number"==typeof r.maxLength?Math.min(r.maxLength,a.value):a.value;break;case"email":switch(t.emailStrategy){case"format:email":ar(r,"email",a.message,t);break;case"format:idn-email":ar(r,"idn-email",a.message,t);break;case"pattern:zod":aa(r,r1,a.message,t)}break;case"url":ar(r,"uri",a.message,t);break;case"uuid":ar(r,"uuid",a.message,t);break;case"regex":aa(r,a.regex,a.message,t);break;case"cuid":aa(r,rQ,a.message,t);break;case"cuid2":aa(r,rX,a.message,t);break;case"startsWith":aa(r,RegExp(`^${ae(a.value,t)}`),a.message,t);break;case"endsWith":aa(r,RegExp(`${ae(a.value,t)}$`),a.message,t);break;case"datetime":ar(r,"date-time",a.message,t);break;case"date":ar(r,"date",a.message,t);break;case"time":ar(r,"time",a.message,t);break;case"duration":ar(r,"duration",a.message,t);break;case"length":r.minLength="number"==typeof r.minLength?Math.max(r.minLength,a.value):a.value,r.maxLength="number"==typeof r.maxLength?Math.min(r.maxLength,a.value):a.value;break;case"includes":aa(r,RegExp(ae(a.value,t)),a.message,t);break;case"ip":"v6"!==a.version&&ar(r,"ipv4",a.message,t),"v4"!==a.version&&ar(r,"ipv6",a.message,t);break;case"base64url":aa(r,r9,a.message,t);break;case"jwt":aa(r,r8,a.message,t);break;case"cidr":"v6"!==a.version&&aa(r,r5,a.message,t),"v4"!==a.version&&aa(r,r4,a.message,t);break;case"emoji":aa(r,r2(),a.message,t);break;case"ulid":aa(r,r0,a.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":ar(r,"binary",a.message,t);break;case"contentEncoding:base64":r.contentEncoding="base64";break;case"pattern:zod":aa(r,r3,a.message,t)}break;case"nanoid":aa(r,r6,a.message,t)}return r}function ae(e,t){return"escape"===t.patternStrategy?function(e){let t="";for(let r=0;r<e.length;r++)at.has(e[r])||(t+="\\"),t+=e[r];return t}(e):e}var at=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function ar(e,t,r,a){var n;e.format||(null==(n=e.anyOf)?void 0:n.some(e=>e.format))?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format}),delete e.format),e.anyOf.push({format:t,...r&&a.errorMessages&&{errorMessage:{format:r}}})):e.format=t}function aa(e,t,r,a){var n;e.pattern||(null==(n=e.allOf)?void 0:n.some(e=>e.pattern))?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern}),delete e.pattern),e.allOf.push({pattern:an(t,a),...r&&a.errorMessages&&{errorMessage:{pattern:r}}})):e.pattern=an(t,a)}function an(e,t){var r;
27if(!t.applyRegexFlags||!e.flags)return e.source;let a={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},n=a.i?e.source.toLowerCase():e.source,i="",s=!1,o=!1,l=!1;for(let e=0;e<n.length;e++){if(s){i+=n[e],s=!1;continue}if(a.i){if(o){if(n[e].match(/[a-z]/)){l?(i+=n[e],i+=`${n[e-2]}-${n[e]}`.toUpperCase(),l=!1):"-"===n[e+1]&&(null==(r=n[e+2])?void 0:r.match(/[a-z]/))?(i+=n[e],l=!0):i+=`${n[e]}${n[e].toUpperCase()}`;continue}}else if(n[e].match(/[a-z]/)){i+=`[${n[e]}${n[e].toUpperCase()}]`;continue}}if(a.m){if("^"===n[e]){i+=`(^|(?<=[\r
28]))`;continue}else if("$"===n[e]){i+=`($|(?=[\r
29]))`;continue}}if(a.s&&"."===n[e]){i+=o?`${n[e]}\r
30`:`[${n[e]}\r
31]`;continue}i+=n[e],"\\"===n[e]?s=!0:o&&"]"===n[e]?o=!1:o||"["!==n[e]||(o=!0)}try{new RegExp(i)}catch(r){return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function ai(e,t){var r,a,n,i,s,o;let l={type:"object",additionalProperties:null!=(r=ao(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]}))?r:t.allowedAdditionalProperties};if((null==(a=e.keyType)?void 0:a._def.typeName)==="ZodString"&&(null==(n=e.keyType._def.checks)?void 0:n.length)){let{type:r,...a}=r7(e.keyType._def,t);return{...l,propertyNames:a}}if((null==(i=e.keyType)?void 0:i._def.typeName)==="ZodEnum")return{...l,propertyNames:{enum:e.keyType._def.values}};if((null==(s=e.keyType)?void 0:s._def.typeName)==="ZodBranded"&&"ZodString"===e.keyType._def.type._def.typeName&&(null==(o=e.keyType._def.type._def.checks)?void 0:o.length)){let{type:r,...a}=rJ(e.keyType._def,t);return{...l,propertyNames:a}}return l}var as={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function ao(e,t,r=!1){var a;let n=t.seen.get(e);if(t.override){let i=null==(a=t.override)?void 0:a.call(t,e,t,n,r);if(i!==rG)return i}if(n&&!r){let e=al(n,t);if(void 0!==e)return e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let s=((e,t,r)=>{var a,n,i,s,o,l;switch(t){case"ZodString":return r7(e,r);case"ZodNumber":let u={type:"number"};if(!e.checks)return u;for(let t of e.checks)switch(t.kind){case"int":u.type="integer";break;case"min":t.inclusive?u.minimum=t.value:u.exclusiveMinimum=t.value;break;case"max":t.inclusive?u.maximum=t.value:u.exclusiveMaximum=t.value;break;case"multipleOf":u.multipleOf=t.value}return u;case"ZodObject":return function(e,t){let r={type:"object",properties:{}},a=[],n=e.shape();for(let e in n){let i=n[e];if(void 0===i||void 0===i._def)continue;let s=function(e){try{return e.isOptional()}catch(e){return!0}}(i),o=ao(i._def,{...t,currentPath:[...t.currentPath,"properties",e],propertyPath:[...t.currentPath,"properties",e]});void 0!==o&&(r.properties[e]=o,s||a.push(e))}a.length&&(r.required=a);let i=function(e,t){if("ZodNever"!==e.catchall._def.typeName)return ao(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return"strict"===t.removeAdditionalStrategy?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}(e,t);return void 0!==i&&(r.additionalProperties=i),r}(e,r);case"ZodBigInt":let c={type:"integer",format:"int64"};if(!e.checks)return c;for(let t of e.checks)switch(t.kind){case"min":t.inclusive?c.minimum=t.value:c.exclusiveMinimum=t.value;break;case"max":t.inclusive?c.maximum=t.value:c.exclusiveMaximum=t.value;break;case"multipleOf":c.multipleOf=t.value}return c;case"ZodBoolean":return{type:"boolean"};case"ZodDate":return function e(t,r,a){let n=null!=a?a:r.dateStrategy;if(Array.isArray(n))return{anyOf:n.map(a=>e(t,r,a))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":var i=t;let s={type:"integer",format:"unix-time"};for(let e of i.checks)switch(e.kind){case"min":s.minimum=e.value;break;case"max":s.maximum=e.value}return s}}(e,r);case"ZodUndefined":case"ZodNaN":case"ZodNever":return{not:{}};case"ZodNull":return{type:"null"};case"ZodArray":let d;return d={type:"array"},(null==(i=e.type)?void 0:i._def)&&(null==(o=null==(s=e.type)?void 0:s._def)?void 0:o.typeName)!=="ZodAny"&&(d.items=ao(e.type._def,{...r,currentPath:[...r.currentPath,"items"]})),e.minLength&&(d.minItems=e.minLength.value),e.maxLength&&(d.maxItems=e.maxLength.value),e.exactLength&&(d.minItems=e.exactLength.value,d.maxItems=e.exactLength.value),d;case"ZodUnion":case"ZodDiscriminatedUnion":let p,h=e.options instanceof Map?Array.from(e.options.values()):e.options;if(h.every(e=>e._def.typeName in as&&(!e._def.checks||!e._def.checks.length))){let e=h.reduce((e,t)=>
31{let r=as[t._def.typeName];return r&&!e.includes(r)?[...e,r]:e},[]);return{type:e.length>1?e:e[0]}}if(h.every(e=>"ZodLiteral"===e._def.typeName&&!e.description)){let e=h.reduce((e,t)=>{let r=typeof t._def.value;switch(r){case"string":case"number":case"boolean":return[...e,r];case"bigint":return[...e,"integer"];case"object":if(null===t._def.value)return[...e,"null"];default:return e}},[]);if(e.length===h.length){let t=e.filter((e,t,r)=>r.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:h.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(h.every(e=>"ZodEnum"===e._def.typeName))return{type:"string",enum:h.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return a=e,n=r,(p=(a.options instanceof Map?Array.from(a.options.values()):a.options).map((e,t)=>ao(e._def,{...n,currentPath:[...n.currentPath,"anyOf",`${t}`]})).filter(e=>!!e&&(!n.strictUnions||"object"==typeof e&&Object.keys(e).length>0))).length?{anyOf:p}:void 0;case"ZodIntersection":let m,f;return m=[ao(e.left._def,{...r,currentPath:[...r.currentPath,"allOf","0"]}),ao(e.right._def,{...r,currentPath:[...r.currentPath,"allOf","1"]})].filter(e=>!!e),f=[],m.forEach(e=>{if((!("type"in e)||"string"!==e.type)&&"allOf"in e)f.push(...e.allOf);else{let t=e;if("additionalProperties"in e&&!1===e.additionalProperties){let{additionalProperties:r,...a}=e;t=a}f.push(t)}}),f.length?{allOf:f}:void 0;case"ZodTuple":return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((e,t)=>ao(e._def,{...r,currentPath:[...r.currentPath,"items",`${t}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[]),additionalItems:ao(e.rest._def,{...r,currentPath:[...r.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,t)=>ao(e._def,{...r,currentPath:[...r.currentPath,"items",`${t}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[])};case"ZodRecord":return ai(e,r);case"ZodLiteral":let g;return"bigint"!=(g=typeof e.value)&&"number"!==g&&"boolean"!==g&&"string"!==g?{type:Array.isArray(e.value)?"array":"object"}:{type:"bigint"===g?"integer":g,const:e.value};case"ZodEnum":return{type:"string",enum:Array.from(e.values)};case"ZodNativeEnum":let v,y,b;return v=e.values,{type:1===(b=Array.from(new Set((y=Object.keys(e.values).filter(e=>"number"!=typeof v[v[e]]).map(e=>v[e])).map(e=>typeof e)))).length?"string"===b[0]?"string":"number":["string","number"],enum:y};case"ZodNullable":if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[as[e.innerType._def.typeName],"null"]};let x=ao(e.innerType._def,{...r,currentPath:[...r.currentPath,"anyOf","0"]});return x&&{anyOf:[x,{type:"null"}]};case"ZodOptional":if(r.currentPath.toString()===(null==(l=r.propertyPath)?void 0:l.toString()))return ao(e.innerType._def,r);let w=ao(e.innerType._def,{...r,currentPath:[...r.currentPath,"anyOf","1"]});return w?{anyOf:[{not:{}},w]}:{};case"ZodMap":if("record"===r.mapStrategy)return ai(e,r);return{type:"array",maxItems:125,items:{type:"array",items:[ao(e.keyType._def,{...r,currentPath:[...r.currentPath,"items","items","0"]})||{},ao(e.valueType._def,{...r,currentPath:[...r.currentPath,"items","items","1"]})||{}],minItems:2,maxItems:2}};case"ZodSet":let _;return _={type:"array",uniqueItems:!0,items:ao(e.valueType._def,{...r,currentPath:[...r.currentPath,"items"]})},e.minSize&&(_.minItems=e.minSize.value),e.maxSize&&(_.maxItems=e.maxSize.value),_;case"ZodLazy":return()=>e.getter()._def;case"ZodPromise":return ao(e.type._def,r);case"ZodEffects":return"input"===r.effectStrategy?ao(e.schema._def,r):{};case"ZodAny":case"ZodUnknown":return{};case"ZodDefault":return{...ao(e.innerType._def,r),default:e.defaultValue()};case"ZodBranded":return rJ(e,r);case"ZodReadonly":case"ZodCatch":return ao(e.innerType._def,r);case"ZodPipeline":if("input"===r.pipeStrategy)return ao(e.in._def,r);if("output"===r.pipeStrategy)return ao(e.out._def,r);let k=ao(e.in._def,{...r,currentPath:[...r.currentPath,"allOf","0"]}),S=ao(e.out._def,{...r,currentPath:[...r.currentPath,"allOf",k?"1":"0"]});return{allOf:[k,S].filter(e=>void 0!==e)};default:return}})(e,e.typeName,t),o="function"==typeof s?ao(s(),t):s;if(o&&au(e,t,o),t.postProcess){let r=t.postProcess(o,e,t);return i.jsonSchema=o,r}return i.jsonSchema=o,o}var al=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:((e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")})(t.currentPath,e.path)};case"none":case"seen":if(e.path.length<t.currentPath.length&&e.path.every((e,r)=>t.currentPath[r]===e))return console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),{};return"seen"===t.$refStrategy?{}:void 0}},au=(e,t,r)=>(e.description&&(r.description=e.description),r),ac=Symbol.for("vercel.ai.schema");function ad(e){let t;return()=>(null==t&&(t=e()),t)}function ap(e,{validate:t}={}){return{[ac]:!0,_type:void 0,get jsonSchema(){return"function"==typeof e&&(e=e()),e},validate:t}}function ah(e){var t;return null==e?ap({type:"object",properties:{},additionalProperties:!1}):"object"==typeof e&&null!==e&&ac in e&&!0===e[ac]&&"jsonSchema"in e&&"validate"in e?e:"~standard"in e?"zod"===e["~standard"].vendor?am(e):(t=e,ap(()=>
31{if(null==t["~standard"].jsonSchema)throw Error(`Standard schema vendor '${t["~standard"].vendor}' does not support JSON Schema conversion.`);return rV(t["~standard"].jsonSchema.input({target:"draft-07"}))},{validate:async e=>{let r=await t["~standard"].validate(e);return"value"in r?{success:!0,value:r.value}:{success:!1,error:new to({value:e,cause:r.issues})}}})):e()}function am(e,t){var r,a;let n;if("_zod"in e){let a;return a=null!=(r=null==t?void 0:t.useReferences)&&r,ap(()=>rV(function(e,t){if(e instanceof t0){let r=new t2(t),a={};for(let t of e._idmap.entries()){let[e,a]=t;r.process(a)}let n={},i={registry:e,uri:t?.uri,defs:a};for(let a of e._idmap.entries()){let[e,s]=a;n[e]=r.emit(s,{...t,external:i})}return Object.keys(a).length>0&&(n.__shared={["draft-2020-12"===r.target?"$defs":"definitions"]:a}),{schemas:n}}let r=new t2(t);return r.process(e),r.emit(e,t)}(e,{target:"draft-7",io:"input",reused:a?"ref":"inline"})),{validate:async t=>{let r=await tX(e,t);return r.success?{success:!0,value:r.data}:{success:!1,error:r.error}}})}return n=null!=(a=null==t?void 0:t.useReferences)&&a,ap(()=>((e,t)=>{var r;let a,n,i=(n=void 0!==(a="string"==typeof t?{...rY,name:t}:{...rY,...t}).name?[...a.basePath,a.definitionPath,a.name]:a.basePath,{...a,currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(a.definitions).map(([e,t])=>[t._def,{def:t._def,path:[...a.basePath,a.definitionPath,e],jsonSchema:void 0}]))}),s="object"==typeof t&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>{var a;return{...e,[t]:null!=(a=ao(r._def,{...i,currentPath:[...i.basePath,i.definitionPath,t]},!0))?a:{}}},{}):void 0,o="string"==typeof t?t:(null==t?void 0:t.nameStrategy)==="title"||null==t?void 0:t.name,l=null!=(r=ao(e._def,void 0===o?i:{...i,currentPath:[...i.basePath,i.definitionPath,o]},!1))?r:{},u="object"==typeof t&&void 0!==t.name&&"title"===t.nameStrategy?t.name:void 0;void 0!==u&&(l.title=u);let c=void 0===o?s?{...l,[i.definitionPath]:s}:l:{$ref:[..."relative"===i.$refStrategy?[]:i.basePath,i.definitionPath,o].join("/"),[i.definitionPath]:{...s,[o]:l}};return c.$schema="http://json-schema.org/draft-07/schema#",c})(e,{$refStrategy:n?"root":"none"}),{validate:async t=>{let r=await e.safeParseAsync(t);return r.success?{success:!0,value:r.data}:{success:!1,error:r.error}}})}async function af({value:e,schema:t,context:r}){let a=await ag({value:e,schema:t,context:r});if(!a.success)throw to.wrap({value:e,cause:a.error,context:r});return a.value}async function ag({value:e,schema:t,context:r}){let a=ah(t);try{if(null==a.validate)return{success:!0,value:e,rawValue:e};let t=await a.validate(e);if(t.success)return{success:!0,value:t.value,rawValue:e};return{success:!1,error:to.wrap({value:e,cause:t.error,context:r}),rawValue:e}}catch(t){return{success:!1,error:to.wrap({value:e,cause:t,context:r}),rawValue:e}}}async function av({text:e,schema:t}){try{let r=rq(e);if(null==t)return r;return await af({value:r,schema:t})}catch(t){if(e6.isInstance(t)||to.isInstance(t))throw t;throw new e6({text:e,cause:t})}}async function ay({text:e,schema:t}){try{let r=rq(e);if(null==t)return{success:!0,value:r,rawValue:r};return await ag({value:r,schema:t})}catch(t){return{success:!1,error:e6.isInstance(t)?t:new e6({text:e,cause:t}),rawValue:void 0}}}function ab({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new t6).pipeThrough(new TransformStream({async transform({data:e},r){"[DONE]"!==e&&r.enqueue(await ay({text:e,schema:t}))}}))}var ax=()=>globalThis.fetch,aw=async({url:e,headers:t,body:r,failedResponseHandler:a,successfulResponseHandler:n,abortSignal:i,fetch:s})=>await a_({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(r),values:r},failedResponseHandler:a,successfulResponseHandler:n,abortSignal:i,fetch:s}),a_=async({url:e,headers:t={},body:r,successfulResponseHandler:a,failedResponseHandler:n,abortSignal:i,fetch:s=ax()})=>{try{let o=await s(e,{method:"POST",headers:rv(t,`ai-sdk/provider-utils/${rf}`,rc()),body:r.content,signal:i}),l=ru(o);if(!o.ok){let t;try{t=await n({response:o,url:e,requestBodyValues:r.values})}catch(t){if(rd(t)||eW.isInstance(t))throw t;throw new eW({message:"Failed to process error response",cause:t,statusCode:o.status,url:e,responseHeaders:l,requestBodyValues:r.values})}throw t.value}try{return await a({response:o,url:e,requestBodyValues:r.values})}catch(t){if(t instanceof Error&&(rd(t)||eW.isInstance(t)))throw t;throw new eW({message:"Failed to process successful response",cause:t,statusCode:o.status,url:e,responseHeaders:l,requestBodyValues:r.values})}}
31catch(t){throw rm({error:t,url:e,requestBodyValues:r.values})}};function ak({id:e,inputSchema:t,outputSchema:r,supportsDeferredResults:a}){return({onInputStart:n,onInputDelta:i,onInputAvailable:s,...o})=>({type:"provider",isProviderExecuted:!0,id:e,args:o,inputSchema:t,outputSchema:r,onInputStart:n,onInputDelta:i,onInputAvailable:s,supportsDeferredResults:a})}async function aS(e){return"function"==typeof e&&(e=e()),Promise.resolve(e)}var aE=new TextDecoder;async function aC({response:e,url:t}){return aE.decode(await rO({response:e,url:t}))}var aj=({errorSchema:e,errorToMessage:t,isRetryable:r})=>async({response:a,url:n,requestBodyValues:i})=>{let s=await aC({response:a,url:n}),o=ru(a);if(""===s.trim())return{responseHeaders:o,value:new eW({message:a.statusText,url:n,requestBodyValues:i,statusCode:a.status,responseHeaders:o,responseBody:s,isRetryable:null==r?void 0:r(a)})};try{let l=await av({text:s,schema:e});return{responseHeaders:o,value:new eW({message:t(l),url:n,requestBodyValues:i,statusCode:a.status,responseHeaders:o,responseBody:s,data:l,isRetryable:null==r?void 0:r(a,l)})}}catch(e){return{responseHeaders:o,value:new eW({message:a.statusText,url:n,requestBodyValues:i,statusCode:a.status,responseHeaders:o,responseBody:s,isRetryable:null==r?void 0:r(a)})}}},aI=e=>async({response:t,url:r,requestBodyValues:a})=>{let n=await aC({response:t,url:r}),i=await ay({text:n,schema:e}),s=ru(t);if(!i.success)throw new eW({message:"Invalid JSON response",cause:i.error,statusCode:t.status,responseHeaders:s,responseBody:n,url:r,requestBodyValues:a});return{responseHeaders:s,value:i.value,rawValue:i.rawValue}};async function*aT({stream:e,schema:t}){let r=e.getReader(),a=new TextDecoder,n="",i=!1;try{for(;;){let{done:e,value:s}=await r.read();if(e){i=!0,n+=a.decode();break}let o=(n+=a.decode(s,{stream:!0})).indexOf("\n");for(;-1!==o;){let e=n.slice(0,o).replace(/\r$/,"");n=n.slice(o+1),e.trim().length>0&&(yield await av({text:e,schema:t})),o=n.indexOf("\n")}}let e=n.replace(/\r$/,"");e.trim().length>0&&(yield await av({text:e,schema:t}))}finally{i||await r.cancel().catch(()=>{}),r.releaseLock()}}function aN(e){if(null==e)return!0;let t=typeof e;return"string"===t||"number"===t||"boolean"===t||"function"!==t&&"symbol"!==t&&"bigint"!==t&&(Array.isArray(e)?e.every(aN):Object.getPrototypeOf(e)===Object.prototype&&Object.values(e).every(aN))}var aR="AI_SerializationError",aA=`vercel.ai.error.${aR}`,az=Symbol.for(aA),aM=class extends(b=eB,y=az,b){constructor({message:e="Failed to serialize value.",cause:t}={}){super({name:aR,message:e,cause:t}),this[y]=!0}static isInstance(e){return eB.hasMarker(e,aA)}};function aO(e){let t={};for(let[r,a]of Object.entries(e.config))if("headers"===r){let e=function(e){let t=e;if("function"==typeof e&&(t=e()),t instanceof Promise)throw new aM({message:"Cannot serialize asynchronous model options."});return t}(a);aN(e)&&(t[r]=e)}else aN(a)&&(t[r]=a);return{modelId:e.modelId,config:t}}function aP(e){return"string"==typeof e}function a$(e){return"number"==typeof e}function aD(e,t){return void 0===e||t(e)}function aU(e){return rU(e)&&aP(e.type)}function aL(e){return rU(e)&&aP(e.text)&&a$(e.startSecond)&&a$(e.endSecond)}var aF=e.i(467034);let aZ=/^[cC][^\s-]{8,}$/,aB=/^[0-9a-z]+$/,aH=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,aq=/^[0-9a-vA-V]{20}$/,aV=/^[A-Za-z0-9]{27}$/,aW=/^[a-zA-Z0-9_-]{21}$/,aG=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,aY=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,aJ=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,aK=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,aQ=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,aX=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,a0=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,a1=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,a2=/^$|^(?:[0-9a-zA-Z+/]{4}
31)*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,a5=/^[A-Za-z0-9_-]*$/,a4=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,a3=/^\+(?:[0-9]){6,14}[0-9]$/,a9="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",a6=RegExp(`^${a9}$`);function a8(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"==typeof e.precision?-1===e.precision?`${t}`:0===e.precision?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}let a7=/^\d+n?$/,ne=/^\d+$/,nt=/^-?\d+(?:\.\d+)?/i,nr=/true|false/i,na=/null/i,nn=/undefined/i,ni=/^[^A-Z]*$/,ns=/^[^a-z]*$/,no=tu("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),nl={number:"number",bigint:"bigint",object:"date"},nu=tu("$ZodCheckLessThan",(e,t)=>{no.init(e,t);let r=nl[typeof t.value];e._zod.onattach.push(e=>{let r=e._zod.bag,a=(t.inclusive?r.maximum:r.exclusiveMaximum)??1/0;t.value<a&&(t.inclusive?r.maximum=t.value:r.exclusiveMaximum=t.value)}),e._zod.check=a=>{(t.inclusive?a.value<=t.value:a.value<t.value)||a.issues.push({origin:r,code:"too_big",maximum:t.value,input:a.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),nc=tu("$ZodCheckGreaterThan",(e,t)=>{no.init(e,t);let r=nl[typeof t.value];e._zod.onattach.push(e=>{let r=e._zod.bag,a=(t.inclusive?r.minimum:r.exclusiveMinimum)??-1/0;t.value>a&&(t.inclusive?r.minimum=t.value:r.exclusiveMinimum=t.value)}),e._zod.check=a=>{(t.inclusive?a.value>=t.value:a.value>t.value)||a.issues.push({origin:r,code:"too_small",minimum:t.value,input:a.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),nd=tu("$ZodCheckMultipleOf",(e,t)=>{no.init(e,t),e._zod.onattach.push(e=>{var r;(r=e._zod.bag).multipleOf??(r.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof r.value?r.value%t.value===BigInt(0):0===ty(r.value,t.value))||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),np=tu("$ZodCheckNumberFormat",(e,t)=>{no.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),a=r?"int":"number",[n,i]=tz[t.format];e._zod.onattach.push(e=>{let a=e._zod.bag;a.format=t.format,a.minimum=n,a.maximum=i,r&&(a.pattern=ne)}),e._zod.check=s=>{let o=s.value;if(r){if(!Number.isInteger(o))return void s.issues.push({expected:a,format:t.format,code:"invalid_type",input:o,inst:e});if(!Number.isSafeInteger(o))return void(o>0?s.issues.push({input:o,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:a,continue:!t.abort}):s.issues.push({input:o,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:a,continue:!t.abort}))}o<n&&s.issues.push({origin:"number",input:o,code:"too_small",minimum:n,inclusive:!0,inst:e,continue:!t.abort}),o>i&&s.issues.push({origin:"number",input:o,code:"too_big",maximum:i,inst:e})}}),nh=tu("$ZodCheckBigIntFormat",(e,t)=>{no.init(e,t);let[r,a]=tM[t.format];e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,n.minimum=r,n.maximum=a}),e._zod.check=n=>{let i=n.value;i<r&&n.issues.push({origin:"bigint",input:i,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort}),i>a&&n.issues.push({origin:"bigint",input:i,code:"too_big",maximum:a,inst:e})}}),nm=tu("$ZodCheckMaxSize",(e,t)=>{var r;no.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return!tg(t)&&void 0!==t.size}),e._zod.onattach.push(e=>{let r=e._zod.bag.maximum??1/0;t.maximum<r&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{let a=r.value;a.size<=t.maximum||r.issues.push({origin:tU(a),code:"too_big",maximum:t.maximum,input:a,inst:e,continue:!t.abort})}}),nf=tu("$ZodCheckMinSize",(e,t)=>{var r;no.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return!tg(t)&&void 0!==t.size}),e._zod.onattach.push(e=>{let r=e._zod.bag.minimum??-1/0;t.minimum>r&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{let a=r.value;a.size>=t.minimum||r.issues.push({origin:tU(a),code:"too_small",minimum:t.minimum,input:a,inst:e,continue:!t.abort})}}),ng=((e,t)=>{var r;no.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return!tg(t)&&void 0!==t.size}),e._zod.onattach.push(e=>{let r=e._zod.bag;r.minimum=t.size,r.maximum=t.size,r.size=t.size}),e._zod.check=r=>{let a=r.value,n=a.size;if(n===t.size)return;let i=n>t.size;r.issues.push({origin:tU(a),...i?{code:"too_big",maximum:t.size}:{code:"too_small",minimum:t.size},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}},tu("$ZodCheckMaxLength",(e,t)=>{var r;no.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return!tg(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{let r=e._zod.bag.maximum??1/0;t.maximum<r&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{let a=r.value;if(a.length<=t.maximum)return;let n=tL(a);r.issues.push({origin:n,code:"too_big",maximum:t.maximum,inclusive:!0,input:a,inst:e,continue:!t.abort})}})),nv=tu("$ZodCheckMinLength",(e,t)=>{var r;no.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return!tg(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{let r=e._zod.bag.minimum??-1/0;t.minimum>r&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{let a=r.value;if(a.length>=t.minimum)return;let n=tL(a);r.issues.push({origin:n,code:"too_small",minimum:t.minimum,inclusive:!0,input:a,inst:e,continue:!t.abort})}}),ny=tu("$ZodCheckLengthEquals",(e,t)=>{var r;no.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return!tg(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{let r=e._zod.bag;r.minimum=t.length,r.maximum=t.length,r.length=t.length}),e._zod.check=r=>{let a=r.value,n=a.length;if(n===t.length)return;let i=tL(a),s=n>t.length;r.issues.push({origin:i,...s?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),nb=tu("$ZodCheckStringFormat",(e,t)=>{var r,a;no.init(e,t),e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,t.pattern&&(r.patterns??(r.patterns=new Set),r.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=r=>{t.pattern.lastIndex=0,t.pattern.test(r.value)||r.issues.push({origin:"string",code:"invalid_format",format:t.format,input:r.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(a=e._zod).check??(a.check=()=>{})}),nx=tu("$ZodCheckRegex",(e,t)=>{nb.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,t.pattern.test(r.value)||r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),nw=tu("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=ni),nb.init(e,t)}),n_=tu("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=ns),nb.init(e,t)}),nk=tu("$ZodCheckIncludes",(e,t)=>{no.init(e,t);let r=tI(t.includes),a=new RegExp("number"==typeof t.position?`^.{${t.position}}${r}`:r);t.pattern=a,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(a)}),e._zod.check=r=>{r.value.includes(t.includes,t.position)||r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input
31:r.value,inst:e,continue:!t.abort})}}),nS=tu("$ZodCheckStartsWith",(e,t)=>{no.init(e,t);let r=RegExp(`^${tI(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(r)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),nE=tu("$ZodCheckEndsWith",(e,t)=>{no.init(e,t);let r=RegExp(`.*${tI(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(r)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}});(e,t)=>{no.init(e,t);let r=new Set(t.mime);e._zod.onattach.push(e=>{e._zod.bag.mime=t.mime}),e._zod.check=a=>{r.has(a.value.type)||a.issues.push({code:"invalid_value",values:t.mime,input:a.value.type,inst:e})}};let nC=tu("$ZodCheckOverwrite",(e,t)=>{no.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});
31class nj{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if("function"==typeof e){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let t=e.split("\n").filter(e=>e),r=Math.min(...t.map(e=>e.length-e.trimStart().length));for(let e of t.map(e=>e.slice(r)).map(e=>" ".repeat(2*this.indent)+e))this.content.push(e)}compile(){return Function(...this?.args,[...(this?.content??[""]).map(e=>`  ${e}`)].join("\n"))}}let nI={major:4,minor:0,patch:0},nT=tu("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=nI;let a=[...e._zod.def.checks??[]];for(let t of(e._zod.traits.has("$ZodCheck")&&a.unshift(e),a))for(let r of t._zod.onattach)r(e);if(0===a.length)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,r)=>{let a,n=tO(e);for(let i of t){if(i._zod.def.when){if(!i._zod.def.when(e))continue}else if(n)continue;let t=e.issues.length,s=i._zod.check(e);if(s instanceof Promise&&r?.async===!1)throw new tc;if(a||s instanceof Promise)a=(a??Promise.resolve()).then(async()=>{await s,e.issues.length!==t&&(n||(n=tO(e,t)))});else{if(e.issues.length===t)continue;n||(n=tO(e,t))}}return a?a.then(()=>e):e};e._zod.run=(r,n)=>{let i=e._zod.parse(r,n);if(i instanceof Promise){if(!1===n.async)throw new tc;return i.then(e=>t(e,a,n))}return t(i,a,n)}}e["~standard"]={validate:t=>{try{let r=tV(e,t);return r.success?{value:r.data}:{issues:r.error?.issues}}catch(r){return tG(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}}),nN=tu("$ZodString",(e,t)=>{var r;let a;nT.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??(a=(r=e._zod.bag)?`[\\s\\S]{${r?.minimum??0},${r?.maximum??""}}`:"[\\s\\S]*",RegExp(`^${a}$`)),e._zod.parse=(r,a)=>{if(t.coerce)try{r.value=String(r.value)}catch(e){}return"string"==typeof r.value||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),nR=tu("$ZodStringFormat",(e,t)=>{nb.init(e,t),nN.init(e,t)}),nA=tu("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=aY),nR.init(e,t)}),nz=tu("$ZodUUID",(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(void 0===e)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=aJ(e))}else t.pattern??(t.pattern=aJ());nR.init(e,t)}),nM=tu("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=aK),nR.init(e,t)}),nO=tu("$ZodURL",(e,t)=>{nR.init(e,t),e._zod.check=r=>{try{let a=r.value,n=new URL(a),i=n.href;t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(n.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:a4.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(n.protocol.endsWith(":")?n.protocol.slice(0,-1):n.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),!a.endsWith("/")&&i.endsWith("/")?r.value=i.slice(0,-1):r.value=i;return}catch(a){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),nP=tu("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),nR.init(e,t)}),n$=tu("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=aW),nR.init(e,t)}),nD=tu("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=aZ),nR.init(e,t)}),nU=tu("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=aB),nR.init(e,t)}),nL=tu("$ZodULID",(e,t)=>{t.pattern??(t.pattern=aH),nR.init(e,t)}),nF=tu("$ZodXID",(e,t)=>{t.pattern??(t.pattern=aq),nR.init(e,t)}),nZ=tu("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=aV),nR.init(e,t)}),nB=tu("$ZodISODateTime",(e,t)=>{let r,a,n;t.pattern??(r=a8({precision:t.precision}),a=["Z"],t.local&&a.push(""),t.offset&&a.push("([+-]\\d{2}:\\d{2})"),n=`${r}(?:${a.join("|")})`,t.pattern=RegExp(`^${a9}T(?:${n})$`)),nR.init(e,t)}),nH=tu("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=a6),nR.init(e,t)}),nq=tu("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=RegExp(`^${a8(t)}$`)),nR.init(e,t)}),nV=tu("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=aG),nR.init(e,t)}),nW=tu("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=aQ),nR.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.format="ipv4"})}),nG=tu("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=aX),nR.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.format="ipv6"}),e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),nY=tu("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=a0),nR.init(e,t)}),nJ=tu("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=a1),nR.init(e,t),e._zod.check=r=>{let[a,n]=r.value.split("/");try{if(!n)throw Error();let e=Number(n);if(`${e}`!==n||e<0||e>128)throw Error();new URL(`http://[${a}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function nK(e){if(""===e)return!0;
31if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}let nQ=tu("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=a2),nR.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{nK(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}}),nX=tu("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=a5),nR.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{!function(e){if(!a5.test(e))return!1;let t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return nK(t.padEnd(4*Math.ceil(t.length/4),"="))}(r.value)&&r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),n0=tu("$ZodE164",(e,t)=>{t.pattern??(t.pattern=a3),nR.init(e,t)}),n1=tu("$ZodJWT",(e,t)=>{nR.init(e,t),e._zod.check=r=>{!function(e,t=null){try{let r=e.split(".");if(3!==r.length)return!1;let[a]=r;if(!a)return!1;let n=JSON.parse(atob(a));if("typ"in n&&n?.typ!=="JWT"||!n.alg||t&&(!("alg"in n)||n.alg!==t))return!1;return!0}catch{return!1}}(r.value,t.alg)&&r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),n2=((e,t)=>{nR.init(e,t),e._zod.check=r=>{t.fn(r.value)||r.issues.push({code:"invalid_format",format:t.format,input:r.value,inst:e,continue:!t.abort})}},tu("$ZodNumber",(e,t)=>{nT.init(e,t),e._zod.pattern=e._zod.bag.pattern??nt,e._zod.parse=(r,a)=>{if(t.coerce)try{r.value=Number(r.value)}catch(e){}let n=r.value;if("number"==typeof n&&!Number.isNaN(n)&&Number.isFinite(n))return r;let i="number"==typeof n?Number.isNaN(n)?"NaN":Number.isFinite(n)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:n,inst:e,...i?{received:i}:{}}),r}})),n5=tu("$ZodNumber",(e,t)=>{np.init(e,t),n2.init(e,t)}),n4=tu("$ZodBoolean",(e,t)=>{nT.init(e,t),e._zod.pattern=nr,e._zod.parse=(r,a)=>{if(t.coerce)try{r.value=!!r.value}catch(e){}let n=r.value;return"boolean"==typeof n||r.issues.push({expected:"boolean",code:"invalid_type",input:n,inst:e}),r}}),n3=tu("$ZodBigInt",(e,t)=>{nT.init(e,t),e._zod.pattern=a7,e._zod.parse=(r,a)=>{if(t.coerce)try{r.value=BigInt(r.value)}catch(e){}return"bigint"==typeof r.value||r.issues.push({expected:"bigint",code:"invalid_type",input:r.value,inst:e}),r}}),n9=((e,t)=>{nh.init(e,t),n3.init(e,t)},tu("$ZodNull",(e,t)=>{nT.init(e,t),e._zod.pattern=na,e._zod.values=new Set([null]),e._zod.parse=(t,r)=>{let a=t.value;return null===a||t.issues.push({expected:"null",code:"invalid_type",input:a,inst:e}),t}})),n6=tu("$ZodAny",(e,t)=>{nT.init(e,t),e._zod.parse=e=>e}),n8=tu("$ZodUnknown",(e,t)=>{nT.init(e,t),e._zod.parse=e=>e}),n7=tu("$ZodNever",(e,t)=>{nT.init(e,t),e._zod.parse=(t,r)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)});function ie(e,t,r){e.issues.length&&t.issues.push(...tP(r,e.issues)),t.value[r]=e.value}(e,t)=>{nT.init(e,t),e._zod.parse=(t,r)=>{let a=t.value;return void 0===a||t.issues.push({expected:"void",code:"invalid_type",input:a,inst:e}),t}},(e,t)=>{nT.init(e,t),e._zod.parse=(r,a)=>{if(t.coerce)try{r.value=new Date(r.value)}catch(e){}let n=r.value,i=n instanceof Date;return i&&!Number.isNaN(n.getTime())||r.issues.push({expected:"date",code:"invalid_type",input:n,...i?{received:"Invalid Date"}:{},inst:e}),r}};let it=tu("$ZodArray",(e,t)=>{nT.init(e,t),e._zod.parse=(r,a)=>{let n=r.value;if(!Array.isArray(n))return r.issues.push({expected:"array",code:"invalid_type",input:n,inst:e}),r;r.value=Array(n.length);let i=[];for(let e=0;e<n.length;e++){let s=n[e],o=t.element._zod.run({value:s,issues:[]},a);o instanceof Promise?i.push(o.then(t=>ie(t,r,e))):ie(o,r,e)}return i.length?Promise.all(i).then(()=>r):r}});function ir(e,t,r){e.issues.length&&t.issues.push(...tP(r,e.issues)),t.value[r]=e.value}function ia(e,t,r,a){e.issues.length?void 0===a[r]?r in a?t.value[r]=void 0:t.value[r]=e.value:t.issues.push(...tP(r,e.issues)):void 0===e.value?r in a&&(t.value[r]=void 0):t.value[r]=e.value}let ii=tu("$ZodObject",(e,t)=>{let r,a;nT.init(e,t);let n=tf(()=>{let e=Object.keys(t.shape);for(let r of e)if(!(t.shape[r]instanceof nT))throw Error(`Invalid element at key "${r}": expected a Zod schema`);let r=tA(t.shape);return{shape:t.shape,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(r)}});tb(e._zod,"propValues",()=>{let e=t.shape,r={};for(let t in e){let a=e[t]._zod;if(a.values)for(let e of(r[t]??(r[t]=new Set),a.values))r[t].add(e)}return r});let i=!td.jitless,s=i&&tS.value,o=t.catchall;e._zod.parse=(l,u)=>{a??(a=n.value);let c=l.value;if(!tk(c))return l.issues.push({expected:"object",code:"invalid_type",input:c,inst:e}),l;let d=[];if(i&&s&&u?.async===!1&&!0!==u.jitless)r||(r=(e=>{let t=new nj(["shape","payload","ctx"]),r=n.value,a=e=>{let t=tw(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write("const input = payload.value;");let i=Object.create(null),s=0;for(let e of r.keys)i[e]=`key_${s++}`;for(let e of(t.write("const newResult = {}"),r.keys))if(r.optionalKeys.has(e)){let r=i[e];t.write(`const ${r} = ${a(e)};`);let n=tw(e);t.write(`
32        if (${r}.issues.length) {
33          if (input[${n}] === undefined) {
34            if (${n} in input) {
35              newResult[${n}] = undefined;
36            }
37          } else {
38            payload.issues = payload.issues.concat(
39              ${r}.issues.map((iss) => ({
40                ...iss,
41                path: iss.path ? [${n}, ...iss.path] : [${n}],
42              }))
43            );
44          }
45        } else if (${r}.value === undefined) {
46          if (${n} in input) newResult[${n}] = undefined;
47        } else {
48          newResult[${n}] = ${r}.value;
49        }
50        `)}else{let r=i[e];t.write(`const ${r} = ${a(e)};`),t.write(`
51          if (${r}.issues.length) payload.issues = payload.issues.concat(${r}.issues.map(iss => ({
52            ...iss,
53            path: iss.path ? [${tw(e)}, ...iss.path] : [${tw(e)}]
54          })));`),t.write(`newResult[${tw(e)}] = ${r}.value`)}t.write("payload.value = newResult;"),t.write("return payload;");let o=t.compile();return(t,r)=>o(e,t,r)})(t.shape)),l=r(l,u);else{l.value={};let e=a.shape;for(let t of a.keys){let r=e[t],a=r._zod.run({value:c[t],issues:[]},u),n="optional"===r._zod.optin&&"optional"===r._zod.optout;a instanceof Promise?d.push(a.then(e=>n?ia(e,l,t,c):ir(e,l,t))):n?ia(a,l,t,c):ir(a,l,t)}}if(!o)return d.length?Promise.all(d).then(()=>l):l;let p=[],h=a.keySet,m=o._zod,f=m.def.type;
54for(let e of Object.keys(c)){if(h.has(e))continue;if("never"===f){p.push(e);continue}let t=m.run({value:c[e],issues:[]},u);t instanceof Promise?d.push(t.then(t=>ir(t,l,e))):ir(t,l,e)}return(p.length&&l.issues.push({code:"unrecognized_keys",keys:p,input:c,inst:e}),d.length)?Promise.all(d).then(()=>l):l}});function is(e,t,r,a){for(let r of e)if(0===r.issues.length)return t.value=r.value,t;return t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(e=>e.issues.map(e=>tD(e,a,tp())))}),t}let io=tu("$ZodUnion",(e,t)=>{nT.init(e,t),tb(e._zod,"optin",()=>t.options.some(e=>"optional"===e._zod.optin)?"optional":void 0),tb(e._zod,"optout",()=>t.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),tb(e._zod,"values",()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),tb(e._zod,"pattern",()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>tv(e.source)).join("|")})$`)}}),e._zod.parse=(r,a)=>{let n=!1,i=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},a);if(t instanceof Promise)i.push(t),n=!0;else{if(0===t.issues.length)return t;i.push(t)}}return n?Promise.all(i).then(t=>is(t,r,e,a)):is(i,r,e,a)}}),il=tu("$ZodDiscriminatedUnion",(e,t)=>{io.init(e,t);let r=e._zod.parse;tb(e._zod,"propValues",()=>{let e={};for(let r of t.options){let a=r._zod.propValues;if(!a||0===Object.keys(a).length)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(let[t,r]of Object.entries(a))for(let a of(e[t]||(e[t]=new Set),r))e[t].add(a)}return e});let a=tf(()=>{let e=t.options,r=new Map;for(let a of e){let e=a._zod.propValues[t.discriminator];if(!e||0===e.size)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(a)}"`);for(let t of e){if(r.has(t))throw Error(`Duplicate discriminator value "${String(t)}"`);r.set(t,a)}}return r});e._zod.parse=(n,i)=>{let s=n.value;if(!tk(s))return n.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),n;let o=a.value.get(s?.[t.discriminator]);return o?o._zod.run(n,i):t.unionFallback?r(n,i):(n.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:s,path:[t.discriminator],inst:e}),n)}}),iu=tu("$ZodIntersection",(e,t)=>{nT.init(e,t),e._zod.parse=(e,r)=>{let a=e.value,n=t.left._zod.run({value:a,issues:[]},r),i=t.right._zod.run({value:a,issues:[]},r);return n instanceof Promise||i instanceof Promise?Promise.all([n,i]).then(([t,r])=>ic(e,t,r)):ic(e,n,i)}});function ic(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),tO(e))return e;let a=function e(t,r){if(t===r||t instanceof Date&&r instanceof Date&&+t==+r)return{valid:!0,data:t};if(tE(t)&&tE(r)){let a=Object.keys(r),n=Object.keys(t).filter(e=>-1!==a.indexOf(e)),i={...t,...r};for(let a of n){let n=e(t[a],r[a]);if(!n.valid)return{valid:!1,mergeErrorPath:[a,...n.mergeErrorPath]};i[a]=n.data}return{valid:!0,data:i}}if(Array.isArray(t)&&Array.isArray(r)){if(t.length!==r.length)return{valid:!1,mergeErrorPath:[]};let a=[];for(let n=0;n<t.length;n++){let i=e(t[n],r[n]);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};a.push(i.data)}return{valid:!0,data:a}}return{valid:!1,mergeErrorPath:[]}}(t.value,r.value);if(!a.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(a.mergeErrorPath)}`);return e.value=a.data,e}function id(e,t,r){e.issues.length&&t.issues.push(...tP(r,e.issues)),t.value[r]=e.value}(e,t)=>{nT.init(e,t);let r=t.items,a=r.length-[...r].reverse().findIndex(e=>"optional"!==e._zod.optin);e._zod.parse=(n,i)=>{let s=n.value;if(!Array.isArray(s))return n.issues.push({input:s,inst:e,expected:"tuple",code:"invalid_type"}),n;n.value=[];let o=[];if(!t.rest){let t=s.length>r.length,i=s.length<a-1;if(t||i)return n.issues.push({input:s,inst:e,origin:"array",...t?{code:"too_big",maximum:r.length}:{code:"too_small",minimum:r.length}}),n}let l=-1;for(let e of r){if(++l>=s.length&&l>=a)continue;let t=e._zod.run({value:s[l],issues:[]},i);t instanceof Promise?o.push(t.then(e=>id(e,n,l))):id(t,n,l)}if(t.rest)for(let e of s.slice(r.length)){l++;let r=t.rest._zod.run({value:e,issues:[]},i);r instanceof Promise?o.push(r.then(e=>id(e,n,l))):id(r,n,l)}return o.length?Promise.all(o).then(()=>n):n}};let ip=tu("$ZodRecord",(e,t)=>{nT.init(e,t),e._zod.parse=(r,a)=>{let n=r.value;if(!tE(n))return r.issues.push({expected:"record",code:"invalid_type",input:n,inst:e}),r;let i=[];if(t.keyType._zod.values){let s,o=t.keyType._zod.values;for(let e of(r.value={},o))if("string"==typeof e||"number"==typeof e||"symbol"==typeof e){let s=t.valueType._zod.run({value:n[e],issues:[]},a);s instanceof Promise?i.push(s.then(t=>{t.issues.length&&r.issues.push(...tP(e,t.issues)),r.value[e]=t.value})):(s.issues.length&&r.issues.push(...tP(e,s.issues)),r.value[e]=s.value)}for(let e in n)o.has(e)||(s=s??[]).push(e);s&&s.length>0&&r.issues.push({code:"unrecognized_keys",input:n,inst:e,keys:s})}else for(let s of(r.value={},Reflect.ownKeys(n))){if("__proto__"===s)continue;let o=t.keyType._zod.run({value:s,issues:[]},a);if(o instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(o.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:o.issues.map(e=>
54tD(e,a,tp())),input:s,path:[s],inst:e}),r.value[o.value]=o.value;continue}let l=t.valueType._zod.run({value:n[s],issues:[]},a);l instanceof Promise?i.push(l.then(e=>{e.issues.length&&r.issues.push(...tP(s,e.issues)),r.value[o.value]=e.value})):(l.issues.length&&r.issues.push(...tP(s,l.issues)),r.value[o.value]=l.value)}return i.length?Promise.all(i).then(()=>r):r}});function ih(e,t,r,a,n,i,s){e.issues.length&&(tC.has(typeof a)?r.issues.push(...tP(a,e.issues)):r.issues.push({origin:"map",code:"invalid_key",input:n,inst:i,issues:e.issues.map(e=>tD(e,s,tp()))})),t.issues.length&&(tC.has(typeof a)?r.issues.push(...tP(a,t.issues)):r.issues.push({origin:"map",code:"invalid_element",input:n,inst:i,key:a,issues:t.issues.map(e=>tD(e,s,tp()))})),r.value.set(e.value,t.value)}function im(e,t){e.issues.length&&t.issues.push(...e.issues),t.value.add(e.value)}(e,t)=>{nT.init(e,t),e._zod.parse=(r,a)=>{let n=r.value;if(!(n instanceof Map))return r.issues.push({expected:"map",code:"invalid_type",input:n,inst:e}),r;let i=[];for(let[s,o]of(r.value=new Map,n)){let l=t.keyType._zod.run({value:s,issues:[]},a),u=t.valueType._zod.run({value:o,issues:[]},a);l instanceof Promise||u instanceof Promise?i.push(Promise.all([l,u]).then(([t,i])=>{ih(t,i,r,s,n,e,a)})):ih(l,u,r,s,n,e,a)}return i.length?Promise.all(i).then(()=>r):r}},(e,t)=>{nT.init(e,t),e._zod.parse=(r,a)=>{let n=r.value;if(!(n instanceof Set))return r.issues.push({input:n,inst:e,expected:"set",code:"invalid_type"}),r;let i=[];for(let e of(r.value=new Set,n)){let n=t.valueType._zod.run({value:e,issues:[]},a);n instanceof Promise?i.push(n.then(e=>im(e,r))):im(n,r)}return i.length?Promise.all(i).then(()=>r):r}};let ig=tu("$ZodEnum",(e,t)=>{nT.init(e,t);let r=th(t.entries);e._zod.values=new Set(r),e._zod.pattern=RegExp(`^(${r.filter(e=>tC.has(typeof e)).map(e=>"string"==typeof e?tI(e):e.toString()).join("|")})$`),e._zod.parse=(t,a)=>{let n=t.value;return e._zod.values.has(n)||t.issues.push({code:"invalid_value",values:r,input:n,inst:e}),t}}),iv=tu("$ZodLiteral",(e,t)=>{nT.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=RegExp(`^(${t.values.map(e=>"string"==typeof e?tI(e):e?e.toString():String(e)).join("|")})$`),e._zod.parse=(r,a)=>{let n=r.value;return e._zod.values.has(n)||r.issues.push({code:"invalid_value",values:t.values,input:n,inst:e}),r}}),iy=((e,t)=>{nT.init(e,t),e._zod.parse=(t,r)=>{let a=t.value;return a instanceof File||t.issues.push({expected:"file",code:"invalid_type",input:a,inst:e}),t}},tu("$ZodTransform",(e,t)=>{nT.init(e,t),e._zod.parse=(e,r)=>{let a=t.transform(e.value,e);if(r.async)return(a instanceof Promise?a:Promise.resolve(a)).then(t=>(e.value=t,e));if(a instanceof Promise)throw new tc;return e.value=a,e}})),ib=tu("$ZodOptional",(e,t)=>{nT.init(e,t),e._zod.optin="optional",e._zod.optout="optional",tb(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),tb(e._zod,"pattern",()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${tv(e.source)})?$`):void 0}),e._zod.parse=(e,r)=>"optional"===t.innerType._zod.optin?t.innerType._zod.run(e,r):void 0===e.value?e:t.innerType._zod.run(e,r)}),ix=tu("$ZodNullable",(e,t)=>{nT.init(e,t),tb(e._zod,"optin",()=>t.innerType._zod.optin),tb(e._zod,"optout",()=>t.innerType._zod.optout),tb(e._zod,"pattern",()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${tv(e.source)}|null)$`):void 0}),tb(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,r)=>null===e.value?e:t.innerType._zod.run(e,r)}),iw=tu("$ZodDefault",(e,t)=>{nT.init(e,t),e._zod.optin="optional",tb(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>{if(void 0===e.value)return e.value=t.defaultValue,e;let a=t.innerType._zod.run(e,r);return a instanceof Promise?a.then(e=>i_(e,t)):i_(a,t)}});function i_(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}let ik=tu("$ZodPrefault",(e,t)=>{nT.init(e,t),e._zod.optin="optional",tb(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>(void 0===e.value&&(e.value=t.defaultValue),t.innerType._zod.run(e,r))}),iS=tu("$ZodNonOptional",(e,t)=>{nT.init(e,t),tb(e._zod,"values",()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>void 0!==e)):void 0}),e._zod.parse=(r,a)=>{let n=t.innerType._zod.run(r,a);return n instanceof Promise?n.then(t=>iE(t,e)):iE(n,e)}});function iE(e,t){return e.issues.length||void 0!==e.value||e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}(e,t)=>{nT.init(e,t),e._zod.parse=(e,r)=>{let a=t.innerType._zod.run(e,r);return a instanceof Promise?a.then(t=>(e.value=0===t.issues.length,e)):(e.value=0===a.issues.length,e)}};let iC=tu("$ZodCatch",(e,t)=>{nT.init(e,t),e._zod.optin="optional",tb(e._zod,"optout",()=>t.innerType._zod.optout),tb(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>{let a=t.innerType._zod.run(e,r);return a instanceof Promise?a.then(a=>(e.value=a.value,a.issues.length&&(e.value=t.catchValue({...e,error:{issues:a.issues.map(e=>tD(e,r,tp()))},input:e.value}),e.issues=[]),e)):(e.value=a.value,a.issues.length&&(e.value=t.catchValue({...e,error:{issues:a.issues.map(e=>tD(e,r,tp()))},input:e.value}),e.issues=[]),e)}}),ij=((e,t)=>{nT.init(e,t),e._zod.parse=(t,r)=>("number"==typeof t.value&&Number.isNaN(t.value)||t.issues.push({input:t.value,inst:e,expected:"nan",code:"invalid_type"}),t)},tu("$ZodPipe",(e,t)=>{nT.init(e,t),tb(e._zod,"values",()=>t.in._zod.values),tb(e._zod,"optin",()=>t.in._zod.optin),tb(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(e,r)=>{let a=t.in._zod.run(e,r);return a instanceof Promise?a.then(e=>iI(e,t,r)):iI(a,t,r)}}));function iI(e,t,r){return tO(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}let iT=tu("$ZodReadonly",(e,t)=>{nT.init(e,t),tb(e._zod,"propValues",()=>t.innerType._zod.propValues),tb(e._zod,"values",()=>t.innerType._zod.values),tb(e._zod,"optin",()=>t.innerType._zod.optin),tb(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(e,r)=>{let a=t.innerType._zod.run(e,r);return a instanceof Promise?a.then(iN):iN(a)}});function iN(e){return e.value=Object.freeze(e.value),e}(e,t)=>{nT.init(e,t);let r=[];for(let e of t.parts)if(e instanceof nT){if(!e._zod.pattern)throw Error(`Invalid template literal part, no pattern found: ${[...e._zod.traits].shift()}`);let t=e._zod.pattern instanceof RegExp?e._zod.pattern.source:e._zod.pattern;if(!t)throw Error(`Invalid template literal part: ${e._zod.traits}`);let a=+!!t.startsWith("^"),n=t.endsWith("$")?t.length-1:t.length;r.push(t.slice(a,n))}else if(null===e||tj.has(typeof e))r.push(tI(`${e}`));else throw Error(`Invalid template literal part: ${e}`);e._zod.pattern=RegExp(`^${r.join("")}$`),e._zod.parse=(t,r)=>("string"!=typeof t.value?t.issues.push({input:t.value,inst:e,expected:"template_literal",code:"invalid_type"}):(e._zod.pattern.lastIndex=0,e._zod.pattern.test(t.value)||t.issues.push({input:t.value,inst:e,code:"invalid_format",format:"template_literal",pattern:e._zod.pattern.source})),t)},(e,t)=>{nT.init(e,t),e._zod.parse=(e,r)=>Promise.resolve(e.value).then(e=>t.innerType._zod.run({value:e,issues:[]},r))};let iR=tu("$ZodLazy",(e,t)=>{nT.init(e,t),tb(e._zod,"innerType",()=>t.getter()),tb(e._zod,"pattern",()=>e._zod.innerType._zod.pattern),tb(e._zod,"propValues",()=>e._zod.innerType._zod.propValues),tb(e._zod,"optin",()=>e._zod.innerType._zod.optin),tb(e._zod,"optout",()=>e._zod.innerType._zod.optout),e._zod.parse=(t,r)=>e._zod.innerType._zod.run(t,r)}),iA=tu("$ZodCustom",(e,t)=>{no.init(e,t),nT.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=r=>{let a=r.value,n=t.fn(a);if(n instanceof Promise)return n.then(t=>iz(t,r,a,e));iz(n,r,a,e)}});function iz(e,t,r,a){if(!e){let e={code:"custom",input:r,inst:a,path:[...a._zod.def.path??[]],continue:!a._zod.def.abort};a._zod.def.params&&(e.params=a._zod.def.params),t.issues.push(tF(e))}}function iM(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...tN(t)})}function iO(e,t){return new nu({check:"less_than",...tN(t),value:e,inclusive:!1})}function iP(e,t){return new nu({check:"less_than",...tN(t),value:e,inclusive:!0})}function i$(e,t){return new nc({check:"greater_than",...tN(t),value:e,inclusive:!1})}function iD(e,t){return new nc({check:"greater_than",...tN(t),value:e,inclusive:!0})}function iU(e,t){return new nd({check:"multiple_of",...tN(t),value:e})}function iL(e,t){return new ng({check:"max_length",...tN(t),maximum:e})}function iF(e,t){return new nv({check:"min_length",...tN(t),minimum:e})}function iZ(e,t){return new ny({check:"length_equals",...tN(t),length:e})}function iB(e){return new nC({check:"overwrite",tx:e})}var iH=e.i(922143),iH=iH;let iq=tu("ZodISODateTime",(e,t)=>{nB.init(e,t),iX.init(e,t)}),iV=tu("ZodISODate",(e,t)=>{nH.init(e,t),iX.init(e,t)}),iW=tu("ZodISOTime",(e,t)=>{nq.init(e,t),iX.init(e,t)}),iG=tu("ZodISODuration",(e,t)=>{nV.init(e,t),iX.init(e,t)}),iY=tu("ZodType",(e,t)=>(nT.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]}),e.clone=(t,r)=>tT(e,t,r),e.brand=()=>e,e.register=(t,r)=>(t.add(e,r),e),e.parse=(t,r)=>tJ(e,t,r,{callee:e.parse}),e.safeParse=(t,r)=>tQ(e,t,r),e.parseAsync=async(t,r)=>tK(e,t,r,{callee:e.parseAsync}),e.safeParseAsync=async(t,r)=>tX(e,t,r),e.spa=e.safeParseAsync,e.refine=(t,r)=>e.check(function(e,t={}){return new sY({type:"custom",check:"custom",fn:e,...tN(t)})}(t,r)),e.superRefine=t=>{var r,a;let n,i;return e.check((r=t,i=(a=e=>(e.addIssue=t=>{"string"==typeof t?e.issues.push(iH.issue(t,e.value,i._zod.def)):(t.fatal&&(t.continue=!1),t.code??(t.code="custom"),t.input??(t.input=e.value),t.inst??(t.inst=i),t.continue??(t.continue=!i._zod.def.abort),e.issues.push(iH.issue(t)))},r(e.value,e)),(n=new no({check:"custom"}
54))._zod.check=a,n)))},e.overwrite=t=>e.check(iB(t)),e.optional=()=>sD(e),e.nullable=()=>sL(e),e.nullish=()=>sD(sL(e)),e.nonoptional=t=>{var r,a;return r=e,a=t,new sB({type:"nonoptional",innerType:r,...iH.normalizeParams(a)})},e.array=()=>s_(e),e.or=t=>sC([e,t]),e.and=t=>new sT({type:"intersection",left:e,right:t}),e.transform=t=>sV(e,new sP({type:"transform",transform:t})),e.default=t=>{var r,a;return r=e,a=t,new sF({type:"default",innerType:r,get defaultValue(){return"function"==typeof a?a():a}})},e.prefault=t=>{var r,a;return r=e,a=t,new sZ({type:"prefault",innerType:r,get defaultValue(){return"function"==typeof a?a():a}})},e.catch=t=>{var r;return new sH({type:"catch",innerType:e,catchValue:"function"==typeof(r=t)?r:()=>r})},e.pipe=t=>sV(e,t),e.readonly=()=>new sW({type:"readonly",innerType:e}),e.describe=t=>{let r=e.clone();return t1.add(r,{description:t}),r},Object.defineProperty(e,"description",{get:()=>t1.get(e)?.description,configurable:!0}),e.meta=(...t)=>{if(0===t.length)return t1.get(e);let r=e.clone();return t1.add(r,t[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),iJ=tu("_ZodString",(e,t)=>{nN.init(e,t),iY.init(e,t);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,e.regex=(...t)=>e.check(function(e,t){return new nx({check:"string_format",format:"regex",...tN(t),pattern:e})}(...t)),e.includes=(...t)=>e.check(function(e,t){return new nk({check:"string_format",format:"includes",...tN(t),includes:e})}(...t)),e.startsWith=(...t)=>e.check(function(e,t){return new nS({check:"string_format",format:"starts_with",...tN(t),prefix:e})}(...t)),e.endsWith=(...t)=>e.check(function(e,t){return new nE({check:"string_format",format:"ends_with",...tN(t),suffix:e})}(...t)),e.min=(...t)=>e.check(iF(...t)),e.max=(...t)=>e.check(iL(...t)),e.length=(...t)=>e.check(iZ(...t)),e.nonempty=(...t)=>e.check(iF(1,...t)),e.lowercase=t=>e.check(new nw({check:"string_format",format:"lowercase",...tN(t)})),e.uppercase=t=>e.check(new n_({check:"string_format",format:"uppercase",...tN(t)})),e.trim=()=>e.check(iB(e=>e.trim())),e.normalize=(...t)=>e.check(function(e){return iB(t=>t.normalize(e))}(...t)),e.toLowerCase=()=>e.check(iB(e=>e.toLowerCase())),e.toUpperCase=()=>e.check(iB(e=>e.toUpperCase()))}),iK=tu("ZodString",(e,t)=>{nN.init(e,t),iJ.init(e,t),e.email=t=>e.check(new i0({type:"string",format:"email",check:"string_format",abort:!1,...tN(t)})),e.url=t=>e.check(new i5({type:"string",format:"url",check:"string_format",abort:!1,...tN(t)})),e.jwt=t=>e.check(new sl({type:"string",format:"jwt",check:"string_format",abort:!1,...tN(t)})),e.emoji=t=>e.check(new i4({type:"string",format:"emoji",check:"string_format",abort:!1,...tN(t)})),e.guid=t=>e.check(iM(i1,t)),e.uuid=t=>e.check(new i2({type:"string",format:"uuid",check:"string_format",abort:!1,...tN(t)})),e.uuidv4=t=>e.check(new i2({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...tN(t)})),e.uuidv6=t=>e.check(new i2({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...tN(t)})),e.uuidv7=t=>e.check(new i2({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...tN(t)})),e.nanoid=t=>e.check(new i3({type:"string",format:"nanoid",check:"string_format",abort:!1,...tN(t)})),e.guid=t=>e.check(iM(i1,t)),e.cuid=t=>e.check(new i9({type:"string",format:"cuid",check:"string_format",abort:!1,...tN(t)})),e.cuid2=t=>e.check(new i6({type:"string",format:"cuid2",check:"string_format",abort:!1,...tN(t)})),e.ulid=t=>e.check(new i8({type:"string",format:"ulid",check:"string_format",abort:!1,...tN(t)})),e.base64=t=>e.check(new si({type:"string",format:"base64",check:"string_format",abort:!1,...tN(t)})),e.base64url=t=>e.check(new ss({type:"string",format:"base64url",check:"string_format",abort:!1,...tN(t)})),e.xid=t=>e.check(new i7({type:"string",format:"xid",check:"string_format",abort:!1,...tN(t)})),e.ksuid=t=>e.check(new se({type:"string",format:"ksuid",check:"string_format",abort:!1,...tN(t)})),e.ipv4=t=>e.check(new st({type:"string",format:"ipv4",check:"string_format",abort:!1,...tN(t)})),e.ipv6=t=>e.check(new sr({type:"string",format:"ipv6",check:"string_format",abort:!1,...tN(t)})),e.cidrv4=t=>e.check(new sa({type:"string",format:"cidrv4",check:"string_format",abort:!1,...tN(t)})),e.cidrv6=t=>e.check(new sn({type:"string",format:"cidrv6",check:"string_format",abort:!1,...tN(t)})),e.e164=t=>e.check(new so({type:"string",format:"e164",check:"string_format",abort:!1,...tN(t)})),e.datetime=t=>e.check(new iq({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...tN(t)})),e.date=t=>e.check(new iV({type:"string",format:"date",check:"string_format",...tN(t)})),e.time=t=>e.check(new iW({type:"string",format:"time",check:"string_format",precision:null,...tN(t)})),e.duration=t=>e.check(new iG({type:"string",format:"duration",check:"string_format",...tN(t)}))});function iQ(e){return new iK({type:"string",...tN(e)})}let iX=tu("ZodStringFormat",(e,t)=>{nR.init(e,t),iJ.init(e,t)}),i0=tu("ZodEmail",(e,t)=>{nM.init(e,t),iX.init(e,t)}),i1=tu("ZodGUID",(e,t)=>{nA.init(e,t),iX.init(e,t)}),i2=tu("ZodUUID",(e,t)=>{nz.init(e,t),iX.init(e,t)}),i5=tu("ZodURL",(e,t)=>{nO.init(e,t),iX.init(e,t)}),i4=tu("ZodEmoji",(e,t)=>{nP.init(e,t),iX.init(e,t)}),i3=tu("ZodNanoID",(e,t)=>{n$.init(e,t),iX.init(e,t)}),i9=tu("ZodCUID",(e,t)=>{nD.init(e,t),iX.init(e,t)}),i6=tu("ZodCUID2",(e,t)=>{nU.init(e,t),iX.init(e,t)}
54),i8=tu("ZodULID",(e,t)=>{nL.init(e,t),iX.init(e,t)}),i7=tu("ZodXID",(e,t)=>{nF.init(e,t),iX.init(e,t)}),se=tu("ZodKSUID",(e,t)=>{nZ.init(e,t),iX.init(e,t)}),st=tu("ZodIPv4",(e,t)=>{nW.init(e,t),iX.init(e,t)}),sr=tu("ZodIPv6",(e,t)=>{nG.init(e,t),iX.init(e,t)}),sa=tu("ZodCIDRv4",(e,t)=>{nY.init(e,t),iX.init(e,t)}),sn=tu("ZodCIDRv6",(e,t)=>{nJ.init(e,t),iX.init(e,t)}),si=tu("ZodBase64",(e,t)=>{nQ.init(e,t),iX.init(e,t)}),ss=tu("ZodBase64URL",(e,t)=>{nX.init(e,t),iX.init(e,t)}),so=tu("ZodE164",(e,t)=>{n0.init(e,t),iX.init(e,t)}),sl=tu("ZodJWT",(e,t)=>{n1.init(e,t),iX.init(e,t)}),su=tu("ZodNumber",(e,t)=>{n2.init(e,t),iY.init(e,t),e.gt=(t,r)=>e.check(i$(t,r)),e.gte=(t,r)=>e.check(iD(t,r)),e.min=(t,r)=>e.check(iD(t,r)),e.lt=(t,r)=>e.check(iO(t,r)),e.lte=(t,r)=>e.check(iP(t,r)),e.max=(t,r)=>e.check(iP(t,r)),e.int=t=>e.check(sp(t)),e.safe=t=>e.check(sp(t)),e.positive=t=>e.check(i$(0,t)),e.nonnegative=t=>e.check(iD(0,t)),e.negative=t=>e.check(iO(0,t)),e.nonpositive=t=>e.check(iP(0,t)),e.multipleOf=(t,r)=>e.check(iU(t,r)),e.step=(t,r)=>e.check(iU(t,r)),e.finite=()=>e;let r=e._zod.bag;e.minValue=Math.max(r.minimum??-1/0,r.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(r.maximum??1/0,r.exclusiveMaximum??1/0)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function sc(e){return new su({type:"number",checks:[],...tN(e)})}let sd=tu("ZodNumberFormat",(e,t)=>{n5.init(e,t),su.init(e,t)});function sp(e){return new sd({type:"number",check:"number_format",abort:!1,format:"safeint",...tN(e)})}let sh=tu("ZodBoolean",(e,t)=>{n4.init(e,t),iY.init(e,t)});function sm(e){return new sh({type:"boolean",...tN(e)})}(e,t)=>{n3.init(e,t),iY.init(e,t),e.gte=(t,r)=>e.check(iD(t,r)),e.min=(t,r)=>e.check(iD(t,r)),e.gt=(t,r)=>e.check(i$(t,r)),e.gte=(t,r)=>e.check(iD(t,r)),e.min=(t,r)=>e.check(iD(t,r)),e.lt=(t,r)=>e.check(iO(t,r)),e.lte=(t,r)=>e.check(iP(t,r)),e.max=(t,r)=>e.check(iP(t,r)),e.positive=t=>e.check(i$(BigInt(0),t)),e.negative=t=>e.check(iO(BigInt(0),t)),e.nonpositive=t=>e.check(iP(BigInt(0),t)),e.nonnegative=t=>e.check(iD(BigInt(0),t)),e.multipleOf=(t,r)=>e.check(iU(t,r));let r=e._zod.bag;e.minValue=r.minimum??null,e.maxValue=r.maximum??null,e.format=r.format??null};let sf=tu("ZodNull",(e,t)=>{n9.init(e,t),iY.init(e,t)}),sg=tu("ZodAny",(e,t)=>{n6.init(e,t),iY.init(e,t)}),sv=tu("ZodUnknown",(e,t)=>{n8.init(e,t),iY.init(e,t)});function sy(){return new sv({type:"unknown"})}let sb=tu("ZodNever",(e,t)=>{n7.init(e,t),iY.init(e,t)});function sx(e){return new sb({type:"never",...tN(e)})}let sw=tu("ZodArray",(e,t)=>{it.init(e,t),iY.init(e,t),e.element=t.element,e.min=(t,r)=>e.check(iF(t,r)),e.nonempty=t=>e.check(iF(1,t)),e.max=(t,r)=>e.check(iL(t,r)),e.length=(t,r)=>e.check(iZ(t,r)),e.unwrap=()=>e.element});function s_(e,t){return new sw({type:"array",element:e,...tN(t)})}let sk=tu("ZodObject",(e,t)=>{ii.init(e,t),iY.init(e,t),iH.defineLazy(e,"shape",()=>t.shape),e.keyof=()=>sz(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:sy()}),e.loose=()=>e.clone({...e._zod.def,catchall:sy()}),e.strict=()=>e.clone({...e._zod.def,catchall:sx()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>iH.extend(e,t),e.merge=t=>iH.merge(e,t),e.pick=t=>iH.pick(e,t),e.omit=t=>iH.omit(e,t),e.partial=(...t)=>iH.partial(s$,e,t[0]),e.required=(...t)=>iH.required(sB,e,t[0])});function sS(e,t){return new sk({type:"object",get shape(){return iH.assignProp(this,"shape",{...e}),this.shape},...iH.normalizeParams(t)})}let sE=tu("ZodUnion",(e,t)=>{io.init(e,t),iY.init(e,t),e.options=t.options});function sC(e,t){return new sE({type:"union",options:e,...iH.normalizeParams(t)})}let sj=tu("ZodDiscriminatedUnion",(e,t)=>{sE.init(e,t),il.init(e,t)});function sI(e,t,r){return new sj({type:"union",options:t,discriminator:e,...iH.normalizeParams(r)})}let sT=tu("ZodIntersection",(e,t)=>{iu.init(e,t),iY.init(e,t)}),sN=tu("ZodRecord",(e,t)=>{ip.init(e,t),iY.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function sR(e,t,r){return new sN({type:"record",keyType:e,valueType:t,...iH.normalizeParams(r)})}let sA=tu("ZodEnum",(e,t)=>{ig.init(e,t),iY.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(e,a)=>{let n={};for(let a of e)if(r.has(a))n[a]=t.entries[a];else throw Error(`Key ${a} not found in enum`);return new sA({...t,checks:[],...iH.normalizeParams(a),entries:n})},e.exclude=(e,a)=>{let n={...t.entries};for(let t of e)if(r.has(t))delete n[t];else throw Error(`Key ${t} not found in enum`);return new sA({...t,checks:[],...iH.normalizeParams(a),entries:n})}});function sz(e,t){return new sA({type:"enum",entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...iH.normalizeParams(t)})}let sM=tu("ZodLiteral",(e,t)=>{iv.init(e,t),iY.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if
54(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function sO(e,t){return new sM({type:"literal",values:Array.isArray(e)?e:[e],...iH.normalizeParams(t)})}let sP=tu("ZodTransform",(e,t)=>{iy.init(e,t),iY.init(e,t),e._zod.parse=(r,a)=>{r.addIssue=a=>{"string"==typeof a?r.issues.push(iH.issue(a,r.value,t)):(a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=r.value),a.inst??(a.inst=e),a.continue??(a.continue=!0),r.issues.push(iH.issue(a)))};let n=t.transform(r.value,r);return n instanceof Promise?n.then(e=>(r.value=e,r)):(r.value=n,r)}}),s$=tu("ZodOptional",(e,t)=>{ib.init(e,t),iY.init(e,t),e.unwrap=()=>e._zod.def.innerType});function sD(e){return new s$({type:"optional",innerType:e})}let sU=tu("ZodNullable",(e,t)=>{ix.init(e,t),iY.init(e,t),e.unwrap=()=>e._zod.def.innerType});function sL(e){return new sU({type:"nullable",innerType:e})}let sF=tu("ZodDefault",(e,t)=>{iw.init(e,t),iY.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap}),sZ=tu("ZodPrefault",(e,t)=>{ik.init(e,t),iY.init(e,t),e.unwrap=()=>e._zod.def.innerType}),sB=tu("ZodNonOptional",(e,t)=>{iS.init(e,t),iY.init(e,t),e.unwrap=()=>e._zod.def.innerType}),sH=tu("ZodCatch",(e,t)=>{iC.init(e,t),iY.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap}),sq=tu("ZodPipe",(e,t)=>{ij.init(e,t),iY.init(e,t),e.in=t.in,e.out=t.out});function sV(e,t){return new sq({type:"pipe",in:e,out:t})}let sW=tu("ZodReadonly",(e,t)=>{iT.init(e,t),iY.init(e,t)}),sG=tu("ZodLazy",(e,t)=>{iR.init(e,t),iY.init(e,t),e.unwrap=()=>e._zod.def.getter()}),sY=tu("ZodCustom",(e,t)=>{iA.init(e,t),iY.init(e,t)});var sJ=e.i(725150),sK="ai-gateway-transcription.v1";function sQ(e,t,r){let a=[e,`ai-gateway-auth.${t}`];return(null==r?void 0:r.teamIdOrSlug)&&a.push(`ai-gateway-team.${function(e){let t=new TextEncoder().encode(e),r="";for(let e of t)r+=String.fromCharCode(e);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/u,"")}(r.teamIdOrSlug)}`),a}var sX=function(){return new sg({type:"any"})},s0=s_,s1=sz,s2=sC,s5=Symbol.for("vercel.ai.gateway.error"),s4=class e extends(w=Error,x=s5,w){constructor({message:e,statusCode:t=500,cause:r,generationId:a,isRetryable:n=null!=t&&(408===t||409===t||429===t||t>=500)}){super(a?`${e} [${a}]`:e),this[x]=!0,this.statusCode=t,this.cause=r,this.generationId=a,this.isRetryable=n}static isInstance(t){return e.hasMarker(t)}static hasMarker(e){return"object"==typeof e&&null!==e&&s5 in e&&!0===e[s5]}},s3="GatewayAuthenticationError",s9=Symbol.for(`vercel.ai.gateway.error.${s3}`),s6=class e extends(k=s4,_=s9,k){constructor({message:e="Authentication failed",statusCode:t=401,cause:r,generationId:a}={}){super({message:e,statusCode:t,cause:r,generationId:a}),this[_]=!0,this.name=s3,this.type="authentication_error"}static isInstance(e){return s4.hasMarker(e)&&s9 in e}static createContextualError({apiKeyProvided:t,oidcTokenProvided:r,statusCode:a=401,cause:n,generationId:i}){return new e({message:t?`AI Gateway authentication failed: Invalid API key or token.
55
56Create a new API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
57
58Provide an API key or Vercel access token via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`:r?`AI Gateway authentication failed: Invalid OIDC token.
59
60Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.
61
62Alternatively, use an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
63or pass a Vercel access token via the 'apiKey' option.`:`AI Gateway authentication failed: No authentication provided.
64
65Option 1 - API key:
66Create an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
67Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.
68
69Option 2 - Vercel access token:
70Pass a Vercel personal access token or Vercel app access token via the 'apiKey' option.
71
72Option 3 - OIDC token:
73Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,statusCode:a,cause:n,generationId:i})}},s8="GatewayInvalidRequestError",s7=Symbol.for(`vercel.ai.gateway.error.${s8}`),oe=class extends(E=s4,S=s7,E){constructor({message:e="Invalid request",statusCode:t=400,cause:r,generationId:a}={}){super({message:e,statusCode:t,cause:r,generationId:a}),this[S]=!0,this.name=s8,this.type="invalid_request_error"}static isInstance(e){return s4.hasMarker(e)&&s7 in e}},ot="GatewayRateLimitError",or=Symbol.for(`vercel.ai.gateway.error.${ot}`),oa=class extends(j=s4,C=or,j){constructor({message:e="Rate limit exceeded",statusCode:t=429,cause:r,generationId:a}={}){super({message:e,statusCode:t,cause:r,generationId:a}),this[C]=!0,this.name=ot,this.type="rate_limit_exceeded"}static isInstance(e){return s4.hasMarker(e)&&or in e}},on="GatewayModelNotFoundError",oi=Symbol.for(`vercel.ai.gateway.error.${on}`),os=ad(()=>am(sS({modelId:iQ()}))),oo=class extends(T=s4,I=oi,T){constructor({message:e="Model not found",statusCode:t=404,modelId:r,cause:a,generationId:n}={}){super({message:e,statusCode:t,cause:a,generationId:n}),this[I]=!0,this.name=on,this.type="model_not_found",this.modelId=r}static isInstance(e){return s4.hasMarker(e)&&oi in e}},ol="GatewayNotFoundError",ou=Symbol.for(`vercel.ai.gateway.error.${ol}`),oc=class extends(R=s4,N=ou,R){constructor({message:e="Resource not found",statusCode:t=404,cause:r,generationId:a}={}){super({message:e,statusCode:t,cause:r,generationId:a}),this[N]=!0,this.name=ol,this.type="not_found"}static isInstance(e){return s4.hasMarker(e)&&ou in e}},od="GatewayInternalServerError",op=Symbol.for(`vercel.ai.gateway.error.${od}`),oh=class extends(z=s4,A=op,z){constructor({message:e="Internal server error",statusCode:t=500,cause:r,generationId:a}={}){super({message:e,statusCode:t,cause:r,generationId:a}),this[A]=!0,this.name=od,this.type="internal_server_error"}static isInstance(e){return s4.hasMarker(e)&&op in e}},om="GatewayFailedDependencyError",of=Symbol.for(`vercel.ai.gateway.error.${om}`),og=class extends(O=s4,M=of,O){constructor({message:e="Failed dependency",statusCode:t=424,cause:r,generationId:a}={}){super({message:e,statusCode:t,cause:r,generationId:a}),this[M]=!0,this.name=om,this.type="failed_dependency"}static isInstance(e){return s4.hasMarker(e)&&of in e}},ov="GatewayForbiddenError",oy=Symbol.for(`vercel.ai.gateway.error.${ov}`),ob=ad(()=>am(sS({ruleId:iQ()}))),ox=class extends($=s4,P=oy,$){constructor({message:e="Forbidden",statusCode:t=403,cause:r,generationId:a,ruleId:n}={}){super({message:e,statusCode:t,cause:r,generationId:a}),this[P]=!0,this.name=ov,this.type="forbidden",this.ruleId=n}static isInstance(e){return s4.hasMarker(e)&&oy in e}},ow="GatewayResponseError",o_=Symbol.for(`vercel.ai.gateway.error.${ow}`),ok=class extends(U=s4,D=o_,U){constructor({message:e="Invalid response from Gateway",statusCode:t=502,response:r,validationError:a,cause:n,generationId:i,isRetryable:s}={}){super({message:e,statusCode:t,cause:n,generationId:i,isRetryable:s}),this[D]=!0,this.name=ow,this.type="response_error",this.response=r,this.validationError=a}static isInstance(e){return s4.hasMarker(e)&&o_ in e}};async function oS({response:e,statusCode:t,defaultMessage:r="Gateway request failed",cause:a,authMethod:n,isRetryable:i}){var s;let o=await ag({value:e,schema:oE});if(!o.success){let n="object"==typeof e&&null!==e&&"generationId"in e?e.generationId:void 0;return new ok({message:`Invalid error response format: ${r}`,statusCode:t,response:e,validationError:o.error,cause:a,generationId:n,isRetryable:i})}let l=o.value,u=l.error.type,c=l.error.message,d=null!=(s=l.generationId)?s:void 0;switch(u){case"authentication_error":return s6.createContextualError({apiKeyProvided:"api-key"===n,oidcTokenProvided:"oidc"===n,statusCode:t,cause:a,generationId:d});
73case"invalid_request_error":return new oe({message:c,statusCode:t,cause:a,generationId:d});case"rate_limit_exceeded":return new oa({message:c,statusCode:t,cause:a,generationId:d});case"model_not_found":{let e=await ag({value:l.error.param,schema:os});return new oo({message:c,statusCode:t,modelId:e.success?e.value.modelId:void 0,cause:a,generationId:d})}case"not_found":return new oc({message:c,statusCode:t,cause:a,generationId:d});case"internal_server_error":default:return new oh({message:c,statusCode:t,cause:a,generationId:d});case"failed_dependency":return new og({message:c,statusCode:t,cause:a,generationId:d});case"forbidden":{let e=await ag({value:l.error.param,schema:ob});return new ox({message:c,statusCode:t,cause:a,generationId:d,ruleId:e.success?e.value.ruleId:void 0})}}}var oE=ad(()=>am(sS({error:sS({message:iQ(),type:iQ().nullish(),param:sy().nullish(),code:s2([iQ(),sc()]).nullish()}),generationId:iQ().nullish()}))),oC="GatewayTimeoutError",oj=Symbol.for(`vercel.ai.gateway.error.${oC}`),oI=class e extends(F=s4,L=oj,F){constructor({message:e="Request timed out",statusCode:t=408,cause:r,generationId:a}={}){super({message:e,statusCode:t,cause:r,generationId:a}),this[L]=!0,this.name=oC,this.type="timeout_error"}static isInstance(e){return s4.hasMarker(e)&&oj in e}static createTimeoutError({originalMessage:t,statusCode:r=408,cause:a,generationId:n}){return new e({message:`Gateway request timed out: ${t}
74
75    This is a client-side timeout. To resolve this, increase your timeout configuration: https://vercel.com/docs/ai-gateway/capabilities/video-generation#extending-timeouts-for-node.js`,statusCode:r,cause:a,generationId:n})}};function oT(e){if(!(e instanceof Error))return!1;let t=e.code;return"string"==typeof t&&["UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CONNECT_TIMEOUT"].includes(t)}async function oN(e,t){var r;return s4.isInstance(e)?e:oT(e)?oI.createTimeoutError({originalMessage:e instanceof Error?e.message:"Unknown error",cause:e}):eW.isInstance(e)?e.cause&&oT(e.cause)?oI.createTimeoutError({originalMessage:e.message,cause:e}):await oS({response:function(e){if(void 0!==e.data)return e.data;if(null!=e.responseBody)try{return rq(e.responseBody)}catch(t){return e.responseBody}return{}}(e),statusCode:null!=(r=e.statusCode)?r:500,defaultMessage:"Gateway request failed",cause:e,authMethod:t,isRetryable:!!e.isRetryable&&(null==e.statusCode||e.statusCode<400)||void 0}):await oS({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:"Unknown Gateway error",cause:e,authMethod:t})}var oR="ai-gateway-auth-method",oA="x-vercel-ai-gateway-team";async function oz(e){let t=await ag({value:e[oR],schema:oM});return t.success?t.value:void 0}var oM=ad(()=>am(s2([sO("api-key"),sO("oidc")]))),oO=["embedding","image","language","realtime","reranking","speech","transcription","video"],oP=class{constructor(e){this.config=e}async getAvailableModels(){try{let{value:e}=await rD({url:`${this.config.baseURL}/config`,validateUrl:!1,headers:this.config.headers?await aS(this.config.headers):void 0,successfulResponseHandler:aI(o$),failedResponseHandler:aj({errorSchema:sX(),errorToMessage:e=>{var t;return null!=(t=eQ(e))?t:"unknown error"}}),fetch:this.config.fetch});return e}catch(e){throw await oN(e)}}async getCredits(){try{let e=new URL(this.config.baseURL),{value:t}=await rD({url:`${e.origin}/v1/credits`,validateUrl:!1,headers:this.config.headers?await aS(this.config.headers):void 0,successfulResponseHandler:aI(oD),failedResponseHandler:aj({errorSchema:sX(),errorToMessage:e=>{var t;return null!=(t=eQ(e))?t:"unknown error"}}),fetch:this.config.fetch});return t}catch(e){throw await oN(e)}}},o$=ad(()=>am(sS({models:s0(sS({id:iQ(),name:iQ(),description:iQ().nullish(),pricing:sS({input:iQ(),output:iQ(),input_cache_read:iQ().nullish(),input_cache_write:iQ().nullish()}).transform(({input:e,output:t,input_cache_read:r,input_cache_write:a})=>({input:e,output:t,...r?{cachedInputTokens:r}:{},...a?{cacheCreationInputTokens:a}:{}})).nullish(),specification:sS({specificationVersion:sO("v4"),provider:iQ(),modelId:iQ()}),modelType:iQ().nullish()})).transform(e=>e.filter(e=>null==e.modelType||oO.includes(e.modelType)))}))),oD=ad(()=>am(sS({balance:iQ(),total_used:iQ()}).transform(({balance:e,total_used:t})=>({balance:e,totalUsed:t})))),oU=class{constructor(e){this.config=e}
75async getSpendReport(e){try{let t=new URL(this.config.baseURL),r=new URLSearchParams;r.set("start_date",e.startDate),r.set("end_date",e.endDate),e.groupBy&&r.set("group_by",e.groupBy),e.datePart&&r.set("date_part",e.datePart),e.userId&&r.set("user_id",e.userId),e.model&&r.set("model",e.model),e.provider&&r.set("provider",e.provider),e.credentialType&&r.set("credential_type",e.credentialType),e.tags&&e.tags.length>0&&r.set("tags",e.tags.join(","));let{value:a}=await rD({url:`${t.origin}/v1/report?${r.toString()}`,validateUrl:!1,headers:this.config.headers?await aS(this.config.headers):void 0,successfulResponseHandler:aI(oL),failedResponseHandler:aj({errorSchema:sX(),errorToMessage:e=>{var t;return null!=(t=eQ(e))?t:"unknown error"}}),fetch:this.config.fetch});return a}catch(e){throw await oN(e)}}},oL=ad(()=>am(sS({results:s0(sS({day:iQ().optional(),hour:iQ().optional(),user:iQ().optional(),model:iQ().optional(),tag:iQ().optional(),provider:iQ().optional(),credential_type:s1(["byok","system"]).optional(),total_cost:sc(),market_cost:sc().optional(),input_tokens:sc().optional(),output_tokens:sc().optional(),cached_input_tokens:sc().optional(),cache_creation_input_tokens:sc().optional(),reasoning_tokens:sc().optional(),request_count:sc().optional()}).transform(({credential_type:e,total_cost:t,market_cost:r,input_tokens:a,output_tokens:n,cached_input_tokens:i,cache_creation_input_tokens:s,reasoning_tokens:o,request_count:l,...u})=>({...u,...void 0!==e?{credentialType:e}:{},totalCost:t,...void 0!==r?{marketCost:r}:{},...void 0!==a?{inputTokens:a}:{},...void 0!==n?{outputTokens:n}:{},...void 0!==i?{cachedInputTokens:i}:{},...void 0!==s?{cacheCreationInputTokens:s}:{},...void 0!==o?{reasoningTokens:o}:{},...void 0!==l?{requestCount:l}:{}})))}))),oF=class{constructor(e){this.config=e}async getGenerationInfo(e){try{let t=new URL(this.config.baseURL),{value:r}=await rD({url:`${t.origin}/v1/generation?id=${encodeURIComponent(e.id)}`,validateUrl:!1,headers:this.config.headers?await aS(this.config.headers):void 0,successfulResponseHandler:aI(oZ),failedResponseHandler:aj({errorSchema:sX(),errorToMessage:e=>{var t;return null!=(t=eQ(e))?t:"unknown error"}}),fetch:this.config.fetch});return r}catch(e){throw await oN(e)}}},oZ=ad(()=>am(sS({data:sS({id:iQ(),total_cost:sc(),upstream_inference_cost:sc(),usage:sc(),created_at:iQ(),model:iQ(),is_byok:sm(),provider_name:iQ(),streamed:sm(),finish_reason:iQ(),latency:sc(),generation_time:sc(),native_tokens_prompt:sc(),native_tokens_completion:sc(),native_tokens_reasoning:sc(),native_tokens_cached:sc(),native_tokens_cache_creation:sc(),billable_web_search_calls:sc()}).transform(({total_cost:e,upstream_inference_cost:t,created_at:r,is_byok:a,provider_name:n,finish_reason:i,generation_time:s,native_tokens_prompt:o,native_tokens_completion:l,native_tokens_reasoning:u,native_tokens_cached:c,native_tokens_cache_creation:d,billable_web_search_calls:p,...h})=>({...h,totalCost:e,upstreamInferenceCost:t,createdAt:r,isByok:a,providerName:n,finishReason:i,generationTime:s,promptTokens:o,completionTokens:l,reasoningTokens:u,cachedTokens:c,cacheCreationTokens:d,billableWebSearchCalls:p}))}).transform(({data:e})=>e))),oB=class e{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v4",this.supportedUrls={"*/*":[/.*/]}}static[t8](e){return aO({modelId:e.modelId,config:e.config})}static[t7](t){return new e(t.modelId,t.config)}get provider(){return this.config.provider}async getArgs(e){let{abortSignal:t,...r}=e;return{args:this.maybeEncodeFileParts(r),warnings:[]}}async doGenerate(e){let{args:t,warnings:r}=await this.getArgs(e),{abortSignal:a}=e,n=this.config.headers?await aS(this.config.headers):void 0;try{let{responseHeaders:i,value:s,rawValue:o}=await aw({url:this.getUrl(),headers:re(n,e.headers,this.getModelConfigHeaders(this.modelId,!1),await aS(this.config.o11yHeaders)),body:t,successfulResponseHandler:aI(sX()),failedResponseHandler:aj({errorSchema:sX(),errorToMessage:e=>{var t;return null!=(t=eQ(e))?t:"unknown error"}}),...a&&{abortSignal:a},fetch:this.config.fetch});return{...s,request:{body:t},response:{headers:i,body:o},warnings:r}}catch(e){throw await oN(e,await oz(null!=n?n:{}))}}async doStream(e){let{args:t,warnings:r}=await this.getArgs(e),{abortSignal:a}=e,n=this.config.headers?await aS(this.config.headers):void 0;try{let i,{value:s,responseHeaders:o}=await aw({url:this.getUrl(),headers:re(n,e.headers,this.getModelConfigHeaders(this.modelId,!0),await aS(this.config.o11yHeaders)),body:t,successfulResponseHandler:(i=sX(),async({response:e,url:t,requestBodyValues:r})=>{let a=ru(e);if(null==e.body)throw new eK({});
75return{responseHeaders:a,value:ab({stream:function({stream:e,url:t,requestBodyValues:r,statusCode:a,responseHeaders:n}){let i=e.getReader(),s=!1,o=()=>{s||(i.releaseLock(),s=!0)};return new ReadableStream({async pull(e){try{let{done:t,value:r}=await i.read();t?(o(),e.close()):e.enqueue(r)}catch(i){if(o(),rd(i))return void e.error(i);e.error(rm({error:new eW({message:"Failed to process successful response",cause:i,statusCode:a,url:t,responseHeaders:n,requestBodyValues:r}),url:t,requestBodyValues:r}))}},async cancel(e){try{await i.cancel(e)}finally{o()}}})}({stream:e.body,url:t,requestBodyValues:r,statusCode:e.status,responseHeaders:a}),schema:i})}}),failedResponseHandler:aj({errorSchema:sX(),errorToMessage:e=>{var t;return null!=(t=eQ(e))?t:"unknown error"}}),...a&&{abortSignal:a},fetch:this.config.fetch});return{stream:s.pipeThrough(new TransformStream({start(e){r.length>0&&e.enqueue({type:"stream-start",warnings:r})},transform(t,r){if(t.success){let a=t.value;("raw"!==a.type||e.includeRawChunks)&&("response-metadata"===a.type&&a.timestamp&&"string"==typeof a.timestamp&&(a.timestamp=new Date(a.timestamp)),r.enqueue(a))}else r.error(t.error)}})),request:{body:t},response:{headers:o}}}catch(e){throw await oN(e,await oz(null!=n?n:{}))}}maybeEncodeFileParts(e){for(let t of e.prompt)if(Array.isArray(t.content)){for(let e of t.content)if("file"===e.type||"reasoning-file"===e.type)e.data=oH(e.data);else if("tool-result"===e.type&&"content"===e.output.type)for(let t of e.output.value)"file"===t.type&&(t.data=oH(t.data))}return e}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(e,t){return{"ai-language-model-specification-version":"4","ai-language-model-id":e,"ai-language-model-streaming":String(t)}}};function oH(e){if("data"===e.type){let t=e.data;if(t instanceof Uint8Array)return{...e,data:aF.Buffer.from(t).toString("base64")}}return e}var oq=class e extends oB{static[t8](e){return oB[t8](e)}static[t7](t){return new e(t.modelId,t.config)}constructor(e,t){super(e,t)}async experimental_doStartBatch({requests:e,providerOptions:t,headers:r,abortSignal:a,webhookUrl:n}){var i;let s=this.config.headers?await aS(this.config.headers):void 0,o=function(e){let t=null==e?void 0:e.gateway;if(null==t||"object"!=typeof t||Array.isArray(t))return;let r=t.idempotencyKey;return"string"==typeof r&&r.length>0?r:void 0}(t),l=function(e){let t=null==e?void 0:e.gateway;if(null==t||"object"!=typeof t||Array.isArray(t)||!("idempotencyKey"in t))return e;let{idempotencyKey:r,...a}=t,n={...e};if(0===Object.keys(a).length?delete n.gateway:n.gateway=a,0!==Object.keys(n).length)return n}(t);try{let{value:t}=await aw({url:this.getBatchUrl("start"),headers:re(s,r,this.getBatchConfigHeaders(),await aS(this.config.o11yHeaders),null!=o?{"idempotency-key":o}:void 0),body:{...null!=n&&{callbackUrl:n},modelId:this.modelId,requests:e.map(e=>({id:e.id,options:this.maybeEncodeFileParts(e.options)})),...null!=l&&{providerOptions:l}},successfulResponseHandler:aI(o0),failedResponseHandler:aj({errorSchema:sX(),errorToMessage:e=>{var t;return null!=(t=eQ(e))?t:"unknown error"}}),...a&&{abortSignal:a},fetch:this.config.fetch});return{batchId:t.batchId,...oW(t),warnings:null!=(i=t.warnings)?i:[]}}catch(e){if(oV(e))throw e;throw await oN(e,await oz(null!=s?s:{}))}}async experimental_doGetBatchStatus({batchId:e,headers:t,abortSignal:r}){let a=this.config.headers?await aS(this.config.headers):void 0;try{let{value:n}=await aw({url:this.getBatchUrl("status"),headers:re(a,t,this.getBatchConfigHeaders(),await aS(this.config.o11yHeaders)),body:{batchId:e},successfulResponseHandler:aI(o1),failedResponseHandler:aj({errorSchema:sX(),errorToMessage:e=>{var t;return null!=(t=eQ(e))?t:"unknown error"}}),...r&&{abortSignal:r},fetch:this.config.fetch});return oW(n)}catch(e){if(oV(e))throw e;throw await oN(e,await oz(null!=a?a:{}))}}async experimental_doGetBatchResults({batchId:e,headers:t,abortSignal:r}){let a=this.config.headers?await aS(this.config.headers):void 0;try{var n;let i,{value:s}=await aw({url:this.getBatchUrl("results"),headers:re(a,t,this.getBatchConfigHeaders(),await aS(this.config.o11yHeaders)),body:{batchId:e},successfulResponseHandler:async({response:e})=>{let t=ru(e);if(null==e.body)throw new eK({});
75return{responseHeaders:t,value:aT({stream:e.body,schema:oY})}},failedResponseHandler:aj({errorSchema:sX(),errorToMessage:e=>{var t;return null!=(t=eQ(e))?t:"unknown error"}}),...r&&{abortSignal:r},fetch:this.config.fetch});return n=oG(s),i=!1,new ReadableStream({async pull(e){if(!i)try{let{value:t,done:r}=await n.next();r?e.close():e.enqueue(t)}catch(t){e.error(t)}},async cancel(e){if(i=!0,n.return)try{await n.return(e)}catch(e){}}})}catch(e){if(oV(e))throw e;throw await oN(e,await oz(null!=a?a:{}))}}getBatchUrl(e){return`${this.config.baseURL}/batch/${e}`}getBatchConfigHeaders(){return{"ai-model-id":this.modelId}}};function oV(e){return!!(e instanceof Error||e instanceof DOMException)&&("AbortError"===e.name||"TimeoutError"===e.name)}function oW(e){var t,r,a,n;let i=function({total:e,pending:t,completed:r,failed:a}){if(rF(e)&&rF(t)&&rF(r)&&rF(a)&&t+r+a===e)return{total:e,pending:t,completed:r,failed:a}}({total:null==(t=e.requestCounts)?void 0:t.total,pending:null==(r=e.requestCounts)?void 0:r.pending,completed:null==(a=e.requestCounts)?void 0:a.completed,failed:null==(n=e.requestCounts)?void 0:n.failed});return{status:e.status,...null!=e.rawStatus&&{rawStatus:e.rawStatus},...null!=i&&{requestCounts:i},...null!=e.error&&{error:{message:e.error.message,...null!=e.error.type&&{type:e.error.type},...null!=e.error.code&&{code:e.error.code},...null!=e.error.statusCode&&{statusCode:e.error.statusCode}}},...null!=e.createdAt&&{createdAt:e.createdAt},...null!=e.expiresAt&&{expiresAt:e.expiresAt},...null!=e.providerMetadata&&{providerMetadata:e.providerMetadata}}}async function*oG(e){var t;for await(let r of e){if("succeeded"===r.status){let e=null==(t=r.result)?void 0:t.response;void 0!==e&&"string"==typeof e.timestamp&&(e.timestamp=new Date(e.timestamp))}yield r}}var oY=sS({id:iQ(),status:s1(["cancelled","expired","failed","succeeded"])}).catchall(sy()),oJ=sS({message:iQ(),type:iQ().nullish(),code:iQ().nullish(),statusCode:sc().nullish()}),oK=sS({total:sc().nullish(),pending:sc().nullish(),completed:sc().nullish(),failed:sc().nullish()}),oQ=sR(iQ(),sR(iQ(),sy())),oX=sS({status:s1(["completed","failed","pending"]),rawStatus:iQ().nullish(),requestCounts:oK.nullish(),error:oJ.nullish(),createdAt:iQ().nullish(),expiresAt:iQ().nullish(),providerMetadata:oQ.nullish()}),o0=oX.extend({batchId:iQ(),warnings:s0(sS({requestId:iQ().nullish(),warning:sy()}).catchall(sy())).nullish()}),o1=oX,o2=class e{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v4",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}static[t8](e){return aO({modelId:e.modelId,config:e.config})}static[t7](t){return new e(t.modelId,t.config)}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:r,providerOptions:a}){var n,i;let s=this.config.headers?await aS(this.config.headers):void 0;try{let{responseHeaders:o,value:l,rawValue:u}=await aw({url:this.getUrl(),headers:re(s,null!=t?t:{},this.getModelConfigHeaders(),await aS(this.config.o11yHeaders)),body:{values:e,...a?{providerOptions:a}:{}},successfulResponseHandler:aI(o4),failedResponseHandler:aj({errorSchema:sX(),errorToMessage:e=>{var t;return null!=(t=eQ(e))?t:"unknown error"}}),...r&&{abortSignal:r},fetch:this.config.fetch});return{embeddings:l.embeddings,usage:null!=(n=l.usage)?n:void 0,providerMetadata:l.providerMetadata,response:{headers:o,body:u},warnings:null!=(i=l.warnings)?i:[]}}catch(e){throw await oN(e,await oz(null!=s?s:{}))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"4","ai-model-id":this.modelId}}},o5=sI("type",[sS({type:sO("unsupported"),feature:iQ(),details:iQ().optional()}),sS({type:sO("compatibility"),feature:iQ(),details:iQ().optional()}),sS({type:sO("deprecated"),setting:iQ(),message:iQ()}),sS({type:sO("other"),message:iQ()})]),o4=ad(()=>am(sS({embeddings:s0(s0(sc())),usage:sS({tokens:sc()}).nullish(),warnings:s0(o5).optional(),providerMetadata:sR(iQ(),sR(iQ(),sy())).optional()}))),o3=class e{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v4",this.maxImagesPerCall=Number.MAX_SAFE_INTEGER}static[t8](e){return aO({modelId:e.modelId,config:e.config})}static[t7](t){return new e(t.modelId,t.config)}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:r,aspectRatio:a,seed:n,files:i,mask:s,providerOptions:o,headers:l,abortSignal:u}){var c,d,p,h;let m=this.config.headers?await aS(this.config.headers):void 0;try{let{responseHeaders:f,value:g}=await aw({url:this.getUrl(),headers:re(m,null!=l?l:{},this.getModelConfigHeaders(),await aS(this.config.o11yHeaders)),body:{prompt:e,n:t,...r&&{size:r},...a&&{aspectRatio:a},...n&&{seed:n},...o&&{providerOptions:o},...i&&{files:i.map(e=>o9(e))},...s&&{mask:o9(s)}},successfulResponseHandler:aI(le),failedResponseHandler:aj({errorSchema:sX(),errorToMessage:e=>{var t;return null!=(t=eQ(e))?t:"unknown error"}}
75),...u&&{abortSignal:u},fetch:this.config.fetch});return{images:g.images,warnings:null!=(c=g.warnings)?c:[],providerMetadata:g.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:f},...null!=g.usage&&{usage:{inputTokens:null!=(d=g.usage.inputTokens)?d:void 0,outputTokens:null!=(p=g.usage.outputTokens)?p:void 0,totalTokens:null!=(h=g.usage.totalTokens)?h:void 0}}}}catch(e){throw await oN(e,await oz(null!=m?m:{}))}}getUrl(){return`${this.config.baseURL}/image-model`}getModelConfigHeaders(){return{"ai-image-model-specification-version":"4","ai-model-id":this.modelId}}};function o9(e){return"file"===e.type&&e.data instanceof Uint8Array?{...e,data:rl(e.data)}:e}var o6=sS({images:s0(sy()).optional()}).catchall(sy()),o8=sI("type",[sS({type:sO("unsupported"),feature:iQ(),details:iQ().optional()}),sS({type:sO("compatibility"),feature:iQ(),details:iQ().optional()}),sS({type:sO("deprecated"),setting:iQ(),message:iQ()}),sS({type:sO("other"),message:iQ()})]),o7=sS({inputTokens:sc().nullish(),outputTokens:sc().nullish(),totalTokens:sc().nullish()}),le=sS({images:s0(iQ()),warnings:s0(o8).optional(),providerMetadata:sR(iQ(),o6).optional(),usage:o7.optional()}),lt=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v4",this.maxVideosPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate(e){var t,r;let{headers:a,abortSignal:n}=e,i=this.config.headers?await aS(this.config.headers):void 0;try{let{responseHeaders:s,value:o}=await aw({url:this.getUrl(),headers:re(i,null!=a?a:{},this.getModelConfigHeaders(),await aS(this.config.o11yHeaders),{accept:"text/event-stream"}),body:this.buildRequestBody(e),successfulResponseHandler:async({response:e,url:t,requestBodyValues:r})=>{if(null==e.body)throw new eW({message:"SSE response body is empty",url:t,requestBodyValues:r,statusCode:e.status});let a=ab({stream:e.body,schema:ls}).getReader(),{done:n,value:i}=await a.read();if(a.releaseLock(),n||!i)throw new eW({message:"SSE stream ended without a data event",url:t,requestBodyValues:r,statusCode:e.status});if(!i.success)throw new eW({message:"Failed to parse video SSE event",cause:i.error,url:t,requestBodyValues:r,statusCode:e.status});let s=i.value;if("error"===s.type)throw new eW({message:s.message,statusCode:s.statusCode,url:t,requestBodyValues:r,responseHeaders:Object.fromEntries([...e.headers]),responseBody:JSON.stringify(s),data:{error:{message:s.message,type:s.errorType,param:s.param}}});return{value:{videos:s.videos,warnings:s.warnings,providerMetadata:s.providerMetadata},responseHeaders:Object.fromEntries([...e.headers])}},failedResponseHandler:aj({errorSchema:sX(),errorToMessage:e=>{var t;return null!=(t=eQ(e))?t:"unknown error"}}),...n&&{abortSignal:n},fetch:this.config.fetch});return{videos:o.videos,warnings:null!=(t=o.warnings)?t:[],providerMetadata:null!=(r=o.providerMetadata)?r:void 0,response:{timestamp:new Date,modelId:this.modelId,headers:s}}}catch(e){throw await oN(e,await oz(null!=i?i:{}))}}async handleWebhookOption({webhook:e}){let{url:t,received:r}=await e();return{webhookUrl:t,received:r}}async doStart(e){var t,r;let{headers:a,abortSignal:n,webhookUrl:i}=e,s=this.config.headers?await aS(this.config.headers):void 0;try{let{responseHeaders:o,value:l}=await aw({url:this.getStartUrl(),headers:re(s,null!=a?a:{},this.getModelConfigHeaders(),await aS(this.config.o11yHeaders)),body:{...this.buildRequestBody(e),...i&&{callbackUrl:i}},successfulResponseHandler:aI(lo),failedResponseHandler:aj({errorSchema:sX(),errorToMessage:e=>{var t;return null!=(t=eQ(e))?t:"unknown error"}}),...n&&{abortSignal:n},fetch:this.config.fetch});return{operation:l.operation,warnings:null!=(t=l.warnings)?t:[],providerMetadata:null!=(r=l.providerMetadata)?r:void 0,response:{timestamp:new Date,modelId:this.modelId,headers:o}}}catch(e){throw await oN(e,await oz(null!=s?s:{}))}}async doStatus({operation:e,abortSignal:t,headers:r}){var a,n,i,s,o,l;let u=this.config.headers?await aS(this.config.headers):void 0;try{let{responseHeaders:c,value:d}=await aw({url:this.getStatusUrl(),headers:re(u,null!=r?r:{},this.getModelConfigHeaders(),await aS(this.config.o11yHeaders)),body:{operation:e},successfulResponseHandler:aI(ll),failedResponseHandler:aj({errorSchema:sX(),errorToMessage:e=>{var t;return null!=(t=eQ(e))?t:"unknown error"}}
75),...t&&{abortSignal:t},fetch:this.config.fetch}),p={timestamp:new Date,modelId:this.modelId,headers:c};if("completed"===d.status)return{status:"completed",videos:d.videos,warnings:null!=(a=d.warnings)?a:[],providerMetadata:null!=(n=d.providerMetadata)?n:void 0,response:p};if("error"===d.status)return{status:"error",error:d.error,providerMetadata:null!=(i=d.providerMetadata)?i:void 0,response:p};if("cancelled"===d.status)return{status:"error",error:"Video generation was cancelled.",providerMetadata:null!=(s=d.providerMetadata)?s:void 0,response:p};return{status:"pending",warnings:null!=(o=d.warnings)?o:[],providerMetadata:null!=(l=d.providerMetadata)?l:void 0,response:p}}catch(e){throw await oN(e,await oz(null!=u?u:{}))}}buildRequestBody({prompt:e,n:t,aspectRatio:r,resolution:a,duration:n,fps:i,seed:s,generateAudio:o,image:l,frameImages:u,inputReferences:c,providerOptions:d}){return{prompt:e,n:t,...r&&{aspectRatio:r},...a&&{resolution:a},...n&&{duration:n},...i&&{fps:i},...s&&{seed:s},...void 0!==o&&{generateAudio:o},...d&&{providerOptions:d},...l&&{image:lr(l)},...u&&{frameImages:u.map(e=>({...e,image:lr(e.image)}))},...c&&{inputReferences:c.map(e=>lr(e))}}}getUrl(){return`${this.config.baseURL}/video-model`}getStartUrl(){return`${this.config.baseURL}/video-model/start`}getStatusUrl(){return`${this.config.baseURL}/video-model/status`}getModelConfigHeaders(){return{"ai-video-model-specification-version":"4","ai-model-id":this.modelId}}};function lr(e){return"file"===e.type&&e.data instanceof Uint8Array?{...e,data:rl(e.data)}:e}var la=sS({videos:s0(sy()).optional()}).catchall(sy()),ln=s2([sS({type:sO("url"),url:iQ(),mediaType:iQ()}),sS({type:sO("base64"),data:iQ(),mediaType:iQ()})]),li=sI("type",[sS({type:sO("unsupported"),feature:iQ(),details:iQ().optional()}),sS({type:sO("compatibility"),feature:iQ(),details:iQ().optional()}),sS({type:sO("deprecated"),setting:iQ(),message:iQ()}),sS({type:sO("other"),message:iQ()})]),ls=sI("type",[sS({type:sO("result"),videos:s0(ln),warnings:s0(li).optional(),providerMetadata:sR(iQ(),la).optional()}),sS({type:sO("error"),message:iQ(),errorType:iQ(),statusCode:sc(),param:sy().nullable()})]),lo=sS({operation:sy(),warnings:s0(li).nullish(),providerMetadata:sR(iQ(),la).nullish()}),ll=sI("status",[sS({status:sO("pending"),warnings:s0(li).nullish(),providerMetadata:sR(iQ(),la).nullish()}),sS({status:sO("completed"),videos:s0(ln),warnings:s0(li).nullish(),providerMetadata:sR(iQ(),la).nullish()}),sS({status:sO("error"),error:iQ(),providerMetadata:sR(iQ(),la).nullish()}),sS({status:sO("cancelled"),providerMetadata:sR(iQ(),la).nullish()})]),lu=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v4"}get provider(){return this.config.provider}async doRerank({documents:e,query:t,topN:r,headers:a,abortSignal:n,providerOptions:i}){var s;let o=this.config.headers?await aS(this.config.headers):void 0;try{let{responseHeaders:l,value:u,rawValue:c}=await aw({url:this.getUrl(),headers:re(o,null!=a?a:{},this.getModelConfigHeaders(),await aS(this.config.o11yHeaders)),body:{documents:e,query:t,...null!=r?{topN:r}:{},...i?{providerOptions:i}:{}},successfulResponseHandler:aI(ld),failedResponseHandler:aj({errorSchema:sX(),errorToMessage:e=>{var t;return null!=(t=eQ(e))?t:"unknown error"}}),...n&&{abortSignal:n},fetch:this.config.fetch});return{ranking:u.ranking,providerMetadata:u.providerMetadata,response:{headers:l,body:c},warnings:null!=(s=u.warnings)?s:[]}}catch(e){throw await oN(e,await oz(null!=o?o:{}))}}getUrl(){return`${this.config.baseURL}/reranking-model`}getModelConfigHeaders(){return{"ai-reranking-model-specification-version":"4","ai-model-id":this.modelId}}},lc=sI("type",[sS({type:sO("unsupported"),feature:iQ(),details:iQ().optional()}),sS({type:sO("compatibility"),feature:iQ(),details:iQ().optional()}),sS({type:sO("deprecated"),setting:iQ(),message:iQ()}),sS({type:sO("other"),message:iQ()})]),ld=ad(()=>am(sS({ranking:s0(sS({index:sc(),relevanceScore:sc()})),warnings:s0(lc).optional(),providerMetadata:sR(iQ(),sR(iQ(),sy())).optional()}))),lp=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v4"}get provider(){return this.config.provider}async doGenerate({text:e,voice:t,outputFormat:r,instructions:a,speed:n,language:i,providerOptions:s,headers:o,abortSignal:l}){var u;
75let c=this.config.headers?await aS(this.config.headers):void 0;try{let{responseHeaders:d,value:p,rawValue:h}=await aw({url:this.getUrl(),headers:re(c,null!=o?o:{},this.getModelConfigHeaders(),await aS(this.config.o11yHeaders)),body:{text:e,...t&&{voice:t},...r&&{outputFormat:r},...a&&{instructions:a},...null!=n&&{speed:n},...i&&{language:i},...s&&{providerOptions:s}},successfulResponseHandler:aI(lf),failedResponseHandler:aj({errorSchema:sX(),errorToMessage:e=>{var t;return null!=(t=eQ(e))?t:"unknown error"}}),...l&&{abortSignal:l},fetch:this.config.fetch});return{audio:p.audio,warnings:null!=(u=p.warnings)?u:[],providerMetadata:p.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:d,body:h}}}catch(e){throw await oN(e,await oz(null!=c?c:{}))}}getUrl(){return`${this.config.baseURL}/speech-model`}getModelConfigHeaders(){return{"ai-speech-model-specification-version":"4","ai-model-id":this.modelId}}},lh=sS({}).catchall(sy()),lm=sI("type",[sS({type:sO("unsupported"),feature:iQ(),details:iQ().optional()}),sS({type:sO("compatibility"),feature:iQ(),details:iQ().optional()}),sS({type:sO("deprecated"),setting:iQ(),message:iQ()}),sS({type:sO("other"),message:iQ()})]),lf=sS({audio:iQ(),warnings:s0(lm).optional(),providerMetadata:sR(iQ(),lh).optional()}),lg=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v4"}get provider(){return this.config.provider}async doGenerate({audio:e,mediaType:t,providerOptions:r,headers:a,abortSignal:n}){var i,s,o,l;let u=this.config.headers?await aS(this.config.headers):void 0;try{let{responseHeaders:c,value:d,rawValue:p}=await aw({url:this.getUrl(),headers:re(u,null!=a?a:{},this.getModelConfigHeaders(),await aS(this.config.o11yHeaders)),body:{audio:e instanceof Uint8Array?rl(e):e,mediaType:t,...r&&{providerOptions:r}},successfulResponseHandler:aI(lx),failedResponseHandler:aj({errorSchema:sX(),errorToMessage:e=>{var t;return null!=(t=eQ(e))?t:"unknown error"}}),...n&&{abortSignal:n},fetch:this.config.fetch});return{text:d.text,segments:null!=(i=d.segments)?i:[],language:null!=(s=d.language)?s:void 0,durationInSeconds:null!=(o=d.durationInSeconds)?o:void 0,warnings:null!=(l=d.warnings)?l:[],providerMetadata:d.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:c,body:p}}}catch(e){throw await oN(e,await oz(null!=u?u:{}))}}async doStream(e){var t,r,a,n,i;let s,o,l,u=null!=(a=null==(r=null==(t=this.config._internal)?void 0:t.currentDate)?void 0:r.call(t))?a:new Date,c=re(await aS(null!=(n=this.config.headers)?n:{}),null!=(i=e.headers)?i:{},this.getModelConfigHeaders(),await aS(this.config.o11yHeaders)),d=await oz(c),p={type:"transcription-stream.start",inputAudioFormat:e.inputAudioFormat,...null!=e.providerOptions&&{providerOptions:e.providerOptions},...null!=e.includeRawChunks&&{includeRawChunks:e.includeRawChunks}};return{stream:function({webSocket:e,url:t,protocols:r,headers:a,startFrame:n,audio:i,abortSignal:s,authMethod:o}){let l=!1,u=()=>{};return new ReadableStream({start:c=>{let d,p,h,m=!1,f=!1;u=e=>{null!=d?d.cancel().catch(()=>{}):i.cancel().catch(()=>{}),null==h||h.close(e)};let g=e=>{l||(l=!0,u(),lw(c,e,o))},v=async e=>{let t=i.getReader();d=t;try{for(;;){let{done:r,value:a}=await t.read();if(r||l)break;let n="string"==typeof a?function(e){let t=ro(e.replace(/-/g,"+").replace(/_/g,"/"));return Uint8Array.from(t,e=>e.codePointAt(0))}(a):a;for(let t=0;t<n.length&&!l;t+=65536)e.send(n.subarray(t,t+65536)),await ri(e)}}finally{t.releaseLock(),d===t&&(d=void 0)}l||f||e.send(JSON.stringify({type:"transcription-stream.audio-done"}))};h=function({url:e,protocols:t,headers:r,webSocket:a,abortSignal:n,onOpen:i,onMessageText:s,onProcessingError:o,onSocketError:l,onClose:u,onAbort:c}){var d,p;let h,m,f=e=>{null!=m&&(null==n||n.removeEventListener("abort",m),m=void 0);try{null==h||h.close(e)}catch(e){}};if(null==n?void 0:n.aborted)return null==c||c(null!=(d=n.reason)?d:Error("Aborted")),{socket:void 0,close:f};try{h=new(function(e){let t=null!=e?e:globalThis.WebSocket;if(null==t)throw Error("No WebSocket implementation available.");return t}(a))(e,t,{headers:(p=null!=r?r:{},Object.fromEntries(Object.entries(p).filter(([e,t])=>null!=t)))})}catch(e){return o(e),{socket:void 0,close:f}}null!=n&&null!=c&&(m=()=>{var e;return c(null!=(e=n.reason)?e:Error("Aborted"))},n.addEventListener("abort",m,{once:!0}));let g=h;h.onopen=()=>{try{null==i||i(g)}catch(e){o(e)}};let v=Promise.resolve();return h.onmessage=e=>{v=v.then(()=>rn(e.data)).then(e=>s(e)).catch(o)},h.onerror=()=>{v=v.then(()=>null==l?void 0:l()).catch(o)}
75,h.onclose=e=>{let t="number"==typeof(null==e?void 0:e.code)?e.code:void 0,r="string"==typeof(null==e?void 0:e.reason)?e.reason:void 0;v=v.then(()=>null==u?void 0:u({code:t,reason:r})).catch(o)},{socket:h,close:f}}({url:t,protocols:r,headers:a,webSocket:e,abortSignal:s,onAbort:e=>{l||(l=!0,u(),c.error(e))},onProcessingError:g,onOpen:e=>{e.send(JSON.stringify(n)),v(e).catch(g)},onMessageText:e=>{if(l)return;let t=function(e){let t;try{t=rq(e)}catch(e){return}if(null==t||"object"!=typeof t||Array.isArray(t))return;let r=t;switch(r.type){case"stream-start":return Array.isArray(r.warnings)&&r.warnings.every(aU)?r:void 0;case"transcript-delta":return aP(r.delta)&&aD(r.id,aP)&&aD(r.providerMetadata,rU)?r:void 0;case"transcript-partial":return aP(r.text)&&aD(r.id,aP)&&aD(r.startSecond,a$)&&aD(r.durationInSeconds,a$)&&aD(r.channelIndex,a$)&&aD(r.providerMetadata,rU)?r:void 0;case"transcript-final":return aP(r.text)&&aD(r.id,aP)&&aD(r.startSecond,a$)&&aD(r.endSecond,a$)&&aD(r.channelIndex,a$)&&aD(r.providerMetadata,rU)?r:void 0;case"finish":return aP(r.text)&&Array.isArray(r.segments)&&r.segments.every(aL)&&aD(r.language,aP)&&aD(r.durationInSeconds,a$)&&aD(r.providerMetadata,rU)?r:void 0;case"response-metadata":{if(!(aD(r.modelId,aP)&&aD(r.headers,rU)))return;let e=r.timestamp;if(null==e)return{...r,timestamp:void 0};if("string"!=typeof e)return;let t=new Date(e);return Number.isNaN(t.getTime())?void 0:{...r,timestamp:t}}case"raw":return"rawValue"in r?r:void 0;case"error":return"error"in r?r:void 0;default:return}}(e);if(null!=t){if("finish"===t.type){l=!0,c.enqueue(t),c.close(),u(1e3);return}"error"===t.type&&(m=!0,p=t.error,f=!0,null!=d?(d.cancel().catch(()=>{}),d=void 0):i.cancel().catch(()=>{})),c.enqueue(t)}},onSocketError:()=>{g(Error("Connection error on AI Gateway transcription stream"))},onClose:()=>{if(m){if(l)return;lk(p,o).then(g);return}g(Error("AI Gateway transcription stream closed before a finish part was received"))}})},cancel:()=>{l||(l=!0,u())}})}({webSocket:this.config.webSocket,url:lv(this.config.baseURL,this.modelId),protocols:null==(l=(null==(o=(s=rg(c)).authorization)?void 0:o.startsWith("Bearer "))?o.slice(7):void 0)?[sK]:sQ(sK,l,{teamIdOrSlug:s[oA]}),headers:c,startFrame:p,audio:e.audio,abortSignal:e.abortSignal,authMethod:d}),request:{body:p},response:{timestamp:u,modelId:this.modelId}}}getUrl(){return`${this.config.baseURL}/transcription-model`}getModelConfigHeaders(){return{"ai-transcription-model-specification-version":"4","ai-model-id":this.modelId}}};function lv(e,t){let r=new URL(`${e.replace(/^http/,"ws")}/transcription-model`);return r.searchParams.set("ai-model-id",t),r.toString()}var ly=sS({}).catchall(sy()),lb=sI("type",[sS({type:sO("unsupported"),feature:iQ(),details:iQ().optional()}),sS({type:sO("compatibility"),feature:iQ(),details:iQ().optional()}),sS({type:sO("deprecated"),setting:iQ(),message:iQ()}),sS({type:sO("other"),message:iQ()})]),lx=sS({text:iQ(),segments:s0(sS({text:iQ(),startSecond:sc(),endSecond:sc()})).optional(),language:iQ().nullish(),durationInSeconds:sc().nullish(),warnings:s0(lb).optional(),providerMetadata:sR(iQ(),ly).optional()});async function lw(e,t,r){e.error(await oN(t,r))}var l_={authentication_error:401,failed_dependency:424,forbidden:403,internal_server_error:500,invalid_request_error:400,model_not_found:404,rate_limit_exceeded:429};async function lk(e,t){return"object"==typeof e&&null!=e&&"message"in e&&"string"==typeof e.message&&"type"in e&&"string"==typeof e.type&&e.type in l_?oS({response:{error:{message:e.message,type:e.type}},statusCode:l_[e.type],authMethod:t}):Error(`AI Gateway transcription stream failed: ${null!=e&&"object"==typeof e&&"message"in e&&"string"==typeof e.message?e.message:eQ(e)}`)}var lS=class{constructor(e,t){this.specificationVersion="v4",this.modelId=e,this.provider=t.provider,this.config=t}async doCreateClientSecret(e){var t,r;let a,n=await this.config.createClientSecret({modelId:this.modelId,...(null==e?void 0:e.expiresAfterSeconds)!=null&&{expiresAfterSeconds:e.expiresAfterSeconds}});return{token:n.token,url:(t=this.config.baseURL,r=this.modelId,(a=new URL(`${t.replace(/^http/,"ws")}/realtime-model`)).searchParams.set("ai-model-id",r),a.toString()),...null!=n.expiresAt&&{expiresAt:n.expiresAt}}}getWebSocketConfig(e){return{url:e.url,protocols:sQ("ai-gateway-realtime.v1",e.token,{teamIdOrSlug:this.config.teamIdOrSlug})}}parseServerEvent(e){return e}serializeClientEvent(e){return e}buildSessionConfig(e){return e}},lE=ak({id:"gateway.exa_search",inputSchema:ad(()=>am(sS({query:iQ().describe("Natural-language web search query. This is required."),type:s1(["auto","fast","instant"]).optional().describe("Search method. Use auto for the default balance of speed and quality."),num_results:sc().optional().describe("Maximum number of results to return (1-100, default: 10)."),category:s1(["company","people","research paper","news","personal site","financial report"]).optional().describe("Optional content category to focus results."),user_location:iQ().optional().describe("Two-letter ISO country code such as 'US'."),include_domains:s0(iQ()).optional().describe("Only return results from these domains."),exclude_domains:s0(iQ()).optional().describe("Exclude results from these domains."),start_published_date:iQ().optional().describe("Only return links published after this ISO 8601 date."),end_published_date:iQ().optional().describe("Only return links published before this ISO 8601 date."),contents:sS({text:s2([sm(),sS({max_characters:sc().optional(),include_html_tags:sm().optional(),verbosity:s1(["compact","standard","full"]).optional(),include_sections:s0(s1(["header","navigation","banner","body","sidebar","footer","metadata"])).optional(),exclude_sections:s0(s1(["header","navigation","banner","body","sidebar","footer","metadata"])).optional()})]).optional(),highlights:s2([sm(),sS({query:iQ().optional(),max_characters:sc().optional()})]).optional(),max_age_hours:sc().optional(),livecrawl_timeout:sc().optional(),subpages:sc().optional(),subpage_target:s2([iQ(),s0(iQ())]).optional(),extras:sS({links:sc().optional(),image_links:sc().optional()}).optional()}).optional().describe("Controls extracted page content and freshness.")}
vendor: 5,092 bytes, line 75
75))),outputSchema:ad(()=>am(s2([sS({requestId:iQ(),searchType:iQ().optional(),resolvedSearchType:iQ().optional(),results:s0(sS({title:iQ(),url:iQ(),id:iQ(),publishedDate:iQ().nullable().optional(),author:iQ().nullable().optional(),image:iQ().nullable().optional(),favicon:iQ().nullable().optional(),text:iQ().optional(),highlights:s0(iQ()).optional(),highlightScores:s0(sc()).optional(),summary:iQ().optional(),subpages:s0(sX()).optional(),extras:sS({links:s0(iQ()).optional(),imageLinks:s0(iQ()).optional()}).optional()})),costDollars:sS({total:sc().optional(),search:sR(iQ(),sc()).optional()}).optional()}),sS({error:s1(["api_error","rate_limit","timeout","invalid_input","configuration_error","execution_error","unknown"]),statusCode:sc().optional(),message:iQ()})])))}),lC=ak({id:"gateway.parallel_search",inputSchema:ad(()=>am(sS({objective:iQ().describe("Natural-language description of the web research goal, including source or freshness guidance and broader context from the task. Maximum 5000 characters."),search_queries:s0(iQ()).optional().describe("Optional search queries to supplement the objective. Maximum 200 characters per query."),mode:s1(["one-shot","agentic"]).optional().describe('Mode preset: "one-shot" for comprehensive results with longer excerpts (default), "agentic" for concise, token-efficient results for multi-step workflows.'),max_results:sc().optional().describe("Maximum number of results to return (1-20). Defaults to 10 if not specified."),source_policy:sS({include_domains:s0(iQ()).optional().describe("Limit results to these domains. Use plain domain names only — e.g. example.com or sub.example.gov, or a bare extension like .edu. Do not include a scheme, path, or port (e.g. not https://example.com/page)."),exclude_domains:s0(iQ()).optional().describe("Exclude results from these domains. Use plain domain names only — e.g. example.com or sub.example.gov, or a bare extension like .edu. Do not include a scheme, path, or port (e.g. not https://example.com/page)."),after_date:iQ().optional().describe("Only include results published after this date. Use an ISO 8601 calendar date formatted YYYY-MM-DD (e.g. 2025-01-01); do not include a time.")}).optional().describe("Source policy for controlling which domains to include/exclude and freshness."),excerpts:sS({max_chars_per_result:sc().optional().describe("Maximum characters per result."),max_chars_total:sc().optional().describe("Maximum total characters across all results.")}).optional().describe("Excerpt configuration for controlling result length."),fetch_policy:sS({max_age_seconds:sc().optional().describe("Maximum age in seconds for cached content. Set to 0 to always fetch fresh content.")}).optional().describe("Fetch policy for controlling content freshness.")}))),outputSchema:ad(()=>am(s2([sS({searchId:iQ(),results:s0(sS({url:iQ(),title:iQ(),excerpt:iQ(),publishDate:iQ().nullable().optional(),relevanceScore:sc().optional()}))}),sS({error:s1(["api_error","rate_limit","timeout","invalid_input","configuration_error","unknown"]),statusCode:sc().optional(),message:iQ()})])))}),lj=ak({id:"gateway.perplexity_search",inputSchema:ad(()=>am(sS({query:s2([iQ(),s0(iQ())]).describe("Search query (string) or multiple queries (array of up to 5 strings). Multi-query searches return combined results from all queries."),max_results:sc().optional().describe("Maximum number of search results to return (1-20, default: 10)"),max_tokens_per_page:sc().optional().describe("Maximum number of tokens to extract per search result page (256-2048, default: 2048)"),max_tokens:sc().optional().describe("Maximum total tokens across all search results (default: 25000, max: 1000000)"),country:iQ().optional().describe("Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')"),search_domain_filter:s0(iQ()).optional().describe("List of domains to include or exclude from search results (max 20). To include: ['nature.com', 'science.org']. To exclude: ['-example.com', '-spam.net']"),search_language_filter:s0(iQ()).optional().describe("List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']"),search_after_date:iQ().optional().describe("Include only results published after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),search_before_date:iQ().optional().describe("Include only results published before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),last_updated_after_filter:iQ().optional().describe("Include only results last updated after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),last_updated_before_filter:iQ().optional().describe("Include only results last updated before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),search_recency_filter:s1(["day","week","month","year"]).optional().describe("Filter results by relative time period. Cannot be used with search_after_date or search_before_date.")}
75))),outputSchema:ad(()=>am(s2([sS({results:s0(sS({title:iQ(),url:iQ(),snippet:iQ(),date:iQ().optional(),lastUpdated:iQ().optional()})),id:iQ()}),sS({error:s1(["api_error","rate_limit","timeout","invalid_input","unknown"]),statusCode:sc().optional(),message:iQ()})])))}),lI=sS({count:sc().optional().describe("Maximum number of data results to return (1-20). When include_contents is true, each additional result adds its own data surcharge."),include_contents:sm().optional().describe("Inline rows for each data result. This adds a data surcharge based on row count and dataset source. To estimate cost, search with include_contents disabled and inspect cards.content.export_pricing. This applies to every returned card; limit sources.data.count and sources.data.max_rows to control cost."),mode:s1(["inline","url"]).optional().describe("Requested data delivery mode. Search card data is always inline."),content_format:s1(["card_json","csv","json_compact","json_records"]).optional().describe("Serialization for inlined card data."),max_rows:sc().optional().describe("Maximum rows to inline per result. Omit to use the allowance in cards.content.export_pricing. A data surcharge applies per 1,000 exported rows; lower values reduce cost."),node_ids:s0(iQ()).optional().describe("Data Graph node IDs to prioritize. Maximum 20."),strict:sm().optional().describe("Only return cards matching node_ids. Requires a non-empty node_ids.")}),lT=sS({count:sc().optional().describe("Maximum number of web results to return (1-20)."),include_contents:sm().optional().describe("Inline extracted web page text. This can add a data charge."),category:s1(["finance","news","sports"]).optional().describe("Optional web-result category filter."),include_domains:s0(iQ()).optional().describe("Only return results from these bare domains."),exclude_domains:s0(iQ()).optional().describe("Exclude results from these bare domains."),snippet_max_chars:sc().optional().describe("Maximum characters in each web-result snippet."),highlights:sm().optional().describe("Include highlighted passages in web results. Defaults to true in AI Gateway."),article_content_max_chars:sc().optional().describe("Maximum extracted characters per web page when including contents."),published_after:iQ().optional().describe("Keep results published on or after this ISO date (YYYY-MM-DD)."),published_before:iQ().optional().describe("Keep results published on or before this ISO date (YYYY-MM-DD).")}),lN=ad(()=>am(sS({query:iQ().describe('Natural-language search query. Include the entity, metric, and time period. Quote a phrase to force it to one entity, for example "Tesla":PRODUCT price.'),effort:s1(["deep","fast","instant"]).optional().describe("Search effort. fast is the balanced default, instant favors cached results and low latency, and deep broadens retrieval with reranking at higher cost and latency."),sources:sS({data:lI.optional(),web:lT.optional()}).optional().describe("Sources to search. Omit to search both curated data and the web. When provided, only keys present are searched."),location:sS({latitude:sc().describe("Latitude between -90 and 90."),longitude:sc().describe("Longitude between -180 and 180.")}).optional().describe("End-user coordinates for localized results."),country_code:iQ().optional().describe("Two-letter ISO 3166-1 country code, such as 'US'."),locale:iQ().optional().describe("BCP-47 locale, such as 'en-US'."),timezone:iQ().optional().describe("IANA timezone, such as 'America/New_York'."),output_settings:sS({image_dark_mode:sm().optional().describe("Render card preview images in dark mode."),force_refresh:sm().optional().describe("Instant-effort only. Request a refreshed instant result.")}).optional().describe("Controls card rendering in the search response."),include_related:sc().optional().describe("Maximum related search suggestions to include (1-20).")}))),lR=s2([sm(),sc(),iQ()]).nullable(),lA=sS({content_format:s1(["card_json","csv","json_compact","json_records"]).nullish(),cost:sc().optional(),data:iQ().nullish(),records:s0(sR(iQ(),lR)).nullish(),dataset:sS({columns:s0(sS({name:iQ(),type:s1(["boolean","date","datetime","number","string"]),unit:iQ().nullish()})),rows:s0(s0(lR)),total_rows:sc(),truncated:sm(),ref:iQ(),sources:s0(sS({name:iQ(),index:s1(["data","web"]).optional()})),provenance:s1(["query","web_extraction"]).optional()}).nullish(),card_data:sS({}).passthrough().nullish(),card_data_schema:sS({}).passthrough().nullish(),url:iQ().nullish(),expires_at:iQ().nullish(),total_rows:sc().nullish(),truncated:sm().optional(),export_pricing:sS({baseline_usd:sc(),free_rows:sc(),max_rows_ceiling:sc(),row_cpm_usd:sc()}).nullish(),manifest:s0(sS({dtype:s1(["boolean","date","datetime","number","string"]).nullish(),entity:iQ().nullish(),metric:iQ().nullish(),name:iQ().nullish(),unit:iQ().nullish()})).nullish()}).passthrough(),lz=sS({card_id:iQ().nullish(),title:iQ().nullish(),description:iQ().nullish(),semantic_description:iQ().nullish(),webpage_url:iQ().nullish(),image_url:iQ().nullish(),embed_url:iQ().nullish(),sources:s0(sS({source_name:iQ().nullish(),source_description:iQ().nullish(),source_index:s1(["data","web"]),source_text:iQ().nullish(),url:iQ().nullish()})).nullish(),methodologies:s0(sS({methodology_name:iQ().nullable(),methodology_description:iQ().nullable()})).nullish(),source_indexes:s0(s1(["data","web"])).nullish(),card_type:iQ().nullish(),relevance:s1(["High","Low","Medium"]).nullish(),content:lA.nullish(),exportable:sm().optional(),nodes:s0(sS({id:iQ(),type:s1(["entity","metric"]),name:iQ(),description:iQ().nullish()})).nullish(),metric_definitions:s0(sS({name:iQ(),definition:iQ()})).nullish(),data_freshness:sS({coverage_end:iQ().nullish(),data_as_of:iQ().nullish(),last_updated:iQ().nullish()}).nullish()}).passthrough(),lM=sS({title:iQ(),url:iQ(),snippet:iQ().nullish(),source_name:iQ().nullish(),publish_date:iQ().nullish(),content:lA.nullish()}).passthrough(),lO=ak({id:"gateway.tako_search",inputSchema:lN,outputSc
75hema:ad(()=>am(s2([sS({request_id:iQ(),cards:s0(lz).optional(),web_results:s0(lM).optional(),usage:sS({total_cost_usd:sc(),compute:sS({cost_usd:sc()}).nullish(),data:sS({cost_usd:sc(),datasets:sc()}).nullish()}).nullish(),related:s0(sS({}).passthrough()).nullish()}).passthrough(),sS({error:s1(["api_error","configuration_error","execution_error","invalid_input","rate_limit","timeout","unknown_tool"]),statusCode:sc().optional(),message:iQ()})])))}),lP={exaSearch:(e={})=>lE(e),parallelSearch:(e={})=>lC(e),perplexitySearch:(e={})=>lj(e),takoSearch:(e={})=>lO(e)};async function l$(){var e;return null==(e=(0,sJ.getContext)().headers)?void 0:e["x-vercel-id"]}var lD=sS({token:iQ(),expiresAt:sc().nullish()});async function lU(e){let t=rL({settingValue:e.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});return t?{token:t,authMethod:"api-key"}:{token:await (0,sJ.getVercelOidcToken)(),authMethod:"oidc"}}!function(e={}){var t,r,a;let n=null,i=null,s=null!=(t=e.metadataCacheRefreshMillis)?t:3e5,o=0,l=null!=(r=null==(a=e.baseURL)?void 0:a.replace(/\/$/,""))?r:"https://ai-gateway.vercel.sh/v4/ai",u=t=>rv({Authorization:`Bearer ${t.token}`,"ai-gateway-protocol-version":"0.0.1",[oR]:t.authMethod,...null!=e.teamIdOrSlug?{[oA]:e.teamIdOrSlug}:{},...e.headers},"ai-sdk/gateway/4.0.75"),c=async()=>{try{return u(await lU(e))}catch(e){throw s6.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401,cause:e})}},d=async()=>{try{return await lU(e)}catch(e){throw s6.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401,cause:e})}},p=async t=>{if(void 0!==globalThis.window)throw Error("AI Gateway client secrets must be minted server-side: minting needs your Gateway credential, which must never reach the browser. Call gateway.experimental_realtime.getToken() or gateway.experimental_transcription.getToken() from your server and pass the returned token to the client.");let r=u(await d()),a=new URL("/v1/realtime/client-secrets",l).toString();try{let{value:n}=await aw({url:a,headers:r,body:{model:t.modelId,...null!=t.routeKind&&{routeKind:t.routeKind},...null!=t.expiresAfterSeconds&&{expiresIn:t.expiresAfterSeconds}},successfulResponseHandler:aI(lD),failedResponseHandler:aj({errorSchema:sX(),errorToMessage:e=>{var t;return null!=(t=eQ(e))?t:"unknown error"}}),fetch:e.fetch});return{token:n.token,...null!=n.expiresAt&&{expiresAt:n.expiresAt}}}catch(e){throw await oN(e,await oz(r))}},h=()=>{let e=rL({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),t=rL({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),r=rL({settingValue:void 0,environmentVariableName:"VERCEL_REGION"}),a=rL({settingValue:void 0,environmentVariableName:"VERCEL_PROJECT_ID"});return async()=>{let n=await l$();return{...e&&{"ai-o11y-deployment-id":e},...t&&{"ai-o11y-environment":t},...r&&{"ai-o11y-region":r},...n&&{"ai-o11y-request-id":n},...a&&{"ai-o11y-project-id":a}}}},m=t=>new oq(t,{provider:"gateway",baseURL:l,headers:c,fetch:e.fetch,o11yHeaders:h()}),f=async()=>{var t,r,a;let u=null!=(a=null==(r=null==(t=e._internal)?void 0:t.currentDate)?void 0:r.call(t).getTime())?a:Date.now();return(!n||u-o>s)&&(o=u,n=new oP({baseURL:l,headers:c,fetch:e.fetch}).getAvailableModels().then(e=>(i=e,e)).catch(async e=>{throw await oN(e,await oz(await c()))})),i?Promise.resolve(i):n},g=async()=>new oP({baseURL:l,headers:c,fetch:e.fetch}).getCredits().catch(async e=>{throw await oN(e,await oz(await c()))}),v=async t=>new oU({baseURL:l,headers:c,fetch:e.fetch}).getSpendReport(t).catch(async e=>{throw await oN(e,await oz(await c()))}),y=async t=>new oF({baseURL:l,headers:c,fetch:e.fetch}).getGenerationInfo(t).catch(async e=>{throw await oN(e,await oz(await c()))}),b=function(e){if(new.target)throw Error("The Gateway Provider model function cannot be called with the new keyword.");return m(e)};b.specificationVersion="v4",b.getAvailableModels=f,b.getCredits=g,b.getSpendReport=v,b.getGenerationInfo=y,b.imageModel=t=>new o3(t,{provider:"gateway",baseURL:l,headers:c,fetch:e.fetch,o11yHeaders:h()}),b.languageModel=m;let x=t=>new o2(t,{provider:"gateway",baseURL:l,headers:c,fetch:e.fetch,o11yHeaders:h()});b.embeddingModel=x,b.textEmbeddingModel=x,b.videoModel=t=>new lt(t,{provider:"gateway",baseURL:l,headers:c,fetch:e.fetch,o11yHeaders:h()});let w=t=>new lu(t,{provider:"gateway",baseURL:l,headers:c,fetch:e.fetch,o11yHeaders:h()});b.rerankingModel=w,b.reranking=w;let _=t=>new lp(t,{provider:"gateway",baseURL:l,headers:c,fetch:e.fetch,o11yHeaders:h()});b.speechModel=_,b.speech=_;let k=t=>new lg(t,{provider:"gateway",baseURL:l,headers:c,fetch:e.fetch,o11yHeaders:h(),webSocket:e.webSocket});b.transcriptionModel=k,b.transcription=k,b.experimental_transcription=Object.assign(e=>k(e),{getToken:async e=>{let t=await p({modelId:e.model,routeKind:"transcription",...null!=e.expiresAfterSeconds&&{expiresAfterSeconds:e.expiresAfterSeconds}});return{token:t.token,url:lv(l,e.model),...null!=t.expiresAt&&{expiresAt:t.expiresAt}}}});let S=t=>new lS(t,{provider:"gateway.realtime",baseURL:l,teamIdOrSlug:e.teamIdOrSlug,createClientSecret:p});b.experimental_realtime=Object.assign(e=>S(e),{getToken:async e=>{let{model:t,...r}=e,a=S(t),n=await a.doCreateClientSecret(r);return{token:n.token,url:n.url,...null!=n.expiresAt&&{expiresAt:n.expiresAt}}}}),b.chat=b.languageModel,b.embedding=b.embeddingModel,b.image=b.imageModel,b.video=b.videoModel,b.tools=lP}();var lL=Object.defineProperty,lF="AI_InvalidArgumentError",lZ=`vercel.ai.error.${lF}`,lB=Symbol.for(lZ),lH=class extends(B=eB,Z=lB,B){constructor({parameter:e,value:t,message:r}){super({name:lF,message:`Invalid argument for parameter ${e}: ${r}`}),this[Z]=!0,this.parameter=e,this.value=t}static isInstance(e){return eB.hasMarker(e,lZ)}},lq=Symbol.for("vercel.ai.error.AI_InvalidStreamPartError");Symbol.for("vercel.ai.error.AI_InvalidToolApprovalError");Symbol.for("vercel.ai.error.AI_InvalidToolApprovalSignatureError");Symbol.for("vercel.ai.error.AI_InvalidToolInputError");Symbol.for("vercel.ai.error.AI_ToolCallNotFoundForApprovalError");Symbol.for("vercel.ai.error.AI_MissingToolResultsError");Symbol.for("vercel.ai.error.AI_NoImageGeneratedError");var lV="AI_NoObjectGeneratedError",lW=`vercel.ai.error.${lV}`,lG=Symbol.for(lW),lY=class extends(q=eB,H=lG,q){constructor({message:e="No object generated.",cause:t,text:r,response:a,usage:n,finishReason:i}){super({name:lV,message:e,cause:t}),this[H]=!0,this.text=r,this.response=a,this.usage=n,this.finishReason=i}static isInstance(e){return eB.hasMarker(e,lW)}},lJ=Symbol.for("vercel.ai.error.AI_NoOutputGeneratedError");Symbol.for("vercel.ai.error.AI_NoSpeechGeneratedError");Symbol.for("vercel.ai.error.AI_NoTranscriptGeneratedError");Symbol.for("vercel.ai.error.AI_NoTranslationGeneratedError");Symbol.for("vercel.ai.error.AI_NoVideoGeneratedError");Symbol.for("vercel.ai.error.AI_NoSuchToolError");Symbol.for("vercel.ai.error.AI_StreamProviderError");Symbol.for("vercel.ai.error.AI_ToolCallRepairError");Symbol.for("vercel.ai.error.AI_ToolChoiceViolationError");var lK="AI_UIMessageStreamError",lQ=`vercel.ai.error.${lK}`,lX=Symbol.for(lQ),l0=class extends(W=eB,V=lX,W){constructor({chunkType:e,chunkId:t,message:r}){super({name:lK,message:r}),this[V]=!0,this.chunkType=e,this.chunkId=t}static isInstance(e){return eB.hasMarker(e,lQ)}},l1=Symbol.for("vercel.ai.error.AI_InvalidDataContentError");Symbol.for("vercel.ai.error.AI_InvalidMessageRoleError");Symbol.for("vercel.ai.error.AI_MessageConversionError");Symbol.for("vercel.ai.error.AI_RetryError");var l2=async({url:e,maxBytes:t,abortSignal:r})=>{var a;let n=e.toString();try{let e=rv({},"ai-sdk/7.0.93",rc()),i=await rM({url:n,headers:e,abortSignal:r});if(!i.ok)throw await ry(i),new r_({url:n,statusCode:i.status,statusText:i.statusText});return{data:await rO({response:i,url:n,maxBytes:null!=t?t:0x80000000}),mediaType:null!=(a=i.headers.get("content-type"))?a:void 0}}catch(e){if(r_.isInstance(e))throw e;throw new r_({url:n,cause:e})}},l5=s_,l4=function(e,t){var r;let a;return r=e??(()=>!0),(a=tN(t)).abort??(a.abort=!0),new sY({type:"custom",check:"custom",fn:r,...a})},l3=sz,l9=function(e,t={error:`Input not instance of ${e.name}`}){let r=new sY({type:"custom",check:"custom",fn:t=>t instanceof e,abort:!0,...iH.normalizeParams(t)});return r._zod.bag.Class=e,r},l6=function(e,t){return new sk({type:"object",get shape(){return iH.assignProp(this,"shape",{...e}),this.shape},catchall:sy(),...iH.normalizeParams(t)})},l8=sC,l7=new sG({type:"lazy",getter:()=>l8([new sf({type:"null",...tN(void 0)}),iQ(),sc(),sm(),sR(iQ(),l7.optional()),l5(l7)])}
75),ue=sR(iQ(),sR(iQ(),l7.optional())),ut=l8([iQ(),l9(Uint8Array),l9(ArrayBuffer),l4(function(e){var t,r;return null!=(r=null==(t=globalThis.Buffer)?void 0:t.isBuffer(e))&&r},{message:"Must be a Buffer"})]),ur=sR(iQ(),iQ()),ua=sS({type:sO("text"),text:iQ(),providerOptions:ue.optional()}),un=sS({type:sO("image"),image:l8([ut,l9(URL),ur]),mediaType:iQ().optional(),providerOptions:ue.optional()}),ui=sI("type",[sS({type:sO("data"),data:ut}),sS({type:sO("url"),url:l9(URL)}),sS({type:sO("reference"),reference:ur}),sS({type:sO("text"),text:iQ()})]),us=sI("type",[sS({type:sO("data"),data:ut}),sS({type:sO("url"),url:l9(URL)})]),uo=sS({type:sO("file"),data:l8([ui,ut,l9(URL),ur]),filename:iQ().optional(),mediaType:iQ(),providerOptions:ue.optional()}),ul=sS({type:sO("reasoning"),text:iQ(),providerOptions:ue.optional()}),uu=sS({type:sO("custom"),kind:iQ().transform(e=>e),providerOptions:ue.optional()}),uc=sS({type:sO("reasoning-file"),data:l8([us,ut,l9(URL)]),mediaType:iQ(),providerOptions:ue.optional()}),ud=sS({type:sO("tool-call"),toolCallId:iQ(),toolName:iQ(),input:sy(),providerOptions:ue.optional(),providerExecuted:sm().optional()}),up=sI("type",[sS({type:sO("text"),value:iQ(),providerOptions:ue.optional()}),sS({type:sO("json"),value:l7,providerOptions:ue.optional()}),sS({type:sO("execution-denied"),reason:iQ().optional(),providerOptions:ue.optional()}),sS({type:sO("error-text"),value:iQ(),providerOptions:ue.optional()}),sS({type:sO("error-json"),value:l7,providerOptions:ue.optional()}),sS({type:sO("content"),value:l5(l8([sS({type:sO("text"),text:iQ(),providerOptions:ue.optional()}),sS({type:sO("file"),data:ui,mediaType:iQ(),filename:iQ().optional(),providerOptions:ue.optional()}),sS({type:sO("file-data"),data:iQ(),mediaType:iQ(),filename:iQ().optional(),providerOptions:ue.optional()}),sS({type:sO("file-url"),url:iQ(),mediaType:iQ().optional(),providerOptions:ue.optional()}),sS({type:sO("file-id"),fileId:l8([iQ(),sR(iQ(),iQ())]),providerOptions:ue.optional()}),sS({type:sO("file-reference"),providerReference:sR(iQ(),iQ()),providerOptions:ue.optional()}),sS({type:sO("image-data"),data:iQ(),mediaType:iQ(),providerOptions:ue.optional()}),sS({type:sO("image-url"),url:iQ(),providerOptions:ue.optional()}),sS({type:sO("image-file-id"),fileId:l8([iQ(),sR(iQ(),iQ())]),providerOptions:ue.optional()}),sS({type:sO("image-file-reference"),providerReference:sR(iQ(),iQ()),providerOptions:ue.optional()}),sS({type:sO("custom"),providerOptions:ue.optional()})]))})]),uh=sS({type:sO("tool-result"),toolCallId:iQ(),toolName:iQ(),output:up,providerOptions:ue.optional()}),um=sS({type:sO("tool-approval-request"),approvalId:iQ(),toolCallId:iQ(),reason:iQ().optional()}),uf=sS({type:sO("tool-approval-response"),approvalId:iQ(),approved:sm(),reason:iQ().optional()}),ug=sS({role:sO("system"),content:iQ(),providerOptions:ue.optional()}),uv=sS({role:sO("user"),content:l8([iQ(),l5(l8([ua,un,uo]))]),providerOptions:ue.optional()}),uy=sS({role:sO("assistant"),content:l8([iQ(),l5(l8([ua,uu,uo,ul,uc,ud,uh,um]))]),providerOptions:ue.optional()}),ub=sS({role:sO("tool"),content:l5(l8([uh,uf])),providerOptions:ue.optional()});l8([ug,uv,uy,ub]);var ux={},uw={array:()=>uC,choice:()=>uT,json:()=>uN,object:()=>uE,text:()=>uS};for(var u_ in uw)lL(ux,u_,{get:uw[u_],enumerable:!0});async function uk(e){if(void 0===e)return{value:void 0,state:"undefined-input"};let t=await ay({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await ay({text:function(e){let t=["ROOT"],r=-1,a=null,n=0;function i(e,n,i){switch(e){case'"':r=n,t.pop(),t.push(i),t.push("INSIDE_STRING");break;case"f":case"t":case"n":r=n,a=n,t.pop(),t.push(i),t.push("INSIDE_LITERAL");break;case"-":t.pop(),t.push(i),t.push("INSIDE_NUMBER");break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":r=n,t.pop(),t.push(i),t.push("INSIDE_NUMBER");break;case"{":r=n,t.pop(),t.push(i),t.push("INSIDE_OBJECT_START");break;case"[":r=n,t.pop(),t.push(i),t.push("INSIDE_ARRAY_START")}}function s(e,a){switch(e){case",":t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break;case"}":r=a,t.pop()}}function o(e,a){switch(e){case",":t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break;case"]":r=a,t.pop()}}for(let l=0;l<e.length;l++){let u=e[l];switch(t[t.length-1]){case"ROOT":i(u,l,"FINISH");break;case"INSIDE_OBJECT_START":switch(u){case'"':t.pop(),t.push("INSIDE_OBJECT_KEY");break;case"}":r=l,t.pop()}break;case"INSIDE_OBJECT_AFTER_COMMA":'"'===u&&(t.pop(),t.push("INSIDE_OBJECT_KEY"));break;case"INSIDE_OBJECT_KEY":'"'===u&&(t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY"));break;case"INSIDE_OBJECT_AFTER_KEY":":"===u&&(t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE"));break;case"INSIDE_OBJECT_BEFORE_VALUE":i(u,l,"INSIDE_OBJECT_AFTER_VALUE");break;case"INSIDE_OBJECT_AFTER_VALUE":s(u,l);break;case"INSIDE_STRING":switch(u){case'"':t.pop(),r=l;break;case"\\":t.push("INSIDE_STRING_ESCAPE");break;default:r=l}break;case"INSIDE_ARRAY_START":"]"===u?(r=l,t.pop()):(r=l,i(u,l,"INSIDE_ARRAY_AFTER_VALUE"));break;case"INSIDE_ARRAY_AFTER_VALUE":switch(u){case",":t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break;case"]":r=l,t.pop();break;default:r=l}break;case"INSIDE_ARRAY_AFTER_COMMA":i(u,l,"INSIDE_ARRAY_AFTER_VALUE");break;case"INSIDE_STRING_ESCAPE":t.pop(),"u"===u?(n=0,t.push("INSIDE_STRING_UNICODE_ESCAPE")):r=l;break;case"INSIDE_STRING_UNICODE_ESCAPE":(u>="0"&&u<="9"||u>="A"&&u<="F"||u>="a"&&u<="f")&&4==++n&&(t.pop(),r=l);break;case"INSIDE_NUMBER":switch(u){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":r=l;break;case"e":case"E":case"-":case".":break;case",":t.pop(),"INSIDE_ARRAY_AFTER_VALUE"===t[t.length-1]&&o(u,l),"INSIDE_OBJECT_AFTER_VALUE"===t[t.length-1]&&s(u,l);break;case"}":t.pop(),"INSIDE_OBJECT_AFTER_VALUE"===t[t.length-1]&&s(u,l);break;case"]":t.pop(),"INSIDE_ARRAY_AFTER_VALUE"===t[t.length-1]&&o(u,l);break;default:t.pop()}break;case"INSIDE_LITERAL":{let n=e.substring(a,l+1);"false".startsWith(n)||"true".startsWith(n)||"null".startsWith(n)?r=l:(t.pop(),"INSIDE_OBJECT_AFTER_VALUE"===t[t.length-1]?s(u,l):"INSIDE_ARRAY_AFTER_VALUE"===t[t.length-1]&&o(u,l))}}}let l=e.slice(0,r+1);for(let r=t.length-1;r>=0;r--)switch(t[r]){case"INSIDE_STRING":l+='"';break;case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":l+="}";break;case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":l+="]";break;case"INSIDE_LITERAL":{let t=e.substring(a,e.length);"true".startsWith(t)?l+="true".slice(t.length):"false".startsWith(t)?l+="false".slice(t.length):"null".startsWith(t)&&(l+="null".slice(t.length))}}return l}(e)})).success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"}}var uS=()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),parseCompleteOutput:async({text:e})=>e,parsePartialOutput:async({text:e})=>({partial:e}),createElementStreamTransform(){}}),uE=({schema:e,name:t,description:r})=>{let a=ah(e);return{name:"object",responseFormat:aS(a.jsonSchema).then(e=>({type:"json",schema:e,...null!=t&&{name:t},...null!=r&&{description:r}})),async parseCompleteOutput({text:e},t){let r=await ay({text:e});if(!r.success)throw new lY({message:"No object generated: could not parse the response.",cause:r.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});let n=await ag({value:r.value,schema:a});if(!n.success)throw new lY({message:"No object generated: response did not match sc
75hema.",cause:n.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});return n.value},async parsePartialOutput({text:e}){let t=await uk(e);switch(t.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:t.value}}},createElementStreamTransform(){}}},uC=({element:e,minItems:t,maxItems:r,name:a,description:n})=>{if(uj({name:"minItems",value:t}),uj({name:"maxItems",value:r}),null!=t&&null!=r&&t>r)throw new lH({parameter:"minItems",value:t,message:"minItems must be less than or equal to maxItems"});let i=ah(e);return{name:"array",responseFormat:aS(i.jsonSchema).then(e=>{let{$schema:i,definitions:s,$defs:o,...l}=e;return{type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",...null!=s&&{definitions:s},...null!=o&&{$defs:o},type:"object",properties:{elements:{type:"array",items:l,...null!=t&&{minItems:t},...null!=r&&{maxItems:r}}},required:["elements"],additionalProperties:!1},...null!=a&&{name:a},...null!=n&&{description:n}}}),async parseCompleteOutput({text:e},a){let n=await ay({text:e});if(!n.success)throw new lY({message:"No object generated: could not parse the response.",cause:n.error,text:e,response:a.response,usage:a.usage,finishReason:a.finishReason});let s=n.value;if(null==s||"object"!=typeof s||!("elements"in s)||!Array.isArray(s.elements))throw new lY({message:"No object generated: response did not match schema.",cause:new to({value:s,cause:"response must be an object with an elements array"}),text:e,response:a.response,usage:a.usage,finishReason:a.finishReason});let o=uI({value:s.elements,minItems:t,maxItems:r});if(null!=o)throw new lY({message:"No object generated: response did not match schema.",cause:o,text:e,response:a.response,usage:a.usage,finishReason:a.finishReason});let l=[];for(let t of s.elements){let r=await ag({value:t,schema:i});if(!r.success)throw new lY({message:"No object generated: response did not match schema.",cause:r.error,text:e,response:a.response,usage:a.usage,finishReason:a.finishReason});l.push(r.value)}return l},async parsePartialOutput({text:e}){let t=await uk(e);switch(t.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let e=t.value;if(null==e||"object"!=typeof e||!("elements"in e)||!Array.isArray(e.elements))return;let r="repaired-parse"===t.state&&e.elements.length>0?e.elements.slice(0,-1):e.elements,a=[];for(let e of r){let t=await ag({value:e,schema:i});t.success&&a.push(t.value)}return{partial:a}}}},createElementStreamTransform(){let e=0;return new TransformStream({transform({partialOutput:t},a){if(null!=t)for(;e<t.length;e++){if(null!=r&&e>=r)return void a.error(uI({value:t,maxItems:r}));a.enqueue(t[e])}}})}}};function uj({name:e,value:t}){if(null!=t){if(!Number.isInteger(t))throw new lH({parameter:e,value:t,message:`${e} must be an integer`});if(t<0)throw new lH({parameter:e,value:t,message:`${e} must be greater than or equal to 0`})}}function uI({value:e,minItems:t,maxItems:r}){return null!=t&&e.length<t?new to({value:e,cause:`elements array must contain at least ${t} items`}):null!=r&&e.length>r?new to({value:e,cause:`elements array must contain at most ${r} items`}):void 0}var uT=({options:e,name:t,description:r})=>({name:"choice",responseFormat:Promise.resolve({type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{result:{type:"string",enum:e}},required:["result"],additionalProperties:!1},...null!=t&&{name:t},...null!=r&&{description:r}}),async parseCompleteOutput({text:t},r){let a=await ay({text:t});if(!a.success)throw new lY({message:"No object generated: could not parse the response.",cause:a.error,text:t,response:r.response,usage:r.usage,finishReason:r.finishReason});let n=a.value;if(null==n||"object"!=typeof n||!("result"in n)||"string"!=typeof n.result||!e.includes(n.result))throw new lY({message:"No object generated: response did not match schema.",cause:new to({value:n,cause:"response must be an object that contains a choice value."}),text:t,response:r.response,usage:r.usage,finishReason:r.finishReason});return n.result},async parsePartialOutput({text:t}){let r=await uk(t);switch(r.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let t=r.value;if(null==t||"object"!=typeof t||!("result"in t)||"string"!=typeof t.result)return;let a=e.filter(e=>e.startsWith(t.result));if("successful-parse"===r.state)return a.includes(t.result)?{partial:t.result}:void 0;return 1===a.length?{partial:a[0]}:void 0}}},createElementStreamTransform(){}}),uN=({name:e,description:t}={})=>({name:"json",responseFormat:Promise.resolve({type:"json",...null!=e&&{name:e},...null!=t&&{description:t}}),async parseCompleteOutput({text:e},t){let r=await ay({text:e});if(!r.success)throw new lY({message:"No object generated: could not parse the response.",cause:r.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});return r.value},async parsePartialOutput({text:e}){let t=await uk(e);switch(t.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return void 0===t.value?void 0:{partial:t.value}}},createElementStreamTransform(){}});new TextEncoder,new TextEncoder,rP({prefix:"aitxt",size:24}),rP({prefix:"call",size:24}),TransformStream;var uR=sR(iQ(),l7.optional()),uA=ad(()=>am(l8([l6({type:sO("text-start"),id:iQ(),providerMetadata:ue.optional()}),l6({type:sO("text-delta"),id:iQ(),delta:iQ(),providerMetadata:ue.optional()}),l6({type:sO("text-end"),id:iQ(),providerMetadata:ue.optional()}),l6({type:sO("error"),errorText:iQ()}),l6({type:sO("tool-input-start"),toolCallId:iQ(),toolName:iQ(),providerExecuted:sm().optional(),providerMetadata:ue.optional(),toolMetadata:uR.optional(),dynamic:sm().optional(),title:iQ().optional()}),l6({type:sO("tool-input-delta"),toolCallId:iQ(),inputTextDelta:iQ()}),l6({type:sO("tool-input-available"),toolCallId:iQ(),toolName:iQ(),input:sy(),providerExecuted:sm().optional(),providerMetadata:ue.optional(),toolMetadata:uR.optional(),dynamic:sm().optional(),title:iQ().optional()}),l6({type:sO("tool-input-error"),toolCallId:iQ(),toolName:iQ(),input:sy(),providerExecuted:sm().optional(),providerMetadata:ue.optional(),toolMetadata:uR.optional(),dynamic:sm().optional(),errorText:iQ(),title:iQ().optional()}),l6({type:sO("tool-approval-request"),approvalId:iQ(),toolCallId:iQ(),approvalDescriptor:sy().optional(),reason:iQ().optional(),isAutomatic:sm().optional(),signature:iQ().optional()}),l6({type:sO("tool-approval-response"),approvalId:iQ(),approved:sm(),reason:iQ().optional(),providerExecuted:sm().optional(),providerMetadata:ue.optional()}),l6({type:sO("tool-output-available"),toolCallId:iQ(),output:sy(),providerExecuted:sm().optional(),providerMetadata:ue.optional(),toolMetadata:uR.optional(),dynamic:sm().optional(),preliminary:sm().optional()}),l6({type:sO("tool-output-error"),toolCallId:iQ(),errorText:iQ(),providerExecuted:sm().optional(),providerMetadata:ue.optional(),toolMetadata:uR.optional(),dynamic:sm().optional()}),l6({type:sO("tool-output-denied"),toolCallId:iQ()}),l6({type:sO("reasoning-start"),id:iQ(),providerMetadata:ue.optional()}),l6({type:sO("reasoning-delta"),id:iQ(),delta:iQ(),providerMetadata:ue.optional()}),l6({type:sO("reasoning-end"),id:iQ(),providerMetadata:ue.optional()}),l6({type:sO("custom"),kind:iQ().transform(e=>e),providerMetadata:ue.optional()}),l6({type:sO("source-url"),sourceId:iQ(),url:iQ(),title:iQ().optional(),providerMetadata:ue.optional()}),l6({type:sO("source-document"),sourceId:iQ(),mediaType:iQ(),title:iQ(),filename:iQ().optional(),providerMetadata:ue.optional()}),l6({type:sO("file"),url:iQ(),mediaType:iQ(),providerMetadata:ue.optional()}),l6({type:sO("reasoning-file"),url:iQ(),mediaType:iQ(),providerMetadata:ue.optional()}),l6({type:l4(e=>"string"==typeof e&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:iQ().optional(),data:sy(),transient:sm().optional()}),l6({type:sO("start-step")}),l6({type:sO("finish-step")}),l6({type:sO("reset-step")}),l6({type:sO("start"),messageId:iQ().optional(),messageMetadata:sy().optional()}),l6({type:sO("finish"),finishReason:l3(["stop","length","content-filter","tool-calls","error","other"]).optional(),messageMetadata:sy().optional()}),l6({type:sO("abort"),reason:iQ().optional()}),l6({type:sO("message-metadata"),messageMetadata:sy()})])));function uz(){return Object.create(null)}function uM(e){return e.type.startsWith("tool-")}function uO(e){return uM(e)||"dynamic-tool"===e.type}function uP(e){return e.type.split("-").slice(1).join("-")}
75async function u$({stream:e,onError:t,abortSignal:r}){let a=e.getReader(),n=()=>{a.cancel().catch(()=>{})};(null==r?void 0:r.aborted)?n():null==r||r.addEventListener("abort",n,{once:!0});try{for(;;){let{done:e}=await a.read();if(e)break}}catch(e){null==t||t(e)}finally{null==r||r.removeEventListener("abort",n),a.releaseLock()}}rP({prefix:"aitxt",size:24}),rP({prefix:"call",size:24}),rP({prefix:"aitxt",size:24}),rP({prefix:"call",size:24});var uD=sR(iQ(),l7.optional()),uU=sR(iQ(),iQ());function uL(e){return({url:t,abortSignal:r})=>l2({url:t,maxBytes:null==e?void 0:e.maxBytes,abortSignal:r})}ad(()=>am(l5(sS({id:iQ(),role:l3(["system","user","assistant"]),metadata:sy().optional(),parts:l5(l8([sS({type:sO("text"),text:iQ(),state:l3(["streaming","done"]).optional(),providerMetadata:ue.optional()}),sS({type:sO("reasoning"),id:iQ().optional(),text:iQ(),state:l3(["streaming","done"]).optional(),providerMetadata:ue.optional()}),sS({type:sO("custom"),kind:iQ(),providerMetadata:ue.optional()}),sS({type:sO("source-url"),sourceId:iQ(),url:iQ(),title:iQ().optional(),providerMetadata:ue.optional()}),sS({type:sO("source-document"),sourceId:iQ(),mediaType:iQ(),title:iQ(),filename:iQ().optional(),providerMetadata:ue.optional()}),sS({type:sO("file"),mediaType:iQ(),filename:iQ().optional(),url:iQ(),providerReference:uU.optional(),providerMetadata:ue.optional()}),sS({type:sO("reasoning-file"),mediaType:iQ(),url:iQ(),providerMetadata:ue.optional()}),sS({type:sO("step-start")}),sS({type:iQ().startsWith("data-"),id:iQ().optional(),data:sy()}),sS({type:sO("dynamic-tool"),toolName:iQ(),toolCallId:iQ(),title:iQ().optional(),toolMetadata:uD.optional(),state:sO("input-streaming"),input:sy().optional(),providerExecuted:sm().optional(),callProviderMetadata:ue.optional(),output:sx().optional(),errorText:sx().optional(),approval:sx().optional()}),sS({type:sO("dynamic-tool"),toolName:iQ(),toolCallId:iQ(),title:iQ().optional(),toolMetadata:uD.optional(),state:sO("input-available"),input:sy(),providerExecuted:sm().optional(),output:sx().optional(),errorText:sx().optional(),callProviderMetadata:ue.optional(),approval:sx().optional()}),sS({type:sO("dynamic-tool"),toolName:iQ(),toolCallId:iQ(),title:iQ().optional(),toolMetadata:uD.optional(),state:sO("approval-requested"),input:sy(),providerExecuted:sm().optional(),output:sx().optional(),errorText:sx().optional(),callProviderMetadata:ue.optional(),approval:sS({id:iQ(),approved:sx().optional(),descriptor:sy().optional(),requestReason:iQ().optional(),reason:sx().optional(),isAutomatic:sm().optional(),signature:iQ().optional()})}),sS({type:sO("dynamic-tool"),toolName:iQ(),toolCallId:iQ(),title:iQ().optional(),toolMetadata:uD.optional(),state:sO("approval-responded"),input:sy(),providerExecuted:sm().optional(),output:sx().optional(),errorText:sx().optional(),callProviderMetadata:ue.optional(),approval:sS({id:iQ(),approved:sm(),descriptor:sy().optional(),requestReason:iQ().optional(),reason:iQ().optional(),isAutomatic:sm().optional(),signature:iQ().optional()})}),sS({type:sO("dynamic-tool"),toolName:iQ(),toolCallId:iQ(),title:iQ().optional(),toolMetadata:uD.optional(),state:sO("output-available"),input:sy(),providerExecuted:sm().optional(),output:sy(),errorText:sx().optional(),callProviderMetadata:ue.optional(),resultProviderMetadata:ue.optional(),preliminary:sm().optional(),approval:sS({id:iQ(),approved:sO(!0),descriptor:sy().optional(),requestReason:iQ().optional(),reason:iQ().optional(),isAutomatic:sm().optional(),signature:iQ().optional()}).optional()}),sS({type:sO("dynamic-tool"),toolName:iQ(),toolCallId:iQ(),title:iQ().optional(),toolMetadata:uD.optional(),state:sO("output-error"),input:sy().optional(),rawInput:sy().optional(),providerExecuted:sm().optional(),output:sx().optional(),errorText:iQ(),callProviderMetadata:ue.optional(),resultProviderMetadata:ue.optional(),approval:sS({id:iQ(),approved:sO(!0),descriptor:sy().optional(),requestReason:iQ().optional(),reason:iQ().optional(),isAutomatic:sm().optional(),signature:iQ().optional()}).optional()}),sS({type:sO("dynamic-tool"),toolName:iQ(),toolCallId:iQ(),title:iQ().optional(),toolMetadata:uD.optional(),state:sO("output-denied"),input:sy(),providerExecuted:sm().optional(),output:sx().optional(),errorText:sx().optional(),callProviderMetadata:ue.optional(),approval:sS({id:iQ(),approved:sO(!1),descriptor:sy().optional(),requestReason:iQ().optional(),reason:iQ().optional(),isAutomatic:sm().optional(),signature:iQ().optional()})}),sS({type:iQ().startsWith("tool-"),toolCallId:iQ(),title:iQ().optional(),toolMetadata:uD.optional(),state:sO("input-streaming"),providerExecuted:sm().optional(),callProviderMetadata:ue.optional(),input
75:sy().optional(),output:sx().optional(),errorText:sx().optional(),approval:sx().optional()}),sS({type:iQ().startsWith("tool-"),toolCallId:iQ(),title:iQ().optional(),toolMetadata:uD.optional(),state:sO("input-available"),providerExecuted:sm().optional(),input:sy(),output:sx().optional(),errorText:sx().optional(),callProviderMetadata:ue.optional(),approval:sx().optional()}),sS({type:iQ().startsWith("tool-"),toolCallId:iQ(),title:iQ().optional(),toolMetadata:uD.optional(),state:sO("approval-requested"),input:sy(),providerExecuted:sm().optional(),output:sx().optional(),errorText:sx().optional(),callProviderMetadata:ue.optional(),approval:sS({id:iQ(),approved:sx().optional(),descriptor:sy().optional(),requestReason:iQ().optional(),reason:sx().optional(),isAutomatic:sm().optional(),signature:iQ().optional()})}),sS({type:iQ().startsWith("tool-"),toolCallId:iQ(),title:iQ().optional(),toolMetadata:uD.optional(),state:sO("approval-responded"),input:sy(),providerExecuted:sm().optional(),output:sx().optional(),errorText:sx().optional(),callProviderMetadata:ue.optional(),approval:sS({id:iQ(),approved:sm(),descriptor:sy().optional(),requestReason:iQ().optional(),reason:iQ().optional(),isAutomatic:sm().optional(),signature:iQ().optional()})}),sS({type:iQ().startsWith("tool-"),toolCallId:iQ(),title:iQ().optional(),toolMetadata:uD.optional(),state:sO("output-available"),providerExecuted:sm().optional(),input:sy(),output:sy(),errorText:sx().optional(),callProviderMetadata:ue.optional(),resultProviderMetadata:ue.optional(),preliminary:sm().optional(),approval:sS({id:iQ(),approved:sO(!0),descriptor:sy().optional(),requestReason:iQ().optional(),reason:iQ().optional(),isAutomatic:sm().optional(),signature:iQ().optional()}).optional()}),sS({type:iQ().startsWith("tool-"),toolCallId:iQ(),title:iQ().optional(),toolMetadata:uD.optional(),state:sO("output-error"),providerExecuted:sm().optional(),input:sy().optional(),rawInput:sy().optional(),output:sx().optional(),errorText:iQ(),callProviderMetadata:ue.optional(),resultProviderMetadata:ue.optional(),approval:sS({id:iQ(),approved:sO(!0),descriptor:sy().optional(),requestReason:iQ().optional(),reason:iQ().optional(),isAutomatic:sm().optional(),signature:iQ().optional()}).optional()}),sS({type:iQ().startsWith("tool-"),toolCallId:iQ(),title:iQ().optional(),toolMetadata:uD.optional(),state:sO("output-denied"),providerExecuted:sm().optional(),input:sy(),output:sx().optional(),errorText:sx().optional(),callProviderMetadata:ue.optional(),approval:sS({id:iQ(),approved:sO(!1),descriptor:sy().optional(),requestReason:iQ().optional(),reason:iQ().optional(),isAutomatic:sm().optional(),signature:iQ().optional()})})]))}).superRefine((e,t)=>{"assistant"!==e.role&&0===e.parts.length&&t.addIssue({origin:"array",code:"too_small",minimum:1,inclusive:!0,input:e.parts,path:["parts"],message:"Message must contain at least one part"})})).nonempty("Messages array must not be empty"))),rP({prefix:"call",size:24}),rP({prefix:"call",size:24}),new TextEncoder,rP({prefix:"aiobj",size:24});var uF=class{constructor(){this.queue=[],this.isProcessing=!1}async processQueue(){if(!this.isProcessing){for(this.isProcessing=!0;this.queue.length>0;)await this.queue[0](),this.queue.shift();this.isProcessing=!1}}async run(e){return new Promise((t,r)=>{this.queue.push(async()=>{try{await e(),t()}catch(e){r(e)}}),this.processQueue()})}};rP({prefix:"aiobj",size:24}),uL();Symbol.for("vercel.ai.error.AI_NoSuchProviderError");async function uZ(e){if(null==e)return[];if(!globalThis.FileList||!(e instanceof globalThis.FileList))throw Error("FileList is not supported in the current environment");return Promise.all(Array.from(e).map(async e=>{let{name:t,type:r}=e;return{type:"file",mediaType:r,filename:t,url:await new Promise((t,r)=>{let a=new FileReader;a.onload=e=>{var r;t(null==(r=e.target)?void 0:r.result)},a.onerror=e=>r(e),a.readAsDataURL(e)})}}))}rP({prefix:"call",size:24}),uL();var uB=class{constructor({api:e="/api/chat",credentials:t,headers:r,body:a,fetch:n,prepareSendMessagesRequest:i,prepareReconnectToStreamRequest:s}){this.api=e,this.credentials=t,this.headers=r,this.body=a,this.fetch=n,this.prepareSendMessagesRequest=i,this.prepareReconnectToStreamRequest=s}async sendMessages({abortSignal:e,...t}){var r,a,n,i;let s=await aS(this.body),o=await aS(this.headers),l=await aS(this.credentials),u={...rg(o),...rg(t.headers)},c=await (null==(r=this.prepareSendMessagesRequest)?void 0:r.call(this,{api:this.api,id:t.chatId,messages:t.messages,body:{...s,...t.body},headers:u,credentials:l,requestMetadata:t.metadata,trigger:t.trigger,messageId:t.messageId})),d=null!=(a=null==c?void 0:c.api)?a:this.api,p=(null==c?void 0:c.headers)!==void 0?rg(c.headers):u,h=(null==c?void 0:c.body)!==void 0?c.body:{...s,...t.body,id:t.chatId,messages:t.messages,trigger:t.trigger,messageId:t.messageId},m=null!=(n=null==c?void 0:c.credentials)?n:l,f=null!=(i=this.fetch)?i:globalThis.fetch,g=await f(d,{method:"POST",headers:{"Content-Type":"application/json",...p},body:JSON.stringify(h),credentials:m,signal:e});if(!g.ok)throw Error(await g.text()||"Failed to fetch the chat response.");if(!g.body)throw Error("The response body is empty.");return this.processResponseStream(g.body)}async reconnectToStream(e){var t,r,a,n;let i=await aS(this.body),s=await aS(this.headers),o=await aS(this.credentials),l={...rg(s),...rg(e.headers)},u=await (null==(t=this.prepareReconnectToStreamRequest)?void 0:t.call(this,{api:this.api,id:e.chatId,body:{...i,...e.body},headers:l,credentials:o,requestMetadata:e.metadata})),c=null!=(r=null==u?void 0:u.api)?r:`${this.api}/${e.chatId}/stream`,d=(null==u?void 0:u.headers)!==void 0?rg(u.headers):l,p=null!=(a=null==u?void 0:u.credentials)?a:o,h=null!=(n=this.fetch)?n:globalThis.fetch,m=await h(c,{method:"GET",headers:d,credentials:p,signal:e.abortSignal});if(204===m.status)return null;if(!m.ok)throw Error(await m.text()||"Failed to fetch the chat response.");if(!m.body)throw Error("The response body is empty.");return this.processResponseStream(m.body)}},uH=class extends uB{constructor(e={}){super(e)}
75processResponseStream(e){return ab({stream:e,schema:uA}).pipeThrough(new TransformStream({async transform(e,t){if(!e.success)throw e.error;t.enqueue(e.value)}}))}},uq=class{constructor({generateId:e=r$,id:t=e(),transport:r=new uH,messageMetadataSchema:a,dataPartSchemas:n,state:i,onError:s,onToolCall:o,onFinish:l,onData:u,sendAutomaticallyWhen:c}){this.pendingMessagePreparations=new Set,this.activeResponse=void 0,this.activeResumeRequest=void 0,this.jobExecutor=new uF,this.sendMessage=async(e,t)=>{var r,a,n,i;let s;if(null==e)return void await this.makeRequest({trigger:"submit-message",messageId:null==(r=this.lastMessage)?void 0:r.id,...t});if("text"in e||"files"in e){let t,r=new AbortController;this.pendingMessagePreparations.add(r);try{t=Array.isArray(e.files)?e.files:await uZ(e.files)}finally{this.pendingMessagePreparations.delete(r)}if(r.signal.aborted)return;s={parts:[...t,..."text"in e&&null!=e.text?[{type:"text",text:e.text}]:[]]}}else s=e;if(null!=e.messageId){let t=this.state.messages.findIndex(t=>t.id===e.messageId);if(-1===t)throw Error(`message with id ${e.messageId} not found`);if("user"!==this.state.messages[t].role)throw Error(`message with id ${e.messageId} is not a user message`);this.state.messages=this.state.messages.slice(0,t+1),this.state.replaceMessage(t,{id:e.messageId,...s,role:null!=(a=s.role)?a:"user",metadata:e.metadata})}else this.state.pushMessage({...s,id:null!=(n=s.id)?n:this.generateId(),role:null!=(i=s.role)?i:"user",metadata:e.metadata});await this.makeRequest({trigger:"submit-message",messageId:e.messageId,...t})},this.regenerate=async({messageId:e,...t}={})=>{let r=null==e?this.state.messages.length-1:this.state.messages.findIndex(t=>t.id===e);if(-1===r)throw Error(`message ${e} not found`);this.state.messages=this.state.messages.slice(0,"assistant"===this.messages[r].role?r:r+1),await this.makeRequest({trigger:"regenerate-message",messageId:e,...t})},this.resumeStream=async(e={})=>{await this.makeRequest({trigger:"resume-stream",...e})},this.clearError=()=>{"error"===this.status&&(this.state.error=void 0,this.setStatus({status:"ready"}))},this.addToolApprovalResponse=async({id:e,approved:t,reason:r,options:a})=>this.jobExecutor.run(async()=>{let n=this.state.messages,i=n[n.length-1],s=a=>uO(a)&&"approval-requested"===a.state&&a.approval.id===e?{...a,state:"approval-responded",approval:{...a.approval,id:e,approved:t,reason:r}}:a;this.state.replaceMessage(n.length-1,{...i,parts:i.parts.map(s)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(s)),"streaming"!==this.status&&"submitted"!==this.status&&this.sendAutomaticallyWhen&&this.shouldSendAutomatically().then(e=>{var t;e&&this.makeRequest({trigger:"submit-message",messageId:null==(t=this.lastMessage)?void 0:t.id,...a})})}),this.addToolOutput=async({state:e="output-available",toolCallId:t,output:r,errorText:a,options:n})=>this.jobExecutor.run(async()=>{let i=this.state.messages,s=i[i.length-1],o=n=>uO(n)&&n.toolCallId===t?{...n,state:e,output:r,errorText:a}:n;this.state.replaceMessage(i.length-1,{...s,parts:s.parts.map(o)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(o)),"streaming"!==this.status&&"submitted"!==this.status&&this.sendAutomaticallyWhen&&this.shouldSendAutomatically().then(e=>{var t;e&&this.makeRequest({trigger:"submit-message",messageId:null==(t=this.lastMessage)?void 0:t.id,...n})})}),this.addToolResult=this.addToolOutput,this.stop=async()=>{var e,t;for(let e of this.pendingMessagePreparations)e.abort();null==(e=this.activeResumeRequest)||e.abortController.abort(),null==(t=this.activeResponse)||t.abortController.abort()},this.id=t,this.transport=r,this.generateId=e,this.messageMetadataSchema=a,this.dataPartSchemas=n,this.state=i,this.onError=s,this.onToolCall=o,this.onFinish=l,this.onData=u,this.sendAutomaticallyWhen=c}get status(){return this.state.status}setStatus({status:e,error:t}){this.status!==e&&(this.state.status=e,this.state.error=t)}get error(){return this.state.error}get messages(){return this.state.messages}get lastMessage(){return this.state.messages[this.state.messages.length-1]}set messages(e){this.state.messages=e}
75async shouldSendAutomatically(){if(!this.sendAutomaticallyWhen)return!1;let e=this.sendAutomaticallyWhen({messages:this.state.messages});return e&&"object"==typeof e&&"then"in e?await e:e}async makeRequest({trigger:e,metadata:t,headers:r,body:a,messageId:n}){var i,s,o;let l,u,c=new AbortController,d="resume-stream"===e?{abortController:c}:void 0;d&&(null==(i=this.activeResumeRequest)||i.abortController.abort(),this.activeResumeRequest=d);let p=()=>null==d||this.activeResumeRequest===d,h=()=>{this.activeResumeRequest===d&&(this.activeResumeRequest=void 0)};if("resume-stream"===e)try{let e=await this.transport.reconnectToStream({chatId:this.id,abortSignal:c.signal,metadata:t,headers:r,body:a});if(c.signal.aborted||!p()){await (null==e?void 0:e.cancel().catch(()=>{})),p()&&this.setStatus({status:"ready"}),h();return}if(null==e){this.setStatus({status:"ready"}),h();return}l=e}catch(e){if(c.signal.aborted||"AbortError"===e.name){p()&&this.setStatus({status:"ready"}),h();return}if(!p())return;this.onError&&e instanceof Error&&this.onError(e),this.setStatus({status:"error",error:e}),h();return}this.setStatus({status:"submitted",error:void 0});let m=this.lastMessage,f=!1,g=!1,v=!1;try{let i,s={state:function({lastMessage:e,messageId:t}){return{message:(null==e?void 0:e.role)==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:uz(),activeReasoningParts:uz(),partialToolCalls:uz()}}({lastMessage:"resume-stream"===e||"regenerate-message"===e?void 0:this.state.snapshot(m),messageId:this.generateId()}),abortController:c};u=s,s.abortController.signal.addEventListener("abort",()=>{f=!0}),this.activeResponse=s,i="resume-stream"===e?l:await this.transport.sendMessages({chatId:this.id,messages:this.state.messages,abortSignal:s.abortController.signal,metadata:t,headers:r,body:a,trigger:e,messageId:n});let o=e=>this.jobExecutor.run(()=>s.abortController.signal.aborted?Promise.resolve():e({state:s.state,write:({updateStatus:e=!0}={})=>{var t;s.abortController.signal.aborted||(e&&this.setStatus({status:"streaming"}),s.state.message.id===(null==(t=this.lastMessage)?void 0:t.id)?this.state.replaceMessage(this.state.messages.length-1,s.state.message):this.state.pushMessage(s.state.message))}}));if(await u$({stream:function({stream:e,messageMetadataSchema:t,dataPartSchemas:r,runUpdateMessageJob:a,onError:n,onToolCall:i,onData:s}){return e.pipeThrough(new TransformStream({async transform(e,o){await a(async({state:a,write:l})=>{var u,c,d,p;function h(){let e=a.message.parts,t=e.length-1;for(;t>=0&&"step-start"!==e[t].type;)t--;return e.slice(t+1)}function m(e){let t=h().filter(uO).find(t=>t.toolCallId===e);if(null==t){let r=a.message.parts;for(let a=r.length-1;a>=0;a--){let n=r[a];if(uO(n)&&n.toolCallId===e){t=n;break}}}if(null==t)throw new l0({chunkType:"tool-invocation",chunkId:e,message:`No tool invocation found for tool call ID "${e}".`});return t}function f(e,t){var r;let n=null!=t?t:h().find(t=>uM(t)&&t.toolCallId===e.toolCallId);if(null!=n){n.state=e.state,n.input=e.input,n.output=e.output,n.errorText=e.errorText,n.rawInput=e.rawInput,n.preliminary=e.preliminary,void 0!==e.title&&(n.title=e.title),void 0!==e.toolMetadata&&(n.toolMetadata=e.toolMetadata),n.providerExecuted=null!=(r=e.providerExecuted)?r:n.providerExecuted;let t=e.providerMetadata;null!=t&&("output-available"===e.state||"output-error"===e.state?n.resultProviderMetadata=t:n.callProviderMetadata=t)}else a.message.parts.push({type:`tool-${e.toolName}`,toolCallId:e.toolCallId,state:e.state,title:e.title,...void 0!==e.toolMetadata?{toolMetadata:e.toolMetadata}:{},input:e.input,output:e.output,rawInput:e.rawInput,errorText:e.errorText,providerExecuted:e.providerExecuted,preliminary:e.preliminary,...null!=e.providerMetadata&&("output-available"===e.state||"output-error"===e.state)?{resultProviderMetadata:e.providerMetadata}:{},...null!=e.providerMetadata&&"output-available"!==e.state&&"output-error"!==e.state?{callProviderMetadata:e.providerMetadata}:{}})}function g(e,t){var r,n;let i=null!=t?t:h().find(t=>"dynamic-tool"===t.type&&t.toolCallId===e.toolCallId);if(null!=i){i.state=e.state,i.toolName=e.toolName,i.input=e.input,i.output=e.output,i.errorText=e.errorText,i.rawInput=null!=(r=e.rawInput)?r:i.rawInput,i.preliminary=e.preliminary,void 0!==e.title&&(i.title=e.title),void 0!==e.toolMetadata&&(i.toolMetadata=e.toolMetadata),i.providerExecuted=null!=(n=e.providerExecuted)?n:i.providerExecuted;let t=e.providerMetadata;null!=t&&("output-available"===e.state||"output-error"===e.state?i.resultProviderMetadata=t:i.callProviderMetadata=t)}else a.message.parts.push({type:"dynamic-tool",toolName:e.toolName,toolCallId:e.toolCallId,state:e.state,input:e.input,output:e.output,errorText:e.errorText,preliminary:e.preliminary,providerExecuted:e.providerExecuted,title:e.title,...void 0!==e.toolMetadata?{toolMetadata:e.toolMetadata}:{},...null!=e.providerMetadata&&("output-available"===e.state||"output-error"===e.state)?{resultProviderMetadata:e.providerMetadata}:{}
75,...null!=e.providerMetadata&&"output-available"!==e.state&&"output-error"!==e.state?{callProviderMetadata:e.providerMetadata}:{}})}async function v(e){if(null!=e){let r=null!=a.message.metadata?function e(t,r){if(void 0===t&&void 0===r)return;if(void 0===t)return r;if(void 0===r)return t;let a={...t};for(let n in r)if("__proto__"!==n&&"constructor"!==n&&"prototype"!==n&&Object.prototype.hasOwnProperty.call(r,n)){let i=r[n];if(void 0===i)continue;let s=n in t?t[n]:void 0,o=null!==i&&"object"==typeof i&&!Array.isArray(i)&&!(i instanceof Date)&&!(i instanceof RegExp),l=null!=s&&"object"==typeof s&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp);o&&l?a[n]=e(s,i):a[n]=i}return a}(a.message.metadata,e):e;null!=t&&await af({value:r,schema:t,context:{field:"message.metadata",entityId:a.message.id}}),a.message.metadata=r}}switch(e.type){case"text-start":{let t={type:"text",text:"",providerMetadata:e.providerMetadata,state:"streaming"};a.activeTextParts[e.id]=t,a.message.parts.push(t),l();break}case"text-delta":{let t=a.activeTextParts[e.id];if(null==t)throw new l0({chunkType:"text-delta",chunkId:e.id,message:`Received text-delta for missing text part with ID "${e.id}". Ensure a "text-start" chunk is sent before any "text-delta" chunks.`});t.text+=e.delta,t.providerMetadata=null!=(u=e.providerMetadata)?u:t.providerMetadata,l();break}case"text-end":{let t=a.activeTextParts[e.id];if(null==t)throw new l0({chunkType:"text-end",chunkId:e.id,message:`Received text-end for missing text part with ID "${e.id}". Ensure a "text-start" chunk is sent before any "text-end" chunks.`});t.state="done",t.providerMetadata=null!=(c=e.providerMetadata)?c:t.providerMetadata,delete a.activeTextParts[e.id],l();break}case"custom":{let t={type:"custom",kind:e.kind,providerMetadata:e.providerMetadata};a.message.parts.push(t),l();break}case"reasoning-start":{let t={type:"reasoning",id:e.id,text:"",providerMetadata:e.providerMetadata,state:"streaming"};a.activeReasoningParts[e.id]=t,a.message.parts.push(t),l();break}case"reasoning-delta":{let t=a.activeReasoningParts[e.id];if(null==t)throw new l0({chunkType:"reasoning-delta",chunkId:e.id,message:`Received reasoning-delta for missing reasoning part with ID "${e.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-delta" chunks.`});t.text+=e.delta,t.providerMetadata=null!=(d=e.providerMetadata)?d:t.providerMetadata,l();break}case"reasoning-end":{let t=a.activeReasoningParts[e.id];if(null==t)throw new l0({chunkType:"reasoning-end",chunkId:e.id,message:`Received reasoning-end for missing reasoning part with ID "${e.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-end" chunks.`});t.providerMetadata=null!=(p=e.providerMetadata)?p:t.providerMetadata,t.state="done",delete a.activeReasoningParts[e.id],l();break}case"file":case"reasoning-file":a.message.parts.push({type:e.type,mediaType:e.mediaType,url:e.url,...null!=e.providerMetadata?{providerMetadata:e.providerMetadata}:{}}),l();break;case"source-url":a.message.parts.push({type:"source-url",sourceId:e.sourceId,url:e.url,title:e.title,providerMetadata:e.providerMetadata}),l();break;case"source-document":a.message.parts.push({type:"source-document",sourceId:e.sourceId,mediaType:e.mediaType,title:e.title,filename:e.filename,providerMetadata:e.providerMetadata}),l();break;case"tool-input-start":{let t=h().filter(uM);a.partialToolCalls[e.toolCallId]={text:"",toolName:e.toolName,index:t.length,dynamic:e.dynamic,title:e.title,toolMetadata:e.toolMetadata},e.dynamic?g({toolCallId:e.toolCallId,toolName:e.toolName,state:"input-streaming",input:void 0,providerExecuted:e.providerExecuted,title:e.title,toolMetadata:e.toolMetadata,providerMetadata:e.providerMetadata}):f({toolCallId:e.toolCallId,toolName:e.toolName,state:"input-streaming",input:void 0,providerExecuted:e.providerExecuted,title:e.title,toolMetadata:e.toolMetadata,providerMetadata:e.providerMetadata}),l();break}case"tool-input-delta":{let t=a.partialToolCalls[e.toolCallId];if(null==t)throw new l0({chunkType:"tool-input-delta",chunkId:e.toolCallId,message:`Received tool-input-delta for missing tool call with ID "${e.toolCallId}". Ensure a "tool-input-start" chunk is sent before any "tool-input-delta" chunks.`});t.text+=e.inputTextDelta;let{value:r}=await uk(t.text);t.dynamic?g({toolCallId:e.toolCallId,toolName:t.toolName,state:"input-streaming",input:r,title:t.title,toolMetadata:t.toolMetadata}):f({toolCallId:e.toolCallId,toolName:t.toolName,state:"input-streaming",input:r,title:t.title,toolMetadata:t.toolMetadata}),l();break}case"tool-input-available":e.dynamic?g({toolCallId:e.toolCallId,toolName:e.toolName,state:"input-available",input:e.input,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:e.title,toolMetadata:e.toolMetadata}):f({toolCallId:e.toolCallId,toolName:e.toolName,state:"input-available",input:e.input,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:e.title,toolMetadata:e.toolMetadata}),l(),i&&!e.providerExecuted&&await i({toolCall:e});break;case"tool-input-error":{let t=h().filter(uO).find(t=>t.toolCallId===e.toolCallId);(null!=t?"dynamic-tool"===t.type:e.dynamic)?g({toolCallId:e.toolCallId,toolName:e.toolName,state:"output-error",input:e.input,errorText:e.errorText,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,toolMetadata:e.toolMetadata}):f({toolCallId:e.toolCallId,toolName:e.toolName,state:"output-error",input:void 0,rawInput:e.input,errorText:e.errorText,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,toolMetadata:e.toolMetadata}),l();break}case"tool-approval-request":{let t=m(e.toolCallId);t.state="approval-requested",t.approval={id:e.approvalId,...null!=e.approvalDescriptor?{descriptor:e.approvalDescriptor}:{},...null!=e.reason?{requestReason:e.reason}:{},...!0===e.isAutomatic?{isAutomatic:!0}:{},...null!=e.signature?{signature:e.signature}:{}},l();break}case"tool-approval-response":{let t=function(e){let t=a.message.parts.filter(uO).find(t=>{var r;return(null==(r=t.approval)?void 0:r.id)===e});if(null==t)throw new l0({chunkType:"tool-approval-response",chunkId:e,message:`No tool invocation found for approval ID "${e}".`});return t}(e.approvalId),r=null==t.approval?{id:e.approvalId}:t.approval;t.state="approval-responded",t.approval={...r,id:e.approvalId,approved:e.approved,...null!=e.reason?{reason:e.reason}:{}},null!=e.providerExecuted&&(t.providerExecuted=e.providerExecuted),null!=e.providerMetadata&&(t.callProviderMetadata=e.providerMetadata),l();break}case"tool-output-denied":m(e.toolCallId).state="output-denied",l();break;case"tool-output-available":{let t=m(e.toolCallId);"dynamic-tool"===t.type?g({toolCallId:e.toolCallId,toolName:t.toolName,state:"output-available",input:t.input,output:e.output,preliminary:e.preliminary,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:t.title,toolMetadata:t.toolMetadata},t):f({toolCallId:e.toolCallId,toolName:uP(t),state:"output-available",input:t.input,output:e.output,providerExecuted:e.providerExecuted,preliminary:e.preliminary,providerMetadata:e.providerMetadata,title:t.title,toolMetadata:t.toolMetadata},t),l();break}case"tool-output-error":{let t=m(e.toolCallId);"dynamic-tool"===t.type?g({toolCallId:e.toolCallId,toolName:t.toolName,state:"output-error",input:t.input,errorText:e.errorText,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:t.title,toolMetadata:t.toolMetadata},t):f({toolCallId:e.toolCallId,toolName:uP(t),state:"output-error",input:t.input,rawInput:t.rawInput,errorText:e.errorText,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:t.title,toolMetadata:t.toolMetadata},t),l();break}case"start-step":a.message.parts.push({type:"step-start"});break;case"finish-step":break;case"reset-step":{let e=h();a.activeTextParts=uz(),a.activeReasoningParts=uz(),a.partialToolCalls=uz(),e.length>0&&(a.message.parts.splice(a.message.parts.length-e.length,e.length),l());break}case"start":null!=e.messageId&&(a.message.id=e.messageId),await v(e.messageMetadata),(null!=e.messageId||null!=e.messageMetadata)&&l({updateStatus:!1});break;
75case"finish":null!=e.finishReason&&(a.finishReason=e.finishReason),await v(e.messageMetadata),null!=e.messageMetadata&&l();break;case"message-metadata":await v(e.messageMetadata),null!=e.messageMetadata&&l();break;case"error":null==n||n(Error(e.errorText));break;default:if(e.type.startsWith("data-")){if((null==r?void 0:r[e.type])!=null){let t=a.message.parts.findIndex(t=>"id"in t&&"data"in t&&t.id===e.id&&t.type===e.type),n=t>=0?t:a.message.parts.length;await af({value:e.data,schema:r[e.type],context:{field:`message.parts[${n}].data`,entityName:e.type,entityId:e.id}})}if(e.transient){null==s||s(e);break}let t=null!=e.id?a.message.parts.find(t=>e.type===t.type&&e.id===t.id):void 0;null!=t?t.data=e.data:a.message.parts.push(e),null==s||s(e),l()}}o.enqueue(e)})}}))}({stream:i,onToolCall:this.onToolCall,onData:this.onData,messageMetadataSchema:this.messageMetadataSchema,dataPartSchemas:this.dataPartSchemas,runUpdateMessageJob:o,onError:e=>{throw e}}),abortSignal:s.abortController.signal,onError:e=>{throw e}}),f)return p()&&this.setStatus({status:"ready"}),null;p()&&this.setStatus({status:"ready"})}catch(e){if(f||"AbortError"===e.name)return f=!0,p()&&this.setStatus({status:"ready"}),null;if(!p())return null;v=!0,e instanceof TypeError&&(e.message.toLowerCase().includes("fetch")||e.message.toLowerCase().includes("network"))&&(g=!0),this.onError&&e instanceof Error&&this.onError(e),this.setStatus({status:"error",error:e})}finally{try{u&&(null==(s=this.onFinish)||s.call(this,{message:u.state.message,messages:this.state.messages,isAbort:f,isDisconnect:g,isError:v,finishReason:u.state.finishReason}))}finally{this.activeResponse===u&&(this.activeResponse=void 0),h()}}!v&&await this.shouldSendAutomatically()&&await this.makeRequest({trigger:"submit-message",messageId:null==(o=this.lastMessage)?void 0:o.id,metadata:t,headers:r,body:a})}};function uV({messages:e}){let t=e[e.length-1];if(!t||"assistant"!==t.role)return!1;let r=t.parts.reduce((e,t,r)=>"step-start"===t.type?r:e,-1),a=t.parts.slice(r+1).filter(uO);return a.filter(e=>"approval-responded"===e.state).length>0&&a.every(e=>"output-available"===e.state||"output-error"===e.state||"output-denied"===e.state||"approval-responded"===e.state)}var uW=e.i(802239),uG=Object.prototype.hasOwnProperty;let uY=new WeakMap,uJ=()=>{},uK=uJ(),uQ=Object,uX=e=>e===uK,u0=(e,t)=>({...e,...t}),u1={},u2={},u5="undefined",u4=typeof window!=u5,u3=typeof document!=u5,u9=u4&&"Deno"in window,u6=(e,t)=>{let r=uY.get(e);return[()=>!uX(t)&&e.get(t)||u1,a=>{if(!uX(t)){let n=e.get(t);t in u2||(u2[t]=n),r[5](t,u0(n,a),n||u1)}},r[6],()=>!uX(t)&&t in u2?u2[t]:!uX(t)&&e.get(t)||u1]},u8=!0,[u7,ce]=u4&&window.addEventListener?[window.addEventListener.bind(window),window.removeEventListener.bind(window)]:[uJ,uJ],ct={initFocus:e=>(u3&&document.addEventListener("visibilitychange",e),u7("focus",e),()=>{u3&&document.removeEventListener("visibilitychange",e),ce("focus",e)}),initReconnect:e=>{let t=()=>{u8=!0,e()},r=()=>{u8=!1};return u7("online",t),u7("offline",r),()=>{ce("online",t),ce("offline",r)}}},cr=!ek.default.useId,ca=!u4||u9,cn=ca?ek.useEffect:ek.useLayoutEffect,ci="u">typeof navigator&&navigator.connection,cs=!ca&&ci&&(["slow-2g","2g"].includes(ci.effectiveType)||ci.saveData),co=new WeakMap,cl=(e,t)=>e===`[object ${t}]`,cu=0,cc=e=>{let t,r,a=typeof e,n=uQ.prototype.toString.call(e),i=cl(n,"Date"),s=cl(n,"RegExp"),o=cl(n,"Object");if(uQ(e)!==e||i||s)t=i?e.toJSON():"symbol"==a?e.toString():"string"==a?JSON.stringify(e):""+e;else{if(t=co.get(e))return t;if(t=++cu+"~",co.set(e,t),Array.isArray(e)){for(r=0,t="@";r<e.length;r++)t+=cc(e[r])+",";co.set(e,t)}if(o){t="#";let a=uQ.keys(e).sort();for(;!uX(r=a.pop());)uX(e[r])||(t+=r+":"+cc(e[r])+",");co.set(e,t)}}return t},cd=e=>{if("function"==typeof e)try{e=e()}catch(t){e=""}let t=e;return[e="string"==typeof e?e:(Array.isArray(e)?e.length:e)?cc(e):"",t]},cp=0,ch=()=>++cp;async function cm(...e){let[t,r,a,n]=e,i=u0({populateCache:!0,throwOnError:!0},"boolean"==typeof n?{revalidate:n}:n||{}),s=i.populateCache,o=i.rollbackOnError,l=i.optimisticData,u=i.throwOnError;if("function"==typeof r){let e=[];for(let a of t.keys())!/^\$(inf|sub)\$/.test(a)&&r(t.get(a)._k)&&e.push(a);return Promise.all(e.map(c))}return c(r);async function c(r){let n,[c]=cd(r);if(!c)return;let[d,p]=u6(t,c),[h,m,f,g]=uY.get(t),v=()=>{let e=h[c];return("function"==typeof i.revalidate?i.revalidate(d().data,r):!1!==i.revalidate)&&(delete f[c],delete g[c],e&&e[0])?e[0](2).then(()=>d().data):d().data};if(e.length<3)return v();let y=a,b=!1,x=ch();m[c]=[x,0];let w=!uX(l),_=d(),k=_.data,S=_._c,E=uX(S)?k:S;if(w&&p({data:l="function"==typeof l?l(E,k):l,_c:E}),"function"==typeof y)try{y=y(E)}catch(e){n=e,b=!0}if(y&&"function"==typeof y.then){let e;if(y=await y.catch(e=>{n=e,b=!0}
75),x!==m[c][0]){if(b)throw n;return y}b&&w&&(e=n,"function"==typeof o?o(e):!1!==o)&&(s=!0,p({data:E,_c:uK}))}if(s&&!b&&("function"==typeof s?p({data:s(y,E),error:uK,_c:uK}):p({data:y,error:uK,_c:uK})),m[c][1]=ch(),Promise.resolve(v()).then(()=>{p({_c:uK})}),b){if(u)throw n;return}return y}}let cf=(e,t)=>{for(let r in e)e[r][0]&&e[r][0](t)},cg=(e,t)=>{if(!uY.has(e)){let r=u0(ct,t),a=Object.create(null),n=cm.bind(uK,e),i=uJ,s=Object.create(null),o=(e,t)=>{let r=s[e]||[];return s[e]=r,r.push(t),()=>{let e=r.indexOf(t);e>=0&&(r[e]=r[r.length-1],r.pop())}},l=(t,r,a)=>{e.set(t,r);let n=s[t];if(n)for(let e of n)e(r,a)},u=t=>{let r=uY.get(e),[,n,i,o]=r,l=ch();for(let e in r[8]++,i)delete i[e];for(let e in o)delete o[e];for(let e in n)n[e]=[l,l];let u={};for(let t of[...e.keys()]){let r=e.get(t);e.delete(t);let a=s[t];if(a)for(let e of a)e(u,r)}let c=!t||!1!==t.revalidate;for(let e in a){let t=a[e];for(let e=0;e<t.length;e++)t[e](4,{revalidate:c&&!e})}},c=()=>{if(!uY.has(e)&&(uY.set(e,[a,Object.create(null),Object.create(null),Object.create(null),n,l,o,u,0]),!ca)){let t=r.initFocus(setTimeout.bind(uK,cf.bind(uK,a,0))),n=r.initReconnect(setTimeout.bind(uK,cf.bind(uK,a,1)));i=()=>{t&&t(),n&&n(),uY.delete(e)}}};return c(),[e,n,c,i,u]}let r=uY.get(e);return[e,r[4],uK,uK,r[7]]},[cv,cy,,,cb]=cg(new Map),cx=u0({onLoadingSlow:uJ,onSuccess:uJ,onError:uJ,onErrorRetry:(e,t,r,a,n)=>{let i=r.errorRetryCount,s=n.retryCount,o=~~((Math.random()+.5)*(1<<(s<8?s:8)))*r.errorRetryInterval;(uX(i)||!(s>i))&&setTimeout(a,o,n)},onDiscarded:uJ,revalidateOnFocus:!0,revalidateOnReconnect:!0,revalidateIfStale:!0,shouldRetryOnError:!0,errorRetryInterval:cs?1e4:5e3,focusThrottleInterval:5e3,dedupingInterval:2e3,loadingTimeout:cs?5e3:3e3,compare:function e(t,r){var a,n;if(t===r)return!0;if(t&&r&&(a=t.constructor)===r.constructor){if(a===Date)return t.getTime()===r.getTime();if(a===RegExp)return t.toString()===r.toString();if(a===Array){if((n=t.length)===r.length)for(;n--&&e(t[n],r[n]););return -1===n}if(!a||"object"==typeof t){for(a in n=0,t)if(uG.call(t,a)&&++n&&!uG.call(r,a)||!(a in r)||!e(t[a],r[a]))return!1;return Object.keys(r).length===n}}return t!=t&&r!=r},isPaused:()=>!1,cache:cv,mutate:cy,unload:cb,fallback:{}},{isOnline:()=>u8,isVisible:()=>{let e=u3&&document.visibilityState;return uX(e)||"hidden"!==e}}),cw=(0,ek.createContext)({}),c_=u4&&window.__SWR_DEVTOOLS_USE__;(c_?window.__SWR_DEVTOOLS_USE__:[]).concat(e=>(t,r,a)=>{let n=r&&((...e)=>{let[a]=cd(t),[,,,n]=uY.get(cv);if(a.startsWith("$inf$"))return r(...e);let i=n[a];return uX(i)?r(...e):(delete n[a],i)});return e(t,n,a)}),c_&&(window.__SWR_DEVTOOLS_REACT__=ek.default);let ck=ek.default.use||(e=>{switch(e.status){case"pending":throw e;case"fulfilled":return e.value;case"rejected":throw e.reason;default:throw e.status="pending",e.then(t=>{e.status="fulfilled",e.value=t},t=>{e.status="rejected",e.reason=t}),e}}),cS={dedupe:!0},cE=Promise.resolve(uK);cE.status="fulfilled",cE.value=uK;uQ.defineProperty(e=>{let{value:t}=e,r=(0,ek.useContext)(cw),a="function"==typeof t,n=(0,ek.useMemo)(()=>a?t(r):t,[a,r,t]),i=(0,ek.useMemo)(()=>a?n:((e,t)=>{let r=u0(e,t);if(t){let{use:a,fallback:n,cacheData:i}=e,{use:s,fallback:o,cacheData:l}=t;a&&s&&(r.use=a.concat(s)),n&&o&&(r.fallback=u0(n,o)),i&&l&&(r.cacheData=u0(i,l))}return r})(r,n),[a,r,n]),s=n&&n.provider,o=(0,ek.useRef)(uK);s&&!o.current&&(o.current=cg(s(i.cache||cv),n));let l=o.current;return l&&(i.cache=l[0],i.mutate=l[1],i.unload=l[4]),cn(()=>{if(l)return l[2]&&l[2](),l[3]},[]),(0,ek.createElement)(cw.Provider,u0(e,{value:i}))},"defaultValue",{value:cx});var cC=e.i(561866),cj=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)},cI=(e,t,r)=>(cj(e,t,"read from private field"),r?r.call(e):t.get(e)),cT=(e,t,r)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,r)},cN=(e,t,r,a)=>(cj(e,t,"write to private field"),a?a.call(e,r):t.set(e,r),r),cR=class{constructor(e=[]){cT(this,G,void 0),cT(this,Y,"ready"),cT(this,J,void 0),cT(this,K,new Set),cT(this,Q,new Set),cT(this,X,new Set),this.pushMessage=e=>
75{cN(this,G,cI(this,G).concat(e)),cI(this,ee).call(this)},this.popMessage=()=>{cN(this,G,cI(this,G).slice(0,-1)),cI(this,ee).call(this)},this.replaceMessage=(e,t)=>{cN(this,G,[...cI(this,G).slice(0,e),this.snapshot(t),...cI(this,G).slice(e+1)]),cI(this,ee).call(this)},this.snapshot=e=>{var t;if(null==e||"object"!=typeof e||!("parts"in e)||!Array.isArray(e.parts))return e;let r={...e,parts:e.parts.map(e=>({...e}))};return"metadata"in e&&(r.metadata=Array.isArray(t=e.metadata)?[...t]:null!=t&&"object"==typeof t&&(Object.getPrototypeOf(t)===Object.prototype||null===Object.getPrototypeOf(t))?{...t}:t),r},this["~registerMessagesCallback"]=(e,t)=>{let r=t?null!=t?(0,cC.default)(e,t):e:e;return cI(this,K).add(r),()=>{cI(this,K).delete(r)}},this["~registerStatusCallback"]=e=>(cI(this,Q).add(e),()=>{cI(this,Q).delete(e)}),this["~registerErrorCallback"]=e=>(cI(this,X).add(e),()=>{cI(this,X).delete(e)}),cT(this,ee,()=>{cI(this,K).forEach(e=>e())}),cT(this,et,()=>{cI(this,Q).forEach(e=>e())}),cT(this,er,()=>{cI(this,X).forEach(e=>e())}),cN(this,G,e)}get status(){return cI(this,Y)}set status(e){cN(this,Y,e),cI(this,et).call(this)}get error(){return cI(this,J)}set error(e){cN(this,J,e),cI(this,er).call(this)}get messages(){return cI(this,G)}set messages(e){cN(this,G,[...e]),cI(this,ee).call(this)}};G=new WeakMap,Y=new WeakMap,J=new WeakMap,K=new WeakMap,Q=new WeakMap,X=new WeakMap,ee=new WeakMap,et=new WeakMap,er=new WeakMap;var cA=class extends uq{constructor({messages:e,...t}){const r=new cR(e);super({...t,state:r}),cT(this,ea,void 0),this["~registerMessagesCallback"]=(e,t)=>cI(this,ea)["~registerMessagesCallback"](e,t),this["~registerStatusCallback"]=e=>cI(this,ea)["~registerStatusCallback"](e),this["~registerErrorCallback"]=e=>cI(this,ea)["~registerErrorCallback"](e),cN(this,ea,r)}};ea=new WeakMap;var cz=e.i(192875),cM=e.i(87947),cO=e.i(846696),cP=e.i(613176),c$=e.i(685904),cD=e.i(522016),cU=e.i(371532);function cL({title:e,siteName:t,excerpt:r,returnHref:a,articleVisible:n=!1}){let i=(0,ec.useTranslations)("chat"),s=r.replace(/[#*_>`\[\]()]/g," ").replace(/\s+/g," ").trim(),o=s.length>220?`${s.slice(0,220).replace(/\s+\S*$/,"")}…`:s;return n?(0,en.jsxs)("div",{className:"mx-4 my-2 flex min-w-0 shrink-0 items-center gap-2 rounded-md bg-muted/35 px-2.5 py-2","data-current-article-context":"",children:[(0,en.jsx)(cU.BookOpen,{"aria-hidden":"true",className:"size-3.5 shrink-0 text-muted-foreground"}),(0,en.jsxs)("p",{className:"min-w-0 truncate text-xs leading-4 text-muted-foreground",title:e,children:[(0,en.jsxs)("span",{className:"sr-only",children:[i("readingNow"),": "]}),e]})]}):(0,en.jsx)("div",{className:"shrink-0 bg-background px-3 pb-2 pt-3 sm:px-4",children:(0,en.jsxs)(cD.default,{href:a,"aria-label":i("backToArticleLabel",{title:e}),className:"group mx-auto flex w-full max-w-[42.5rem] touch-manipulation items-start gap-3 rounded-[14px] bg-card p-3.5 text-start shadow-hairline outline-none transition-[background-color,scale] hover:bg-muted/35 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background active:scale-[0.96] motion-reduce:transition-none motion-reduce:active:scale-100",children:[(0,en.jsx)("span",{className:"flex size-9 shrink-0 items-center justify-center rounded-[10px] bg-muted/45 text-muted-foreground transition-colors group-hover:text-foreground",children:(0,en.jsx)(cU.ChevronLeft,{className:"size-4.5 rtl:rotate-180",strokeWidth:1.75,"aria-hidden":"true"})}),(0,en.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,en.jsx)("span",{className:"block text-xs font-medium text-muted-foreground",children:t?i("backToArticleWithSite",{siteName:t}):i("backToArticle")}),(0,en.jsx)("span",{className:"mt-0.5 line-clamp-2 text-sm font-medium leading-5 text-foreground",children:e}),(0,en.jsx)("span",{className:"mt-1 line-clamp-2 text-xs leading-4 text-muted-foreground",children:o})]})]})})}var cF=e.i(370937),cZ=e.i(176782),cB=e.i(911825),cH=e.i(225913),cq=e.i(102321);let cV=(0,cH.cva)("group/attachment relative flex max-w-full min-w-0 shrink-0 flex-wrap border bg-card text-card-foreground transition-colors has-[>a,>button]:hover:bg-muted/50 data-[state=error]:border-destructive/30 data-[state=idle]:border-dashed",{variants:{size:{default:"gap-2.5 rounded-lg px-3 py-2.5 text-sm",sm:"gap-2 rounded-lg px-2.5 py-2 text-sm",xs:"gap-2 rounded-md px-2 py-1.5 text-xs"},orientation:{horizontal:"items-center",vertical:"flex-col"}},defaultVariants:{size:"default",orientation:"horizontal"}});function cW({className:e,state:t="done",size:r="default",orientation:a="horizontal",...n}){return(0,en.jsx)("div",{"data-slot":"attachment","data-state":t,"data-size":r,"data-orientation":a,className:(0,eE.cn)(cV({size:r,orientation:a}),e),...n})}
75let cG=(0,cH.cva)("relative flex aspect-square shrink-0 items-center justify-center overflow-hidden group-data-[state=error]/attachment:bg-destructive/10 group-data-[state=error]/attachment:text-destructive [&_svg]:pointer-events-none",{variants:{variant:{icon:"rounded-md bg-muted/60 text-muted-foreground [&_svg]:size-4",image:"rounded-md bg-muted/60 [&_img]:aspect-square [&_img]:w-full [&_img]:object-cover"},size:{default:"size-8",sm:"size-7",xs:"size-6"}},defaultVariants:{variant:"icon",size:"default"}});function cY({className:e,variant:t="icon",size:r="default",...a}){return(0,en.jsx)("div",{"data-slot":"attachment-media","data-variant":t,className:(0,eE.cn)(cG({variant:t,size:r}),e),...a})}function cJ({className:e,...t}){return(0,en.jsx)("div",{"data-slot":"attachment-content",className:(0,eE.cn)("max-w-full min-w-0 flex-1",e),...t})}function cK({className:e,children:t,title:r,...a}){return(0,en.jsx)("span",{"data-slot":"attachment-title",title:r??("string"==typeof t?t:void 0),className:(0,eE.cn)("block max-w-full min-w-0 truncate font-medium",e),...a,children:t})}function cQ({className:e,children:t,title:r,...a}){return(0,en.jsx)("span",{"data-slot":"attachment-description",title:r??("string"==typeof t?t:void 0),className:(0,eE.cn)("block max-w-full min-w-0 truncate text-muted-foreground group-data-[state=error]/attachment:text-destructive/80",e),...a,children:t})}function cX({className:e,...t}){return(0,en.jsx)("div",{"data-slot":"attachment-actions",className:(0,eE.cn)("flex shrink-0 items-center",e),...t})}let c0=(0,cH.cva)("group/bubble relative flex w-fit min-w-0 max-w-[80%] flex-col gap-1 data-[variant=ghost]:max-w-full",{variants:{variant:{default:"bg-chat-bubble text-chat-bubble-foreground",secondary:"bg-secondary text-secondary-foreground",muted:"bg-muted text-foreground",tinted:"bg-primary/10 text-foreground",outline:"border border-border bg-card text-card-foreground",ghost:"w-full bg-transparent text-foreground",destructive:"bg-destructive text-destructive-foreground"}},defaultVariants:{variant:"default"}});function c1({variant:e="default",align:t="start",className:r,...a}){return(0,en.jsx)("div",{"data-slot":"bubble","data-variant":e,"data-align":t,className:(0,eE.cn)(c0({variant:e}),"rounded-xl data-[align=end]:ml-auto data-[variant=ghost]:rounded-none",r),...a})}function c2({className:e,render:t,...r}){return(0,cB.useRender)({defaultTagName:"div",props:(0,cZ.mergeProps)({className:(0,eE.cn)("w-fit max-w-full min-w-0 overflow-hidden break-words text-sm leading-relaxed [&_a]:transition-colors [&_button]:text-left [&_button]:transition-colors",e)},r),render:t,state:{slot:"bubble-content"}})}(0,cH.cva)("absolute z-10 flex w-fit items-center justify-center",{variants:{side:{top:"bottom-full mb-1",bottom:"top-full mt-1"},align:{start:"left-2",end:"right-2"}},defaultVariants:{side:"bottom",align:"end"}});var c5=e.i(407294);function c4({text:e,isGenerating:t=!1}){let[r,a]=(0,ek.useState)(null),n=r??t,i=e.trim();return i?(0,en.jsxs)("details",{"data-chat-thought":"",className:"group/thought max-w-full text-muted-foreground",open:n,children:[(0,en.jsxs)("summary",{className:"-mx-1.5 flex min-h-8 w-fit cursor-pointer list-none items-center gap-1 rounded-md px-1.5 text-[0.8125rem] font-medium leading-5 transition-colors hover:bg-muted/45 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background pointer-coarse:min-h-11 [&::-webkit-details-marker]:hidden",onClick:function(e){e.preventDefault(),a(!n)},children:[(0,en.jsx)("span",{children:t?"Thinking":"Thought"}),(0,en.jsx)(cU.ChevronDown,{className:"size-3.5 shrink-0 transition-transform duration-150 group-open/thought:rotate-180 motion-reduce:transition-none",strokeWidth:1.5,"aria-hidden":"true"})]}),(0,en.jsx)("div",{"aria-busy":t,className:(0,eE.cn)("mt-1.5 max-w-prose border-s border-border/60 ps-3 text-[0.8125rem] font-normal leading-5 text-muted-foreground",t&&"flex max-h-40 flex-col justify-end overflow-hidden [mask-image:linear-gradient(to_bottom,transparent,black_2.5rem)]"),children:(0,en.jsx)("p",{className:"whitespace-pre-wrap break-words text-pretty",children:i})})]}):null}var c3=e.i(269999);function c9(e){return"dynamic-tool"===e.type?e.toolName:e.type.slice(5)}let c6={search_library:{icon:cU.Search,label:"Searched your library",running:"Searching your library"},read_article:{icon:cU.BookOpen,label:"Read saved article",running:"Reading saved article"},fetch_article_url:{icon:cU.BookOpen,label:"Fetched article",running:"Fetching article"},show_articles:{icon:cU.Bookmark,label:"Showed saved articles",running:"Preparing saved articles"},get_article:{icon:cU.BookOpen,label:"Opened article",running:"Opening article"},search_article:{icon:cU.Search,label:"Searched article",running:"Searching article"},outline_current_article:{icon:cU.BookOpen,label:"Outlined this article",running:"Outlining this article"},search_current_article:{icon:cU.Search,label:"Searched this article",running:"Searching this article"},read_current_article:{icon:cU.BookOpen,label:"Read this article",running:"Reading this article"},search_feeds:{icon:cU.Rss,label:"Found public feeds",running:"Finding public feeds"},list_library:{icon:cU.Bookmark,label:"Listed saved articles",running:"Listing saved articles"},get_saved_article:{icon:cU.BookOpen,label:"Opened saved article",running:"Opening saved article"},save_article:{icon:cU.Bookmark,label:"Saved article",running:"Saving article"},update_library_item:{icon:cU.Settings,label:"Updated saved article",running:"Updating saved article"},remove_library_item:{icon:cU.Trash,label:"Removed saved article",running:"Removing saved article"},query_feeds:{icon:cU.Rss,label:"Queried followed feeds",running:"Querying followed feeds"},get_feed_changes:{icon:cU.RefreshCw,label:"Checked for new entries",running:"Checking for new entries"},follow_feeds:{icon:cU.Rss,label:"Followed feeds",running:"Following feeds"},mutate_feeds:{icon:cU.Settings,label:"Updated feeds",running:"Updating feeds"},manage_feed_consumers:{icon:cU.Compass,label:"Managed feed consumers",running:"Managing feed consumers"},create_monitor:{icon:cU.Rss,label:"Created web monitor",running:"Creating web monitor"}};function c8(e){return null===e||"object"!=typeof e||Array.isArray(e)?null:e}function c7(e){return e.replaceAll("_"," ").replace(/^./,e=>e.toUpperCase())}function de(e,t=240){let r=(e.split("\n").map(e=>e.trim()).find(e=>e&&!e.startsWith("<"))??"").replace(/\s+/g," ");return r.length>t?`${r.slice(0,t-1).trimEnd()}…`:r}function dt(e){let t=c8(e);return t?c8(t.structuredContent)??t:null}function dr({items:e}){if(0===e.length)return null;let t=e.slice(0,3);return(0,en.jsxs)("div",{className:"mt-1.5 space-y-1.5",children:[t.map(e=>{let t=function(e){for(let t of["title","name","heading","feedTitle","siteName","url"])if("string"==typeof e[t]&&e[t])return de(e[t],160);return null}(e)??"Result",r=function(e){for(let t of["description","summary","excerpt","text","domain","siteUrl","sourceUrl","source_url","feedUrl","url"])if("string"==typeof e[t]&&e[t])return de(e[t],240);return null}(e),a="string"==typeof e.id||"number"==typeof e.id?String(e.id):"string"==typeof e.url?e.url:JSON.stringify(e);return(0,en.jsxs)("div",{className:"min-w-0",children:[(0,en.jsx)("p",{className:"truncate text-[0.8125rem] font-medium leading-5 text-foreground
75/90",children:t}),r&&r!==t?(0,en.jsx)("p",{className:"truncate text-xs leading-5 text-muted-foreground/75",children:r}):null]},`${a}-${t}`)}),e.length>t.length?(0,en.jsxs)("p",{className:"text-xs leading-5 text-muted-foreground/75",children:["+",e.length-t.length," more"]}):null]})}function da({part:e,onApprovalResponse:t,approvalDisabled:r=!1}){let[a,n]=(0,ek.useState)(!1),i=c9(e),s=c6[i],o=s??{icon:cU.Settings,label:c7(i),running:`${c7(i)}…`},l=o.icon,u=function(e){if("output-error"===e.state||"output-denied"===e.state)return!0;if("output-available"!==e.state)return!1;let t=c8(e.output),r=dt(e.output);return t?.isError===!0||"string"==typeof r?.error}(e),c="output-available"===e.state||"output-error"===e.state,d="approval-requested"===e.state?c8(c8(e)?.approval):null,p="string"==typeof d?.id?d.id:null,h=p&&d?.isAutomatic!==!0,m="approval-responded"===e.state,f="output-denied"===e.state,g=dt(e.output),v=function(e){if(!e)return[];for(let t of["data","entries","subscriptions","items","results","passages"]){let r=e[t];if(Array.isArray(r))return r.map(c8).filter(e=>!!e)}let t=c8(e.feed)??c8(e.article)??c8(e.subscription)??c8(e.item)??c8(e.collection);return t?[t]:[]}(g),y="output-error"===e.state?e.errorText?de(e.errorText,400):null:"output-available"===e.state?function(e,t,r,a){if("string"==typeof r?.error)return de(r.error);if("string"==typeof r?.message)return de(r.message);if(a.length>0){let t=e.includes("rss")?"feed":e.includes("library")?"article":"item";return`${a.length} ${t}${1===a.length?"":"s"}`}if(r?.deleted===!0)return"Deleted";if(r?.read===!0)return"Marked as read";if("string"==typeof r?.feedback)return`Feedback: ${r.feedback}`;let n=c8(t);if(!n)return null;let i=(Array.isArray(n.content)?n.content:[]).find(e=>{let t=c8(e);return t?.type==="text"&&"string"==typeof t.text}),s=c8(i);if("string"==typeof s?.text)return de(s.text);let o=dt(t);return"string"==typeof o?.message?de(o.message):null}(i,e.output,g,v):null,b=s?c&&!u?o.label:o.running:e.title??(c&&!u?o.label:o.running),x=h?"Approve this action?":f?"Action canceled":u?`${o.label} failed`:b,w=c&&!u&&v.length>0,_=[x,y].filter(Boolean).join(" · "),k=w?(0,en.jsxs)("button",{type:"button",onClick:()=>n(e=>!e),"aria-expanded":a,className:"-mx-1 flex min-h-8 max-w-full items-center gap-2 rounded-md px-1 text-[0.8125rem] leading-5 text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring pointer-coarse:min-h-11",children:[(0,en.jsx)(l,{"aria-hidden":"true",className:"size-4 shrink-0"}),(0,en.jsx)("span",{className:"min-w-0 truncate text-start",children:_}),(0,en.jsx)(cU.ChevronDown,{"aria-hidden":"true",className:(0,eE.cn)("size-3.5 shrink-0 transition-transform duration-150 motion-reduce:transition-none",a&&"rotate-180")})]}):(0,en.jsxs)("div",{className:"flex min-h-8 max-w-full items-center gap-2 text-[0.8125rem] leading-5 text-muted-foreground pointer-coarse:min-h-11",children:[(0,en.jsx)(l,{"aria-hidden":"true",className:"size-4 shrink-0"}),(0,en.jsx)("span",{className:(0,eE.cn)("min-w-0 truncate",!c&&"shimmer"),children:_}),c||f||h?u||f?(0,en.jsx)(cU.X,{"aria-hidden":"true",className:"size-3.5 shrink-0"}):null:(0,en.jsx)(c3.Ring,{"aria-hidden":"true",className:"size-3.5 shrink-0"})]});return(0,en.jsxs)("section",{"aria-live":c?"off":"polite","aria-label":`${c7(i)} tool activity`,className:(0,eE.cn)("my-1",h&&"rounded-[10px] bg-muted/30 p-3 shadow-hairline"),role:u||f?"alert":"status",children:[k,(0,en.jsxs)("div",{className:"ps-6",children:[h?(0,en.jsxs)("div",{className:"mt-1",children:[(0,en.jsx)("p",{className:"text-[0.8125rem] leading-5 text-muted-foreground",children:"Remy is waiting for your approval before changing your account."}),(0,en.jsxs)("div",{className:"mt-2 flex flex-wrap gap-2",children:[(0,en.jsx)("button",{type:"button",disabled:r||!t,onClick:()=>void t?.(p,!0),className:"inline-flex min-h-9 items-center justify-center rounded-lg bg-primary px-3 text-xs font-medium text-primary-foreground transition-opacity hover:opacity-90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:pointer-events-none disabled:opacity-50 pointer-coarse:min-h-11",children:"Approve"}),(0,en.jsx)("button",{type:"button",disabled:r||!t,onClick:()=>void t?.(p,!1),className:"inline-flex min-h-9 items-center justify-center rounded-lg bg-background px-3 text-xs font-medium text-foreground shadow-hairline transition-colors hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:pointer-events-none disabled:opacity-50 pointer-coarse:min-h-11",children:"Cancel"})]})]}
75):m?(0,en.jsx)("p",{className:"text-xs leading-5 text-muted-foreground/75",children:"Approval recorded. Completing the action…"}):f?(0,en.jsx)("p",{className:"text-xs leading-5 text-muted-foreground/75",children:"You canceled this request. Nothing was added to your account."}):null,w&&a?(0,en.jsx)(dr,{items:v}):null]})]})}var dn=e.i(23084);function di({part:e,onContinue:t,disabled:r=!1}){let{isLoaded:a,isSignedIn:n}=(0,cz.useAuth)(),i=(0,dn.useOpenSignInModal)({preserveClientState:!0}),s=dt(e.output),o="string"==typeof s?.continuation?s.continuation:"Continue the account action I just requested.";return"output-available"!==e.state?(0,en.jsx)("div",{"aria-live":"polite",className:"my-2 rounded-[14px] border border-border/55 bg-muted/40 px-3 py-3 shadow-workbench",role:"status",children:(0,en.jsx)("p",{className:"text-sm text-muted-foreground",children:"Preparing sign in…"})}):(0,en.jsx)("section",{className:"my-3 rounded-[14px] border border-border/55 bg-card p-4 shadow-workbench",children:(0,en.jsxs)("div",{className:"flex items-start gap-3",children:[(0,en.jsx)("span",{className:"flex size-8 shrink-0 items-center justify-center rounded-lg bg-muted text-muted-foreground",children:(0,en.jsx)(cU.LogIn,{"aria-hidden":"true",className:"size-4"})}),(0,en.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,en.jsx)("p",{className:"text-balance text-sm font-medium text-foreground",children:"Sign in to make this yours"}),(0,en.jsx)("p",{className:"mt-1 text-pretty text-xs leading-5 text-muted-foreground",children:"Public research stays here. Signing in unlocks your library and lets Remy save, follow, and sync the action you already chose."}),(0,en.jsx)("div",{className:"mt-3",children:a&&n?(0,en.jsx)(cq.Button,{variant:"default",type:"button",size:"sm",disabled:r,onClick:()=>t?.(o),children:"Continue"}):(0,en.jsx)(cq.Button,{variant:"outline",type:"button",size:"sm",disabled:r,onClick:i,children:"Sign in to continue"})})]})]})})}var ds=e.i(108286);let dl=(0,ek.createContext)(null);var du=e.i(689554),dc=e.i(671428),dd=e.i(831123),dp=e.i(422488),dh=e.i(521976),dm=e.i(802822),df=e.i(537510);let dg=null;function dv(){return(0,en.jsxs)("div",{"aria-busy":"true","aria-live":"polite",className:"mx-px my-3 rounded-xl bg-card p-4 shadow-hairline",role:"status",children:[(0,en.jsx)("span",{className:"sr-only",children:"Opening the secure connection"}),(0,en.jsxs)("div",{className:"flex items-start gap-3",children:[(0,en.jsx)(dc.Skeleton,{className:"size-8 shrink-0 rounded-lg"}),(0,en.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,en.jsx)(dc.Skeleton,{className:"h-4 w-44 rounded-md"}),(0,en.jsx)(dc.Skeleton,{className:"mt-2.5 h-3 w-[92%] rounded-md",delay:80}),(0,en.jsx)(dc.Skeleton,{className:"mt-1.5 h-3 w-[64%] rounded-md",delay:160}),(0,en.jsx)(dc.Skeleton,{className:"mt-3 h-8 w-24 rounded-full",delay:240})]})]})]})}function dy({part:e,onRetry:t}){let r=(0,ek.useRef)(null),a=(0,ek.useRef)(null),[n,i]=(0,ek.useState)("loading"),{isLoaded:s,isSignedIn:o}=(0,cz.useAuth)(),l=(0,ek.useContext)(dl),u=(0,dh.useConfigureSignIn)(),{resolvedTheme:c,theme:d}=(0,du.useTheme)(),p=(0,ek.useMemo)(()=>(0,df.isDarkTheme)(d,c)?"dark":"light",[c,d]),h=dt(e.output),m=(0,dd.configureMintedUrl)(h?.connectUrl||h?.connect_url||h?.import_url||h?.connect?.connect_url||h?.connect?.import_url||null),f=(0,dd.configureHostOrigin)(h?.hostOrigin),g="output-available"===e.state,v=!!h?.connected||h?.connect?.connected===!0,{track:y}=(0,dm.useAnalytics)(),b=(0,ek.useRef)(!1);return((0,eP.useExternalSync)(()=>{b.current||(b.current=!0,y("configure_card_shown",{connected:v,signed_in:s?!0===o:null}))},[v,s,o,y]),(0,eP.useExternalSync)(()=>{if(!g||!m||"loading"!==n)return;if(!r.current)return void i("failed");let e=!1;return(window.ConfigureMcpAppHost?Promise.resolve():dg??=new Promise((e,t)=>{let r=document.createElement("script");r.src=`${f}/mcp-apps/configure-mcp-host.js`,r.async=!0,r.onload=()=>{dg=null,e()},r.onerror=()=>{dg=null,t(Error("Configure host script failed to load"))},document.head.appendChild(r)})).then(()=>{if(e||!r.current)return;let t=window.ConfigureMcpAppHost;if(!t?.mount)throw Error("Configure host script loaded without mount()");a.current=t.mount({container:r.current,resourceUri:"ui://configure/connect/v8.html",result:h?.connect?.mcp_result??h?.connect??{connect_url:m},agentName:"Smry",theme:p,origin:f,onOpenLink:e=>{window.location.assign(e)}})??null,i("mounted")}
75).catch(()=>{e||i("failed")}),()=>{e=!0}},[g,m,n,h,p,f]),(0,eP.useExternalSync)(()=>{a.current?.setTheme?.(p)},[p]),(0,eP.useExternalSync)(()=>()=>{let e=a.current;a.current=null;try{e?.dispose?.()}catch{}},[]),g)?m&&"failed"!==n?(0,en.jsxs)("div",{className:"my-3",children:["loading"===n?(0,en.jsx)(dv,{}):null,(0,en.jsx)("div",{ref:r})]}):(0,en.jsxs)("section",{className:"mx-px my-3 rounded-xl bg-card p-4 shadow-hairline",children:[(0,en.jsxs)("div",{className:"flex items-start gap-3",children:[(0,en.jsx)("span",{className:"flex size-8 shrink-0 items-center justify-center rounded-lg bg-muted text-muted-foreground",children:v?(0,en.jsx)(cU.Check,{"aria-hidden":"true",className:"size-4",strokeWidth:2.25}):(0,en.jsx)(cU.Link2,{"aria-hidden":"true",className:"size-4"})}),(0,en.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,en.jsx)("p",{className:"text-sm font-medium text-foreground",children:v?"Connected":"Connect your accounts"}),(0,en.jsx)("p",{className:"mt-1 text-xs leading-5 text-muted-foreground",children:v?"Smry now personalizes from your Configure profile. Manage or disconnect on Configure anytime.":"Securely connect your other AI assistants so Smry can personalize with what they already know. You approve everything on Configure's page; disconnect anytime."}),v?null:(0,en.jsx)("div",{className:"mt-3",children:m?(0,en.jsx)(cq.Button,{variant:"default",onClick:()=>window.location.assign(function(e){try{let t=new URL(window.location.href);if("https:"!==t.protocol&&"http:"!==t.protocol||t.username||t.password)return e;let r=t.toString();if(r.length>1024)return e;let a=new URL(e);return a.searchParams.set("rt",r),a.toString()}catch{return e}}(m)),size:"sm",children:"Connect"}):h?.signedOut&&o?t?(0,en.jsx)(cq.Button,{onClick:()=>t(),size:"sm",variant:"outline",children:"Continue connecting"}):null:s&&!o?(0,en.jsx)(cq.Button,{onClick:()=>{u.start((0,dd.connectReturnPathForThread)(l,(0,ds.getCurrentUrl)()),{signedIn:s?o:void 0})},size:"sm",variant:"default",children:"Connect"}):(0,en.jsx)("p",{className:"text-xs text-muted-foreground",children:h?.message??"Connection is temporarily unavailable. Try again soon."})})]})]}
75),u.leaving?(0,en.jsx)(dp.ConfigureHandoffCover,{label:"Taking you to Configure…"}):null]}):(0,en.jsx)(dv,{})}var db=e.i(908665),dx=e.i(640777);let dw=/(?:\b(?:recommend(?:ed|ation|ations)?|reading list|read next|worth reading|start with|suggested order|why read|best if you liked|empfehl\w*|leseempfehl\w*|recomiend\w*|recomend\w*|lecturas? recomendadas?|aanbevol\w*|aanrad\w*|leeslijst|leituras? recomendadas?)\b|推荐|阅读顺序|先读|值得读)/i;function d_(e){return e.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLocaleLowerCase("en-US").replace(/&/g," and ").replace(/[’‘`]/g,"'").replace(/["']/g,"").replace(/[\u0000-\u002f\u003a-\u0040\u005b-\u0060\u007b-\u00bf\u2000-\u206f]+/g," ").replace(/\s+/g," ").trim()}function dk({source:e,index:t,getSaveState:r,onSaveSource:a,saveLabels:n,labels:i}){let s=r?.(e),o=!!(s&&a&&n),l="saved"===s,u="saving"===s,c=u?n?.saving:l?n?.saved:n?.save;return(0,en.jsxs)("div",{className:"group/recommendation grid min-w-0 grid-cols-[minmax(0,1fr)_auto] items-stretch transition-colors hover:bg-muted/45 focus-within:bg-muted/45",children:[(0,en.jsxs)("a",{href:e.url,target:"_blank",rel:"noopener noreferrer","aria-label":`${i.openOriginal}: ${e.title}`,className:"grid min-h-16 min-w-0 grid-cols-[1.25rem_1.75rem_minmax(0,1fr)_auto] items-center gap-2.5 rounded-lg px-3 py-2.5 text-start outline-none focus-visible:z-10 focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring pointer-coarse:min-h-[4.5rem]",children:[(0,en.jsx)("span",{className:"self-start pt-0.5 text-[0.6875rem] leading-5 tabular-nums text-muted-foreground/70",children:String(t+1).padStart(2,"0")}),(0,en.jsx)("span",{className:"flex size-7 items-center justify-center overflow-hidden rounded-[7px] bg-muted/65",children:(0,en.jsx)(cF.FaviconImage,{domain:e.domain,className:"size-[18px] rounded-[5px] object-contain outline outline-1 -outline-offset-1 outline-black/10 dark:outline-white/10"})}),(0,en.jsxs)("span",{className:"min-w-0",children:[(0,en.jsx)("span",{className:"line-clamp-2 text-[0.875rem] font-medium leading-5 text-foreground",children:e.title}),(0,en.jsx)("span",{className:"mt-0.5 block truncate text-[0.75rem] leading-4 text-muted-foreground",children:e.domain})]}),(0,en.jsx)(cU.ArrowUpRight,{className:"size-3.5 shrink-0 text-muted-foreground/55 transition-colors group-hover/recommendation:text-foreground","aria-hidden":"true"})]}),o?(0,en.jsxs)("button",{type:"button",onClick:()=>void a?.(e),disabled:"idle"!==s,"aria-label":l?`${n?.savedInLibrary}: ${e.title}`:`${n?.saveToLibrary}: ${e.title}`,className:(0,eE.cn)("my-auto me-2 inline-flex h-8 shrink-0 items-center gap-1.5 whitespace-nowrap rounded-md px-2 text-[0.75rem] font-medium outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-default pointer-coarse:h-11 pointer-coarse:min-w-11 pointer-coarse:justify-center",l?"text-foreground":"text-muted-foreground enabled:hover:bg-background/80 enabled:hover:text-foreground","loading"===s&&"opacity-45"),children:[u?(0,en.jsx)(c3.Ring,{className:"size-3.5","aria-hidden":"true"}):l?(0,en.jsx)(cU.Check,{className:"size-3.5","aria-hidden":"true"}):(0,en.jsx)(cU.Bookmark,{className:"size-3.5","aria-hidden":"true"}),(0,en.jsxs)("span",{"data-slot":"recommendation-save-label",className:"grid","aria-live":"polite",children:[n?["save","saving","saved"].map(e=>(0,en.jsx)("span",{"aria-hidden":"true",className:"invisible col-start-1 row-start-1",children:n[e]},e)):null,(0,en.jsx)("span",{className:"col-start-1 row-start-1",children:c})]})]}):null]})}function dS({sources:e,labels:t,getSaveState:r,onSaveSource:a,saveLabels:n,className:i}){let s=(0,ek.useId)(),[o,l]=(0,ek.useState)(!1);if(0===e.length)return null;let u=Math.max(0,e.length-5),c=o?e:e.slice(0,5);return(0,en.jsxs)("section",{className:(0,eE.cn)("min-w-0",i),"aria-labelledby":s,children:[(0,en.jsxs)("div",{className:"mb-2 flex min-w-0 items-center justify-between gap-3 px-0.5",children:[(0,en.jsxs)("h3",{id:s,className:"flex min-w-0 items-center gap-2 text-[0.8125rem] font-medium leading-5 text-foreground",children:[(0,en.jsx)(cU.BookOpen,{className:"size-4 shrink-0 text-muted-foreground","aria-hidden":"true"}),(0,en.jsx)("span",{className:"truncate",children:t.title})]}),(0,en.jsxs)("span",{className:"shrink-0 text-[0.75rem] leading-5 tabular-nums text-muted-foreground",children:[e.length," ",1===e.length?t.article:t.articles]})]}),(0,en.jsxs)("div",{className:"overflow-hidden rounded-[14px] bg-card shadow-hairline",children:[(0,en.jsx)("ol",{className:"divide-y divide-border/55",children:c.map((e,i)=>(0,en.jsx)("li",{children:(0,en.jsx)(dk,{source:e,index:i,getSaveState:r,onSaveSource:a,saveLabels:n,labels:t})},(0,dx.normalizeCacheUrl)(e.url)))}),u>0?(0,en.jsx)("button",{type:"button",onClick:()=>l(e=>!e),"aria-expanded":o,className:"flex min-h-10 w-full items-center justify-center border-t border-border/55 px-3 text-[0.75rem] font-medium leading-5 text-muted-foreground outline-none transition-colors hover:bg-muted/45 hover:text-foreground focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring pointer-coarse:min-h-11",children:o?t.showFewer:`${t.showMore} \xb7 +${u}`}):null]})]})}var dE=e.i(770703),dC=e.i(728231);let dj={csv:"text/csv",gif:"image/gif",jpeg:"image/jpeg",jpg:"image/jpeg",markdown:"text/markdown",md:"text/markdown",pdf:"application/pdf",png:"image/png",txt:"text/plain",webp:"image/webp"},dI=new Set(Object.values(dj));function dT(e){return e.startsWith("image/")}function dN(e,t){return`data:${t};base64,`.length+4*Math.ceil(e/3)}function dR(e){let t="u">typeof crypto&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`;return`${e.name}-${e.size}-${e.lastModified}-${t}`}async function dA(e){try{var t,r;let a=await (t=e.sourceFile,r=e.mediaType,new Promise((e,a)=>{let n=new FileReader;n.onerror=()=>a(Error(`Could not read ${t.name}`)),n.onload=()=>{"string"==typeof n.result?e(n.result.replace(/^data:[^;,]*/,`data:${r}`)):a(Error(`Could not read ${t.name}`))},n.readAsDataURL(t)})),n=dT(e.mediaType)?await ("u"<typeof Image?Promise.resolve({status:"unavailable"}):new Promise(e=>{let t=new Image,r=!1,n=a=>{r||(r=!0,clearTimeout(i),t.onload=null,t.onerror=null,e(a))},i=setTimeout(()=>n({status:"timeout"}),5e3);t.onload=()=>
75{n(t.naturalWidth>0&&t.naturalHeight>0?{status:"loaded",width:t.naturalWidth,height:t.naturalHeight}:{status:"error"})},t.onerror=()=>n({status:"error"}),t.src=a})):{status:"unavailable"};if("error"===n.status)return{id:e.id,type:"file",filename:e.filename,mediaType:e.mediaType,size:e.size,status:"error",error:`${e.filename} is not a readable image.`,retryable:!1};return{id:e.id,type:"file",filename:e.filename,mediaType:e.mediaType,size:e.size,status:"ready",url:a,..."loaded"===n.status?{width:n.width,height:n.height}:{}}}catch{return{...e,status:"error",error:`Could not read ${e.filename}`,retryable:!0}}}function dz(e){return e.filter(e=>"ready"===e.status)}let dM=(0,dE.default)(()=>e.A(196410).then(e=>e.LocalChatImageDialog),{loadableGenerated:{modules:[358965]},ssr:!1});function dO(e,t){let r=e.match(/\.([a-z0-9]+)$/i)?.[1]?.toUpperCase();return r?"JPEG"===r?"JPG":r:"application/pdf"===t?"PDF":"text/markdown"===t?"Markdown":"text/csv"===t?"CSV":"text/plain"===t?"Text":dT(t)?"Image":"File"}function dP({files:e,onRemove:t,onRetry:r}){return 0===e.length?null:(0,en.jsx)("ul",{"aria-label":"Attached files",className:"scroll-fade-x flex min-w-0 snap-x snap-mandatory gap-2 overflow-x-auto overscroll-x-contain px-0.5 pb-2",children:e.map(e=>{var a;return(0,en.jsx)("li",{className:"min-w-0 max-w-full shrink-0 snap-start",children:(0,en.jsxs)(cW,{state:"preparing"===e.status?"processing":"error"===e.status?"error":"done",size:"sm",className:"max-w-[min(18rem,calc(100dvw-3.5rem))] rounded-[10px] border-border/60 bg-muted/30 pe-1.5 shadow-none",children:[(0,en.jsx)(cY,{size:"default",variant:"ready"===e.status&&dT(e.mediaType)?"image":"icon",children:"ready"===e.status&&dT(e.mediaType)?(0,en.jsx)("img",{src:e.url,alt:"",width:e.width,height:e.height}):(0,en.jsx)(cU.FileText,{"aria-hidden":"true"})}),(0,en.jsxs)(cJ,{className:"min-w-0",children:[(0,en.jsx)(cK,{className:"text-[0.8125rem] leading-4",children:e.filename}),(0,en.jsx)(cQ,{role:"error"===e.status?"alert":"preparing"===e.status?"status":void 0,"aria-live":"preparing"===e.status?"polite":void 0,className:(0,eE.cn)("text-[0.6875rem] leading-4 tabular-nums","error"===e.status&&"text-destructive","preparing"===e.status&&"shimmer"),children:"preparing"===e.status?`Preparing ${dO(e.filename,e.mediaType)}…`:"error"===e.status?e.error:`${dO(e.filename,e.mediaType)} \xb7 ${(a=e.size)<1e3?`${a} B`:a<1e6?`${Math.round(a/1e3)} KB`:`${(a/1e6).toFixed(1)} MB`}`})]}),(0,en.jsxs)(cX,{children:["error"===e.status&&e.retryable?(0,en.jsxs)(dC.Tooltip,{children:[(0,en.jsx)(dC.TooltipTrigger,{render:(0,en.jsx)("button",{type:"button","aria-label":`Retry ${e.filename}`,onClick:()=>r(e.id),className:"relative z-20 flex size-7 shrink-0 items-center justify-center rounded-md text-muted-foreground outline-none transition-[background-color,color] hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring pointer-coarse:size-11"}),children:(0,en.jsx)(cU.ReloadIcon,{className:"size-3.5","aria-hidden":"true"})}),(0,en.jsx)(dC.TooltipContent,{children:"Try preparing again"})]}):null,(0,en.jsxs)(dC.Tooltip,{children:[(0,en.jsx)(dC.TooltipTrigger,{render:(0,en.jsx)("button",{type:"button","aria-label":`Remove ${e.filename}`,onClick:()=>t(e.id),className:"relative z-20 flex size-7 shrink-0 items-center justify-center rounded-md text-muted-foreground outline-none transition-[background-color,color] hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring pointer-coarse:size-11"}),children:(0,en.jsx)(cU.X,{className:"size-3.5","aria-hidden":"true"})}),(0,en.jsx)(dC.TooltipContent,{children:"Remove file"})]})]})]})},e.id)})})}function d$({parts:e}){let[t,r]=(0,ek.useState)(null);if(0===e.length)return null;let a=e.filter(e=>dT(e.mediaType)),n=e.filter(e=>!dT(e.mediaType));return(0,en.jsxs)(en.Fragment,{children:[(0,en.jsxs)("div",{className:"flex max-w-full flex-col items-end gap-1.5",children:[a.length>0?(0,en.jsx)("div",{className:(0,eE.cn)("grid max-w-[min(100%,26rem)] gap-1.5",a.length>1&&"grid-cols-2"),children:a.map((e,t)=>{let a=e.filename||`Image ${t+1}`;return(0,en.jsx)("button",{type:"button",onClick:()=>r(e),"aria-label":`Open ${a}`,className:"group/image overflow-hidden rounded-[12px] bg-muted/45 shadow-hairline outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background",children:(0,en.jsx)("img",{src:e.url,alt:a,width:e.width,height:e.height,loading:"lazy",decoding:"async",style:{aspectRatio:e.width&&e.height?`${e.width} / ${e.height}`:"4 / 3"},className:"max-h-72 min-h-24 w-full object-cover transition-transform duration-150 ease-out group-hover/image:scale-[1.01] motion-reduce:transition-none"})},e.url)})}):null,n.length>0?(0,en.jsx)("ul",{className:"flex max-w-full flex-wrap justify-end gap-1.5",children:n.map((e,t)=>{let r=e.filename||`File ${t+1}`;return(0,en.jsx)("li",{className:"min-w-0 max-w-full",children:(0,en.jsxs)(dC.Tooltip,{children:[(0,en.jsxs)(dC.TooltipTrigger,{render:(0,en.jsx)("a",{href:e.url,download:r,className:"flex min-h-10 max-w-[min(18rem,calc(100dvw-3rem))] items-center gap-2 rounded-[10px] bg-muted/55 px-2.5 text-start text-[0.8125rem] font-medium text-foreground no-underline shadow-hairline outline-none transition-colors hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring pointer-coarse:min-h-11"}),children:[(0,en.jsx)(cU.FileText,{className:"size-4 shrink-0 text-muted-foreground","aria-hidden":"true"}),(0,en.jsx)("span",{className:"min-w-0 flex-1 truncate",children:r})]}),(0,en.jsx)(dC.TooltipContent,{children:"Download file"})]})},e.url)})}):null]}),t?(0,en.jsx)(dM,{file:t,open:!0,onOpenChange:e=>{e||r(null)}}):null]})}var dD=e.i(753814),dU=e.i(39839),dL=e.i(743687),dF=e.i(59377),dZ=e.i(829939);function dB({children:e,open:t,onOpenChange:r,trigger:a,title:n,popoverProps:i,drawerSurfaceClassName:s,mobileBreakpoint:o=dZ.MOBILE_BREAKPOINT}){let l=(0,dU.useMediaQuery)(`(max-width: ${o-1}px)`,{defaultValue:!1,initializeWithValue:!1}),u=ek.useRef(null),c=ek.useCallback(()=>{null!==u.current&&(globalThis.clearTimeout(u.current),u.current=null)},[]),d=ek.useCallback(()=>{c(),r(!0)},[c,r]),p=ek.useCallback(()=>{c(),u.current=globalThis.setTimeout(()=>{u.current=null,r(!1)},120)},[c,r]);return((0,eP.useExternalSync)(()=>c,[c]),l)?(0,en.jsxs)(dL.Drawer,{open:t,onOpenChange:r,children:[(0,en.jsx)("span",{className:"relative inline-flex align-middle",children:(0,en.jsx)(dL.DrawerTrigger,{nativeButton:!0,render:a})}),(0,en.jsxs)(dL.DrawerContent,{initialFocus:!1,surfaceClassName:(0,eE.cn)("max-h-[min(75dvh,28rem)] overflow-hidden",s),children:[(0,en.jsx)(dL.DrawerTitle,{className:"sr-only",children:n}),e]})]}):(0,en.jsxs)(dF.Popover,{open:t,onOpenChange:r,children:[(0,en.jsx)("span",{className:"relative inline-flex align-middle",onPointerEnter:d,onPointerLeave:p,children:(0,en.jsx)(dF.PopoverTrigger,{render:a})}),(0,en.jsx)(dF.PopoverPopup,{...i,initialFocus:e=>"keyboard"===e,onPointerEnter:c,onPointerLeave:p,children:e})]})}function dH({className:e,align:t="start",...r}){return(0,en.jsx)("div",{"data-slot":"message","data-align":t,className:(0,eE.cn)("group/message relative flex w-full min-w-0 gap-2 text-sm data-[align=end]:flex-row-reverse",e),...r})}function dq({className:e,...t}){return(0,en.jsx)("div",{"data-slot":"message-content",className:(0,eE.cn)("flex w-full min-w-0 flex-col gap-2.5 break-words group-data-[align=end]/message:*:data-slot:self-end",e),...t})}let dV=new Set(["ArrowDown","ArrowUp","End","Home","PageDown","PageUp"," "]),dW={start:!1,end:!1},dG={currentAnchorId:null,visibleMessageIds:[]};function dY(e,t){return Array.from(e.children).filter(e=>e instanceof HTMLElement&&e!==t)}function dJ(e,t){let r=e.getBoundingClientRect(),a=t.getBoundingClientRect();return r.top-a.top+t.scrollTop}function dK(e,t){return e.getBoundingClientRect().top-t.getBoundingClientRect().top}function dQ({content:e,spacer:t,viewport:r}){let a=dY(e,t),n=dX(e),i=r.getBoundingClientRect(),s=r.scrollTop,o=n.start+n.end;for(let e of a)o=Math.max(o,e.getBoundingClientRect().bottom-i.top+s+n.end);return o}function dX(e){let t=window.getComputedStyle(e);return{end:d0(t.paddingBlockEnd||t.paddingBottom),start:d0(t.paddingBlockStart||t.paddingTop)}}function d0(e){if(!e)return 0;let t=Number.parseFloat(e);return Number.isFinite(t)?t:0}function d1(e,t){let r=e,a=new Set;return{getSnapshot:()=>r,hasListeners:()=>a.size>0,setSnapshot:e=>
75{t(r,e)||(r=e,a.forEach(e=>e()))},subscribe:(e,t,r)=>{let n=0===a.size;return a.add(e),n&&t?.(),()=>{a.delete(e),0===a.size&&r?.()}}}}function d2(e,t){return e.start===t.start&&e.end===t.end}function d5(e,t){return e.currentAnchorId===t.currentAnchorId&&e.visibleMessageIds.length===t.visibleMessageIds.length&&e.visibleMessageIds.every((e,r)=>e===t.visibleMessageIds[r])}function d4(e,t){return ek.useCallback(r=>{e.current=r,r&&t()},[e,t])}function d3(...e){let t=e.filter(Boolean);if(0!==t.length)return e=>{for(let r of t)"function"==typeof r?r(e):r&&(r.current=e)}}let d9=ek.createContext(null),d6=ek.createContext(null);function d8(){let e=ek.useContext(d9);if(!e)throw Error("useMessageScroller must be used within a MessageScroller.");return e}function d7({autoScroll:e=!1,children:t,defaultScrollPosition:r="end",scrollEdgeThreshold:a,scrollPreviousItemPeek:n,scrollMargin:i}){let{context:s,registerMessage:o}=function({autoScroll:e=!1,defaultScrollPosition:t="end",scrollEdgeThreshold:r=8,scrollPreviousItemPeek:a=64,scrollMargin:n=0}){let i=function({autoScroll:e,scrollEdgeThreshold:t,scrollMargin:r,scrollPreviousItemPeek:a}){let n=ek.useRef(e),i=ek.useRef(!1),s=ek.useRef(null),o=ek.useRef(!1),l=ek.useRef(t),u=ek.useRef(0),c=ek.useRef(null),d=ek.useRef(e?"following-bottom":"free-scrolling"),p=ek.useRef(new Map),h=ek.useRef(null),m=ek.useRef(null),f=ek.useRef(null),g=ek.useRef(a),v=ek.useRef(!0),y=ek.useRef(null),b=ek.useRef(r),x=ek.useRef(null),w=ek.useRef(0),_=ek.useRef(0),k=ek.useRef(null),S=ek.useRef(null),E=ek.useRef(null),C=ek.useRef(null),j=ek.useRef(null),I=ek.useRef(null),T=ek.useRef(null),N=ek.useRef(null),R=ek.useRef(new Set),A=ek.useRef(new WeakSet);return null===E.current&&(E.current=d1(dW,d2)),null===N.current&&(N.current=d1(dG,d5)),ek.useLayoutEffect(()=>{n.current=e,l.current=t,b.current=r,g.current=a},[e,t,r,a]),{autoScrollRef:n,autoscrollingRef:i,autoscrollingTimeoutRef:C,streamingTurnRef:f,contentRef:s,defaultScrollPositionAppliedRef:o,firstItemRef:c,itemCountRef:u,messageElementsRef:p,modeRef:d,pendingScrollFrameRef:x,pendingScrollToMessageRef:h,prependRestoreRef:m,preserveScrollOnPrependRef:v,rootRef:y,scrollEdgeThresholdRef:l,scrollMarginRef:b,scrollPreviousItemPeekRef:g,spacerGapRef:w,spacerHeightRef:_,spacerRef:k,stateFrameRef:S,stateStore:E.current,viewportRef:j,visibilityFrameRef:I,visibilityObserverRef:T,visibilityStore:N.current,visibleMessageIdsRef:R,handledScrollAnchorsRef:A}}({autoScroll:e,scrollEdgeThreshold:r,scrollMargin:n,scrollPreviousItemPeek:a}),{streamingTurnRef:s,autoScrollRef:o,autoscrollingRef:l,autoscrollingTimeoutRef:u,contentRef:c,defaultScrollPositionAppliedRef:d,firstItemRef:p,itemCountRef:h,messageElementsRef:m,modeRef:f,pendingScrollFrameRef:g,pendingScrollToMessageRef:v,prependRestoreRef:y,preserveScrollOnPrependRef:b,rootRef:x,scrollEdgeThresholdRef:w,scrollMarginRef:_,scrollPreviousItemPeekRef:k,spacerGapRef:S,spacerRef:E,stateFrameRef:C,stateStore:j,viewportRef:I,visibilityFrameRef:T,visibilityObserverRef:N,visibilityStore:R,visibleMessageIdsRef:A,handledScrollAnchorsRef:z}=i,M=ek.useRef(t),O=ek.useRef({clientHeight:0,scrollTop:0});ek.useLayoutEffect(()=>{M.current!==t&&(M.current=t,d.current=!1)},[t,d]);let P=ek.useCallback(e=>{let t=x.current,r=I.current,a=[e.start&&"start",e.end&&"end"].filter(
75Boolean).join(" "),n=l.current;for(let e of[t,r])e&&(a?e.setAttribute("data-scrollable",a):e.removeAttribute("data-scrollable"),e.toggleAttribute("data-autoscrolling",n))},[]),$=ek.useCallback((e,t)=>{o.current&&!e.end&&"settling-jump"!==f.current?f.current="following-bottom":"following-bottom"===f.current&&e.end&&t&&!l.current&&(f.current="free-scrolling")},[]),D=ek.useCallback(()=>{let e=I.current;if(!e)return{layoutDriven:!1,movedTowardStart:!1};let t=O.current,r=t.clientHeight!==e.clientHeight||e.scrollTop<=1&&t.scrollTop>e.clientHeight,a=!r&&e.scrollTop<t.scrollTop-.5;return O.current={clientHeight:e.clientHeight,scrollTop:e.scrollTop},{layoutDriven:r,movedTowardStart:a}},[]),U=ek.useCallback(()=>{let e=function({content:e,scrollEdgeThreshold:t,spacer:r,viewport:a}){if(!a||!e)return dW;let n=dQ({content:e,spacer:r,viewport:a});return{start:a.scrollTop>t,end:n-a.scrollTop-a.clientHeight>t}}({content:c.current,scrollEdgeThreshold:w.current,spacer:E.current,viewport:I.current}),{movedTowardStart:t}=D();$(e,t),P(e),j.setSnapshot(e)},[D,$,j,P]),L=ek.useCallback(()=>{null===C.current&&(C.current=window.requestAnimationFrame(()=>{C.current=null,U()}))},[U]),F=ek.useCallback(()=>{R.hasListeners()&&null===T.current&&(T.current=window.requestAnimationFrame(()=>{T.current=null,R.hasListeners()&&R.setSnapshot(function({content:e,scrollMargin:t,scrollPreviousItemPeek:r,spacer:a,viewport:n,visibleMessageIds:i}){if(!e||!n)return dG;let s=n.getBoundingClientRect(),o=s.top+t+r,l="u"<typeof IntersectionObserver,u=[],c=null;for(let t of dY(e,a)){let e=t.dataset.messageId;if(!e)continue;let r="true"===t.dataset.scrollAnchor,a=r||l?t.getBoundingClientRect():null;(l&&a?a.bottom>o&&a.top<s.bottom:i.has(e))&&u.push(e),r&&a&&a.top<=o+.5&&(c=e)}return 0===u.length&&null===c?dG:{currentAnchorId:c,visibleMessageIds:u}}({content:c.current,scrollMargin:_.current,scrollPreviousItemPeek:k.current,spacer:E.current,viewport:I.current,visibleMessageIds:A.current}))}))},[R]),{flushPendingScrollToMessage:Z,reanchorToAnchoredMessage:B,scrollToElement:H,scrollToEnd:q,scrollToMessage:V,scrollToStart:W}=function({refs:e,commitScrollState:t,scheduleStateCommit:r,scheduleVisibilitySync:a}){let{streamingTurnRef:n,autoScrollRef:i,autoscrollingRef:s,autoscrollingTimeoutRef:o,contentRef:l,defaultScrollPositionAppliedRef:u,itemCountRef:c,messageElementsRef:d,modeRef:p,pendingScrollToMessageRef:h,prependRestoreRef:m,scrollMarginRef:f,scrollPreviousItemPeekRef:g,spacerGapRef:v,spacerHeightRef:y,spacerRef:b,viewportRef:x}=e,w=ek.useCallback(e=>{null!==o.current&&(window.clearTimeout(o.current),o.current=null),s.current!==e&&(s.current=e,t()),e&&(o.current=window.setTimeout(()=>{o.current=null,s.current=!1,t()},180))},[t]),_=ek.useCallback(e=>{let t=b.current;if(!t)return;let r=Math.max(0,Math.ceil(e));y.current!==r&&(y.current=r,t.hidden=0===r,t.style.height=`${r}px`,t.style.marginTop=r>0?`${-v.current}px`:"")},[]),k=ek.useCallback((e,{behavior:a="auto",autoscrolling:n=!1}={})=>{let i=x.current;if(!i)return;let s=Math.max(0,e);if(.5>=Math.abs(i.scrollTop-s)){i.scrollTop=s,t();return}n&&w(!0),i.scrollTo({top:s,behavior:a}),r()},[t,r,w]),S=ek.useCallback(({behavior:e="auto"}={})=>!!x.current&&(_(0),n.current=null,p.current="free-scrolling",k(0,{behavior:e}),a(),!0),[a,k,_]),E=ek.useCallback(({behavior:e="auto"}={})=>{let t=x.current;return!!t&&(_(0),n.current=null,p.current=i.current?"following-bottom":"free-scrolling",k(Math.max(0,t.scrollHeight-t.clientHeight),{autoscrolling:!0,behavior:e}),a(),!0)},[a,k,_]),C=ek.useCallback((e,{align:t="start",behavior:r="auto",scrollMargin:i=f.current}={},{keepPreviousPeek:s=!1}={})=>{let o=l.current,u=x.current;if(!o||!u||!o.contains(e))return!1;let c=function({align:e,element:t,scrollMargin:r,spacer:a,viewport:n}){var i;let s,o=dJ(t,n),l=t.getBoundingClientRect().height,u=(i=a,(s=i?.parentElement)?dX(s):{end:0,start:0});if("center"===e){let e=Math.max(0,n.clientHeight-u.start-u.end);return o-u.start-(e-l)/2-r}if("end"===e)return o-n.clientHeight+l+u.end+r;if("nearest"===e){let e=o+l,t=n.scrollTop+u.start,a=n.scrollTop+n.clientHeight-u.end;return o>=t&&e<=a?n.scrollTop:o<t?o-u.start-r:e-n.clientHeight+u.end+r}return o-u.start-r}({align:t,element:e,scrollMargin:s?i+g.current:i,spacer:b.current,viewport:u});
75return _(function({content:e,scrollTop:t,spacer:r,viewport:a}){let n=dQ({content:e,spacer:r,viewport:a});return t+a.clientHeight-n}({content:o,scrollTop:c,spacer:b.current,viewport:u})),m.current={element:e,viewportTop:dK(e,u)},p.current=s?"anchored-to-message":"settling-jump",n.current=s?e:null,k(c,{behavior:r}),a(),!0},[a,k,_]),j=ek.useCallback(()=>{let e=n.current;return!!e&&!!e.isConnected&&"anchored-to-message"===p.current&&C(e,{align:"start"},{keepPreviousPeek:!0})},[C]),I=ek.useCallback((e,t)=>{let r=d.current.get(e);return r?((u.current=!0,C(r,t))?h.current=null:h.current={messageId:e,options:t},!0):0===c.current&&(h.current={messageId:e,options:t},u.current=!0,!0)},[C]);return{flushPendingScrollToMessage:ek.useCallback(()=>{let e=h.current;if(!e)return!1;let t=d.current.get(e.messageId);return!!t&&!!C(t,e.options)&&(h.current=null,u.current=!0,!0)},[C]),reanchorToAnchoredMessage:j,scrollToElement:C,scrollToEnd:E,scrollToMessage:I,scrollToStart:S}}({refs:i,commitScrollState:U,scheduleStateCommit:L,scheduleVisibilitySync:F}),G=ek.useCallback(()=>{let e=y.current,t=I.current;if(!e||!t||!e.element.isConnected)return!1;let r=dK(e.element,t)-e.viewportTop;return!(.5>=Math.abs(r))&&(t.scrollTop+=r,e.viewportTop=dK(e.element,t),L(),F(),!0)},[L,F]),Y=ek.useCallback(()=>{let e=c.current,t=I.current;if(!e||!t){y.current=null;return}let r=function({content:e,spacer:t,viewport:r}){let a=r.getBoundingClientRect();for(let r of dY(e,t)){if(!r.dataset.messageId)continue;let e=r.getBoundingClientRect();if(e.bottom>a.top&&e.top<a.bottom)return r}return null}({content:e,spacer:E.current,viewport:t});y.current=r?{element:r,viewportTop:dK(r,t)}:null},[]),J=ek.useCallback(()=>{null===g.current&&(g.current=window.requestAnimationFrame(()=>{g.current=null,Z()&&Y()}))},[Y,Z]),K=ek.useCallback(()=>{if(!t||d.current||0===h.current)return!1;let e=!1;if("last-anchor"===t){let t=c.current,r=I.current,a=t&&r?function(e){for(let t=e.length-1;t>=0;t--){let r=e[t];if(r?.dataset.scrollAnchor==="true")return r}return null}(dY(t,E.current)):null;if(t&&r&&a){let n=dJ(a,r);e=dQ({content:t,spacer:E.current,viewport:r})-n<=r.clientHeight?q({behavior:"auto"}):H(a,{align:"start"},{keepPreviousPeek:!0})}else e=q({behavior:"auto"})}else e="end"===t?q({behavior:"auto"}):W({behavior:"auto"});return!!e&&(d.current=!0,!0)},[t,H,q,W]),Q=ek.useCallback(()=>{let e=c.current;if(!e)return;let t=dY(e,E.current),r=h.current,a=p.current;h.current=t.length,p.current=t[0]??null,(()=>{if(Z())return;if(0===r){if(K()||t.length>0&&o.current&&q({behavior:"auto"}))return;U(),F();return}let e=a?t.indexOf(a):-1;if(b.current&&e>0)return G();if(t.length>r){let e=function(e,t){for(let r=t;r<e.length;r++){let t=e[r];if(t?.dataset.scrollAnchor==="true")return t}return null}(t,r);if(e)return o.current&&"following-bottom"===f.current&&function(e,t){let r=0;for(let a=t;a<e.length;a++){let t=e[a];if(t?.dataset.scrollAnchor==="true"&&(r+=1)>1)return!0}return!1}(t,r)?q({behavior:"auto"}):(H(e,{align:"start"},{keepPreviousPeek:!0}),z.current.add(e))}if(t.length===r){let e=function(e,t){for(let r of e)if("true"===r.dataset.scrollAnchor&&!t.has(r))return r;return null}(t,z.current);if(e){H(e,{align:"start"},{keepPreviousPeek:!0}),z.current.add(e);return}}"following-bottom"===f.current&&o.current?q({behavior:"auto"}):(U(),F())})(),Y()},[K,Y,U,Z,G,F,H,q]),X=ek.useCallback(()=>{"following-bottom"===f.current&&o.current?q({behavior:"auto"}):B()||(L(),F())},[B,L,F,q]),ee=ek.useCallback(()=>{let e=I.current;if(e&&R.hasListeners()){if("u"<typeof IntersectionObserver)return void F();N.current||(N.current=new IntersectionObserver(e=>{for(let t of e){let e=t.target.dataset.messageId;e&&(t.isIntersecting?A.current.add(e):A.current.delete(e))}F()},{root:e,rootMargin:`${-(_.current+k.current)}px 0px 0px 0px`,threshold:[0,.01,.5,1]})),m.current.forEach(e=>{N.current?.observe(e)}),F()}},[F,R]),et=ek.useCallback(()=>{null!==T.current&&(window.cancelAnimationFrame(T.current),T.current=null),N.current?.disconnect(),N.current=null,A.current.clear(),R.setSnapshot(dG)},[R]),er=ek.useCallback((e,t,r)=>{if(t){m.current.set(e,t),N.current?.observe(t),F(),v.current?.messageId===e&&J();return}r&&m.current.get(e)===r&&(m.current.delete(e),A.current.delete(e),N.current?.unobserve(r),F())}
75,[J,F]),ea=ek.useCallback(()=>{("following-bottom"===f.current||"anchored-to-message"===f.current||"settling-jump"===f.current)&&(s.current=null,f.current="free-scrolling")},[]),en=ek.useCallback(()=>P(j.getSnapshot()),[j,P]),ei=d4(x,en),es=d4(I,en),eo=ek.useCallback(e=>{c.current=e},[]),el=ek.useCallback(e=>{E.current=e,S.current=function(e){if(!e)return 0;let t=window.getComputedStyle(e);return d0("normal"===t.rowGap?t.gap:t.rowGap)}(e?.parentElement??null)},[]),eu=ek.useCallback(()=>{if("following-bottom"===f.current&&o.current&&D().layoutDriven){q({behavior:"auto"}),Y();return}U(),F(),Y()},[Y,U,D,F,q]),ec=ek.useMemo(()=>({handleContentChange:Q,handleResize:X,observeVisibility:ee,preserveScrollOnPrependRef:b,scrollToEnd:q,scrollToMessage:V,scrollToStart:W,setContentElement:eo,setRootElement:ei,setSpacerElement:el,setViewportElement:es,stateStore:j,syncAfterScroll:eu,unobserveVisibility:et,userScrollIntent:ea,viewportRef:I,visibilityStore:R}),[Q,X,ee,q,V,W,eo,ei,el,es,j,eu,et,ea,R]);return ek.useLayoutEffect(()=>{K()},[K]),ek.useEffect(()=>()=>{null!==C.current&&(window.cancelAnimationFrame(C.current),C.current=null),null!==T.current&&(window.cancelAnimationFrame(T.current),T.current=null),null!==u.current&&(window.clearTimeout(u.current),u.current=null),null!==g.current&&(window.cancelAnimationFrame(g.current),g.current=null),N.current?.disconnect(),N.current=null},[]),ek.useLayoutEffect(()=>{e&&"following-bottom"===f.current&&h.current>0?q({behavior:"auto"}):U()},[e,U,q]),{context:ec,registerMessage:er}}({autoScroll:e,defaultScrollPosition:r,scrollEdgeThreshold:a,scrollPreviousItemPeek:n,scrollMargin:i});return(0,en.jsx)(d9.Provider,{value:s,children:(0,en.jsx)(d6.Provider,{value:o,children:t})})}function pe({children:e,...t}){let{setRootElement:r}=d8();return(0,en.jsx)("div",{ref:r,...t,children:e})}function pt({"aria-label":e,children:t,onKeyDown:r,onScroll:a,onTouchMove:n,onWheel:i,preserveScrollOnPrepend:s=!0,ref:o,role:l,tabIndex:u,...c}){let{handleResize:d,preserveScrollOnPrependRef:p,setViewportElement:h,syncAfterScroll:m,userScrollIntent:f,viewportRef:g}=d8();p.current=s;let v=ek.useCallback(e=>{h(e),d3(o)?.(e)},[o,h]);return ek.useEffect(()=>{let e=g.current;if(!e||"u"<typeof ResizeObserver)return;let t=new ResizeObserver(d);return t.observe(e),()=>t.disconnect()},[d,g]),(0,en.jsx)("div",{ref:v,role:l??"region","aria-label":e??"Messages",tabIndex:u??0,onKeyDown:function(e){dV.has(e.key)&&f(),r?.(e)},onScroll:function(e){m(),a?.(e)},onTouchMove:function(e){f(),n?.(e)},onWheel:function(e){f(),i?.(e)},...c,children:t})}function pr({"aria-relevant":e,children:t,ref:r,role:a,spacerClassName:n,...i}){let{handleContentChange:s,handleResize:o,setContentElement:l,setSpacerElement:u}=d8(),c=ek.useRef(null),d=ek.useCallback(e=>{c.current=e,l(e),d3(r)?.(e)},[r,l]);return ek.useLayoutEffect(()=>{let e=c.current;if(!e||(s(),"u"<typeof MutationObserver))return;let t=new MutationObserver(()=>{s()});return t.observe(e,{childList:!0}),()=>t.disconnect()},[s]),ek.useEffect(()=>{let e=c.current;if(!e||"u"<typeof ResizeObserver)return;let t=new ResizeObserver(o);return t.observe(e),()=>t.disconnect()},[o]),(0,en.jsxs)("div",{ref:d,role:a??"log","aria-relevant":e??"additions",...i,children:[t,(0,en.jsx)("div",{ref:u,"aria-hidden":"true","data-message-scroller-spacer":"",hidden:!0,className:n})]})}function pa({messageId:e,ref:t,scrollAnchor:r=!1,...a}){let n=function(){let e=ek.useContext(d6);if(!e)throw Error("MessageScrollerItem must be used within a MessageScroller.");return e}(),i=ek.useRef(null),s=ek.useCallback(r=>{let a=i.current;i.current=r,e&&n(e,r,a),d3(t)?.(r)},[e,t,n]);return(0,en.jsx)("div",{ref:s,"data-message-id":e,"data-scroll-anchor":r?"true":"false",...a})}function pn({behavior:e="smooth",children:t,direction:r="end",onClick:a,render:n,tabIndex:i,type:s="button",...o}){let l,{scrollToEnd:u,scrollToStart:c,stateStore:d}=d8(),p=(l=ek.useRef(a),ek.useLayoutEffect(()=>{l.current=a},[a]),l),h=ek.useCallback(e=>d.subscribe(e),[d]),m=ek.useCallback(()=>{let e=d.getSnapshot();return"start"===r?e.start:e.end},[r,d]),f=ek.useSyncExternalStore(h,m,m),g=ek.useCallback(t=>{f&&(p.current?.(t),t.defaultPrevented||(t.currentTarget.blur(),"start"===r?c({behavior:e}):u({behavior:e})))},[e,r,f,p,u,c]);return(0,cB.useRender)({defaultTagName:"button",props:(0,cZ.mergeProps)({type:s,inert:!f,tabIndex:f?i:-1,children:t??(0,en.jsxs)("span",{children:["Scroll to ",r]}),onClick:g},o),render:n,state:{active:f,direction:r},stateAttributesMapping:{active:e=>({"data-active":e?"true":"false"})}})}function pi(e){return(0,en.jsx)(d7,{...e})}function ps({className:e,...t}){return(0,en.jsx)(pe,{"data-slot":"message-scroller",className:(0,eE.cn)("group/message-scroller relative flex size-full min-h-0 flex-col overflow-hidden",e),...t})}function po({className:e,...t}){return(0,en.jsx)(pt,{"data-slot":"message-scroller-viewport",className:(0,eE.cn)("scroll-fade-b size-full min-h-0 min-w-0 overflow-y-auto overscroll-contain [scrollbar-gutter:stable] contain-content data-[autoscrolling]:scrollbar-hide",e),...t})}function pl({className:e,...t}){return(0,en.jsx)(pr,{"data-slot":"message-scroller-content",className:(0,eE.cn)("flex h-max min-h-full flex-col",e),...t})}function pu({className:e,scrollAnchor:t=!1,...r}){return(0,en.jsx)(pa,{"data-slot":"message-scroller-item",scrollAnchor:t,className:(0,eE.cn)("min-w-0 shrink-0 [contain-intrinsic-size:auto_10rem] [content-visibility:auto]",e),...r})}function pc({direction:e="end",className:t,children:r,render:a,variant:n="outline",size:i="icon-sm",...s}){return(0,en.jsx)(pn,{"data-slot":"message-scroller-button","data-direction":e,direction:e,className:(0,eE.cn)("absolute start-1/2 z-10 -translate-x-1/2 border-border bg-background text-foreground shadow-sm transition-[translate,scale,opacity] duration-200 hover:bg-muted hover:text-foreground data-[active=false]:pointer-events-none data-[active=false]:scale-95 data-[active=false]:opacity-0 data-[active=true]:scale-100 data-[active=true]:opacity-100 data-[direction=end]:bottom-4 data-[direction=end]:data-[active=false]:translate-y-full data-[direction=start]:top-4 data-[direction=start]:data-[active=false]:-translate-y-full data-[active=false]:duration-300 data-[active=false]:ease-[cubic-bezier(0.7,0,0.84,0)] data-[active=true]:ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:transition-none data-[direction=start]:[&_svg]:rotate-180 rtl:translate-x-1/2",t),render:a??(0,en.jsx)(cq.Button,{variant:n,size:i}),...s,children:r??(0,en.jsxs)(en.Fragment,{children:[(0,en.jsx)(cU.ArrowDown,{"aria-hidden":"true",className:"size-4"}),(0,en.jsx)("span",{className:"sr-only",children:"end"===e?"Scroll to end":"Scroll to start"})]})})}var pd=e.i(141798),pp=e.i(110031),ph=e.i(792855),pm=e.i(751525),pf=e.i(274330),pg=e.i(491743),pv=e.i(578352);let py=(0,dE.default)(()=>e.A(432721).then(e=>
75e.ProxyContent),{loadableGenerated:{modules:[250873]},ssr:!1,loading:()=>(0,en.jsx)("div",{className:"min-h-0 flex-1 overflow-hidden bg-background",children:(0,en.jsx)(pm.ArticleLoadingSkeleton,{})})});function pb({item:e,width:t,onWidthChange:r,expanded:a,onRestoreChat:n,onClose:i}){let s=(0,ek.useRef)(null),o=(0,ek.useRef)(null),[l,u]=(0,ek.useState)(0),c=Math.max(512,Math.min(980,l>0?l-320:980)),d=Math.min(c,Math.max(512,t)),p=(0,ek.useCallback)(e=>{s.current=e,o.current=e?.parentElement??null},[]);(0,eP.useResizeObserver)(o,e=>{let t=e[0]?.contentRect.width;void 0!==t&&u(t)}),(0,eP.useExternalSync)(()=>{t>c&&r(c)},[c,r,t]),(0,eP.useExternalSync)(()=>{if(window.matchMedia("(min-width: 80rem)").matches)return;let e=document.activeElement instanceof HTMLElement?document.activeElement:null,t=requestAnimationFrame(()=>{s.current?.focus({preventScroll:!0})});return()=>{cancelAnimationFrame(t),requestAnimationFrame(()=>e?.focus({preventScroll:!0}))}},[]);let{onPointerDown:h}=(0,pv.useResizeHandle)({width:d,onWidthChange:r,minWidth:512,maxWidth:c,side:"right"});return(0,en.jsxs)("section",{ref:p,"aria-label":`Presented article: ${e.title}`,"data-remy-presentation-panel":"article",tabIndex:-1,className:(0,eE.cn)("absolute inset-0 z-30 flex min-h-0 min-w-0 flex-col overflow-hidden bg-background","max-md:fixed max-md:z-50 max-md:pt-[env(safe-area-inset-top)]",a?"xl:relative xl:inset-auto xl:z-auto xl:flex-1":"xl:relative xl:inset-auto xl:z-auto xl:w-[var(--remy-presentation-width)] xl:min-w-[32rem] xl:border-s xl:border-border/60"),style:{"--remy-presentation-width":`${d}px`},children:[(0,en.jsx)("div",{role:"separator","aria-label":"Resize article workspace","aria-orientation":"vertical","aria-valuemin":512,"aria-valuemax":c,"aria-valuenow":d,"aria-valuetext":`${Math.round(d)} pixels wide`,tabIndex:0,onPointerDown:h,onKeyDown:e=>{"ArrowLeft"!==e.key&&"ArrowRight"!==e.key&&"Home"!==e.key&&"End"!==e.key||((e.preventDefault(),"Home"===e.key||"End"===e.key)?r("Home"===e.key?512:c):r(Math.min(c,Math.max(512,d+("ArrowLeft"===e.key?1:-1)*32))))},className:(0,eE.cn)("group absolute inset-y-0 start-0 z-50 hidden w-3 -translate-x-1/2 cursor-col-resize touch-none items-center justify-center focus-visible:outline-none",!a&&"xl:flex"),children:(0,en.jsx)("span",{className:"h-full w-px bg-transparent transition-colors group-hover:bg-border group-focus-visible:bg-ring"})}),(0,en.jsxs)("header",{className:"flex h-11 shrink-0 items-center gap-2 border-b border-border/40 bg-background px-2.5 sm:px-3",children:[(0,en.jsxs)(cq.Button,{type:"button",variant:"ghost",size:"sm",onClick:i,className:"h-8 shrink-0 gap-1.5 rounded-md px-2 text-muted-foreground hover:text-foreground xl:hidden","aria-label":"Back to conversation",children:[(0,en.jsx)(cU.ChevronLeft,{className:"size-4","aria-hidden":"true"}),(0,en.jsx)("span",{className:"text-xs font-medium",children:"Back to conversation"})]}),a?(0,en.jsx)(cq.Button,{type:"button",variant:"ghost",size:"icon-sm",onClick:n,className:"hidden shrink-0 rounded-full text-muted-foreground hover:bg-muted/55 hover:text-foreground xl:inline-flex","aria-label":"Show conversation",children:(0,en.jsx)(cU.ChevronsRight,{className:"size-5",strokeWidth:2,"aria-hidden":"true"})}):null,(0,en.jsxs)("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[(0,en.jsx)("span",{className:"flex size-7 shrink-0 items-center justify-center rounded-md bg-muted/45 text-muted-foreground",children:(0,en.jsx)(cU.Newspaper,{className:"size-4","aria-hidden":"true"})}),(0,en.jsxs)("div",{className:"min-w-0",children:[(0,en.jsx)("p",{className:"truncate text-sm font-medium text-foreground",children:e.title}),(0,en.jsx)("p",{className:"truncate text-[0.6875rem] leading-4 text-muted-foreground",children:e.domain})]})]}),(0,en.jsx)(cq.Button,{variant:"ghost",size:"icon",className:"size-8 shrink-0 text-muted-foreground hover:text-foreground","aria-label":"Open article in a new tab",nativeButton:!1,render:t=>{let{key:r,...a}=t;return(0,en.jsx)("a",{...a,href:e.href,target:"_blank",rel:"noopener noreferrer",children:(0,en.jsx)(cU.ExternalLink,{className:"size-4","aria-hidden":"true"})},r)}}),(0,en.jsx)(cq.Button,{type:"button",variant:"ghost",size:"icon",onClick:i,className:"size-8 shrink-0 text-muted-foreground hover:text-foreground","aria-label":"Close article workspace",children:(0,en.jsx)(cU.X,{className:"size-4",strokeWidth:1.75,"aria-hidden":"true"})})]}),(0,en.jsx)("div",{className:"min-h-0 flex-1 overflow-hidden",children:(0,en.jsx)(pg.AudioPlaybackBoundary,{children:(0,en.jsx)(pf.KeyboardShortcutsBoundary,{children:(0,en.jsx)(py,{url:e.url,entrySurface:"recommendations",embedded:!0},e.url)})})})]})}var px=e.i(203348),pw=e.i(463415),p_=e.i(299382),pk=e.i(987368),pS=e.i(956512);function pE(e){return!!e&&(/[0-9A-Za-z]/.test(e)||e.toLowerCase()!==e.toUpperCase())}let pC=new Set(["*","_","~","`","[","]"]);function pj(e){let t="";for(let r of e.parts)"text"===r.type&&(function(e,t){let r=function(e){for(let t=e.length-1;t>=0;t-=1){let r=e[t];if(!pC.has(r))return r}}(e),a=function(e){for(let t of e)if(!pC.has(t))return t}(t);return!(!r||!a||/\s/.test(r)||/\s/.test(a))&&pE(r)&&pE(a)}(t,r.text)&&(t+=" "),t+=r.text);return t}var pI=e.i(439137),pT=e.i(177433);function pN(){try{let e=window.localStorage.getItem("smry-reader-preferences");if(!e)return"";return(0,pT.normalizeReaderPreferences)(JSON.parse(e)).customInstru
75ctions}catch{return""}}var pR=e.i(50270);let pA=pR.z.object({url:pR.z.string().trim().max(8192).url().refine(e=>{try{let t=new URL(e);return["https:","http:"].includes(t.protocol)&&!t.username&&!t.password}catch{return!1}}).transform(e=>{let t=new URL(e);return`${t.origin}${t.pathname}`}),title:pR.z.string().trim().max(500).optional().catch(void 0),language:pR.z.string().trim().max(40).optional().catch(void 0)}).optional().catch(void 0);var pz=e.i(600318),pM=e.i(523526),pO=e.i(512482);let pP=/\[\s*(\d+(?:\s*,\s*\d+)*)\s*\]/g,p$=/\]\((https?:\/\/[^)\s]+)(?:\s+"[^"]*")?\)/g;function pD(e,t,r,a){return{kind:t,url:r,title:e.title,domain:e.domain,citationNumber:a,savedAt:"savedAt"in e?e.savedAt:null,lastReadAt:"lastReadAt"in e?e.lastReadAt:null,cachedAt:"cachedAt"in e?e.cachedAt:null}}var pU=e.i(826534);let pL=new Set(["follow_feeds","mutate_feeds","manage_feed_consumers","create_monitor"]);[...pL],e.i(404948);var pF=e.i(853651),pZ=e.i(209920),pB=e.i(249755),pH=e.i(705538),pq=e.i(256203),pV=e.i(159354),pW=e.i(912598);let pG=(0,eE.cn)("cursor-pointer font-[inherit] text-[inherit] text-foreground underline decoration-dotted decoration-foreground/70 decoration-[2px] underline-offset-[4px]","transition-[color,text-decoration-color] duration-150 hover:text-primary hover:decoration-primary","focus-visible:rounded-[3px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background");function pY({reference:e,surface:t,children:r}){let{trackArticleViaBeacon:a}=(0,dm.useAnalytics)(),n=function(e){let t=[e.domain];if(e.publishedAt){let r=new Date(e.publishedAt);Number.isNaN(r.getTime())||t.push(String(r.getFullYear()))}return e.wordCount&&e.wordCount>0&&t.push(`${Math.max(1,Math.round(e.wordCount/200))} min read`),t.push(e.author),t.filter(Boolean).join(" · ")}(e),i=(0,pW.useQueryClient)();return(0,en.jsxs)(pZ.PreviewCard.Root,{children:[(0,en.jsx)(pZ.PreviewCard.Trigger,{delay:240,closeDelay:120,"data-chat-article-mention":"",render:(0,en.jsx)(pF.Link,{href:e.href,"data-chat-article-surface":t,target:"local_chat"===t?"_blank":void 0,rel:"local_chat"===t?"noopener noreferrer":void 0,onPointerEnter:()=>void(0,pV.prewarmReader)(i,e.url),onPointerDown:()=>void(0,pV.prewarmReader)(i,e.url),onFocus:()=>void(0,pV.prewarmReader)(i,e.url),onClick:r=>{(0,pq.isPlainPrimaryArticleNavigationClick)(r)&&a("article_recommendation_opened",e.url,{surface:t,open_method:"inline_article_mention"}),(0,pH.handleReaderArticleNavigationClick)(r,{url:e.url,from:"recommendations"})}}),className:pG,children:r??e.title}),(0,en.jsx)(pZ.PreviewCard.Portal,{children:(0,en.jsx)(pZ.PreviewCard.Positioner,{side:"top",align:"center",sideOffset:9,collisionPadding:12,className:"z-100",children:(0,en.jsxs)(pZ.PreviewCard.Popup,{"data-chat-article-preview":"",className:(0,eE.cn)("w-[min(23rem,calc(100vw-1.5rem))] rounded-[14px] bg-popover p-3.5 text-popover-foreground shadow-hairline outline-none","transition-opacity duration-100 ease-out data-[starting-style]:opacity-0 data-[ending-style]:opacity-0 motion-reduce:transition-none"),children:[(0,en.jsxs)("div",{className:"flex min-w-0 items-center gap-2.5",children:[(0,en.jsx)("span",{className:"flex size-9 shrink-0 items-center justify-center overflow-hidden rounded-xl bg-muted/55",children:(0,en.jsx)(cF.FaviconImage,{domain:e.domain,className:"size-5 rounded-[4px] object-contain outline outline-1 -outline-offset-1 outline-black/10 dark:outline-white/10"})}),(0,en.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,en.jsx)("p",{className:"line-clamp-2 text-[0.9375rem] font-medium leading-[1.35rem] text-pretty",children:e.title}),n?(0,en.jsx)("p",{"data-chat-article-meta":"",className:"mt-0.5 truncate text-xs leading-[1.125rem] text-muted-foreground tabular-nums",children:n}):null]})]}),e.excerpt?(0,en.jsx)("p",{className:"mt-2.5 line-clamp-3 text-[0.8125rem] leading-5 text-muted-foreground text-pretty",children:e.excerpt}):null]})})})]})}function pJ({references:e,surface:t,href:r,children:a,className:n,...i}){let s=(0,pB.findChatArticleReference)(e,r);return s?(0,en.jsx)(pY,{reference:s,surface:t,children:a}):(0,en.jsx)("a",{href:r,className:(0,eE.cn)("font-medium text-primary underline decoration-from-font underline-offset-2",n),rel:"noopener noreferrer",target:"_blank",...i,children:a})}var pK=e.i(728235);function pQ({timestampMs:e,onOpen:t,ariaLabel:r}){let a=(0,pK.formatYouTubeTimestamp)(e);return(0,en.jsxs)("button",{type:"button",onClick:r=>t(e,r.currentTarget),className:"mx-0.5 inline-flex min-h-7 touch-manipulation items-center gap-1 rounded-md bg-muted/60 px-1.5 align-baseline font-mono text-xs font-medium text-foreground no-underline shadow-hairline outline-none motion-safe:transition-colors motion-safe:duration-150 hover:bg-accent/50 focus-visible:ring-2 focus-visible:ring-ring active:bg-accent/65 pointer-coarse:min-h-9","aria-label":r??`Watch video at ${a}`,"data-youtube-timestamp-citation":e,children:[(0,en.jsx)(cU.Play,{className:"size-3","aria-hidden":"true"}),(0,en.jsx)("span",{className:"tabular-nums",children:a})]})}var pX=e.i(702278),p0=e.i(323514);let p1=null,p2=null;function p5(){return p1?Promise.resolve(p1):(p2||(p2=e.A(682002).then(e=>(p1=e.Response,e.Response)).catch(e=>{throw p2=null,e})),p2)}async function p4(){for(let e=0;e<4;
75e+=1){try{let e=await fetch("/api/configure/linked",{cache:"no-store",signal:AbortSignal.timeout(4e3)}),t=e.ok?await e.json():null;if("object"==typeof t&&null!==t&&!0===t.linked)return!0}catch(e){(0,eN.reportClientError)("[configure-return] linked check failed while waiting to send the return turn",e)}e<3&&await new Promise(e=>setTimeout(e,750))}return!1}function p3(e){let[t,r]=(0,ek.useState)(()=>p1);return(0,eP.useExternalSync)(()=>{if(t)return;let e=!1;return p5().then(t=>{e||r(()=>t)}),()=>{e=!0}},[t]),t?(0,en.jsx)(t,{...e}):null}let p9="tool-deliver";function p6(e){return(0,en.jsx)(ez,{fallback:null,children:(0,en.jsx)(eU,{...e})})}function p8(e){return"tool-present_article"===e.type||e.type===p9}function p7(e){return p8(e)&&e.output?.mode?{mode:e.output.mode,items:e.output.items??[],primaryId:e.output.primaryId??null,note:e.output.note??"",errors:e.output.errors??[]}:null}function he(e,t){return dd.CONFIGURE_CONNECT_TOOL_NAMES.includes(c9(e))?(0,en.jsx)(dy,{part:e,onRetry:t},e.toolCallId):null}let ht="tool-show_articles",hr={searching:"Searching for",searched:"Searched for",searchFailed:"Couldn’t search the web",reading:"Processing web pages",read:"Processed",readFailed:"Couldn’t process web pages",researched:"Searched the web and processed",showSteps:"Show web research steps",hideSteps:"Hide web research steps",result:"result",results:"results",resultsHeading:"Search results",showMoreResults:"Show more results",showFewerResults:"Show fewer results"},ha={title:"Recommended reading",article:"article",articles:"articles",showMore:"Show more",showFewer:"Show fewer",openOriginal:"Open original"},hn="size-8 shrink-0 rounded-md text-muted-foreground hover:bg-muted/55 hover:text-foreground pointer-coarse:min-h-11 pointer-coarse:min-w-11 sm:size-8",hi="size-4.5 opacity-100",hs="text-foreground",ho="text-muted-foreground",hl="text-muted-foreground/70",hu="bg-card shadow-hairline";function hc(){return"saved"}function hd(){}function hp(e){return"u">typeof crypto&&"randomUUID"in crypto?`${e}-${crypto.randomUUID()}`:`${e}-${Date.now()}-${Math.random().toString(36).slice(2)}`}let hh=dd.PENDING_THREAD_ID,hm="local-article-chat-runtime",hf=[];function hg(e){return e?.kind==="new"?"new":e?.kind==="saved"?`saved:${e.threadId}`:null}function hv(){return window.location.pathname.replace(/(\/chat)(?:\/[^/]+)?\/?$/,"$1")}function hy(e){let t=e.current;if(t){if(window.matchMedia("(min-width: 768px)").matches)return void t.focus();t.blur()}}function hb(e){return"tool-search_library"===e.type}function hx(e){return"tool-read_article"===e.type||"tool-fetch_article_url"===e.type}function hw(e){return{active_view:"local_chat",has_saved_at:!!e.savedAt,has_last_read_at:!!e.lastReadAt,has_cached_at:!!e.cachedAt}}function h_(e){let t=new Map;for(let r of e.parts)for(let e of(0,c5.getResearchPartWebSources)(r)){let r=(0,dx.normalizeCacheUrl)(e.url);t.has(r)||t.set(r,e)}return[...t.values()]}function hk({smryHref:e,originalUrl:t,title:r,domain:a,variant:n="icon",openInNewTab:i=!1,showSmry:s=!0,onOpenSmry:o,onOpenOriginal:l,className:u}){let c="labeled"===n,d=`Open "${r}" in the smry reader`,p=`Open "${r}" on ${a}`,h=c?(0,eE.cn)("inline-flex h-8 flex-1 items-center justify-center gap-1.5 rounded-md px-2 text-[0.75rem] font-medium leading-none no-underline transition-colors hover:border-border hover:bg-muted/45",hu,hs):(0,eE.cn)("relative z-20 inline-flex size-7 shrink-0 items-center justify-center rounded-md no-underline transition-colors hover:bg-muted hover:text-foreground",hl);return(0,en.jsxs)("div",{className:(0,eE.cn)("flex items-center gap-1",u),children:[s?(0,en.jsxs)(dC.Tooltip,{children:[(0,en.jsxs)(dC.TooltipTrigger,{render:(0,en.jsx)(pF.Link,{href:e,prefetch:!1,...i?{target:"_blank",rel:"noopener noreferrer"}:{},onClick:o,"aria-label":d,className:h}),children:[(0,en.jsx)(cU.BookOpen,{className:"size-3.5 shrink-0","aria-hidden":"true"}),c?"Open in smry":null]}),(0,en.jsx)(dC.TooltipContent,{children:"Open in smry"})]}):null,(0,en.jsxs)(dC.Tooltip,{children:[(0,en.jsxs)(dC.TooltipTrigger,{render:(0,en.jsx)("a",{href:t,target:"_blank",rel:"noopener noreferrer",onClick:l,"aria-label":p,className:h}),children:[(0,en.jsx)(cU.ExternalLink,{className:"size-3.5 shrink-0","aria-hidden":"true"}),c?"Open original":null]}),(0,en.jsx)(dC.TooltipContent,{children:"Open original"})]})]})}function hS({sources:e}){let{trackArticleViaBeacon:t}=(0,dm.useAnalytics)(),[r,a]=(0,ek.useState)(!1),[n,i]=(0,ek.useState)(0),s=e[n]??e[0];if(!s)return null;let o=e.length,l=o-1,u=`${s.domain}${l>0?` +${l}`:""}`;return(0,en.jsxs)(dB,{open:r,onOpenChange:e=>{a(e),e||i(0)},title:`${o} citation ${1===o?"source":"sources"}`,trigger:(0,en.jsxs)("button",{type:"button","aria-label":`View ${o} citation ${1===o?"source":"sources"}: ${e.map(e=>e.title).join(", ")}`,title:e.map(e=>e.title).join(" · "),className:"mx-1.5 inline-flex h-6 max-w-44 -translate-y-
75px items-center gap-1.5 rounded-md bg-muted/65 px-2 align-middle text-xs font-medium leading-none text-muted-foreground no-underline shadow-hairline transition-[background-color,color,transform] hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background active:scale-[0.96] motion-reduce:transition-none",children:[(0,en.jsx)(cF.FaviconImage,{domain:s.domain,loading:"eager",className:"size-3.5 shrink-0 rounded-[3px] object-contain outline outline-1 -outline-offset-1 outline-black/10 dark:outline-white/10"}),(0,en.jsx)("span",{className:"truncate",children:u})]}),popoverProps:{side:"top",align:"center",sideOffset:8,className:"w-[min(20rem,calc(100vw-1.5rem))] rounded-[14px]",contentClassName:"overflow-hidden p-0","aria-label":"Citation sources"},drawerSurfaceClassName:"flex flex-col",children:[(0,en.jsxs)("div",{className:"flex min-h-10 items-center justify-between gap-3 border-b border-border/70 px-2.5",children:[(0,en.jsxs)("div",{className:"flex items-center gap-0.5",children:[(0,en.jsx)("button",{type:"button","aria-label":"Previous source",disabled:0===n,onClick:()=>i(e=>Math.max(0,e-1)),className:"inline-flex size-8 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-35",children:(0,en.jsx)(cU.ChevronLeft,{className:"size-4","aria-hidden":"true"})}),(0,en.jsxs)("span",{className:"min-w-10 text-center text-xs tabular-nums text-muted-foreground",children:[n+1,"/",o]}),(0,en.jsx)("button",{type:"button","aria-label":"Next source",disabled:n===o-1,onClick:()=>i(e=>Math.min(o-1,e+1)),className:"inline-flex size-8 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-35",children:(0,en.jsx)(cU.ChevronRight,{className:"size-4","aria-hidden":"true"})})]}),(0,en.jsxs)("span",{className:"text-xs tabular-nums text-muted-foreground",children:[o," ",1===o?"source":"sources"]})]}),(0,en.jsxs)("div",{className:"flex min-w-0 items-start gap-2.5 px-3.5 pt-3.5",children:[(0,en.jsx)(cF.FaviconImage,{domain:s.domain,loading:"eager",className:"mt-0.5 size-5 shrink-0 rounded-[5px] object-contain outline outline-1 -outline-offset-1 outline-black/10 dark:outline-white/10"}),(0,en.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,en.jsx)("p",{className:(0,eE.cn)("truncate text-xs leading-5",hl),children:s.domain}),(0,en.jsx)("p",{className:(0,eE.cn)("mt-1 line-clamp-3 text-[0.9375rem] font-medium leading-5 text-pretty",hs),children:s.title}),s.excerpt&&s.excerpt!==s.title?(0,en.jsx)("p",{className:(0,eE.cn)("mt-2 line-clamp-3 text-[0.8125rem] leading-5 text-pretty",hl),children:s.excerpt}):null]})]}),(0,en.jsx)(hk,{className:"px-3.5 pb-3.5 pt-3",variant:"labeled",openInNewTab:!0,showSmry:!1,smryHref:(0,pU.getArticlePath)(s.url,{from:"library"}),originalUrl:s.url,title:s.title,domain:s.domain,onOpenSmry:()=>{a(!1),t("library_article_opened",s.url,{surface:"local_chat",open_method:"citation_chip",result_position:s.n,...hw(s)})},onOpenOriginal:()=>{a(!1),t("library_article_opened",s.url,{surface:"local_chat",open_method:"citation_chip_original",result_position:s.n,...hw(s)})}})]})}let hE=/\[\s*\d+(?:\s*,\s*\d+)*\s*\]/g;function hC({icon:e,label:t,pending:r=!1}){return(0,en.jsxs)("div",{role:r?"status":void 0,"aria-live":r?"polite":void 0,"aria-atomic":r?"true":void 0,className:(0,eE.cn)("my-1 flex min-h-8 max-w-full items-center gap-2 text-[0.8125rem] leading-5",ho),children:[(0,en.jsx)("span",{className:"flex size-4 shrink-0 items-center justify-center","aria-hidden":"true",children:e}),(0,en.jsx)("span",{className:(0,eE.cn)("min-w-0 truncate",r&&"shimmer"),children:t})]})}function hj({parts:e}){let t,r={errorCount:(t=e.map(e=>{let t="output-error"===e.state||e.output?.error?"error":"output-available"===e.state?"complete":"running";return{query:e.input?.query?.trim()||e.output?.query?.trim()||null,resultCount:e.output?.sources?.length??0,status:t}})).filter(e=>"error"===e.status).length,isRunning:t.some(e=>"running"===e.status),resultCount:t.reduce((e,t)=>
75e+t.resultCount,0),searches:t},a=r.errorCount===r.searches.length,n=`${r.searches.length} searches`,i=`${r.resultCount} ${1===r.resultCount?"result":"results"}`,s=[r.isRunning?"Searching library":a?"Couldn’t search library":"Searched library",r.searches.length>1?n:null,!r.isRunning&&!a&&r.errorCount?`${r.errorCount} failed`:null,!r.isRunning&&!a?i:null].filter(e=>!!e).join(" · ");return(0,en.jsxs)("details",{className:"group/search-details my-1 w-fit max-w-full",children:[(0,en.jsxs)("summary",{className:(0,eE.cn)("-mx-1.5 flex min-h-8 w-fit max-w-[calc(100%+0.75rem)] cursor-pointer list-none items-center gap-2 rounded-lg px-1.5 text-[0.8125rem] leading-5 transition-colors [-webkit-tap-highlight-color:transparent] hover:bg-muted/45 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background pointer-coarse:min-h-11 [&::-webkit-details-marker]:hidden",ho),children:[(0,en.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center","aria-hidden":"true",children:(0,en.jsx)(cU.Search,{className:"size-4"})}),(0,en.jsx)("span",{...r.isRunning?{"aria-atomic":!0,"aria-live":"polite",role:"status"}:null,className:(0,eE.cn)("min-w-0 truncate tabular-nums",r.isRunning&&"shimmer"),children:s}),(0,en.jsx)(cU.ChevronDown,{className:(0,eE.cn)("size-4 shrink-0 transition-transform duration-150 motion-reduce:transition-none group-open/search-details:rotate-180",hl),"aria-hidden":"true"})]}),(0,en.jsx)("ol",{className:"mt-1.5 space-y-1.5 ps-7 text-[0.8125rem] leading-5",children:r.searches.map((e,t)=>(0,en.jsxs)("li",{className:"grid min-w-0 grid-cols-[minmax(0,1fr)_auto] items-baseline gap-4",children:[(0,en.jsx)("span",{className:(0,eE.cn)("truncate",hs),children:e.query??`Library search ${t+1}`}),(0,en.jsx)("span",{className:(0,eE.cn)("whitespace-nowrap tabular-nums",ho),children:"running"===e.status?"Searching":"error"===e.status?"Failed":`${e.resultCount} ${1===e.resultCount?"result":"results"}`})]},`${e.query??"search"}-${t}`))})]})}function hI({parts:e}){let t=e.some(e=>"output-available"!==e.state&&"output-error"!==e.state),r=e.some(e=>"output-available"===e.state&&!e.output?.error),a=e.filter(e=>"output-available"===e.state&&!e.output?.error).length,n=t?e.length:a,i=`${n} ${1===n?"article":"articles"}`;return(0,en.jsx)(hC,{icon:(0,en.jsx)(cU.BookOpen,{className:"size-4"}),label:t?`Reading ${i}`:r?`Read ${i}`:"Couldn’t read articles",pending:t})}function hT({articles:e,note:t}){return null}function hN({part:e,onOpen:t}){let r="output-available"===e.state,a="output-error"===e.state,n=p7(e),i=e.type===p9;if(!r&&!a)return(0,en.jsx)(hC,{icon:(0,en.jsx)(cU.Newspaper,{className:"size-4"}),label:i?"Preparing delivery":"Opening article",pending:!0});if(!n)return(0,en.jsx)("div",{role:"alert",className:"my-2 rounded-[10px] bg-muted/45 px-3 py-2 text-[0.8125rem] leading-5 text-muted-foreground",children:"Couldn’t prepare the article workspace."});let s=i?cU.DeliveryTruck:cU.Presentation;return(0,en.jsxs)("section",{"aria-label":i?"Delivered articles":"Presented article",className:"my-3 space-y-2","data-remy-presentation-receipt":n.mode,children:[(0,en.jsxs)("div",{className:"flex min-w-0 items-center gap-2 px-1 text-muted-foreground",children:[(0,en.jsx)(s,{className:"size-3.5 shrink-0",strokeWidth:1.75,"aria-hidden":"true"}),(0,en.jsx)("span",{className:"shrink-0 text-sm font-medium leading-5",children:i?"Deliver":"Present"}),n.note?(0,en.jsxs)("span",{className:"min-w-0 truncate text-xs leading-5 text-muted-foreground/80",children:["· ",n.note]}):null]}),n.items.length>0?i?(0,en.jsx)("div",{className:"overflow-hidden rounded-[16px] border border-border/55 bg-card shadow-workbench",children:n.items.map((e,r)=>(0,en.jsxs)("div",{className:(0,eE.cn)("flex min-h-[3.25rem] items-center gap-2.5 px-3.5 py-2",r>0&&"border-t border-border/50"),children:[(0,en.jsx)(cU.Newspaper,{className:"size-4 shrink-0 text-muted-foreground",strokeWidth:1.5,"aria-hidden":"true"}),(0,en.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,en.jsx)("p",{className:"truncate text-sm font-medium leading-5 text-foreground",children:e.title}),(0,en.jsxs)("p",{className:"truncate text-xs leading-4 text-muted-foreground",children:[e.domain," · Article"]})]}),(0,en.jsx)(cq.Button,{type:"button",variant:"secondary",size:"sm",onClick:()=>t(e),className:"h-8 rounded-lg px-4","aria-label":`Open ${e.title}`,children:"Open"})]},e.id))}):n.items.slice(0,1).map(e=>(0,en.jsxs)("div",{className:"flex min-h-[6.25rem] items-center gap-3 rounded-[16px] border border-border/55 bg-card p-3 shadow-workbench",children:[(0,en.jsx)("span",{className:"flex h-[4.625rem] w-16 shrink-0 items-center justify-center rounded-[14px] bg-muted/45 text-muted-foreground shadow-hairline",children:(0,en.jsx)(cU.Newspaper,{className:"size-6",strokeWidth:1.5,"aria-hidden":"true"})}),(0,en.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,en.jsxs)("p",{className:"truncate text-xs leading-4 tracking-[0.01em] text-muted-foreground",children:[e.domain," · Article"]}),(0,en.jsx)("p",{className:"mt-0.5 truncate text-sm font-medium leading-5 text-foreground",children:e.title}),e.excerpt?(0,en.jsx)("p",{className:"mt-1 line-clamp-1 text-xs leading-4 text-muted-foreground",children:e.excerpt}):null]}),(0,en.jsx)(cq.Button,{type:"button",variant:"secondary",size:"sm",onClick:()=>t(e),className:"h-8 rounded-lg px-4","aria-label":`Open ${e.title}`,children:"Open"})]},e.id)):null,n.errors.length>0?(0,en.jsx)("div",{role:"status",className:"rounded-[10px] bg-muted/45 px-3 py-2 text-xs leading-5 text-muted-foreground",children:n.errors.join(" ")}):null]})}function hR({article:e,index:t}){let{trackArticleViaBeacon:r}=(0,dm.useAnalytics)(),a="library"===e.kind,n=(0,pU.getArticlePath)(e.url,{from:"library"}),i=()=>{r("library_article_opened",e.url,{surface:"local_chat",open_method:"mentioned_article_chip",result_position:t+1,...hw(e)})};return(0,en.jsxs)("div",{className:(0,eE.cn)("group relative flex min-h-10 w-full items-center gap-2 rounded-full bg-muted/65 pe-1 ps-3 text-[0.8125rem] font-medium leading-5 text-foreground","transition-[background-color,color,scale] duration-150 ease-out hover:bg-muted active:scale-[0.96]"),children:[(0,en.jsx)(cF.FaviconImage,{domain:e.domain,className:"size-4 shrink-0 rounded-[4px] object-contain outline outline-1 -outline-offset-1 outline-black/10 dark:outline-white/10"}),(0,en.jsx)("span",{className:"min-w-0 flex-1 truncate",children:e.title}),(0,en.jsx)(hk,{smryHref:n,originalUrl:e.url,title:e.title,domain:e.domain,openInNewTab:!0,onOpenSmry:i,onOpenOriginal:()=>{r("library_article_opened",e.url,{surface:"local_chat",open_method:"mentioned_article_chip_original",result_position:t+1,...hw(e)})}}),a?(0,en.jsx)(pF.Link,{href:n,prefetch:!1,target:"_blank",rel:"noopener noreferrer",onClick:i,"aria-label":`Open ${e.title} in smry in a new tab`,title:`${e.title} — ${e.domain}`,className:"absolute inset-0 rounded-full outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"}):(0,en.jsx)("a",{href:e.url,target:"_blank",rel:"noopener noreferrer","aria-label":`Open ${e.title} on ${e.domain} in a new tab`,title:`${e.title} — ${e.domain}`,className:"absolute inset-0 rounded-full outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"})]})}function hA({articles:e}){let[t,r]=(0,ek.useState)(!1);if(0===e.length)return null;let a=Math.max(0,e.length-4),n=t?e:e.slice(0,4);return(0,en.jsx)("div",{className:"mb-2.5",children:(0,en.jsxs)("ul",{role:"list","aria-label":"Articles mentioned",className:"flex min-w-0 flex-wrap gap-2",children:[n.map((e,t)=>
75(0,en.jsx)("li",{className:"min-w-0 w-full max-w-72",children:(0,en.jsx)(hR,{article:e,index:t})},`${e.kind}-${e.url}`)),a>0?(0,en.jsx)("li",{children:(0,en.jsxs)("button",{type:"button",onClick:()=>r(e=>!e),"aria-expanded":t,className:(0,eE.cn)("inline-flex min-h-10 items-center gap-1.5 rounded-full bg-muted/40 px-3 text-[0.8125rem] font-medium leading-5","transition-[background-color,color,scale] duration-150 ease-out hover:bg-muted active:scale-[0.96]","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background",ho),children:[(0,en.jsx)("span",{className:"tabular-nums",children:t?"Show fewer":`+${a} more`}),(0,en.jsx)(cU.ChevronDown,{className:(0,eE.cn)("size-3.5 transition-transform duration-150 motion-reduce:transition-none",t&&"rotate-180"),"aria-hidden":"true"})]})}):null]})})}function hz({articles:e,recommendedSources:t,answer:r,isLatest:a,getResearchSourceSaveState:n,onSaveResearchSource:i,researchSourceSaveLabels:s}){return(0,en.jsxs)("div",{className:"mt-4",children:[(0,en.jsx)(dS,{sources:t,labels:ha,getSaveState:n,onSaveSource:i,saveLabels:s,className:"mb-3"}),(0,en.jsx)(hA,{articles:e}),(0,en.jsx)("div",{className:(0,eE.cn)("flex items-center gap-1 transition-opacity motion-reduce:transition-none",!a&&"md:opacity-0 md:group-hover/assistant:opacity-100 md:group-focus-within/assistant:opacity-100"),children:(0,en.jsxs)(dC.Tooltip,{children:[(0,en.jsx)(dC.TooltipTrigger,{render:(0,en.jsx)(px.CopyButton,{value:r,size:"sm",copyLabel:"Copy answer",copiedLabel:"Answer copied",showNativeTooltip:!1,className:(0,eE.cn)("size-7 transition-colors hover:bg-muted/55",hl)})}),(0,en.jsx)(dC.TooltipContent,{children:"Copy answer"})]})})]})}let hM=(0,ek.memo)(function({message:e}){let t=pj(e),r=e.parts.filter(e=>"file"===e.type);return(0,en.jsx)(dH,{align:"end",children:(0,en.jsxs)(dq,{className:"items-end",children:[(0,en.jsx)(d$,{parts:r}),t?(0,en.jsx)(c1,{align:"end",variant:"muted",className:"mt-1.5 max-w-[min(80%,32rem)] bg-muted/70",children:(0,en.jsx)(c2,{className:"px-3 py-2",children:(0,en.jsx)("p",{className:"whitespace-pre-wrap break-words text-pretty text-[0.875rem] leading-5",children:t})})}):null]})})}),hO=(0,ek.memo)(function({message:e,request:t,byNumber:r,libraryUrls:a,knownWebUrls:n,getResearchSourceSaveState:i,onSaveResearchSource:s,researchSourceSaveLabels:o,isGenerating:l,isComplete:u,error:c,onRetry:d,onContinueAfterSignIn:p,onToolApproval:h,onOpenPresentation:m,disableActions:f,isLatest:g,contextArticleReferences:v,readerCitations:y}){let b,x=e.parts,w=x.some(e=>"text"===e.type&&e.text?.trim()),_=x.filter(e=>"reasoning"===e.type&&!!e.text?.trim()).map(e=>e.text?.trim()).filter(e=>!!e).join("\n\n"),k=function(e,t){let r=e.parts,a=pj(e),n=[],i=new Set,s=e=>{let t=(0,dx.normalizeCacheUrl)(e.url);!t||i.has(t)||(i.add(t),n.push(e))},o=new Map;for(let e of r)if("tool-search_library"===e.type)for(let t of e.output?.sources??[])o.has(t.n)||o.set(t.n,t);for(let e of a.matchAll(pP))for(let t of(e[1]??"").split(",").map(e=>Number.parseInt(e.trim(),10)).filter(Number.isFinite)){let e=o.get(t);e&&s(pD(e,"library",e.url,t))}for(let e of r){if("tool-read_article"!==e.type&&"tool-fetch_article_url"!==e.type)continue;let r=e.output?.article;if(!r)continue;let a=t.get((0,dx.normalizeCacheUrl)(r.url)),n="library"===r.source||!!a;s(pD(r,n?"library":"external",a??r.url))}let l=new Map,u=[];for(let e of r){if("tool-search_web"===e.type){for(let t of e.output?.webSources??[])l.set((0,dx.normalizeCacheUrl)(t.url),t);for(let t of e.output?.searches??[])for(let e of t.sources??[])l.set((0,dx.normalizeCacheUrl)(e.url),e)}if("tool-open_web_pages"===e.type||"tool-read_web_page"===e.type)for(let t of e.output?.pages??(e.output?.webPage?[e.output.webPage]:[])){let e=(0,dx.normalizeCacheUrl)(t.url);l.has(e)||l.set(e,t),u.push(t)}}for(let e of a.matchAll(p$)){let r=(0,dx.normalizeCacheUrl)(e[1]??""),a=l.get(r);if(!a)continue;let n=t.get(r);s(pD(a,n?"library":"external",n??a.url))}for(let e of u){let r=(0,dx.normalizeCacheUrl)(e.url),a=t.get(r);s(pD(e,a?"library":"external",a??e.url))}return n}(e,a),S=x.filter(c5.isResearchToolPart),E=(0,ek.useMemo)(()=>h_(e),[e]),C=u?pj(e):"",j=(0,ek.useMemo)(()=>u?function(e,t,r=""){let a=d_(e),n=r?`${a} ${d_(r)}`:a;if(!dw.test(n))return[];let i=new Set;return t.flatMap((e,t)=>{var r;let n,s,o=(0,dx.normalizeCacheUrl)(e.url);if(!o||i.has(o))return[];let l=(n=[r=e.title],(s=r.search(/\s(?:[-–—|])\s/))>0&&n.push(r.slice(0,s)),Array.from(new Set(n.map(d_))).filter(e=>e.length>
75=18&&e.split(" ").filter(Boolean).length>=3)).reduce((e,t)=>{let r=a.indexOf(t);return r<0?e:e<0?r:Math.min(e,r)},-1);return l<0?[]:(i.add(o),[{source:e,matchIndex:l,sourceIndex:t}])}).sort((e,t)=>e.matchIndex-t.matchIndex||e.sourceIndex-t.sourceIndex).map(({source:e})=>e)}(C,E,t):[],[C,u,t,E]),I=(0,ek.useMemo)(()=>{let t=[...v,...function(e,t){let r=new Map;for(let t of e.parts)if(t.type===ht)for(let e of t.output?.articles??[]){let t=(0,pB.createChatArticleReference)(e);t&&!r.has(t.url)&&r.set(t.url,{...t,href:e.href||t.href})}return(0,pB.resolveInlineChatArticleRecommendations)([...r.values()],t).articleReferences}(e,j)];return t.filter((e,r)=>t.findIndex(t=>t.href===e.href||t.url===e.url)===r)},[v,e,j]),T=(b=(0,ec.useTranslations)("chat"),(0,ek.useMemo)(()=>{let e=e=>(function e(t,r,a){return ek.Children.map(t,(t,n)=>{if("string"==typeof t)return function(e,t,r,a){let n=t.flatMap(e=>(0,pB.getChatArticleMentionLabels)(e.title).map(t=>({label:t,reference:e}))).sort((e,t)=>t.label.length-e.label.length);if(0===n.length)return e;let i=e.toLocaleLowerCase(),s=0,o=[];for(;s<e.length;){let t;for(let e of n){let r=i.indexOf(e.label.toLocaleLowerCase(),s);-1!==r&&(!t||r<t.index)&&(t={index:r,...e})}if(!t)break;t.index>s&&o.push(e.slice(s,t.index)),o.push((0,en.jsx)(pY,{reference:t.reference,surface:r,children:e.slice(t.index,t.index+t.label.length)},`${a}-${t.index}-${t.reference.url}`)),s=t.index+t.label.length}return 0===o.length?e:(s<e.length&&o.push(e.slice(s)),o)}(t,r,a,`mention-${n}`);if(!(0,ek.isValidElement)(t)||t.type===pY)return t;if(t.props.href){let e=(0,pB.findChatArticleReference)(r,t.props.href);return e?(0,en.jsx)(pY,{reference:e,surface:a,children:t.props.children}):t}return"code"===t.type||"pre"===t.type||void 0===t.props.children?t:(0,ek.cloneElement)(t,void 0,e(t.props.children,r,a))})})(ek.Children.map(e,(e,t)=>{let a;if("string"!=typeof e||!e.includes("["))return e;let n=[],i=0,s=!1;for(hE.lastIndex=0;null!==(a=hE.exec(e));){s=!0;let o=a[0].replace(/[[\]\s]/g,"").split(",").map(e=>Number.parseInt(e,10)).filter(e=>Number.isFinite(e)&&r.has(e));a.index>i&&n.push(e.slice(i,a.index));let l=[];for(let e of o){let t=r.get(e);t&&l.push(t)}l.length>0&&n.push((0,en.jsx)(hS,{sources:l},`c-${t}-${a.index}-${o.join("-")}`)),i=a.index+a[0].length}return s?(i<e.length&&n.push(e.slice(i)),n):e}),I,"local_chat");return{p:({node:t,children:r,className:a,...n})=>(0,en.jsx)("p",{className:(0,eE.cn)("mb-3 leading-6 last:mb-0",a),...n,children:e(r)}),li:({node:t,children:r,className:a,...n})=>(0,en.jsx)("li",{className:(0,eE.cn)("leading-6",a),...n,children:e(r)}),h1:({node:t,children:r,className:a,...n})=>(0,en.jsx)("h1",{className:(0,eE.cn)("mb-2 mt-4 text-base font-semibold leading-6",a),...n,children:e(r)}),h2:({node:t,children:r,className:a,...n})=>(0,en.jsx)("h2",{className:(0,eE.cn)("mb-2 mt-3 text-[0.9375rem] font-semibold leading-6",a),...n,children:e(r)}),h3:({node:t,children:r,className:a,...n})=>(0,en.jsx)("h3",{className:(0,eE.cn)("mb-2 mt-3 text-sm font-semibold leading-6",a),...n,children:e(r)}),h4:({node:t,children:r,className:a,...n})=>(0,en.jsx)("h4",{className:(0,eE.cn)("mb-2 mt-3 text-sm font-semibold leading-6",a),...n,children:e(r)}),a:({node:e,children:t,className:r,href:i,...s})=>{let o=(0,pX.parseDocumentCitationHref)(i);if(o&&i&&y?.availableDocumentCitations.has(i)){let e="pdf"===o.kind?`p. ${o.page}`:`\xa7 ${o.section}`,t="pdf"===o.kind?b("openPdfPage",{page:o.page}):b("openBookSection",{section:o.section});return(0,en.jsxs)(dC.Tooltip,{children:[(0,en.jsx)(dC.TooltipTrigger,{render:(0,en.jsx)("button",{type:"button","aria-label":t,onClick:()=>(0,pX.dispatchDocumentCitationOpen)(o),className:(0,eE.cn)("mx-0.5 inline-flex h-5 min-w-5 -translate-y-px items-center justify-center rounded-full border border-border bg-muted/70 px-1.5 text-[10px] font-medium tabular-nums text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",r),children:e})}),(0,en.jsx)(dC.TooltipContent,{children:t})]})}let l=(0,pK.parseYouTubeTimestampCitationHref)(i);if(null!==l&&y?.availableYouTubeTimestamps.has(l)&&y.onYouTubeTimestampOpen)return(0,en.jsx)(pQ,{timestampMs:l,onOpen:y.onYouTubeTimestampOpen,ariaLabel:y.getYouTubeTimestampAriaLabel((0,pK.formatYouTubeTimestamp)(l))});if(I.find(e=>e.href===i||e.url===i))return(0,en.jsx)(pJ,{...s,href:i,className:r,references:I,surface:y?"article_chat":"local_chat",children:t});let u=i?(0,dx.normalizeCacheUrl)(i):"",c=a.get(u),d=n.get(u),p=(0,eE.cn)("font-medium text-primary underline underline-offset-2",r);return c?(0,en.jsx)(pF.Link,{href:(0,pU.getArticlePath)(c,{from:"library"}),prefetch:!1,target:"_blank",rel:"noopener noreferrer",className:p,children:t}):d?(0,en.jsx)("a",{href:d,target:"_blank",rel:"noopener noreferrer",className:p,...s,children:t}):(0,en.jsx)("span",{className:(0,eE.cn)("font-medium text-foreground
75/80",r),children:t})}}},[I,r,n,a,y,b])),N=new Set(j.map(e=>(0,dx.normalizeCacheUrl)(e.url))),R=N.size>0?k.filter(e=>!N.has((0,dx.normalizeCacheUrl)(e.url))):k,A=new Set(I.map(e=>(0,dx.normalizeCacheUrl)(e.url))),z=R.filter(e=>!A.has((0,dx.normalizeCacheUrl)(e.url)));return(0,en.jsx)(dH,{align:"start",className:"group/assistant",children:(0,en.jsxs)(dq,{className:"gap-3",children:[(0,en.jsx)(hP,{message:e,thought:_,isGenerating:l}),(0,en.jsx)(c1,{variant:"ghost",className:"w-full",children:(0,en.jsxs)(c2,{className:"w-full max-w-full",children:[S.length>0?(0,en.jsx)(c5.ResearchActivity,{parts:S,labels:hr,sources:E,getSaveState:i,onSaveSource:s,saveLabels:o}):null,x.map((t,r)=>{let a=e.parts[r],n="toolCallId"in t&&"string"==typeof t.toolCallId?t.toolCallId:"text"===t.type&&"string"==typeof t.text?`${e.id}-text-${t.text.slice(0,128)}`:`${e.id}-${t.type}`;if(a&&(0,c5.isResearchToolPart)(a))return null;if(a?.type==="dynamic-tool"){let e=he(a,()=>p(dd.CONNECT_CHIP_PROMPT));return e||("request_sign_in"===c9(a)?(0,en.jsx)(di,{part:a,onContinue:p,disabled:f},a.toolCallId):(0,en.jsx)(da,{part:a,onApprovalResponse:h,approvalDisabled:f},a.toolCallId))}if("text"===t.type){let e=(0,pO.repairAssistantMarkdownWordBoundaries)(t.text??"");return e.trim()?(0,en.jsx)("div",{className:(0,eE.cn)("min-w-0 max-w-full break-words text-[0.9375rem] font-[425] leading-6 tracking-[0.0025em] max-md:select-text max-md:[-webkit-user-select:text]",hs),children:(0,en.jsx)(p3,{isAnimating:l,allowAnyLinks:!0,componentsOverride:T,children:e})},n):null}if("reasoning"===t.type)return null;if(hb(t)){let e=x[r-1];return e&&hb(e)?null:(0,en.jsx)(hj,{parts:function(e,t){let r=t+1;for(;e[r]&&hb(e[r]);)r+=1;return e.slice(t,r)}(x,r)},n)}if(hx(t)){let e=x[r-1];return e&&hx(e)?null:(0,en.jsx)(hI,{parts:function(e,t){let r=[];for(let a=t;a<e.length;a+=1){let t=e[a];if(!t||!hx(t))break;r.push(t)}return r}(x,r)},n)}if(t.type===ht)return(0,en.jsx)(hT,{articles:t.output?.articles??[],note:t.output?.note},n);if(p8(t))return(0,en.jsx)(hN,{part:t,onOpen:m},n);if(a?.type.startsWith("tool-")){let e=he(a,()=>p(dd.CONNECT_CHIP_PROMPT));return e||("request_sign_in"===c9(a)?(0,en.jsx)(di,{part:a,onContinue:p,disabled:f},a.toolCallId):(0,en.jsx)(da,{part:a,onApprovalResponse:h,approvalDisabled:f},a.toolCallId))}return null}),c?(0,en.jsxs)("div",{className:(0,eE.cn)("mt-2 rounded-lg px-3 py-2.5",hu),children:[(0,en.jsx)("p",{className:(0,eE.cn)("text-[0.8125rem] leading-5",ho),children:"Something went wrong generating the answer."}),(0,en.jsxs)("button",{type:"button",onClick:d,className:(0,eE.cn)("mt-2 inline-flex items-center gap-1.5 rounded-md text-[0.8125rem] font-medium transition-colors hover:opacity-70 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background pointer-coarse:min-h-11",hs),children:[(0,en.jsx)(cU.ReloadIcon,{className:"size-3.5","aria-hidden":"true"}),"Try again"]})]}):null,w&&u?(0,en.jsx)(hz,{articles:z,recommendedSources:j.filter(e=>!A.has((0,dx.normalizeCacheUrl)(e.url))),answer:C,isLatest:g,getResearchSourceSaveState:i,onSaveResearchSource:s,researchSourceSaveLabels:o}):null]})})]})})},(e,t)=>e.message===t.message&&e.request===t.request&&e.byNumber===t.byNumber&&e.libraryUrls===t.libraryUrls&&e.knownWebUrls===t.knownWebUrls&&e.getResearchSourceSaveState===t.getResearchSourceSaveState&&e.onSaveResearchSource===t.onSaveResearchSource&&e.researchSourceSaveLabels===t.researchSourceSaveLabels&&e.isGenerating===t.isGenerating&&e.isComplete===t.isComplete&&e.error===t.error&&e.onRetry===t.onRetry&&e.onContinueAfterSignIn===t.onContinueAfterSignIn&&e.disableActions===t.disableActions&&e.isLatest===t.isLatest&&e.contextArticleReferences===t.contextArticleReferences&&e.readerCitations===t.readerCitations);function hP({message:e,thought:t,isGenerating:r}){return"assistant"===e.role&&e.parts.some(e=>"reasoning"===e.type&&!!e.text.trim())?(0,en.jsx)(c4,{text:t,isGenerating:r}):r&&(e?.role!=="assistant"||!(e.parts.length>0))?(0,en.jsx)(c5.ChatLoader,{label:"Thinking"}):null}function h$(){return(0,en.jsx)(dH,{align:"start",className:"group/assistant",children:(0,en.jsx)(dq,{className:"gap-3",children:(0,en.jsx)(c5.ChatLoader,{label:"Thinking"})})})}function hD({onRetry:e}){return(0,en.jsxs)("div",{role:"alert",className:(0,eE.cn)("rounded-lg px-3 py-2.5 text-[0.8125rem] leading-5",hu),children:[(0,en.jsx)("p",{className:ho,children:"Something went wrong sending your message."}),(0,en.jsxs)("button",{type:"button",onClick:e,className:(0,eE.cn)("mt-2 inline-flex items-center gap-1.5 rounded-md font-medium transition-colors hover:opacity-70 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background pointer-coarse:min-h-11",hs),children:[(0,en.jsx)(cU.ReloadIcon,{className:"size-3.5","aria-hidden":"true"}),"Try again"]})]})}let hU=(0,ek.memo)(function({disabled:e,onCopyMarkdown:t,onCopyJson:r,onClear:a,phone:n=!1}){let i=(0,ec.useTranslations)("chat"),s=i("chatActions");return(0,en.jsx)("div",{className:"shrink-0",children:(0,en.jsxs)(pw.DropdownMenu,{children:[n?(0,en.jsx)(pw.DropdownMenuTrigger,{render:(0,en.jsx)(ph.MobileHeaderIconButton,{"aria-label":i("chatActions"),children:(0,en.jsx)("span",{className:"flex size-8 items-center justify-center rounded-full bg-muted/70",children:(0,en.jsx)(cU.MoreHorizontal,{className:"size-[18px]",strokeWidth:2,"aria-hidden":"true"})})})}):(0,en.jsxs)(dC.Tooltip,{children:[(0,en.jsx)(dC.TooltipTrigger,{render:(0,en.jsx)(pw.DropdownMenuTrigger,{render:(0,en.jsx)(cq.Button,{variant:"ghost",size:"icon-sm",className:hn,"aria-label":s,children:(0,en.jsx)(cU.MoreVertical,{className:hi,strokeWidth:2,"aria-hidden":"true"})})})}),(0,en.jsx)(dC.TooltipContent,{children:s})]}),(0,en.jsxs)(pw.DropdownMenuContent,{align:"end",side:"bottom",sideOffset:6,className:"min-w-48",children:[(0,en.jsxs)(pw.DropdownMenuGroup,{children:[(0,en.jsxs)(pw.DropdownMenuItem,{disabled:e,onClick:()=>void t(),children:[(0,en.jsx)(cU.Copy,{className:"size-4","aria-hidden":"true"}),"Copy chat as Markdown"]}),(0,en.jsxs)(pw.DropdownMenuItem,{disabled:e,onClick:()=>void r(),children:[(0,en.jsx)(cU.Copy,{className:"size-4","aria-hidden":"true"}),"Copy full conversation as JSON"]})]}),(0,en.jsx)(pw.DropdownMenuSeparator,{}),(0,en.jsx)(pw.DropdownMenuGroup,{children:(0,en.jsxs)(pw.DropdownMenuItem,{disabled:e,variant:"destructive",onClick:a,children:[(0,en.jsx)(cU.Trash,{className:"size-4","aria-hidden":"true"}),"Clear chat"]})})]})]})})}),hL=(0,ek.memo)(function({onClose:e,onNewChat:t,exportDisabled:r,onCopyMarkdown:a,onCopyJson:n,onClear:i}){let s=(0,ec.useTranslations)("chat")("newChat");return(0,en.jsxs)("div",{className:"flex w-full min-w-0 items-center gap-0.5 md:hidden",children:[(0,en.jsx)(ph.MobileCloseButton,{fallbackHref:"/home",onClick:e?t=>{t.preventDefault(),e()}:void 0}),(0,en.jsx)("div",{className:"min-w-0 flex-1"}),(0,en.jsx)(ph.MobileHeaderIconButton,{onClick:t,"aria-label":s,children:(0,en.jsx)(pp.SquarePen,{className:"size-[21px]",strokeWidth:1.85,"aria-hidden":"true"})}),(0,en.jsx)(hU,{phone:!0,disabled:r,onCopyMarkdown:a,onCopyJson:n,onClear:i})]})});function hF({contentItem:e,highlights:t,signedIn:r,libraryEmpty:a,onDraft:n}){let i=(0,ec.useTranslations)("chat"),s=(0,ec.useTranslations)("remySuggestions"),o=(0,ek.useId)();return(0,en.jsx)("section",{"data-reader-chat-empty-state":!0,"aria-labelledby":o,className:"mx-auto flex min-h-0 w-full max-w-[42.5rem] flex-1 flex-col overflow-y-auto px-4 py-5",children:(0,en.jsxs)("div",{className:"my-auto w-full shrink-0 py-2",children:[(0,en.jsxs)("div",{className:"mb-5 px-1",children:[(0,en.jsxs)("div",{className:"flex items-center gap-2.5",children:[(0,en.jsx)(eS.RemyIcon,{className:"size-5 shrink-0 text-muted-foreground","aria-hidden":"true"}),(0,en.jsx)("h1",{id:o,className:"text-balance text-base font-medium text-foreground",children:i("emptyTitle",{kind:e.kind})})]}),(0,en.jsx)("p",{className:"mt-2 text-pretty text-sm leading-6 text-muted-foreground",children:s("readerDescription")})]}),(0,en.jsx)(e_,{hasSource:!0,hasHighlights:!!t?.length,signedIn:r,libraryEmpty:a,onDraft:n})]})})}function hZ({className:e}){return(0,en.jsxs)("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.25",strokeLinecap:"round",strokeLinejoin:"round",className:e,"aria-hidden":"true",children:[(0,en.jsx)("path",{d:"M12 19V5"}),(0,en.jsx)("path",{d:"m5 12 7-7 7 7"})]})}let hB=(0,ek.memo)(function({disabled:e=!1,restoring:t=!1,input:r,onInputChange:a,isStreaming:n,files:i,isPreparingFiles:s,fileError:o,isPremium:l,modelSelection:u,placement:c="bottom",onAddFiles:d,onModelChange:p,onRemoveFile:h,onRetryFile:m,onSubmit:f,onStop:g,isDraggingFiles:v,placeholder:y,quotedText:b,onDismissQuote:x,presentation:w="page",containerRef:_,textareaRef:k,above:S}){let E=(0,ek.useRef)(null),[C,j]=(0,ek.useState)(!1),I=dz(i),T=!!(r.trim()||I.length>0)&&!e&&!t&&!s,N=n?"Stop generating":e?"Demo conversation":s?"Preparing files":"Send message",R=e=>{e?.length&&d(Array.from(e))},A="reader"===w?(0,en.jsxs)(dF.Popover,{open:C,onOpenChange:j,children:[(0,en.jsx)(dF.PopoverTrigger,{type:"button",disabled:e||n,"aria-label":"Add files","aria-describedby":"local-chat-file-help",className:"flex size-9 shrink-0 items-center justify-center rounded-[10px] text-muted-foreground outline-none transition-[background-color,color] hover:bg-muted/60 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring data-[popup-open]:bg-muted/60 data-[popup-open]:text-foreground pointer-coarse:size-11",children:(0,en.jsx)(cU.Plus,{className:"size-4","aria-hidden":"true"})}),(0,en.jsx)(dF.PopoverPopup,{side:"top",align:"end",sideOffset:8,initialFocus:e=>"keyboard"===e,className:"w-[min(18rem,calc(100vw-2rem))] !min-w-0 rounded-[14px] border-border bg-popover shadow-hairline",contentClassName:"p-1.5",children:(0,en.jsxs)("button",{type:"button",onClick:()=>{E.current?.click(),j(!1)},className:"flex min-h-11 w-full items-center gap-3 rounded-[10px] px-2.5 py-2 text-start outline-none transition-colors hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring motion-reduce:transition-none",children:[(0,en.jsx)("span",{className:"flex size-8 shrink-0 items-center justify-center rounded-[9px] bg-muted text-muted-foreground",children:(0,en.jsx)(cU.Upload,{className:"size-4","aria-hidden":"true"})}),(0,en.jsxs)("span",{className:"min-w-0",children:[(0,en.jsx)("span",{className:"block text-sm font-medium text-foreground",children:"Attach file or image"}),(0,en.jsx)("span",{className:"mt-0.5 block text-xs text-muted-foreground",children:"Images, PDFs, Markdown, text, or CSV"})]})]})})]}):(0,en.jsx)(pd.PromptInputAction,{tooltip:"Attach files",children:(0,en.jsxs)(cq.Button,{type:"button",variant:"ghost",size:"sm",disabled:e||n,"aria-describedby":"local-chat-file-help",onClick:()=>E.current?.click(),className:"h-9 min-w-0 gap-1.5 rounded-[10px] px-2 text-xs font-medium text-muted-foreground shadow-none transition-[background-color,color] hover:bg-muted/60 hover:text-foreground active:scale-100 pointer-coarse:h-11",children:[(0,en.jsx)(cU.Upload,{className:"size-3.5","aria-hidden":"true"}),(0,en.jsx)("span",{className:"truncate",children:"Attach"})]})});return(0,en.jsx)("form",{onSubmit:e=>{e.preventDefault(),T&&!n&&f()},className:(0,eE.cn)("w-full min-w-0","bottom"===c?(0,eE.cn)("relative z-10 shrink-0 bg-background pt-2","reader"===w?"px-4 pb-[max(1rem,env(safe-area-inset-bottom))]":"px-4 pb-[max(0.75rem,env(safe-area-inset-bottom))] md:px-6"):"px-0 sm:px-1"),children:(0,en.jsx)("div",{ref:_,"data-local-chat-composer":!0,"data-article-chat-composer":"reader"===w?"true":void 0,"data-composer-placement":c,className:"mx-auto w-full max-w-[42.5rem]",children:(0,en.jsxs)("div",{className:(0,eE.cn)(S&&"rounded-[14px] bg-card shadow-hairline transition-[box-shadow] focu
75s-within:ring-2 focus-within:ring-ring/55 focus-within:ring-offset-2 focus-within:ring-offset-background motion-reduce:transition-none"),children:[S?(0,en.jsx)("div",{className:"rounded-t-[14px] border-b border-border/60 bg-muted/40 px-1.5 py-1",children:S}):null,(0,en.jsxs)(pd.PromptInput,{disabled:e,value:r,onValueChange:a,isLoading:n,onSubmit:f,maxHeight:192,textareaRef:k,"data-dragging":v?"true":void 0,className:(0,eE.cn)("rounded-[14px] border-0 bg-card shadow-hairline transition-[background-color,box-shadow] focus-within:bg-background focus-within:ring-2 focus-within:ring-ring/55 focus-within:ring-offset-2 focus-within:ring-offset-background data-[dragging=true]:border data-[dragging=true]:border-dashed data-[dragging=true]:border-ring motion-reduce:transition-none","reader"===w?"p-2":"p-2.5",S?"rounded-t-none shadow-none focus-within:ring-0 focus-within:ring-offset-0":void 0),children:[b?(0,en.jsxs)(cW,{size:"sm",className:"mb-1 w-full flex-nowrap border-border/60 bg-muted/35",children:[(0,en.jsx)(cJ,{children:(0,en.jsx)(cQ,{className:"line-clamp-2 whitespace-normal",children:b})}),(0,en.jsx)(cX,{children:(0,en.jsx)(cq.Button,{type:"button",variant:"ghost",size:"icon-xs",onClick:x,"aria-label":"Remove quoted text",children:(0,en.jsx)(cU.X,{className:"size-3.5","aria-hidden":"true"})})})]}):null,(0,en.jsx)(dP,{files:i,onRemove:h,onRetry:m}),(0,en.jsx)(pd.PromptInputTextarea,{placeholder:y,"aria-label":"Message Remy",minHeight:"reader"===w?40:48,onPaste:e=>{e.clipboardData.files.length&&R(e.clipboardData.files)},className:(0,eE.cn)("max-h-48 px-1 py-1.5 text-base leading-6 text-foreground placeholder:text-muted-foreground/70 md:text-[0.9375rem]","reader"===w?"min-h-10":"min-h-12")}),o?(0,en.jsx)("p",{role:"alert",className:"px-1 pb-1 text-xs leading-5 text-destructive",children:o}):null,(0,en.jsxs)(pd.PromptInputActions,{className:"justify-between gap-1 pt-1",children:[(0,en.jsxs)("div",{className:"flex min-w-0 items-center gap-0.5",children:[(0,en.jsx)(dD.ChatModelPicker,{disabled:e,isPremium:l,onSelectionChange:p,selection:u,side:"center"===c?"bottom":"top",upgradePlacement:"remy_chat_model_picker"}),"reader"!==w?A:null]}),(0,en.jsxs)("span",{id:"local-chat-file-help",className:"sr-only",children:["Attach up to ",4," images, PDFs, Markdown, text, or CSV files. You can also paste or drop files into the composer."]}),(0,en.jsx)("input",{ref:E,type:"file",multiple:!0,accept:"image/jpeg,image/png,image/gif,image/webp,application/pdf,text/plain,text/markdown,text/csv,.md,.markdown,.txt,.csv,.pdf",tabIndex:-1,"aria-hidden":"true",className:"sr-only",onChange:e=>{R(e.currentTarget.files),e.currentTarget.value="",j(!1)}}),(0,en.jsxs)("div",{className:"flex shrink-0 items-center gap-0.5",children:["reader"===w?A:null,(0,en.jsx)(eu.RemyVoiceInput,{value:r,onChange:a,disabled:e||n}),(0,en.jsx)(pd.PromptInputAction,{tooltip:N,children:(0,en.jsxs)(cq.Button,{type:n?"button":"submit",variant:"ghost",size:"icon",disabled:e,"data-chat-composer-action":!0,"data-state":n?"stop":"send","aria-label":N,"aria-disabled":!n&&!T||void 0,onClick:n?g:void 0,className:(0,eE.cn)("relative size-9 overflow-hidden rounded-[10px] border-0 shadow-none transition-[background-color,color,scale,opacity] duration-150 active:scale-[0.96] motion-reduce:transition-none pointer-coarse:size-11 [&_svg]:mx-0",n||T?"bg-primary text-primary-foreground hover:bg-primary/90":"bg-muted text-muted-foreground hover:bg-muted/80"),children:[(0,en.jsx)(hZ,{className:(0,eE.cn)("absolute size-4 transition-[opacity,scale,filter] duration-200 ease-[cubic-bezier(0.2,0,0,1)] motion-reduce:transition-none",n?"scale-[0.25] opacity-0 blur-[4px]":"scale-100 opacity-100 blur-0")}),(0,en.jsx)("span",{"aria-hidden":"true",className:(0,eE.cn)("absolute block size-3 rounded-[3px] bg-current transition-[opacity,scale,filter] duration-200 ease-[cubic-bezier(0.2,0,0,1)] motion-reduce:transition-none",n?"scale-100 opacity-100 blur-0":"scale-[0.25] opacity-0 blur-[4px]")})]})})]})]})]})]})})})}),hH=(0,ek.forwardRef)(function(e,t){return(0,ei.useRemyData)()&&!e.demo?(0,en.jsx)(hq,{...e,ref:t}):(0,en.jsxs)(ei.RemyDataProvider,{children:[!e.demo&&(0,en.jsx)(ei.RemyDataBridge,{}),(0,en.jsx)(hq,{...e,ref:t})]})}),hq=(0,ek.memo)((0,ek.forwardRef)(function({presentation:t,isVisible:r=!0,demo:a,initialChatId:n,initialEntryId:i,initialConfigureReturn:s,initialConfigureGuest:o,seededThreadId:l,seededThreadTitle:u,chatPathname:c,contentItem:d,currentArticleReference:p,initialMessages:h,initialAction:m,sourceContext:f,conversationPrelude:g,onDraftTextChange:v,highlights:y,articleReferences:b=hf,onYouTubeTimestampOpen:x,onClose:w,onExpand:_,onDock:k,onCollapse:S},E){var C;let j,I,T="reader"===t,N=(0,eo.useIsDesktop)(),R="page"===t,A="page"===t||"reader"===t&&!!w,{ownerKey:z}=(0,eT.useLibraryOwner)(),[M,O]=(0,ek.useState)({ownerKey:z,item:d}),P=M.ownerKey===z?M.item:void 0,$=(0,ek.useCallback)(e=>{O({ownerKey:z,item:e})},[z]),[D,U]=(0,ek.useState)(),L=!!a,F=(0,ek.useMemo)(()=>
75c?(0,p0.remyChatRouteFromPathname)(c):null,[c]),Z=hg(F),B=function({demoId:e,seededThreadId:t,initialChatId:r,chatRoute:a}){let n=a?.kind==="saved"?a.threadId:null,i=e??t??r??n??hh,s=!!(r||n);return{chatId:i,restoredChatId:e||t?i:s?null:hh,urlSynced:!!(e||t||s),appliedRouteKey:t?`saved:${t}`:r?`saved:${r}`:hg(a)}}({demoId:a?.id,seededThreadId:l,initialChatId:n,chatRoute:F}),[H,q]=(0,ek.useState)(B.chatId),[V,W]=(0,ek.useState)(B.restoredChatId),G=P?.metadata.url??D?.articleUrl,Y=d&&(G?(0,dx.normalizeCacheUrl)(G)===(0,dx.normalizeCacheUrl)(d.metadata.url):V===H),J=(0,ej.useReaderArticle)((0,eI.retainedReaderReference)(L?null:G??(Y?d.metadata.url:null))),K="unavailable"===J.state.status&&("not-found-or-inaccessible"===J.state.reason||"sign-in-required"===J.state.reason),Q=K?void 0:Y?d:P??("ready"===J.state.status?J.state.document.contentItem??void 0:void 0),{isLoaded:X,isSignedIn:ee,userId:et,getToken:er}=(0,cz.useAuth)(),ea=(0,cM.useClerk)(),el=(0,pS.useHasMounted)(),eu=(0,ek.useMemo)(()=>{if(!el||L||n||!i||F?.kind==="saved")return null;let e=(0,pz.peekChatEntryTurn)(i);return e?{turn:e,messageId:`message-${e.id}`}:null},[F?.kind,el,n,i,L]),ed=(0,ek.useMemo)(()=>eu?[{id:eu.messageId,role:"user",parts:[{type:"text",text:eu.turn.prompt}]}]:void 0,[eu]),{isPremium:ep}=(0,p_.useIsPremium)(),{track:eh}=(0,dm.useAnalytics)(),em=(0,ec.useTranslations)("chat"),ef=(0,ec.useTranslations)("youtubeLayout"),eg=(0,ek.useMemo)(()=>{if(Q)return{availableYouTubeTimestamps:"transcript"===Q.role?(0,pK.extractYouTubeTimestampCitationMs)(Q.text):new Set,availableDocumentCitations:new Set(Array.from(Q.text.matchAll(/\]\((#smry-(?:pdf-page|book-section)-\d+)\)/g),e=>e[1])),onYouTubeTimestampOpen:x,getYouTubeTimestampAriaLabel:e=>ef("openAtTimestamp",{timestamp:e})}},[Q,x,ef]),[ev,ey]=(0,ek.useState)(!1);(0,eP.useExternalSync)(()=>{if(!T&&!n&&!l&&F?.kind!=="saved"&&!a)return;let e=!1;return p5().then(()=>{e||ey(!0)},()=>{e||ey(!0)}),()=>{e=!0}},[F?.kind,a,n,T,l]);let eb=(0,ek.useMemo)(()=>({save:em("sourceSave"),saving:em("sourceSaving"),saved:em("sourceSaved"),saveToLibrary:em("sourceSaveToLibrary"),savedInLibrary:em("sourceSavedInLibrary")}),[em]),ex=(0,ek.useRef)(B.urlSynced),ew=(0,ek.useRef)(B.appliedRouteKey),e_=(0,ek.useMemo)(()=>Q?{articleUrl:Q.metadata.url,articleTitle:Q.metadata.title,articleDomain:Q.metadata.siteName??(0,eE.extractHostname)(Q.metadata.url)??void 0}:D??(p?{articleUrl:p.url,articleTitle:p.title,articleDomain:(0,eE.extractHostname)(p.url)}:void 0),[Q,D,p]),eS=(0,ei.useRemyChatStorage)(H,e_,ep),{threads:eR,threadsReady:eA,activeThreadReady:ez,upsertThread:eM,modelSelection:eO,setModelSelection:e$}=eS;(0,eP.useExternalSync)(()=>{T||n||F?.kind==="saved"||a||0===eR.length||p5().catch(()=>{})},[F?.kind,a,n,T,eR.length]);let[eD,eU]=(0,ek.useState)(""),[eL,eF]=(0,ek.useState)(!1),[eZ,eB]=(0,ek.useState)(()=>a?.presentation??null),[eH,eq]=(0,ek.useState)(!1),[eV,eW]=(0,ek.useState)(680),eG=(0,ek.useCallback)(e=>{T?(0,pH.dispatchReaderArticleNavigation)({url:e.url,from:"recommendations"}):(eB(e),eq(!1))},[T]),eY=(0,ek.useCallback)(()=>{eB(null),eq(!1)},[]),[eJ,eK]=(0,ek.useState)(null),eQ=(0,ek.useCallback)(()=>eK(null),[]),eX=(0,ek.useRef)(null),[e0,e1]=(0,ek.useState)([]),[e2,e5]=(0,ek.useState)(null),[e4,e3]=(0,ek.useState)(!1),[e9,e6]=(0,ek.useState)(0),e8=(0,ek.useRef)(null),e7=(0,ek.useRef)(null),te=(0,pk.useLatestRef)(eR),{transport:tt,setTransportChatId:tr}=function({modelSelection:e,chatId:t,article:r,articleReference:a}){let{getToken:n}=(0,cz.useAuth)(),i=(0,pk.useLatestRef)(e),s=(0,pk.useLatestRef)(t),o=(0,ek.useCallback)(()=>i.current,[i]),l=(0,ek.useCallback)(e=>{s.current=e},[s]),u=(0,ek.useCallback)(async(e,t)=>{let r=new Headers(t?.headers);try{var a,i;let e=await (a=n(),!(i=t?.signal)?a:i.aborted?(a.catch(()=>void 0),Promise.reject(i.reason??new DOMException("This operation was aborted","AbortError"))):new Promise((e,t)=>{let r=()=>{t(i.reason??new DOMException("This operation was aborted","AbortError"))};i.addEventListener("abort",r,{once:!0}),a.then(t=>{i.removeEventListener("abort",r),e(t)},e=>{i.removeEventListener("abort",r),t(e)})}));e&&r.set("Authorization",`Bearer ${e}`)}catch(e){if(t?.signal?.aborted)throw e}return fetch(e,{...t,headers:r})},[n]),c=r?.contentItem,d=r?.highlights,p=(0,ek.useMemo)(()=>c?function({contentItem:e,highlights:t}){return{content:e.text,totalCharacters:e.text.length,url:e.metadata.url,title:e.metadata.title,kind:e.kind,role:e.role,format:e.format,author:e.metadata.author,siteName:e.metadata.siteName,language:e.metadata.language,publishedAt:e.metadata.publishedAt,...t?.length?{highlights:t}:{}}}({contentItem:c,highlights:d}):void 0,[c,d]),h=a?.url,m=a?.title;return{modelSelection:e,transport:(0,ek.useMemo)(()=>new uH({api:"/api/remy",fetch:u,prepareSendMessagesRequest:({messages:e,trigger:t,messageId:r})=>({body:{id:s.current,messages:e,trigger:t,...r?{messageId:r}:{},...p?{article:p}:h?{articleReference:{url:h,title:m}}:{}
75,customInstructions:pN(),modelId:o(),pageContext:function(){if("u">typeof document)return pA.parse({url:window.location.href,title:document.title.slice(0,500),language:document.documentElement.lang.slice(0,40)})}(),timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone}})}),[p,h,m,s,u,o]),setTransportChatId:l}}({modelSelection:eO,chatId:H,...Q?{article:{contentItem:Q,highlights:y}}:{},articleReference:e_?.articleUrl?{url:e_.articleUrl,title:e_.articleTitle}:void 0}),ta=(0,pk.useLatestRef)([]),tn=(0,ek.useRef)(0),ti=(0,ek.useRef)(0),ts=(0,ek.useRef)(!1),to=(0,ek.useCallback)((e,t)=>{eU(e),eX.current=e.trim()?t??eX.current:null,v?.(e)},[v]),{messages:tl,status:tu,error:tc,sendMessage:td,stop:tp,regenerate:th,setMessages:tm,clearError:tf,addToolApprovalResponse:tg}=function({throttle:e,experimental_throttle:t,resume:r=!1,...a}={}){let n,i=null!=e?e:t,s=(0,ek.useRef)({});"chat"in a||(s.current={onToolCall:a.onToolCall,onData:a.onData,onFinish:a.onFinish,onError:a.onError,sendAutomaticallyWhen:a.sendAutomaticallyWhen,transport:a.transport});let o=()=>{var e;return null!=(e=s.current.transport)?e:null!=n?n:n=new uH},l={...a,transport:{sendMessages:e=>o().sendMessages(e),reconnectToStream:e=>o().reconnectToStream(e)},onToolCall:e=>{var t,r;return null==(r=(t=s.current).onToolCall)?void 0:r.call(t,e)},onData:e=>{var t,r;return null==(r=(t=s.current).onData)?void 0:r.call(t,e)},onFinish:e=>{var t,r;return null==(r=(t=s.current).onFinish)?void 0:r.call(t,e)},onError:e=>{var t,r;return null==(r=(t=s.current).onError)?void 0:r.call(t,e)},sendAutomaticallyWhen:e=>{var t,r,a;return null!=(a=null==(r=(t=s.current).sendAutomaticallyWhen)?void 0:r.call(t,e))&&a}},u=(0,ek.useRef)("chat"in a?a.chat:new cA(l));("chat"in a&&a.chat!==u.current||"id"in a&&null!=a.id&&u.current.id!==a.id)&&(u.current="chat"in a?a.chat:new cA(l));let c=u.current,d=(0,ek.useRef)({chat:c,messages:c.messages});d.current.chat!==c&&(d.current={chat:c,messages:c.messages});let p=(0,ek.useCallback)(e=>{let t=!0,r=c["~registerMessagesCallback"](()=>{t&&d.current.chat===c&&(d.current={chat:c,messages:c.messages},e())},i);return d.current={chat:c,messages:c.messages},()=>{t=!1,r()}},[c,i]),h=(0,ek.useCallback)(()=>d.current.messages,[]),m=(0,ek.useSyncExternalStore)(p,h,h),f=(0,ek.useCallback)(e=>c["~registerStatusCallback"](()=>{d.current.chat===c&&(("ready"===c.status||"error"===c.status)&&(d.current={chat:c,messages:c.messages}),e())}),[c]),g=(0,ek.useCallback)(()=>c.status,[c]),v=(0,ek.useSyncExternalStore)(f,g,g),y=(0,ek.useSyncExternalStore)(u.current["~registerErrorCallback"],()=>u.current.error,()=>u.current.error),b=(0,ek.useCallback)(e=>{"function"==typeof e&&(e=e(u.current.messages)),u.current.messages=e},[u]);return(0,ek.useEffect)(()=>{r&&u.current.resumeStream()},[r,u]),{id:u.current.id,messages:m,setMessages:b,sendMessage:u.current.sendMessage,regenerate:u.current.regenerate,clearError:u.current.clearError,stop:u.current.stop,error:y,resumeStream:u.current.resumeStream,status:v,addToolResult:u.current.addToolOutput,addToolOutput:u.current.addToolOutput,addToolApprovalResponse:u.current.addToolApprovalResponse}}({id:a?`${hm}-${a.id}`:hm,messages:a?.messages??h??ed,transport:tt,throttle:50,sendAutomaticallyWhen:uV,onFinish:({messages:e})=>{let t=function(e){for(let t=e.length-1;t>=0;t-=1){let r=e[t];for(let e=r.parts.length-1;e>=0;e-=1){let t=r.parts[e];if("output-available"!==t.state)continue;let a=p7(t);if(a)return function(e){return e.items.find(t=>t.id===e.primaryId)??e.items[0]??null}(a)}}return null}(e);t&&eG(t)}}),tv=(0,ek.useCallback)((e,t)=>tg({id:e,approved:t}),[tg]),ty=(0,es.useRefreshFeedQueries)(),tb=(0,ek.useRef)(new Set);(0,eP.useExternalSync)(()=>{if(L)return;let e=!1;for(let r of tl)for(let a of r.parts){var t;("dynamic-tool"===a.type||a.type.startsWith("tool-"))&&("output-available"!==a.state||(t=c9(a),!pL.has(t))||tb.current.has(a.toolCallId)||(tb.current.add(a.toolCallId),e=!0))}e&&ty()},[L,tl,ty]),(0,eP.useExternalSync)(()=>{Y&&!K&&d!==P&&$(d)},[d,Y,K,P,$]),ta.current=tl;let tx="submitted"===tu||"streaming"===tu,tw=(0,ek.useMemo)(()=>tl.some(e=>h_(e).length>0),[tl]);(0,eP.useExternalLayoutSync)(()=>
75{eS.setRequest({canPersist:!0===ee&&!L,activeThreadId:H,metadata:e_,isPremium:ep,researchSources:tw&&!L})},[eS.setRequest,ee,L,H,e_,ep,tw]);let{getResearchSourceSaveState:t_,saveResearchSource:tk}=eS,tS=L?hc:t_,tE=L?hd:tk,tC=e0.some(e=>"preparing"===e.status),tj=(0,ek.useMemo)(()=>dz(e0),[e0]),tI=(0,ek.useCallback)(async e=>{let t=await dA(e);e1(e=>e.map(e=>e.id===t.id?t:e))},[]),tT=(0,ek.useCallback)(e=>{if(0===e.length||tx)return;e5(null);let t=function(e,t,r=0){let a=[],n=Math.max(0,4-t.length),i=e.slice(0,n);e.length>n&&a.push("You can attach up to 4 files.");let s=new Set(t.map(e=>`${e.filename}:${e.size}`)),o=t.reduce((e,t)=>e+("ready"===t.status||"preparing"===t.status||"error"===t.status&&t.retryable?t.size:0),0),l=r+t.reduce((e,t)=>e+("ready"===t.status?t.url.length:"preparing"===t.status||t.retryable?dN(t.size,t.mediaType):0),0);return{files:i.flatMap(e=>{var t,r;let n,i=`${e.name}:${e.size}`;if(s.has(i))return a.push(`${e.name} is already attached.`),[];let u=(t=e,(n=t.type.toLowerCase().split(";")[0]?.trim())&&dI.has(n)?n:dj[r=t.name,r.toLowerCase().match(/\.([a-z0-9]+)$/)?.[1]??""]??null);if(!u)return[{id:dR(e),type:"file",filename:e.name,mediaType:e.type||"application/octet-stream",size:e.size,status:"error",error:`${e.name} is not a supported image, PDF, or text file.`,retryable:!1}];let c=dT(u)?5242880:"application/pdf"===u?8388608:524288;if(e.size>c)return[{id:dR(e),type:"file",filename:e.name,mediaType:u,size:e.size,status:"error",error:`${e.name} must be ${c>=1048576?`${Math.round(c/1048576)} MB`:`${Math.round(c/1024)} KB`} or smaller.`,retryable:!1}];if(o+e.size>0xc00000)return[{id:dR(e),type:"file",filename:e.name,mediaType:u,size:e.size,status:"error",error:"Attachments must be 12 MB or smaller in total.",retryable:!1}];let d=dN(e.size,u);return l+d>0xb00000?[{id:dR(e),type:"file",filename:e.name,mediaType:u,size:e.size,status:"error",error:"This chat has reached its attachment limit. Start a new chat to attach more files.",retryable:!1}]:(o+=e.size,l+=d,s.add(i),[{type:"file",id:dR(e),filename:e.name,mediaType:u,size:e.size,status:"preparing",sourceFile:e}])}),errors:a}}(e,e0,ta.current.reduce((e,t)=>e+t.parts.reduce((e,t)=>"file"===t.type&&"string"==typeof t.url&&t.url.startsWith("data:")?e+t.url.length:e,0),0));if(t.files.length>0)for(let e of(e1(e=>[...e,...t.files]),t.files))"preparing"===e.status&&tI(e);t.errors.length>0&&e5(t.errors[0]??"Could not attach that file.")},[e0,tx,ta,tI]),tN=(0,ek.useCallback)(e=>{e1(t=>t.filter(t=>t.id!==e)),e5(null)},[]),tR=(0,ek.useCallback)(e=>{let t=e0.find(t=>t.id===e&&"error"===t.status);if(!t)return;let r=t.retryable&&t.sourceFile?{id:t.id,type:"file",filename:t.filename,mediaType:t.mediaType,size:t.size,status:"preparing",sourceFile:t.sourceFile}:null;r&&(e1(t=>t.map(t=>t.id===e?r:t)),tI(r))},[e0,tI]),{byNumber:tA,knownWebUrls:tz}=(j=function(e){let t=[],r=[];for(let a of e)if("assistant"===a.role)for(let e of a.parts){for(let r of e.output?.sources??[])t.push(r);for(let t of(0,c5.getResearchPartOpenedWebSources)(e))r.push(t.url)}return JSON.stringify({librarySources:t,webUrls:r})}(tl),(0,ek.useMemo)(()=>{let e=JSON.parse(j),t=new Map;for(let r of e.librarySources)t.has(r.n)||t.set(r.n,r);let r=new Map;for(let t of e.webUrls)r.set((0,dx.normalizeCacheUrl)(t),t);return{byNumber:t,knownWebUrls:r}},[j])),tM=(0,ek.useMemo)(()=>new Map,[]),tO=(0,ek.useRef)(tu),tP=(0,ek.useRef)(0);(0,eP.useExternalSync)(()=>{if(L)return;let e=tO.current;if(tO.current=tu,"ready"!==tu||"streaming"!==e&&"submitted"!==e)return;let t=ta.current.at(-1);if(t?.role!=="assistant")return;let r=function(e){let t=new Map;for(let r of e.parts)if(hb(r))for(let e of r.output?.sources??[])e&&"number"==typeof e.n&&!t.has(e.n)&&t.set(e.n,e);return[...t.values()].sort((e,t)=>e.n-t.n)}(t);eh("local_chat_answer_completed",{sources_count:r.length,had_sources:r.length>0,answer_chars:pj(t).length,duration_ms:tP.current?Date.now()-tP.current:0})},[L,tu,eh]);let t$=(0,ek.useCallback)(()=>{tp(),tf(),tm([]),to(""),e1([]),e5(null),eK(null),eB(null),eq(!1),tn.current=0,e3(!1),eX.current=null,tb.current.clear(),tP.current=0},[tf,tm,tp,to]),tD=(0,ek.useCallback)(()=>{ti.current+=1,ew.current="new",t$(),$(T?d:void 0),U(void 0);let e=hp("thread");W(e),q(e),ex.current=!1},[t$,T,d,$]),tU=(0,ek.useCallback)(e=>{let t=ti.current+1;ti.current=t,ew.current=`saved:${e}`,t$(),$(void 0),U(void 0),W(null),q(e),ex.current=!0;let r=()=>{ti.current===t&&ey(!0)};p1?r():p5().then(r,r)},[t$,$]);(0,eP.useExternalLayoutSync)(()=>{l&&h&&l!==H&&(t$(),$(void 0),U(void 0),ew.current=`saved:${l}`,q(l),W(l),tm(h),ex.current=!0)},[l,h,H,t$,tm]);let tL=(0,ek.useRef)(et);(0,eP.useExternalLayoutSync)(()=>{X&&(tL.current&&tL.current!==et&&(tD(),$(void 0),U(void 0)),tL.current=et)},[X,et,tD]),(0,eP.useExternalSync)(()=>
75{if(L||!eA||!function({chatId:e,restoredChatId:t,status:r,messageCount:a}){return e!==dd.PENDING_THREAD_ID&&t===e&&"ready"===r&&a>0}({chatId:H,restoredChatId:V,status:tu,messageCount:tl.length}))return;let e=te.current.find(e=>e.id===H),t=function({messages:e,seededTitle:t,existingTitle:r}){let a=t?.trim()||r?.trim();if(a)return a;let n=e.find(e=>"user"===e.role);if(!n)return"New chat";let i=pj(n);if((0,dd.isReturnReadingPrompt)(i))return"What to read today";let s=n.parts.find(e=>"file"===e.type)?.filename;return i.slice(0,60)||s||"New chat"}({messages:tl,seededTitle:H===l?u:void 0,existingTitle:e?.title}),r=Date.now();eM({id:H,title:t,messages:tl,createdAt:e?.createdAt??r,updatedAt:r})},[L,T,tu,tl,H,V,l,u,te,eM,eA]),(0,eP.useExternalSync)(()=>{if(!L&&R&&F&&Z&&Z===hg((0,p0.remyChatRouteFromPathname)(window.location.pathname))&&ew.current!==Z){if("new"===F.kind){ex.current=!1;return}if(H===F.threadId){ew.current=Z;return}tU(F.threadId)}},[H,F,Z,L,R,tU]),(0,eP.useExternalSync)(()=>{if(L||!eA||!ez||!ev||V===H)return;let e=eR.find(e=>e.id===H);e&&0===e.messages.length||(U(e?.articleUrl?{articleUrl:e.articleUrl,articleTitle:e.articleTitle,articleDomain:e.articleDomain}:void 0),tm(e?e.messages:[]),W(H))},[eA,ez,eR,H,V,ev,L,T,tm]),(0,eP.useExternalSync)(()=>{let e=e8.current;if(!e)return;let t=()=>e6(Math.max(0,e.clientHeight-152));t();let r=new ResizeObserver(t);return r.observe(e),()=>r.disconnect()},[]),(0,eP.useExternalSync)(()=>{if(L||!R||!r)return;let e=e=>{if(tx||e.metaKey||e.ctrlKey||e.altKey||1!==e.key.length)return;let t=e.target;if(t&&(t.isContentEditable||"INPUT"===t.tagName||"TEXTAREA"===t.tagName||"SELECT"===t.tagName))return;let r=e7.current;r&&(e.preventDefault(),eU(t=>t+e.key),r.focus())};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[L,tx,R,r]);let tF=(0,ek.useCallback)((e,t,r)=>{if(L||!eA||V!==H)return!1;let a=(e??eD).trim(),n=t&&d&&e_?.articleUrl&&(0,dx.normalizeCacheUrl)(d.metadata.url)!==(0,dx.normalizeCacheUrl)(e_.articleUrl)?`${d.metadata.title}
76${d.metadata.url}`:eJ,i=n&&a&&!(e&&(0,dd.isSyntheticPrompt)(e))?`> ${n.replace(/\n/g,"\n> ")}
77
78${a}`:a;if(!i&&0===tj.length||tx||tC)return!1;!D&&e_&&U(e_);let s=H===hh?hp("thread"):H;if(s!==H&&(W(s),q(s)),H===l&&eF(!0),tr(s),eh(T?"chat_message_sent":"local_chat_message_sent",{message_length:i.length,total_threads:eR.length,is_new_thread:0===tl.length||void 0!==r,from_suggestion:void 0!==e,attachment_count:tj.length,...T?{question_source:t??eX.current}:{}}),tP.current=Date.now(),td(i?{text:i,files:tj,messageId:r}:{files:tj,messageId:r}),!ex.current&&R){let e;ex.current=!0;let t=`${hv()}/${s}`;ew.current=`saved:${s}`,window.history.replaceState(null,"",(e=new URLSearchParams(window.location.search).get("article"))?`${t}?article=${encodeURIComponent(e)}`:t),(0,p0.publishRemyChatPathname)(t)}return to(""),eK(null),e1([]),e5(null),hy(e7),!0},[H,V,e_,d,eD,L,tx,tC,T,R,tl.length,eJ,D,tj,td,l,tr,e7,eR.length,eA,eh,to]),tZ=(0,ek.useRef)(null),[tB,tH]=(0,ek.useState)(null);(0,eP.useExternalLayoutSync)(()=>{if(L||n||F?.kind==="saved")return;let e=i??new URLSearchParams(window.location.search).get("entry");if(!e||tZ.current===e)return;tZ.current=e;let t=(0,pz.consumeChatEntryTurn)(e);if(!t){if((0,pz.wasChatEntryConsumed)(e))return;cO.toast.error(em("entryRestoreFailed")),window.history.replaceState(null,"",hv()),(0,p0.publishRemyChatPathname)(hv());return}if((0,pz.peekPendingChatPrompt)()===t.prompt)return;let r=`message-${t.id}`;eu?.turn.id!==e&&tm([{id:r,role:"user",parts:[{type:"text",text:t.prompt}]}]),tH({messageId:r,prompt:t.prompt})},[F?.kind,n,eu,i,s,L,tm,tF,em]),(0,eP.useExternalSync)(()=>{tB&&X&&V===H&&(tm(e=>e.some(e=>e.id===tB.messageId)?e:[...e,{id:tB.messageId,role:"user",parts:[{type:"text",text:tB.prompt}]}]),tF(tB.prompt,void 0,tB.messageId)&&tH(null))},[tB,tF,X,V,H,tm]);let tq=(0,ek.useRef)(!1);(0,eP.useExternalSync)(()=>{if(L||!X||!eA||V!==H)return;if(tl.some(e=>"assistant"===e.role))return void(0,pz.clearPendingChatPrompt)();if(tq.current)return;let e=(0,pz.peekPendingChatPromptEntry)();if(!e||e.requiresSignIn&&!0!==ee)return;let t=tl.find(t=>"user"===t.role&&pj(t)===e.prompt);
78tF(e.prompt,void 0,t?.id)&&(tq.current=!0,(0,pz.clearPendingChatPrompt)())},[L,tl,tF,X,ee,eA,V,H]);let tV=(0,ek.useMemo)(()=>({chatId:H,addressable:!L&&!!H&&H!==hh}),[H,L]),tW=(0,ek.useRef)(!1),tG=(0,ek.useRef)(!1),[tY,tJ]=(0,ek.useState)("idle"),[tK,tQ]=(0,ek.useState)(!!s&&!L);(0,eP.useExternalSync)(()=>{if(!s||!o||L||!X||!0===ee||"idle"!==tY||tG.current||!ea.loaded||!ea.client?.signIn)return;tG.current=!0,tJ("redeeming");let e=ea.client.signIn;(async()=>{try{let t=await fetch(dd.CONFIGURE_SIGNIN_TICKET_PATH,{cache:"no-store",signal:AbortSignal.timeout(4e3)});if(204===t.status)throw Error("no ticket");if(200!==t.status)throw Error(`ticket route returned ${t.status}`);let r=await t.json(),a="object"==typeof r&&null!==r?r.ticket:void 0;if("string"!=typeof a||0===a.length)throw Error("ticket response was missing a ticket");let n=await e.create({strategy:"ticket",ticket:a});if("complete"!==n.status||!n.createdSessionId)throw Error(`ticket sign-in ended in status ${n.status??"unknown"}`);await ea.setActive({session:n.createdSessionId})}catch(e){(0,eN.reportClientError)("[configure-return] could not redeem the sign-in ticket",e)}finally{tJ("settled")}})()},[ea,ea.loaded,o,s,X,L,ee,tY]),(0,eP.useExternalSync)(()=>{if(!tK)return;if(X&&!0!==ee&&(!o||"settled"===tY))return void tQ(!1);let e=window.setTimeout(()=>{tQ(!1),(0,eN.reportClientError)("[configure-return] the return turn did not go out in time; the thread was released",Error(`auth loaded=${String(X)}`))},dd.CONFIGURE_RETURN_PENDING_LIMIT_MS);return()=>window.clearTimeout(e)},[tK,o,X,ee,tY]),(0,eP.useExternalSync)(()=>{if(!s||L||tW.current||!X||!eA||V!==H||o&&!0!==ee&&"settled"!==tY)return;tW.current=!0;let e=new URL(window.location.href);(e.searchParams.get(dd.CONFIGURE_RETURN_PARAM)===dd.CONFIGURE_RETURN_VALUE&&(e.searchParams.delete(dd.CONFIGURE_RETURN_PARAM),e.searchParams.delete(dd.CONFIGURE_GUEST_PARAM),window.history.replaceState(null,"",e.pathname+e.search),(0,p0.publishRemyChatPathname)(e.pathname)),!0!==ee||(0,dd.endsWithReturnReadingTurn)(tl))?tQ(!1):Promise.allSettled([er(),p4()]).then(()=>{tF(dd.RETURN_READING_PROMPT),tQ(!1)})},[o,s,L,X,ee,tY,eA,V,H,tl,tF,er]);let tX=(0,ek.useRef)(null);(0,eP.useExternalSync)(()=>{if(m&&tX.current!==m&&!n&&F?.kind!=="saved"){if("quote"===m.kind){eK(m.text),tX.current=m;return}if("draft"===m.kind){to(m.text,m.source),tX.current=m;return}tF(m.prompt,m.source??"article_launcher")&&(tX.current=m)}},[F?.kind,m,n,tF,to]);let t0=(0,ek.useCallback)(()=>{if(L)return void window.location.assign(hv());if(tD(),R){let e=hv();window.history.pushState(null,"",e),(0,p0.publishRemyChatPathname)(e)}hy(e7)},[L,R,tD,e7]);(0,eP.useExternalSync)(()=>{if(L)return;let e=()=>{t0(),$(void 0)};return window.addEventListener(p0.REMY_NEW_CHAT_EVENT,e),()=>window.removeEventListener(p0.REMY_NEW_CHAT_EVENT,e)},[L,t0,$]);let t1=(0,ek.useCallback)(()=>void th(),[th]),t2=(0,ek.useCallback)(e=>{!L&&!tx&&e.dataTransfer.types.includes("Files")&&(e.preventDefault(),tn.current+=1,e3(!0))},[L,tx]),t5=(0,ek.useCallback)(e=>{!L&&!tx&&e.dataTransfer.types.includes("Files")&&(e.preventDefault(),e.dataTransfer.dropEffect="copy")},[L,tx]),t4=(0,ek.useCallback)(e=>{L||e.dataTransfer.types.includes("Files")&&(tn.current=Math.max(0,tn.current-1),0===tn.current&&e3(!1))},[L]),t3=(0,ek.useCallback)(e=>{L||e.dataTransfer.files.length&&(e.preventDefault(),tn.current=0,e3(!1),tT(Array.from(e.dataTransfer.files)))},[tT,L]),t9=(0,ek.useCallback)(()=>tF(),[tF]),t6=(0,ek.useCallback)(e=>tF(e),[tF]),t8=(0,dh.useConfigureSignIn)(),{start:t7}=t8,re=(0,ek.useCallback)(()=>{t7((0,dd.connectReturnPathForThread)(tV,"/chat"),{signedIn:X?ee:void 0})},[X,ee,tV,t7]),rt=(0,db.useConfigureAvailability)({justLinked:!!s&&!L,reader:X&&(!o||"settled"===tY)?et??null:void 0}),rr=L||T||null===Z||F?.kind==="new"||F?.kind==="saved"&&F.threadId===H||ew.current===Z,ra=L?!ev:V!==H||F?.kind==="saved"&&!rr,rn=rr&&tl.length>0&&!ra,ri=H!==l||eL;(0,eP.useExternalLayoutSync)(()=>{if(ts.current||!ev||!rn||H!==l)return;let e=e8.current;if(!e)return;ts.current=!0,e.scrollTop=0;let t=window.requestAnimationFrame(()=>{e.scrollTop=0});return()=>window.cancelAnimationFrame(t)},[ev,H,rn,l]);let rs=eR.find(e=>e.id===H),ro=a?.title??rs?.title??(H===l?u:void 0)??"New chat",rl=e_?.articleUrl?(0,pU.getArticlePath)(e_.articleUrl,{sidebar:!0}):void 0,ru=e_?.articleUrl?{title:e_.articleTitle||em("untitledArticle"),siteName:e_.articleDomain??null,excerpt:Q?.text||em("openArticleReviewSource"),returnHref:rl}:f,rc=(0,es.useFeedSubscriptions)(),rd=eS.libraryEmpty&&rc.hasLoaded&&!rc.error&&0===rc.subscriptions.length,rp=Q?em("placeholderWeb",{kind:Q.kind}):a?.composerPlaceholder??em(ee&&!rd?"libraryPlaceholder":"researchPlaceholder"),rh=(0,ek.useCallback)(async()=>{try{let e=function({title:e,messages:t}){let r=e.replace(/\s+/g," ").trim()||"Chat with Remy",a=t.flatMap(e=>{let t=pj(e).trim();if(!t)return[];let r="user"===e.role?"You":"Remy";return[`## ${r}
79
80${t}`]});return[`# ${r.replace(/([\\`*_[\]<>#])/g,"\\$1")}`,...a].join("\n\n")+"\n"}({title:ro,messages:tl});await (0,pI.copyTextToClipboard)(e),cO.toast.success("Chat copied as Markdown"),eh("local_chat_export_
80copied",{format:"markdown",message_count:tl.length})}catch(e){(0,eN.reportClientError)("Failed to copy chat as Markdown:","Failed to copy chat as Markdown:",e),cO.toast.error("Couldn’t copy chat")}},[ro,tl,eh]),rm=(0,ek.useCallback)(async()=>{try{let t=function(e){for(let t=e.length-1;t>=0;t-=1){let r=e[t]?.metadata,a=r?.remy?.request?.systemPrompt;if("string"==typeof a&&a.length>0)return a}return null}(tl)??(await e.A(967328)).buildRemySystemPrompt({isSignedIn:!0===ee,customInstructions:pN()}),r=function({title:e,systemPrompt:t,messages:r,exportedAt:a=new Date}){return`${JSON.stringify({format:"smry-remy-chat",version:2,title:e.replace(/\s+/g," ").trim()||"Chat with Remy",exportedAt:a.toISOString(),systemPrompt:t,messages:r},null,2)}
81`}({title:ro,systemPrompt:t,messages:tl});await (0,pI.copyTextToClipboard)(r),cO.toast.success("Full conversation copied as JSON"),eh("local_chat_export_copied",{format:"json",message_count:tl.length})}catch(e){(0,eN.reportClientError)("Failed to copy chat as JSON:","Failed to copy chat as JSON:",e),cO.toast.error("Couldn’t copy chat")}},[ro,ee,tl,eh]),rf=tl.at(-1),rg=(0,ek.useCallback)(()=>{let e=[...tl].reverse().find(e=>"assistant"===e.role);e&&(0,pI.copyTextToClipboard)(pj(e))},[tl]),rv=(0,ek.useCallback)(()=>{tp(),tm([]),to(""),eK(null)},[tm,tp,to]);(0,ek.useImperativeHandle)(E,()=>({clearMessages:t0,focusInput:()=>e7.current?.focus(),stopGeneration:tp,copyLastResponse:rg,setQuotedText:eK,setDraftText:to,askQuestion:(e,t)=>tF(e,t)}),[t0,rg,tp,tF,to]);let ry=!!tc&&"error"===tu&&rf?.role!=="assistant",{showThread:rb,showStartSurface:rx,showPendingLoader:rw}={showThread:I=(C={hasMessages:rn,showStandaloneError:ry,isRestoringThread:ra,awaitingAnswer:tx&&rf?.role!=="assistant",configureReturnPending:tK}).hasMessages||C.showStandaloneError||C.configureReturnPending,showStartSurface:!I&&!C.isRestoringThread,showPendingLoader:C.awaitingAnswer||C.configureReturnPending};return(0,en.jsxs)(en.Fragment,{children:[(0,en.jsxs)("div",{className:"relative flex min-h-0 min-w-0 flex-1 overflow-hidden bg-background text-foreground",children:[(0,en.jsxs)("div",{"data-remy-ready":el&&(L||T||X&&eA)&&!ra?"true":"false","data-remy-presentation":t,"data-remy-status":tu,"data-remy-error":tc?"true":"false","data-remy-message-count":tl.length,onDragEnter:t2,onDragOver:t5,onDragLeave:t4,onDrop:t3,className:(0,eE.cn)("flex min-h-0 min-w-0 flex-1 flex-col bg-transparent text-foreground max-md:max-w-[100dvw] max-md:overflow-x-clip max-md:[-webkit-tap-highlight-color:transparent] max-md:[touch-action:pan-y_pinch-zoom]",eZ&&!T&&(eH?"hidden":"max-xl:hidden")),children:[(0,en.jsxs)("header",{"data-reader-chat-header":T?"":void 0,className:(0,eE.cn)("flex shrink-0 items-center gap-1 overflow-x-clip px-3",T?"h-11 bg-card lg:h-12":"h-11 bg-background/95 backdrop-blur-sm md:px-4",A&&"max-md:h-14 max-md:gap-0 max-md:px-2"),children:[A?(0,en.jsx)(hL,{onClose:T?w:void 0,onNewChat:t0,exportDisabled:!rn||tx,onCopyMarkdown:rh,onCopyJson:rm,onClear:rv}):null,(0,en.jsxs)("div",{className:(0,eE.cn)("flex w-full min-w-0 items-center gap-1",A&&"max-md:hidden"),children:[R?(0,en.jsx)(ei.RemyMenuSlot,{}):null,(0,en.jsx)("div",{className:"min-w-0 flex-1"}),!T&&eZ?(0,en.jsxs)(dC.Tooltip,{children:[(0,en.jsx)(dC.TooltipTrigger,{render:(0,en.jsx)(cq.Button,{type:"button",variant:"ghost",size:"icon-sm",onClick:()=>eq(!0),className:(0,eE.cn)(hn,"hidden xl:inline-flex"),"aria-label":em("hideConversation"),children:(0,en.jsx)(cU.ChevronsLeft,{className:hi,strokeWidth:2,"aria-hidden":"true"})})}),(0,en.jsx)(dC.TooltipContent,{children:em("hideConversation")})]}):null,(0,en.jsxs)(dC.Tooltip,{children:[(0,en.jsx)(dC.TooltipTrigger,{render:(0,en.jsx)(cq.Button,{type:"button",variant:"ghost",size:"icon-sm",onClick:t0,className:hn,"aria-label":em("newChat"),children:(0,en.jsx)(cU.Plus,{className:hi,strokeWidth:2,"aria-hidden":"true"})})}),(0,en.jsx)(dC.TooltipContent,{children:em("newChat")})]}),(0,en.jsx)(hU,{disabled:!rn||tx,onCopyMarkdown:rh,onCopyJson:rm,onClear:rv}),L?null:(0,en.jsxs)(dC.Tooltip,{children:[(0,en.jsx)(dC.TooltipTrigger,{render:(0,en.jsx)(cq.Button,{type:"button",variant:"ghost",size:"icon-sm",className:hn,"aria-label":R?em("collapseChat"):em("expandChat"),onClick:()=>R?S?.(rl):_?.(H===hh?void 0:H),children:R?(0,en.jsx)(cU.PanelRight,{"aria-hidden":"true",className:hi,strokeWidth:2}):(0,en.jsx)(cU.Maximize2,{"aria-hidden":"true",className:hi,strokeWidth:2})})}),(0,en.jsx)(dC.TooltipContent,{children:R?em("collapseChat"):em("expandChat")})]}),k?(0,en.jsxs)(dC.Tooltip,{children:[(0,en.jsx)(dC.TooltipTrigger,{render:(0,en.jsx)(cq.Button,{type:"button",variant:"ghost",size:"icon-sm",className:hn,"aria-label":em("dockChat"),onClick:k,children:(0,en.jsx)(cU.PanelRight,{"aria-hidden":"true",className:hi,strokeWidth:2})})}),(0,en.jsx)(dC.TooltipContent,{children:em("dockChat")})]}):null,T&&w?(0,en.jsxs)(dC.Tooltip,{children:[(0,en.jsx)(dC.TooltipTrigger,{render:(0,en.jsx)(cq.Button,{type:"button",variant:"ghost",size:"icon-sm",onClick:w,className:hn,"aria-label":em("closeSidebar"),children:(0,en.jsx)(cU.ChevronsRight,{className:(0,eE.cn)(hi,"rtl:rotate-180"),strokeWidth:2,"aria-hidden":"true"})})}),(0,en.jsx)(dC.TooltipContent,{children:em("closeSidebar")})]}):null]})]}),ru?(0,en.jsx)(cL,{...ru,articleVisible:T&&!0===N&&(0,dx.normalizeCacheUrl)(d?.metadata.url??p?.url??"")===(0,dx.normalizeCacheUrl)(e_?.articleUrl??"")}):null,T&&d&&Q&&(0,dx.normalizeCacheUrl)(d.metadata.url)!==(0,dx.normalizeCacheUrl)(Q.metadata.url)?(0,en.jsx)("div",{className:"border-b border-border px-4 py-2 text-sm text-muted-foreground",children:(0,en.jsx)(cq.Button,{variant:"ghost",size:"sm",onClick:()=>{eK(`${d.metadata.title}
82${d.metadata.url}`),e7.current?.focus()},children:em("addArticleToChat")})}):null,(0,en.jsxs)("div",{role:R?"main":"region","aria-label":R?void 0:"Conversation",tabIndex:-1,id:R?"main-content":void 0,className:"relative flex min-h-0 min-w-0 flex-1 flex-col overflow-x-clip max-md:[touch-action:pan-y_pinch-zoom]",children:[e4?(0,en.jsx)("div",{"aria-hidden":"true",className:"pointer-events-none absolute inset-3 z-50 flex items-center justify-center rounded-[14px] border border-dashed border-foreground
82/25 bg-background/92 text-sm font-medium text-foreground shadow-hairline backdrop-blur-sm",children:"Drop files to attach"}):null,rx?Q?(0,en.jsx)(hF,{contentItem:Q,highlights:y,signedIn:!0===ee,libraryEmpty:rd,onDraft:e=>{to(e),e7.current?.focus()}}):(0,en.jsx)(eC,{compact:T,signedIn:!0===ee,libraryEmpty:rd,onDraft:e=>{to(e),e7.current?.focus()}}):(0,en.jsx)(en.Fragment,{children:(0,en.jsxs)("div",{className:"relative min-h-0 min-w-0 flex-1 overflow-hidden",children:[(0,en.jsx)(pi,{autoScroll:ri,defaultScrollPosition:H===l?"start":"end",scrollMargin:16,scrollPreviousItemPeek:48,children:(0,en.jsxs)(ps,{children:[(0,en.jsx)(po,{"data-remy-scroll":"",ref:e8,className:"overflow-x-clip max-md:[touch-action:pan-y_pinch-zoom]",children:rb?(0,en.jsxs)(pl,{"aria-busy":tx,className:"mx-auto flex w-full max-w-[44.75rem] flex-col gap-8 overflow-x-clip px-4 py-6 sm:px-[1.125rem]",children:[g&&H===l?(0,en.jsx)("div",{"data-chat-conversation-prelude":!0,children:g}):null,(0,en.jsx)(dl.Provider,{value:tV,children:tl.map((e,t)=>{if("user"===e.role&&(0,dd.isReturnReadingPrompt)(pj(e)))return null;let r=t===tl.length-1,a=!r||"ready"===tu,n=t>0&&tl[t-1]?.role==="user"?pj(tl[t-1]):"",i="assistant"===e.role?pj(e):"",s="assistant"===e.role&&r&&tl.length>1;return(0,en.jsxs)(pu,{messageId:e.id,scrollAnchor:"user"===e.role&&(H!==l||0!==t),style:s?{minHeight:e9}:void 0,children:["user"===e.role?(0,en.jsx)(hM,{message:e}):(0,en.jsx)(hO,{message:e,request:n,byNumber:tA,libraryUrls:tM,knownWebUrls:tz,getResearchSourceSaveState:tS,onSaveResearchSource:tE,researchSourceSaveLabels:eb,isGenerating:r&&tx,isComplete:a,error:r&&"error"===tu,onRetry:t1,onContinueAfterSignIn:t6,onToolApproval:tv,onOpenPresentation:eG,disableActions:L,isLatest:r,contextArticleReferences:b,readerCitations:eg}),r&&"assistant"===e.role&&a&&"ready"===tu&&!L&&!ep&&n.trim()&&!(0,dd.isSyntheticPrompt)(n)&&i.trim()?(0,en.jsx)(p6,{enabled:!0,articleUrl:Q?.metadata.url,question:n,answer:i,turnKey:e.id,isPremium:ep}):null]},e.id)})}),rw?(0,en.jsx)(pu,{style:{minHeight:e9},children:(0,en.jsx)(h$,{})}):null,ry?(0,en.jsx)(pu,{style:{minHeight:e9},children:(0,en.jsx)(hD,{onRetry:t1})}):null]}):(0,en.jsx)("div",{"data-local-chat-entry-surface":!0,"aria-hidden":"true",className:"min-h-full w-full"})}),rn?(0,en.jsx)(pc,{}):null]})}),rn?(0,en.jsx)("div",{"aria-hidden":"true",className:"pointer-events-none absolute inset-x-0 bottom-0 h-5 bg-linear-to-t from-background to-transparent"}):null]})}),(0,en.jsx)(hB,{disabled:L,restoring:!eA||V!==H,input:eD,onInputChange:to,isStreaming:tx,files:e0,isPreparingFiles:tC,fileError:e2,isPremium:ep,modelSelection:eO,onAddFiles:tT,onModelChange:e$,onRemoveFile:tN,onRetryFile:tR,onSubmit:t9,onStop:tp,isDraggingFiles:e4,placeholder:rp,quotedText:eJ,onDismissQuote:eQ,presentation:t,textareaRef:e7,above:!1===rt.enabled||rt.linked||L?null:(0,en.jsx)(db.ConfigureConnectChip,{availability:rt,onPress:re,surface:"reader"===t?"reader":"chat"})})]})]}),eZ&&!T?(0,en.jsx)(pb,{item:eZ,width:eV,onWidthChange:eW,expanded:eH,onRestoreChat:()=>eq(!1),onClose:eY}):null]}
82),t8.leaving?(0,en.jsx)(dp.ConfigureHandoffCover,{label:"Taking you to Configure…"}):null]})}));e.s(["LocalArticleChatContent",0,function({demo:e,initialChatId:t,initialEntryId:r,initialConfigureReturn:a,initialConfigureGuest:n,articleEntryId:i}={}){let s=(0,ec.useTranslations)("chat"),[o,l]=(0,ek.useState)("/chat"),[u,c]=(0,ek.useState)(i?void 0:null),[d,p]=(0,ek.useState)(!1);if((0,eP.useExternalSync)(()=>{if(p(!1),!i)return void c(null);let e=!1;return c(void 0),(0,pM.restoreArticleChatEntry)(i).then(t=>{e||c(t)}),()=>{e=!0}},[i]),(0,eP.useExternalLayoutSync)(()=>{let e=()=>l(window.location.pathname),t=e=>{let t=e.detail?.pathname;"string"==typeof t&&l(t)};return e(),window.addEventListener("popstate",e),window.addEventListener(p0.REMY_CHAT_PATHNAME_EVENT,t),()=>{window.removeEventListener("popstate",e),window.removeEventListener(p0.REMY_CHAT_PATHNAME_EVENT,t)}},[]),i&&void 0===u)return(0,en.jsx)(c$.LocalArticleChatLoadingContent,{});if(i&&null===u&&!d)return(0,en.jsxs)("div",{className:"flex min-h-0 min-w-0 flex-1 flex-col bg-background text-foreground",children:[(0,en.jsx)("header",{className:"flex h-11 shrink-0 items-center gap-1.5 px-3",children:(0,en.jsx)(cP.AppMenuButton,{surface:"chat"})}),(0,en.jsx)("main",{className:"grid min-h-0 flex-1 place-items-center px-4 py-8",id:"main-content",children:(0,en.jsxs)("section",{className:"w-full max-w-sm rounded-[14px] bg-card p-5 text-center shadow-hairline",children:[(0,en.jsxs)("div",{role:"status","aria-atomic":"true",children:[(0,en.jsx)("h1",{className:"text-base font-medium",children:s("returnToArticleTitle")}),(0,en.jsx)("p",{className:"mt-2 text-sm leading-6 text-muted-foreground",children:s("articleContextUnavailable")})]}),(0,en.jsxs)("div",{className:"mt-5 flex flex-col gap-2",children:[(0,en.jsx)(cq.Button,{variant:"outline",type:"button",onClick:()=>window.history.back(),children:s("backToArticle")}),(0,en.jsx)(cq.Button,{type:"button",variant:"ghost",onClick:()=>{p(!0),window.history.replaceState(null,"",o)},children:s("continueWithoutArticle")})]})]})})]});let h=u?.contentItem,m=e?hH:el.RemyView;return(0,en.jsx)(m,{presentation:"page",demo:e,initialChatId:t,initialEntryId:r,initialConfigureReturn:a,initialConfigureGuest:n,chatPathname:o,contentItem:h,initialAction:t?void 0:u?.action,articleReferences:u?.articleReferences,sourceContext:u&&h?{title:h.metadata.title||s("untitledArticle"),siteName:h.metadata.siteName,excerpt:h.text||s("openArticleReviewSource"),returnHref:u.returnHref}:void 0})},"RemyChatContent",0,hH],50582)},99970,(e,t,r)=>{"use strict";var a=Object.defineProperty,n=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,s=Object.prototype.hasOwnProperty,o={},l={SYMBOL_FOR_REQ_CONTEXT:()=>c,getContext:()=>d};for(var u in l)a(o,u,{get:l[u],enumerable:!0});t.exports=((e,t,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let o of i(t))s.call(e,o)||void 0===o||a(e,o,{get:()=>t[o],enumerable:!(r=n(t,o))||r.enumerable});return e})(a({},"__esModule",{value:!0}),o);let c=Symbol.for("@vercel/request-context");function d(){let e=globalThis;return e[c]?.get?.()??{}}},891754,(e,t,r)=>{"use strict";var a=Object.defineProperty,n=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,s=Object.prototype.hasOwnProperty,o={},l={AccessTokenMissingError:()=>c,RefreshAccessTokenFailedError:()=>d};for(var u in l)a(o,u,{get:l[u],enumerable:!0});t.exports=((e,t,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let o of i(t))s.call(e,o)||void 0===o||a(e,o,{get:()=>t[o],enumerable:!(r=n(t,o))||r.enumerable});return e})(a({},"__esModule",{value:!0}),o);class c extends Error{constructor(){super("No authentication found. Please log in with the Vercel CLI (vercel login)."),this.name="AccessTokenMissingError"}}class d extends Error{constructor(e){super("Failed to refresh authentication token.",{cause:e}),this.name="RefreshAccessTokenFailedError"}}},725150,(e,t,r)=>{"use strict";var a=Object.defineProperty,n=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,s=Object.prototype.hasOwnProperty,o={},l={AccessTokenMissingError:()=>d.AccessTokenMissingError,RefreshAccessTokenFailedError:()=>d.RefreshAccessTokenFailedError,getContext:()=>c.getContext,getVercelOidcToken:()=>p,getVercelOidcTokenSync:()=>h,getVercelToken:()=>m};for(var u in l)a(o,u,{get:l[u],enumerable:!0});t.exports=((e,t,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let o of i(t))s.call(e,o)||void 0===o||a(e,o,{get:()=>t[o],enumerable:!(r=n(t,o))||r.enumerable});return e})(a({},"__esModule",{value:!0}),o);var c=e.r(99970),d=e.r(891754);async function p(){return""}function h(){return""}async function m(){throw Error("getVercelToken is not supported in browser environments")}},561866,(e,t,r)=>{t.exports=function(e,t){let r;if("function"!=typeof e)throw TypeError(`Expected the first argument to be a \`function\`, got \`${typeof e}\`.`);let a=0;return function(...n){clearTimeout(r);let i=Date.now(),s=t-(i-a);s<=0?(a=i,e.apply(this,n)):r=setTimeout(()=>{a=Date.now(),e.apply(this,n)},s)}}}]);
83
84//# chunkId=7cee1efb-ca00-5f7e-b3c2-b8354ddc8b36

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.