@waniwani/sdk 0.22.0-beta.1 → 0.22.0-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chat/embed.js +1 -1
- package/dist/chat/index.js +12 -12
- package/dist/chat/index.js.map +1 -1
- package/package.json +3 -3
package/dist/chat/embed.js
CHANGED
|
@@ -118,7 +118,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let n="<p>An error
|
|
|
118
118
|
`)},xx=e=>{let t=!1;for(let n of e)if(n==="\\"||n==="|"){t=!0;break}if(!t)return e;let a=[];for(let n of e)n==="\\"?a.push("\\\\"):n==="|"?a.push("\\|"):a.push(n);return a.join("")},w6=e=>{let{headers:t,rows:a}=e;if(t.length===0)return"";let n=new Array(a.length+2),r=0,o=t.map(l=>xx(l));n[r]=`| ${o.join(" | ")} |`,r+=1;let i=new Array(t.length);for(let l=0;l<t.length;l+=1)i[l]="---";n[r]=`| ${i.join(" | ")} |`,r+=1;for(let l of a)if(l.length<t.length){let s=new Array(t.length);for(let u=0;u<t.length;u+=1)s[u]=u<l.length?xx(l[u]):"";n[r]=`| ${s.join(" | ")} |`,r+=1}else{let s=l.map(u=>xx(u));n[r]=`| ${s.join(" | ")} |`,r+=1}return n.join(`
|
|
119
119
|
`)},y6=({children:e,className:t,onCopy:a,onError:n,timeout:r=2e3})=>{let[o,i]=(0,_.useState)(!1),[l,s]=(0,_.useState)(!1),u=(0,_.useRef)(null),c=(0,_.useRef)(0),{isAnimating:d}=(0,_.useContext)(ya),f=async m=>{var x,S;if(typeof window>"u"||!((x=navigator?.clipboard)!=null&&x.write)){n?.(new Error("Clipboard API not available"));return}try{let w=(S=u.current)==null?void 0:S.closest('[data-streamdown="table-wrapper"]'),y=w?.querySelector("table");if(!y){n?.(new Error("Table not found"));return}let h=RR(y),b=m==="csv"?DR(h):g6(h),T=new ClipboardItem({"text/plain":new Blob([b],{type:"text/plain"}),"text/html":new Blob([y.outerHTML],{type:"text/html"})});await navigator.clipboard.write([T]),s(!0),i(!1),a?.(m),c.current=window.setTimeout(()=>s(!1),r)}catch(w){n?.(w)}};(0,_.useEffect)(()=>{let m=x=>{let S=x.composedPath();u.current&&!S.includes(u.current)&&i(!1)};return document.addEventListener("mousedown",m),()=>{document.removeEventListener("mousedown",m),window.clearTimeout(c.current)}},[]);let p=l?Cx:kx;return(0,E.jsxs)("div",{className:"relative",ref:u,children:[(0,E.jsx)("button",{className:ce("cursor-pointer p-1 text-muted-foreground transition-all hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50",t),disabled:d,onClick:()=>i(!o),title:"Copy table",type:"button",children:e??(0,E.jsx)(p,{size:14})}),o?(0,E.jsxs)("div",{className:"absolute top-full right-0 z-10 mt-1 min-w-[120px] overflow-hidden rounded-md border border-border bg-background shadow-lg",children:[(0,E.jsx)("button",{className:"w-full px-3 py-2 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>f("csv"),title:"Copy table as CSV",type:"button",children:"CSV"}),(0,E.jsx)("button",{className:"w-full px-3 py-2 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>f("tsv"),title:"Copy table as TSV",type:"button",children:"TSV"})]}):null]})},x6=({children:e,className:t,onDownload:a,onError:n})=>{let[r,o]=(0,_.useState)(!1),i=(0,_.useRef)(null),{isAnimating:l}=(0,_.useContext)(ya),s=u=>{var c;try{let d=(c=i.current)==null?void 0:c.closest('[data-streamdown="table-wrapper"]'),f=d?.querySelector("table");if(!f){n?.(new Error("Table not found"));return}let p=RR(f),m=u==="csv"?DR(p):w6(p);Tl(`table.${u==="csv"?"csv":"md"}`,m,u==="csv"?"text/csv":"text/markdown"),o(!1),a?.(u)}catch(d){n?.(d)}};return(0,_.useEffect)(()=>{let u=c=>{let d=c.composedPath();i.current&&!d.includes(i.current)&&o(!1)};return document.addEventListener("mousedown",u),()=>{document.removeEventListener("mousedown",u)}},[]),(0,E.jsxs)("div",{className:"relative",ref:i,children:[(0,E.jsx)("button",{className:ce("cursor-pointer p-1 text-muted-foreground transition-all hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50",t),disabled:l,onClick:()=>o(!r),title:"Download table",type:"button",children:e??(0,E.jsx)(pp,{size:14})}),r?(0,E.jsxs)("div",{className:"absolute top-full right-0 z-10 mt-1 min-w-[120px] overflow-hidden rounded-md border border-border bg-background shadow-lg",children:[(0,E.jsx)("button",{className:"w-full px-3 py-2 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>s("csv"),title:"Download table as CSV",type:"button",children:"CSV"}),(0,E.jsx)("button",{className:"w-full px-3 py-2 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>s("markdown"),title:"Download table as Markdown",type:"button",children:"Markdown"})]}):null]})},v6=({children:e,className:t,showControls:a,...n})=>(0,E.jsxs)("div",{className:"my-4 flex flex-col space-y-2","data-streamdown":"table-wrapper",children:[a?(0,E.jsxs)("div",{className:"flex items-center justify-end gap-1",children:[(0,E.jsx)(y6,{}),(0,E.jsx)(x6,{})]}):null,(0,E.jsx)("div",{className:"overflow-x-auto",children:(0,E.jsx)("table",{className:ce("w-full border-collapse border border-border",t),"data-streamdown":"table",...n,children:e})})]}),b6=(0,_.lazy)(()=>Promise.resolve().then(()=>(wR(),gR)).then(e=>({default:e.CodeBlock}))),S6=(0,_.lazy)(()=>Promise.resolve().then(()=>(vR(),xR)).then(e=>({default:e.Mermaid}))),I6=/language-([^\s]+)/;Ix=(e,t)=>typeof e=="boolean"?e:e[t]!==!1,dp=(e,t)=>{if(typeof e=="boolean")return e;let a=e.mermaid;return a===!1?!1:a===!0||a===void 0?!0:a[t]!==!1},Lx=(0,_.memo)(({children:e,className:t,node:a,...n})=>(0,E.jsx)("ol",{className:ce("list-inside list-decimal whitespace-normal [li_&]:pl-6",t),"data-streamdown":"ordered-list",...n,children:e}),(e,t)=>Lt(e,t));Lx.displayName="MarkdownOl";_R=(0,_.memo)(({children:e,className:t,node:a,...n})=>(0,E.jsx)("li",{className:ce("py-1 [&>p]:inline",t),"data-streamdown":"list-item",...n,children:e}),(e,t)=>e.className===t.className&&mp(e.node,t.node));_R.displayName="MarkdownLi";OR=(0,_.memo)(({children:e,className:t,node:a,...n})=>(0,E.jsx)("ul",{className:ce("list-inside list-disc whitespace-normal [li_&]:pl-6",t),"data-streamdown":"unordered-list",...n,children:e}),(e,t)=>Lt(e,t));OR.displayName="MarkdownUl";PR=(0,_.memo)(({className:e,node:t,...a})=>(0,E.jsx)("hr",{className:ce("my-6 border-border",e),"data-streamdown":"horizontal-rule",...a}),(e,t)=>Lt(e,t));PR.displayName="MarkdownHr";NR=(0,_.memo)(({children:e,className:t,node:a,...n})=>(0,E.jsx)("span",{className:ce("font-semibold",t),"data-streamdown":"strong",...n,children:e}),(e,t)=>Lt(e,t));NR.displayName="MarkdownStrong";C6=({children:e,className:t,href:a,node:n,...r})=>{let{linkSafety:o}=(0,_.useContext)(ya),[i,l]=(0,_.useState)(!1),s=a==="streamdown:incomplete-link",u=(0,_.useCallback)(async p=>{if(!(!(o!=null&&o.enabled&&a)||s)){if(p.preventDefault(),o.onLinkCheck&&await o.onLinkCheck(a)){window.open(a,"_blank","noreferrer");return}l(!0)}},[o,a,s]),c=(0,_.useCallback)(()=>{a&&window.open(a,"_blank","noreferrer")},[a]),d=(0,_.useCallback)(()=>{l(!1)},[]),f={url:a??"",isOpen:i,onClose:d,onConfirm:c};return o!=null&&o.enabled&&a?(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)("button",{className:ce("wrap-anywhere appearance-none text-left font-medium text-primary underline",t),"data-incomplete":s,"data-streamdown":"link",onClick:u,type:"button",children:e}),o.renderModal?o.renderModal(f):(0,E.jsx)(c6,{...f})]}):(0,E.jsx)("a",{className:ce("wrap-anywhere font-medium text-primary underline",t),"data-incomplete":s,"data-streamdown":"link",href:a,rel:"noreferrer",target:"_blank",...r,children:e})},BR=(0,_.memo)(C6,(e,t)=>Lt(e,t)&&e.href===t.href);BR.displayName="MarkdownA";UR=(0,_.memo)(({children:e,className:t,node:a,...n})=>(0,E.jsx)("h1",{className:ce("mt-6 mb-2 font-semibold text-3xl",t),"data-streamdown":"heading-1",...n,children:e}),(e,t)=>Lt(e,t));UR.displayName="MarkdownH1";FR=(0,_.memo)(({children:e,className:t,node:a,...n})=>(0,E.jsx)("h2",{className:ce("mt-6 mb-2 font-semibold text-2xl",t),"data-streamdown":"heading-2",...n,children:e}),(e,t)=>Lt(e,t));FR.displayName="MarkdownH2";zR=(0,_.memo)(({children:e,className:t,node:a,...n})=>(0,E.jsx)("h3",{className:ce("mt-6 mb-2 font-semibold text-xl",t),"data-streamdown":"heading-3",...n,children:e}),(e,t)=>Lt(e,t));zR.displayName="MarkdownH3";qR=(0,_.memo)(({children:e,className:t,node:a,...n})=>(0,E.jsx)("h4",{className:ce("mt-6 mb-2 font-semibold text-lg",t),"data-streamdown":"heading-4",...n,children:e}),(e,t)=>Lt(e,t));qR.displayName="MarkdownH4";HR=(0,_.memo)(({children:e,className:t,node:a,...n})=>(0,E.jsx)("h5",{className:ce("mt-6 mb-2 font-semibold text-base",t),"data-streamdown":"heading-5",...n,children:e}),(e,t)=>Lt(e,t));HR.displayName="MarkdownH5";jR=(0,_.memo)(({children:e,className:t,node:a,...n})=>(0,E.jsx)("h6",{className:ce("mt-6 mb-2 font-semibold text-sm",t),"data-streamdown":"heading-6",...n,children:e}),(e,t)=>Lt(e,t));jR.displayName="MarkdownH6";VR=(0,_.memo)(({children:e,className:t,node:a,...n})=>{let{controls:r}=(0,_.useContext)(ya),o=Ix(r,"table");return(0,E.jsx)(v6,{className:t,showControls:o,...n,children:e})},(e,t)=>Lt(e,t));VR.displayName="MarkdownTable";WR=(0,_.memo)(({children:e,className:t,node:a,...n})=>(0,E.jsx)("thead",{className:ce("bg-muted/80",t),"data-streamdown":"table-header",...n,children:e}),(e,t)=>Lt(e,t));WR.displayName="MarkdownThead";GR=(0,_.memo)(({children:e,className:t,node:a,...n})=>(0,E.jsx)("tbody",{className:ce("divide-y divide-border bg-muted/40",t),"data-streamdown":"table-body",...n,children:e}),(e,t)=>Lt(e,t));GR.displayName="MarkdownTbody";$R=(0,_.memo)(({children:e,className:t,node:a,...n})=>(0,E.jsx)("tr",{className:ce("border-border border-b",t),"data-streamdown":"table-row",...n,children:e}),(e,t)=>Lt(e,t));$R.displayName="MarkdownTr";XR=(0,_.memo)(({children:e,className:t,node:a,...n})=>(0,E.jsx)("th",{className:ce("whitespace-nowrap px-4 py-2 text-left font-semibold text-sm",t),"data-streamdown":"table-header-cell",...n,children:e}),(e,t)=>Lt(e,t));XR.displayName="MarkdownTh";KR=(0,_.memo)(({children:e,className:t,node:a,...n})=>(0,E.jsx)("td",{className:ce("px-4 py-2 text-sm",t),"data-streamdown":"table-cell",...n,children:e}),(e,t)=>Lt(e,t));KR.displayName="MarkdownTd";YR=(0,_.memo)(({children:e,className:t,node:a,...n})=>(0,E.jsx)("blockquote",{className:ce("my-4 border-muted-foreground/30 border-l-4 pl-4 text-muted-foreground italic",t),"data-streamdown":"blockquote",...n,children:e}),(e,t)=>Lt(e,t));YR.displayName="MarkdownBlockquote";ZR=(0,_.memo)(({children:e,className:t,node:a,...n})=>(0,E.jsx)("sup",{className:ce("text-sm",t),"data-streamdown":"superscript",...n,children:e}),(e,t)=>Lt(e,t));ZR.displayName="MarkdownSup";QR=(0,_.memo)(({children:e,className:t,node:a,...n})=>(0,E.jsx)("sub",{className:ce("text-sm",t),"data-streamdown":"subscript",...n,children:e}),(e,t)=>Lt(e,t));QR.displayName="MarkdownSub";JR=(0,_.memo)(({children:e,className:t,node:a,...n})=>{if("data-footnotes"in n){let r=i=>{var l,s;if(!(0,_.isValidElement)(i))return!1;let u=Array.isArray(i.props.children)?i.props.children:[i.props.children],c=!1,d=!1;for(let f of u)if(f){if(typeof f=="string")f.trim()!==""&&(c=!0);else if((0,_.isValidElement)(f))if(((l=f.props)==null?void 0:l["data-footnote-backref"])!==void 0)d=!0;else{let p=Array.isArray(f.props.children)?f.props.children:[f.props.children];for(let m of p){if(typeof m=="string"&&m.trim()!==""){c=!0;break}if((0,_.isValidElement)(m)&&((s=m.props)==null?void 0:s["data-footnote-backref"])===void 0){c=!0;break}}}}return d&&!c},o=Array.isArray(e)?e.map(i=>{if(!(0,_.isValidElement)(i))return i;if(i.type===Lx){let l=(Array.isArray(i.props.children)?i.props.children:[i.props.children]).filter(s=>!r(s));return l.length===0?null:{...i,props:{...i.props,children:l}}}return i}):e;return(Array.isArray(o)?o.some(i=>i!==null):o!==null)?(0,E.jsx)("section",{className:t,...n,children:o}):null}return(0,E.jsx)("section",{className:t,...n,children:e})},(e,t)=>Lt(e,t));JR.displayName="MarkdownSection";k6=({node:e,className:t,children:a,...n})=>{var r,o,i;let l=((r=e?.position)==null?void 0:r.start.line)===((o=e?.position)==null?void 0:o.end.line),{mermaid:s,controls:u}=(0,_.useContext)(ya),c=Tx();if(l)return(0,E.jsx)("code",{className:ce("rounded bg-muted px-1.5 py-0.5 font-mono text-sm",t),"data-streamdown":"inline-code",...n,children:a});let d=t?.match(I6),f=(i=d?.at(1))!=null?i:"",p="";if((0,_.isValidElement)(a)&&a.props&&typeof a.props=="object"&&"children"in a.props&&typeof a.props.children=="string"?p=a.props.children:typeof a=="string"&&(p=a),f==="mermaid"&&c){let x=Ix(u,"mermaid"),S=dp(u,"download"),w=dp(u,"copy"),y=dp(u,"fullscreen"),h=dp(u,"panZoom"),b=x&&(S||w||y);return(0,E.jsx)(_.Suspense,{fallback:(0,E.jsx)(CR,{}),children:(0,E.jsxs)("div",{className:ce("group relative my-4 h-auto rounded-xl border p-4",t),"data-streamdown":"mermaid-block",children:[b?(0,E.jsxs)("div",{className:"flex items-center justify-end gap-2",children:[S?(0,E.jsx)(f6,{chart:p,config:s?.config}):null,w?(0,E.jsx)(SR,{code:p}):null,y?(0,E.jsx)(h6,{chart:p,config:s?.config}):null]}):null,(0,E.jsx)(S6,{chart:p,config:s?.config,showControls:h})]})})}let m=Ix(u,"code");return(0,E.jsx)(_.Suspense,{fallback:(0,E.jsx)(CR,{}),children:(0,E.jsx)(b6,{className:ce("overflow-x-auto border-border border-t",t),code:p,language:f,children:m?(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(o6,{code:p,language:f}),(0,E.jsx)(SR,{})]}):null})})},e2=(0,_.memo)(k6,(e,t)=>e.className===t.className&&mp(e.node,t.node));e2.displayName="MarkdownCode";t2=(0,_.memo)(l6,(e,t)=>e.className===t.className&&mp(e.node,t.node));t2.displayName="MarkdownImg";a2=(0,_.memo)(({children:e,className:t,node:a,...n})=>{var r,o;let i=(Array.isArray(e)?e:[e]).filter(l=>l!=null&&l!=="");if(i.length===1&&(0,_.isValidElement)(i[0])){let l=i[0].props.node,s=l?.tagName;if(s==="img")return(0,E.jsx)(E.Fragment,{children:e});if(s==="code"&&((r=l?.position)==null?void 0:r.start.line)!==((o=l?.position)==null?void 0:o.end.line))return(0,E.jsx)(E.Fragment,{children:e})}return(0,E.jsx)("p",{className:t,...n,children:e})},(e,t)=>Lt(e,t));a2.displayName="MarkdownParagraph";T6={ol:Lx,li:_R,ul:OR,hr:PR,strong:NR,a:BR,h1:UR,h2:FR,h3:zR,h4:qR,h5:HR,h6:jR,table:VR,thead:WR,tbody:GR,tr:$R,th:XR,td:KR,blockquote:YR,code:e2,img:t2,pre:({children:e})=>e,sup:ZR,sub:QR,p:a2,section:JR},kR=[],TR={allowDangerousHtml:!0},fp=new WeakMap,L6=class{constructor(){this.cache=new Map,this.keyCache=new WeakMap,this.maxSize=100}generateCacheKey(e){let t=this.keyCache.get(e);if(t)return t;let a=e.rehypePlugins,n=e.remarkPlugins,r=e.remarkRehypeOptions;if(!(a||n||r)){let c="default";return this.keyCache.set(e,c),c}let o=c=>{if(!c||c.length===0)return"";let d="";for(let f=0;f<c.length;f+=1){let p=c[f];if(f>0&&(d+=","),Array.isArray(p)){let[m,x]=p;if(typeof m=="function"){let S=fp.get(m);S||(S=m.name,fp.set(m,S)),d+=S}else d+=String(m);d+=":",d+=JSON.stringify(x)}else if(typeof p=="function"){let m=fp.get(p);m||(m=p.name,fp.set(p,m)),d+=m}else d+=String(p)}return d},i=o(a),l=o(n),s=r?JSON.stringify(r):"",u=`${l}::${i}::${s}`;return this.keyCache.set(e,u),u}get(e){let t=this.generateCacheKey(e),a=this.cache.get(t);return a&&(this.cache.delete(t),this.cache.set(t,a)),a}set(e,t){let a=this.generateCacheKey(e);if(this.cache.size>=this.maxSize){let n=this.cache.keys().next().value;n&&this.cache.delete(n)}this.cache.set(a,t)}clear(){this.cache.clear()}},LR=new L6,n2=e=>{let t=E6(e),a=e.children||"";return A6(t.runSync(t.parse(a),a),e)},E6=e=>{let t=LR.get(e);if(t)return t;let a=M6(e);return LR.set(e,a),a},M6=e=>{let t=e.rehypePlugins||kR,a=e.remarkPlugins||kR,n=e.remarkRehypeOptions?{...TR,...e.remarkRehypeOptions}:TR;return rx().use(Kf).use(a).use(Jf,n).use(t)},A6=(e,t)=>By(e,{Fragment:E.Fragment,components:t.components,ignoreInvalidStyle:!0,jsx:E.jsx,jsxs:E.jsxs,passKeys:!0,passNode:!0}),R6=/\[\^[^\]\s]{1,200}\](?!:)/,D6=/\[\^[^\]\s]{1,200}\]:/,_6=/<\/(\w+)>/,O6=/<(\w+)[\s>]/,vx=e=>{let t=0;for(;t<e.length&&(e[t]===" "||e[t]===" "||e[t]===`
|
|
120
120
|
`||e[t]==="\r");)t+=1;return t+1<e.length&&e[t]==="$"&&e[t+1]==="$"},P6=e=>{let t=e.length-1;for(;t>=0&&(e[t]===" "||e[t]===" "||e[t]===`
|
|
121
|
-
`||e[t]==="\r");)t-=1;return t>=1&&e[t]==="$"&&e[t-1]==="$"},bx=e=>{let t=0;for(let a=0;a<e.length-1;a+=1)e[a]==="$"&&e[a+1]==="$"&&(t+=1,a+=1);return t},r2=e=>{let t=R6.test(e),a=D6.test(e);if(t||a)return[e];let n=Xa.lex(e,{gfm:!0}),r=[],o=[];for(let i of n){let l=i.raw,s=r.length;if(o.length>0){if(r[s-1]+=l,i.type==="html"){let u=l.match(_6);if(u){let c=u[1];o.at(-1)===c&&o.pop()}}continue}if(i.type==="html"&&i.block){let u=l.match(O6);if(u){let c=u[1];l.includes(`</${c}>`)||o.push(c)}}if(l.trim()==="$$"&&s>0){let u=r[s-1],c=vx(u),d=bx(u);if(c&&d%2===1){r[s-1]=u+l;continue}}if(s>0&&P6(l)){let u=r[s-1],c=vx(u),d=bx(u),f=bx(l);if(c&&d%2===1&&!vx(l)&&f===1){r[s-1]=u+l;continue}}r.push(l)}return r},o2={raw:Uk,sanitize:[hf,{}],harden:[Nk,{allowedImagePrefixes:["*"],allowedLinkPrefixes:["*"],allowedProtocols:["*"],defaultOrigin:void 0,allowDataImages:!0}]},i2={gfm:[zf,{}]},N6=Object.values(o2),B6=Object.values(i2),U6={block:" \u258B",circle:" \u25CF"},F6={shikiTheme:["github-light","github-dark"],controls:!0,isAnimating:!1,mode:"streaming",mermaid:void 0,linkSafety:{enabled:!0}},ya=(0,_.createContext)(F6),Ex=(0,_.memo)(({content:e,shouldParseIncompleteMarkdown:t,index:a,...n})=>(0,E.jsx)(n2,{...n,children:e}),(e,t)=>{if(e.content!==t.content||e.index!==t.index)return!1;if(e.components!==t.components){let a=Object.keys(e.components||{}),n=Object.keys(t.components||{});if(a.length!==n.length||a.some(r=>{var o,i;return((o=e.components)==null?void 0:o[r])!==((i=t.components)==null?void 0:i[r])}))return!1}return!(e.rehypePlugins!==t.rehypePlugins||e.remarkPlugins!==t.remarkPlugins)});Ex.displayName="Block";z6=["github-light","github-dark"],Ll=(0,_.memo)(({children:e,mode:t="streaming",parseIncompleteMarkdown:a=!0,components:n,rehypePlugins:r=N6,remarkPlugins:o=B6,className:i,shikiTheme:l=z6,mermaid:s,controls:u=!0,isAnimating:c=!1,BlockComponent:d=Ex,parseMarkdownIntoBlocksFn:f=r2,caret:p,plugins:m,remend:x,linkSafety:S={enabled:!0},...w})=>{let y=(0,_.useId)(),[h,b]=(0,_.useTransition)(),T=(0,_.useMemo)(()=>typeof e!="string"?"":t==="streaming"&&a?YL(e,x):e,[e,t,a,x]),C=(0,_.useMemo)(()=>f(T),[T,f]),[M,R]=(0,_.useState)(C);(0,_.useEffect)(()=>{t==="streaming"?b(()=>{R(C)}):R(C)},[C,t]);let P=t==="streaming"?M:C,L=(0,_.useMemo)(()=>P.map((N,D)=>`${y}-${D}`),[P.length,y]),$=(0,_.useMemo)(()=>{var N,D;return{shikiTheme:(D=(N=m?.code)==null?void 0:N.getThemes())!=null?D:l,controls:u,isAnimating:c,mode:t,mermaid:s,linkSafety:S}},[l,u,c,t,s,S,m?.code]),H=(0,_.useMemo)(()=>({...T6,...n}),[n]),F=(0,_.useMemo)(()=>{let N=[];return m!=null&&m.cjk&&(N=[...N,...m.cjk.remarkPluginsBefore]),N=[...N,...o],m!=null&&m.cjk&&(N=[...N,...m.cjk.remarkPluginsAfter]),m!=null&&m.math&&(N=[...N,m.math.remarkPlugin]),N},[o,m?.math,m?.cjk]),W=(0,_.useMemo)(()=>m!=null&&m.math?[...r,m.math.rehypePlugin]:r,[r,m?.math]),V=(0,_.useMemo)(()=>p&&c?{"--streamdown-caret":`"${U6[p]}"`}:void 0,[p,c]);return t==="static"?(0,E.jsx)(Sx.Provider,{value:m??null,children:(0,E.jsx)(ya.Provider,{value:$,children:(0,E.jsx)("div",{className:ce("space-y-4 whitespace-normal *:first:mt-0 *:last:mb-0",i),children:(0,E.jsx)(n2,{components:H,rehypePlugins:W,remarkPlugins:F,...w,children:e})})})}):(0,E.jsx)(Sx.Provider,{value:m??null,children:(0,E.jsx)(ya.Provider,{value:$,children:(0,E.jsxs)("div",{className:ce("space-y-4 whitespace-normal *:first:mt-0 *:last:mb-0",p?"*:last:after:inline *:last:after:align-baseline *:last:after:content-(--streamdown-caret)":null,i),style:V,children:[P.length===0&&p&&c&&(0,E.jsx)("span",{}),P.map((N,D)=>(0,E.jsx)(d,{components:H,content:N,index:D,rehypePlugins:W,remarkPlugins:F,shouldParseIncompleteMarkdown:a,...w},L[D]))]})})})},(e,t)=>e.children===t.children&&e.shikiTheme===t.shikiTheme&&e.isAnimating===t.isAnimating&&e.mode===t.mode&&e.plugins===t.plugins&&e.className===t.className&&e.linkSafety===t.linkSafety);Ll.displayName="Streamdown";q6=({children:e,className:t,minZoom:a=.5,maxZoom:n=3,zoomStep:r=.1,showControls:o=!0,initialZoom:i=1,fullscreen:l=!1})=>{let s=(0,_.useRef)(null),u=(0,_.useRef)(null),[c,d]=(0,_.useState)(i),[f,p]=(0,_.useState)({x:0,y:0}),[m,x]=(0,_.useState)(!1),[S,w]=(0,_.useState)({x:0,y:0}),[y,h]=(0,_.useState)({x:0,y:0}),b=(0,_.useCallback)(H=>{d(F=>Math.max(a,Math.min(n,F+H)))},[a,n]),T=(0,_.useCallback)(()=>{b(r)},[b,r]),C=(0,_.useCallback)(()=>{b(-r)},[b,r]),M=(0,_.useCallback)(()=>{d(i),p({x:0,y:0})},[i]),R=(0,_.useCallback)(H=>{H.preventDefault();let F=H.deltaY>0?-r:r;b(F)},[b,r]),P=(0,_.useCallback)(H=>{if(H.button!==0||H.isPrimary===!1)return;x(!0),w({x:H.clientX,y:H.clientY}),h(f);let F=H.currentTarget;F instanceof HTMLElement&&F.setPointerCapture(H.pointerId)},[f]),L=(0,_.useCallback)(H=>{if(!m)return;H.preventDefault();let F=H.clientX-S.x,W=H.clientY-S.y;p({x:y.x+F,y:y.y+W})},[m,S,y]),$=(0,_.useCallback)(H=>{x(!1);let F=H.currentTarget;F instanceof HTMLElement&&F.releasePointerCapture(H.pointerId)},[]);return(0,_.useEffect)(()=>{let H=s.current;if(H)return H.addEventListener("wheel",R,{passive:!1}),()=>{H.removeEventListener("wheel",R)}},[R]),(0,_.useEffect)(()=>{let H=u.current;if(H&&m)return document.body.style.userSelect="none",H.addEventListener("pointermove",L,{passive:!1}),H.addEventListener("pointerup",$),H.addEventListener("pointercancel",$),()=>{document.body.style.userSelect="",H.removeEventListener("pointermove",L),H.removeEventListener("pointerup",$),H.removeEventListener("pointercancel",$)}},[m,L,$]),(0,E.jsxs)("div",{className:ce("relative flex flex-col",l?"h-full w-full":"min-h-28 w-full",t),ref:s,style:{cursor:m?"grabbing":"grab"},children:[o?(0,E.jsxs)("div",{className:ce("absolute z-10 flex flex-col gap-1 rounded-md border border-border bg-background/90 p-1 shadow-sm backdrop-blur-sm",l?"bottom-4 left-4":"bottom-2 left-2"),children:[(0,E.jsx)("button",{className:"flex items-center justify-center rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50",disabled:c>=n,onClick:T,title:"Zoom in",type:"button",children:(0,E.jsx)(n6,{size:16})}),(0,E.jsx)("button",{className:"flex items-center justify-center rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50",disabled:c<=a,onClick:C,title:"Zoom out",type:"button",children:(0,E.jsx)(r6,{size:16})}),(0,E.jsx)("button",{className:"flex items-center justify-center rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",onClick:M,title:"Reset zoom and pan",type:"button",children:(0,E.jsx)(a6,{size:16})})]}):null,(0,E.jsx)("div",{className:ce("flex-1 origin-center transition-transform duration-150 ease-out",l?"flex h-full w-full items-center justify-center":"flex w-full items-center justify-center"),onPointerDown:P,ref:u,role:"application",style:{transform:`translate(${f.x}px, ${f.y}px) scale(${c})`,transformOrigin:"center center",touchAction:"none",willChange:"transform"},children:e})]})},yx=({chart:e,className:t,config:a,fullscreen:n=!1,showControls:r=!0})=>{let[o,i]=(0,_.useState)(null),[l,s]=(0,_.useState)(!1),[u,c]=(0,_.useState)(""),[d,f]=(0,_.useState)(""),[p,m]=(0,_.useState)(0),{mermaid:x}=(0,_.useContext)(ya),S=Tx(),w=x?.errorComponent,{shouldRender:y,containerRef:h}=JH({immediate:n});if((0,_.useEffect)(()=>{if(y){if(!S){i("Mermaid plugin not available. Please add the mermaid plugin to enable diagram rendering.");return}(async()=>{try{i(null),s(!0);let T=S.getMermaid(a),C=e.split("").reduce((P,L)=>(P<<5)-P+L.charCodeAt(0)|0,0),M=`mermaid-${Math.abs(C)}-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,{svg:R}=await T.render(M,e);c(R),f(R)}catch(T){if(!(d||u)){let C=T instanceof Error?T.message:"Failed to render Mermaid chart";i(C)}}finally{s(!1)}})()}},[e,a,p,y,S]),!(y||u||d))return(0,E.jsx)("div",{className:ce("my-4 min-h-[200px]",t),ref:h});if(l&&!u&&!d)return(0,E.jsx)("div",{className:ce("my-4 flex justify-center p-4",t),ref:h,children:(0,E.jsxs)("div",{className:"flex items-center space-x-2 text-muted-foreground",children:[(0,E.jsx)("div",{className:"h-4 w-4 animate-spin rounded-full border-current border-b-2"}),(0,E.jsx)("span",{className:"text-sm",children:"Loading diagram..."})]})});if(o&&!u&&!d)return w?(0,E.jsx)("div",{ref:h,children:(0,E.jsx)(w,{chart:e,error:o,retry:()=>m(C=>C+1)})}):(0,E.jsxs)("div",{className:ce("rounded-lg border border-red-200 bg-red-50 p-4",t),ref:h,children:[(0,E.jsxs)("p",{className:"font-mono text-red-700 text-sm",children:["Mermaid Error: ",o]}),(0,E.jsxs)("details",{className:"mt-2",children:[(0,E.jsx)("summary",{className:"cursor-pointer text-red-600 text-xs",children:"Show Code"}),(0,E.jsx)("pre",{className:"mt-2 overflow-x-auto rounded bg-red-100 p-2 text-red-800 text-xs",children:e})]})]});let b=u||d;return(0,E.jsx)("div",{className:ce("size-full",t),"data-streamdown":"mermaid",ref:h,children:(0,E.jsx)(q6,{className:ce(n?"size-full overflow-hidden":"my-4 overflow-hidden",t),fullscreen:n,maxZoom:3,minZoom:.5,showControls:r,zoomStep:.1,children:(0,E.jsx)("div",{"aria-label":"Mermaid chart",className:ce("flex justify-center",n?"size-full items-center":null),dangerouslySetInnerHTML:{__html:b},role:"img"})})})}});var A_=oa((vse,M_)=>{"use strict";function kV(e,t){if(typeof e!="function")throw new TypeError(`Expected the first argument to be a \`function\`, got \`${typeof e}\`.`);let a,n=0;return function(...o){clearTimeout(a);let i=Date.now(),l=i-n,s=t-l;s<=0?(n=i,e.apply(this,o)):a=setTimeout(()=>{n=Date.now(),e.apply(this,o)},s)}}M_.exports=kV});var Sv=typeof performance>"u"?0:performance.now(),Iv=typeof window<"u"&&!!window.WaniWani?.chat;var di=z(he(),1),Wp=z(Og(),1);var Pg="waniwani/suggestions";function ol(e,t){for(let a of t){let n=e[a];if(typeof n=="string"&&n.length>0)return n}}var NB=["waniwani/sessionId","openai/sessionId","openai/session","sessionId","conversationId","mcp-session-id"],BB=["waniwani/requestId","openai/requestId","requestId","mcp/requestId"],UB=["waniwani/traceId","openai/traceId","traceId","mcp/traceId","openai/requestId","requestId"],FB=["waniwani/userId","openai/userId","externalUserId","userId","actorId"],zB=["waniwani/visitorId","visitorId"],qB=["correlationId","openai/requestId"];function fC(e){return e?ol(e,NB):void 0}function pC(e){return e?ol(e,BB):void 0}function mC(e){return e?ol(e,UB):void 0}function hC(e){return e?ol(e,FB):void 0}function gC(e){return e?ol(e,zB):void 0}function wC(e){return e?ol(e,qB):void 0}var HB=[{key:"openai/sessionId",source:"chatgpt"},{key:"openai/session",source:"chatgpt"}],jB=[{needle:"claude",source:"claude"},{needle:"chatgpt",source:"chatgpt"},{needle:"openai",source:"chatgpt"},{needle:"gemini",source:"gemini"}];function yC(e,t){if(e){let n=e["waniwani/source"];if(typeof n=="string"&&n.length>0)return n;for(let{key:r,source:o}of HB){let i=e[r];if(typeof i=="string"&&i.length>0)return o}}let a=t?.name;if(typeof a=="string"&&a.length>0){let n=a.toLowerCase();for(let{needle:r,source:o}of jB)if(n.includes(r))return o}}var VB="@waniwani/sdk";function xC(e,t={}){let a=t.now??(()=>new Date),n=t.generateId??WB,r=XB(e),o=jd(e.meta),i=jd(e.metadata),l=KB(e,o),s=bn(e.eventId)??n(),u=YB(e.timestamp,a),c=bn(e.source)??yC(o)??t.source??VB,d=Ng(e)?{...e}:void 0,f={...i};return Object.keys(o).length>0&&(f.meta=o),d&&(f.rawLegacy=d),{id:s,type:"mcp.event",name:r,source:c,timestamp:u,correlation:l,properties:GB(e,r),metadata:f,rawLegacy:d}}function WB(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`evt_${crypto.randomUUID()}`:`evt_${Math.random().toString(36).slice(2,10)}_${Date.now().toString(36)}`}function GB(e,t){if(!Ng(e))return jd(e.properties);let a=$B(e,t),n=jd(e.properties);return{...a,...n}}function $B(e,t){switch(t){case"tool.called":{let a={};return bn(e.toolName)&&(a.name=e.toolName),bn(e.toolType)&&(a.type=e.toolType),a}case"link.clicked":{let a={};return bn(e.linkUrl)&&(a.url=e.linkUrl),a}default:return{}}}function XB(e){return Ng(e)?e.eventType:e.event}function KB(e,t){let a=bn(e.requestId)??pC(t),n=bn(e.sessionId)??fC(t),r=bn(e.traceId)??mC(t),o=bn(e.externalUserId)??hC(t),i=bn(e.visitorId)??gC(t),l=bn(e.correlationId)??wC(t)??a,s={};return n&&(s.sessionId=n),r&&(s.traceId=r),a&&(s.requestId=a),l&&(s.correlationId=l),o&&(s.externalUserId=o),i&&(s.visitorId=i),s}function YB(e,t){if(e instanceof Date)return e.toISOString();if(typeof e=="string"){let a=new Date(e);if(!Number.isNaN(a.getTime()))return a.toISOString()}return t().toISOString()}function jd(e){return!e||typeof e!="object"||Array.isArray(e)?{}:e}function bn(e){if(typeof e=="string"&&e.trim().length!==0)return e}function Ng(e){return"eventType"in e}function vC(e){return{priceShown:({amount:t,currency:a,itemId:n,label:r,...o})=>e({event:"price_shown",properties:{amount:t,currency:a,itemId:n,label:r},...o}),pricesCompared:({options:t,...a})=>e({event:"prices_compared",properties:{options:t},...a}),optionSelected:({id:t,amount:a,currency:n,...r})=>e({event:"option_selected",properties:{id:t,amount:a,currency:n},...r}),leadQualified:t=>{let{externalId:a,email:n,name:r,...o}=t??{};return e({event:"lead_qualified",properties:{externalId:a,email:n,name:r},...o})},converted:({amount:t,currency:a,occurredAt:n,...r})=>e({event:"converted",properties:{amount:t,currency:a,occurredAt:n},...r})}}var ZB="/api/mcp/events/v2/batch";var bC="@waniwani/sdk";var QB=new Set([401,403]),JB=new Set([408,425,429,500,502,503,504]),eU=(e,t)=>globalThis.fetch(e,t);function SC(e){return new Bg(e)}var Bg=class{constructor(t){ne(this,"endpointUrl");ne(this,"flushIntervalMs");ne(this,"maxBatchSize");ne(this,"maxBufferSize");ne(this,"maxRetries");ne(this,"retryBaseDelayMs");ne(this,"retryMaxDelayMs");ne(this,"shutdownTimeoutMs");ne(this,"sdkVersion");ne(this,"fetchFn");ne(this,"logger");ne(this,"now");ne(this,"sleep");ne(this,"apiKey");ne(this,"buffer",[]);ne(this,"flushTimer");ne(this,"flushScheduled",!1);ne(this,"flushScheduledTimer");ne(this,"flushInFlight");ne(this,"inFlightCount",0);ne(this,"isStopped",!1);ne(this,"isShuttingDown",!1);this.endpointUrl=nU(t.apiUrl,t.endpointPath??ZB),this.flushIntervalMs=t.flushIntervalMs??1e3,this.maxBatchSize=t.maxBatchSize??20,this.maxBufferSize=t.maxBufferSize??1e3,this.maxRetries=t.maxRetries??3,this.retryBaseDelayMs=t.retryBaseDelayMs??200,this.retryMaxDelayMs=t.retryMaxDelayMs??2e3,this.shutdownTimeoutMs=t.shutdownTimeoutMs??2e3,this.fetchFn=t.fetchFn??eU,this.logger=t.logger??console,this.now=t.now??(()=>new Date),this.sleep=t.sleep??(a=>new Promise(n=>setTimeout(n,a))),this.apiKey=t.apiKey,this.sdkVersion=t.sdkVersion,this.flushIntervalMs>0&&(this.flushTimer=setInterval(()=>{this.flush()},this.flushIntervalMs)),this.registerBrowserTeardown()}enqueue(t){if(this.isStopped||this.isShuttingDown){this.logger.warn("[Waniwani] Tracking transport is stopped, dropping event %s",t.id);return}if(this.buffer.length>=this.maxBufferSize){let a=this.buffer.length-this.maxBufferSize+1;this.buffer.splice(0,a),this.logger.warn("[Waniwani] Tracking buffer overflow, dropped %d oldest event(s)",a)}if(this.buffer.push(t),this.buffer.length>=this.maxBatchSize){this.flush();return}this.scheduleMicroFlush()}pendingEvents(){return this.buffer.length+this.inFlightCount}async flush(){return this.flushInFlight?this.flushInFlight:(this.flushInFlight=this.flushLoop().finally(()=>{this.flushInFlight=void 0}),this.flushInFlight)}async shutdown(t){this.isShuttingDown=!0,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=void 0),this.flushScheduledTimer&&(clearTimeout(this.flushScheduledTimer),this.flushScheduledTimer=void 0,this.flushScheduled=!1);let a=t?.timeoutMs??this.shutdownTimeoutMs,n=this.flush();if(!Number.isFinite(a)||a<=0)return await n,this.isStopped=!0,{timedOut:!1,pendingEvents:this.pendingEvents()};let r=Symbol("shutdown-timeout");return await Promise.race([n.then(()=>"flushed"),this.sleep(a).then(()=>r)])===r?(this.isStopped=!0,{timedOut:!0,pendingEvents:this.pendingEvents()}):(this.isStopped=!0,{timedOut:!1,pendingEvents:this.pendingEvents()})}registerBrowserTeardown(){if(typeof document>"u"||typeof window>"u")return;let t=()=>{document.visibilityState==="hidden"&&this.keepaliveFlush()};document.addEventListener("visibilitychange",t),window.addEventListener("pagehide",()=>this.keepaliveFlush())}keepaliveFlush(){if(this.isStopped||this.buffer.length===0)return;let t=this.buffer.splice(0,this.buffer.length);this.sendKeepaliveChunk(t)}sendKeepaliveChunk(t){let a=JSON.stringify(this.makeBatchRequest(t));if(a.length>6e4&&t.length>1){let n=Math.ceil(t.length/2);this.sendKeepaliveChunk(t.slice(0,n)),this.sendKeepaliveChunk(t.slice(n));return}try{this.fetchFn(this.endpointUrl,{method:"POST",headers:this.requestHeaders(),body:a,keepalive:!0}).catch(()=>{})}catch{}}requestHeaders(){let t={"Content-Type":"application/json","X-WaniWani-SDK":bC};return this.apiKey&&(t.Authorization=`Bearer ${this.apiKey}`),t}scheduleMicroFlush(){this.flushScheduled||(this.flushScheduled=!0,this.flushScheduledTimer=setTimeout(()=>{this.flushScheduledTimer=void 0,this.flushScheduled=!1,this.flush()},0))}async flushLoop(){for(;this.buffer.length>0&&!this.isStopped;){let t=this.buffer.splice(0,this.maxBatchSize);await this.sendBatchWithRetry(t)}}async sendBatchWithRetry(t){let a=0,n=t;for(;n.length>0&&!this.isStopped;){this.inFlightCount=n.length;let r=await this.sendBatchOnce(n);switch(this.inFlightCount=0,r.kind){case"success":return;case"auth":this.stopTransportForAuthFailure(r.status,n.length);return;case"permanent":this.logger.error("[Waniwani] Dropping %d event(s) after permanent failure: %s",n.length,r.reason);return;case"retryable":if(a>=this.maxRetries){this.logger.error("[Waniwani] Dropping %d event(s) after retry exhaustion: %s",n.length,r.reason);return}await this.sleep(this.backoffDelayMs(a)),a+=1;continue;case"partial":if(r.permanent.length>0&&this.logger.error("[Waniwani] Dropping %d event(s) rejected as permanent",r.permanent.length),r.retryable.length===0)return;if(a>=this.maxRetries){this.logger.error("[Waniwani] Dropping %d retryable event(s) after retry exhaustion",r.retryable.length);return}n=r.retryable,await this.sleep(this.backoffDelayMs(a)),a+=1;continue}}}async sendBatchOnce(t){let a;try{a=await this.fetchFn(this.endpointUrl,{method:"POST",headers:this.requestHeaders(),body:JSON.stringify(this.makeBatchRequest(t))})}catch(o){return{kind:"retryable",reason:rU(o)}}if(QB.has(a.status))return{kind:"auth",status:a.status};if(JB.has(a.status))return{kind:"retryable",reason:`HTTP ${a.status}`};if(!a.ok)return{kind:"permanent",reason:`HTTP ${a.status}`};let n=await aU(a);if(!n?.rejected||n.rejected.length===0)return{kind:"success"};let r=this.classifyRejectedEvents(t,n.rejected);return r.retryable.length===0&&r.permanent.length===0?{kind:"success"}:{kind:"partial",retryable:r.retryable,permanent:r.permanent}}makeBatchRequest(t){return{sentAt:this.now().toISOString(),source:{sdk:bC,version:this.sdkVersion??"0.0.0"},events:t}}classifyRejectedEvents(t,a){let n=new Map(t.map(i=>[i.id,i])),r=[],o=[];for(let i of a){let l=n.get(i.eventId);if(l){if(tU(i)){r.push(l);continue}o.push(l)}}return{retryable:r,permanent:o}}backoffDelayMs(t){let a=this.retryBaseDelayMs*2**t;return Math.min(a,this.retryMaxDelayMs)}stopTransportForAuthFailure(t,a){this.isStopped=!0;let n=this.buffer.length;this.buffer.splice(0,n),this.logger.error("[Waniwani] Auth failure (HTTP %d). Stopping tracking transport and dropping %d queued event(s)",t,a+n)}};function tU(e){if(e.retryable===!0)return!0;let t=e.code.toLowerCase();return t.includes("timeout")||t.includes("temporary")||t.includes("unavailable")||t.includes("rate_limit")||t.includes("transient")||t.includes("server")}async function aU(e){let t=await e.text();if(t)try{return JSON.parse(t)}catch{return}}function nU(e,t){let a=e.endsWith("/")?e:`${e}/`,n=t.startsWith("/")?t.slice(1):t;return`${a}${n}`}function rU(e){return e instanceof Error?e.message:String(e)}function IC(e){let{apiUrl:t,endpointPath:a}=oU(e.endpoint),n=SC({apiUrl:t,apiKey:e.token,endpointPath:a,flushIntervalMs:e.flushIntervalMs}),r,o=l=>typeof l=="function"?l():l,i=async l=>{let s=e.identity?.()??{},u=o(e.channelId),c=u===void 0?l.properties:{channelId:u,...l.properties},d=xC({sessionId:s.sessionId,visitorId:s.visitorId,externalUserId:s.externalUserId??r,traceId:s.traceId,...l,properties:c,metadata:{...e.metadata,...l.metadata}},{source:o(e.source)});return n.enqueue(d),{eventId:d.id}};return{track:Object.assign(i,vC(i)),identify(l,s){return r=l,i({event:"user.identified",externalUserId:l,properties:s})},flush:()=>n.flush(),shutdown:l=>n.shutdown(l)}}function oU(e){let t=new URL(e);return{apiUrl:t.origin,endpointPath:`${t.pathname}${t.search}`}}function ma(e,t,a){let[n,r=""]=e.split("?"),o=n.replace(/\/$/,""),i=new URLSearchParams(r);if(a)for(let[s,u]of Object.entries(a))i.set(s,u);let l=i.toString();return`${o}${t}${l?`?${l}`:""}`}var iU="/api/mcp/";function Vd(e,t){let[a=""]=e.split("?"),n="",r=a;try{let o=new URL(a);n=o.origin,r=o.pathname}catch{if(!a.startsWith("/"))return null}return r.startsWith(iU)?`${n}${t}`:null}function lU(){if(typeof window>"u")return!1;try{return window.WANIWANI_DEBUG?!0:!!window.localStorage?.getItem("WANIWANI_DEBUG")}catch{return!1}}function ha(...e){lU()&&console.log("[Waniwani]",...e)}var Ug="waniwani-visitor-id";function sU(){try{if(typeof crypto<"u"){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();if(typeof crypto.getRandomValues=="function"){let e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=Array.from(e,a=>a.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}}}catch{}return`v-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function Zt(){try{let t=localStorage.getItem(Ug);if(t)return t}catch{}let e=sU();try{localStorage.setItem(Ug,e)}catch{}return e}function il(e){let t=typeof e=="string"?e.trim():"";if(!t)return Zt();try{localStorage.setItem(Ug,t)}catch{}return t}function uU(e){return e!=null&&typeof e.then=="function"}function $s(e){let t=!1,a=()=>{t=!0};if(e==null)return a;let n;try{n=typeof e=="function"?e():e}catch{return a}return uU(n)?n.then(r=>{t||il(r??"")},()=>{}):il(n??""),a}var cU="waniwani-memory";var Wa="threads",Wd="by_memoryUserId",dU="by_updatedAt";var kC="memoryUserId",CC="waniwani-memory-user-id",Fg=null;function zg(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}function fU(e,t){if(t<1&&(e.objectStoreNames.contains("ids")||e.createObjectStore("ids")),t<2&&!e.objectStoreNames.contains(Wa)){let a=e.createObjectStore(Wa,{keyPath:"threadId"});a.createIndex(Wd,"memoryUserId",{unique:!1}),a.createIndex(dU,"updatedAt",{unique:!1})}}async function qg(){return new Promise((e,t)=>{let a=indexedDB.open(cU,2);a.onupgradeneeded=n=>{fU(a.result,n.oldVersion)},a.onsuccess=()=>e(a.result),a.onerror=()=>t(a.error)})}async function pU(){return qg()}async function mU(e){return new Promise((t,a)=>{let o=e.transaction("ids","readonly").objectStore("ids").get(kC);o.onsuccess=()=>t(typeof o.result=="string"?o.result:null),o.onerror=()=>a(o.error)})}async function hU(e,t){return new Promise((a,n)=>{let i=e.transaction("ids","readwrite").objectStore("ids").put(t,kC);i.onsuccess=()=>a(),i.onerror=()=>n(i.error)})}async function gU(){if(typeof indexedDB>"u")return null;try{let e=await pU();try{let t=await mU(e);if(t)return t;let a=zg();return await hU(e,a),a}finally{e.close()}}catch{return null}}function wU(){try{let e=localStorage.getItem(CC);if(e)return e;let t=zg();return localStorage.setItem(CC,t),t}catch{return null}}async function TC(){let e=await gU();if(e)return e;let t=wU();return t||(Fg||(Fg=zg()),Fg)}function LC(e,t){return e.match(t)?.[1]??null}function yU(e){let t=[["Edge",/Edg(?:e|A|iOS)?\/(\S+)/],["Opera",/(?:OPR|Opera)\/(\S+)/],["Samsung Internet",/SamsungBrowser\/(\S+)/],["Firefox",/Firefox\/(\S+)/],["Chrome",/Chrome\/(\S+)/],["Safari",/Version\/(\S+).*Safari/]];for(let[a,n]of t){let r=LC(e,n);if(r)return{name:a,version:r}}return null}function xU(e){let t=[["iOS",/(?:iPhone|iPad|iPod).+?OS (\d+[_.\d]*)/],["Android",/Android (\d+[.\d]*)/],["macOS",/Mac OS X (\d+[_.\d]*)/],["Windows",/Windows NT (\d+[.\d]*)/],["ChromeOS",/CrOS \S+ (\d+[.\d]*)/],["Linux",/Linux/]];for(let[a,n]of t){let r=LC(e,n);if(r)return{name:a,version:r.replace(/_/g,".")};if(a==="Linux"&&n.test(e))return{name:a,version:""}}return null}function vU(e){return typeof navigator<"u"&&"userAgentData"in navigator&&navigator.userAgentData?.mobile?"mobile":/iPad|tablet|PlayBook/i.test(e)?"tablet":/Mobi|Android.*Mobile|iPhone|iPod/i.test(e)?"mobile":"desktop"}async function Xs(){let e=navigator.userAgent,t=Zt(),a=await TC();return{userAgent:e,browser:yU(e),os:xU(e),deviceType:vU(e),language:navigator.language,languages:[...navigator.languages],timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,screenWidth:screen.width,screenHeight:screen.height,viewportWidth:window.innerWidth,viewportHeight:window.innerHeight,colorDepth:screen.colorDepth,devicePixelRatio:window.devicePixelRatio??1,touchSupport:"ontouchstart"in window||navigator.maxTouchPoints>0,connectionType:navigator.connection?.effectiveType??"unknown",referrer:document.referrer,visitorId:t,memoryUserId:a}}var bU="0.22.0-beta.1",SU=40,IU=10,CU=6e5;function jg(){return typeof performance>"u"?0:performance.now()}function Vg(e,t){let a={};return{metrics:a,has:n=>n in a,set(n,r){a[n]=r},mark(n,r=jg()){if(!(n in a)){a[n]=r-t;try{performance.mark(`waniwani:${e}:${n}`,{startTime:r})}catch{}}}}}function kU(e){let t={};for(let[a,n]of Object.entries(e)){if(Object.keys(t).length>=SU)break;if(!Number.isFinite(n))continue;let r=Math.round(n);r<0||r>CU||(t[a]=r)}return t}function TU(e){let t={};for(let[a,n]of Object.entries(e)){if(Object.keys(t).length>=IU)break;(typeof n=="string"||typeof n=="boolean")&&(t[a]=n)}return t}function LU(){let e=navigator.connection;if(e)return{effectiveType:e.effectiveType,rtt:e.rtt,downlink:e.downlink,saveData:e.saveData}}function $d(e){let t=e?.Authorization;return typeof t=="string"&&t.startsWith("Bearer ")?t.slice(7):void 0}function EU(e,t,a,n){return{kind:e,sdkVersion:bU,channelId:t.channelId||void 0,sessionId:e==="boot"?void 0:t.sessionId||void 0,visitorId:Zt(),pageHost:window.location.hostname,connection:LU(),tags:TU(a),metrics:kU(n)}}var Hg,Gd=[];function Wg(e){let t=String(e?.chatTimingLogs).trim().toLowerCase()==="true";Hg=t;let a=Gd;if(Gd=[],t)for(let n of a)n()}function Xd(e,t,a,n){let{api:r,token:o}=t;if(!(typeof window>"u"||!r||!o||Hg===!1))try{let i=EU(e,t,a,n),l=()=>{ha("timing",i),fetch(ma(r,"/timing"),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},body:JSON.stringify(i),keepalive:!0}).catch(()=>{})};Hg?l():Gd.length<20&&Gd.push(l)}catch{}}var dr=Vg("boot",0),EC;function Bo(e,t){dr.mark(e,t)}function Kd(e){EC??(EC=e)}var MU=/cdn\.jsdelivr\.net\/npm\/@waniwani\/sdk@[^/]+\/dist\/chat\/embed\.js/,AU=/\/embed\.js(\?|$)/;function RU(){if(typeof performance>"u")return;let e=performance.getEntriesByType("navigation")[0];e?.responseStart&&dr.mark("navTtfb",e.responseStart),e?.domContentLoadedEventEnd&&dr.mark("navDomContentLoaded",e.domContentLoadedEventEnd);let t=performance.getEntriesByType("resource");for(let a of t)MU.test(a.name)?(dr.mark("bundleStart",a.startTime),dr.mark("bundleEnd",a.responseEnd)):AU.test(a.name)&&(dr.mark("loaderStart",a.startTime),dr.mark("loaderEnd",a.responseEnd))}function DU(){if(Iv)return!0;try{return document.querySelectorAll('script[src*="@waniwani/sdk"]').length>1}catch{return!1}}function MC(e){RU(),dr.mark("bundleExecuted",Sv),Xd("boot",e,{configSource:EC,mode:e.mode,secondSdk:DU()},dr.metrics)}var _U=[["text-delta","firstText"],["tool-input-start","firstToolInput"],["tool-output-available","firstToolOutput"]];function AC(e){let t=Vg("turn",jg());t.set("turnIndex",e);let a=!1;return{mark:n=>t.mark(n),instrument(n){if(!n.ok||!n.body||typeof TransformStream>"u")return n;try{let r=new TextDecoder,o=n.body.pipeThrough(new TransformStream({transform(i,l){t.mark("firstChunk");let s=r.decode(i,{stream:!0});for(let[u,c]of _U)!t.has(c)&&s.includes(u)&&t.mark(c);l.enqueue(i)}}));return new Response(o,{status:n.status,statusText:n.statusText,headers:n.headers})}catch{return n}},report(n,r){a||(a=!0,Xd("turn",n,r,t.metrics))}}}function OU(e){let t=e.indexOf("?");return t===-1?e:e.slice(0,t)}function RC(e,t){let a=Vg("widget",jg()),n=!1;return{mark:r=>a.mark(r),has:r=>a.has(r),report(r,o){n||(n=!0,a.set("retries",o),t({widget:OU(e),outcome:r,metrics:a.metrics}))}}}var PU="/api/mcp/events/v2/batch",Gg=new Set;function NU(e,t,a){return`${e}|${t}|${a??""}`}function Ks(e){return Vd(e,PU)}async function DC(e){let{api:t,token:a,channelId:n,mode:r,source:o}=e;if(typeof window>"u"||!t||!a)return;let i=Ks(t);if(!i){ha("page.viewed skipped: the chat api is not a Waniwani endpoint");return}if(!n&&!o){ha("page.viewed skipped: no channelId or source to attribute it");return}let l=NU(t,a,n);if(!Gg.has(l)){Gg.add(l);try{let s=await Xs(),u=new Date().toISOString(),c=JSON.stringify({sentAt:u,source:{sdk:"@waniwani/sdk",version:"0.1.0"},events:[{id:crypto.randomUUID(),type:"mcp.event",name:"page.viewed",source:o,timestamp:u,correlation:{visitorId:s.visitorId},properties:{channelId:n,mode:r,url:window.location.href,referrer:s.referrer,deviceType:s.deviceType,language:s.language,timezone:s.timezone},metadata:{}}]}),d=fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:c,keepalive:!0});Bo("pageViewSent"),await d}catch{Gg.delete(l)}}}function _C(e){let t=Ks(e.api);return t?IC({endpoint:t,token:e.token,channelId:e.channelId,source:e.getSource,identity:()=>({sessionId:e.getSessionId(),visitorId:Zt()})}):Yd("the chat api does not point at a Waniwani event ingest")}function Yd(e){let t=!1,a=async()=>(t||(t=!0,console.warn(`[Waniwani] track() is disabled: ${e}`)),{eventId:""});return{track:Object.assign(a,{priceShown:a,pricesCompared:a,optionSelected:a,leadQualified:a,converted:a}),identify:a,flush:async()=>{},shutdown:async()=>({timedOut:!1,pendingEvents:0})}}var Qd=z(he());var Zd=(...e)=>e.filter((t,a,n)=>!!t&&t.trim()!==""&&n.indexOf(t)===a).join(" ").trim();var OC=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();var PC=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,a,n)=>n?n.toUpperCase():a.toLowerCase());var $g=e=>{let t=PC(e);return t.charAt(0).toUpperCase()+t.slice(1)};var Ys=z(he());var NC={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};var BC=e=>{for(let t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0;return!1};var UC=(0,Ys.forwardRef)(({color:e="currentColor",size:t=24,strokeWidth:a=2,absoluteStrokeWidth:n,className:r="",children:o,iconNode:i,...l},s)=>(0,Ys.createElement)("svg",{ref:s,...NC,width:t,height:t,stroke:e,strokeWidth:n?Number(a)*24/Number(t):a,className:Zd("lucide",r),...!o&&!BC(l)&&{"aria-hidden":"true"},...l},[...i.map(([u,c])=>(0,Ys.createElement)(u,c)),...Array.isArray(o)?o:[o]]));var He=(e,t)=>{let a=(0,Qd.forwardRef)(({className:n,...r},o)=>(0,Qd.createElement)(UC,{ref:o,iconNode:t,className:Zd(`lucide-${OC($g(e))}`,`lucide-${e}`,n),...r}));return a.displayName=$g(e),a};var BU=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],Zs=He("arrow-down",BU);var UU=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],Nn=He("arrow-up",UU);var FU=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Qs=He("check",FU);var zU=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Qr=He("chevron-down",zU);var qU=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],Js=He("chevron-right",qU);var HU=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2",key:"4jdomd"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v4",key:"3hqy98"}],["path",{d:"M21 14H11",key:"1bme5i"}],["path",{d:"m15 10-4 4 4 4",key:"5dvupr"}]],eu=He("clipboard-copy",HU);var jU=[["path",{d:"M12 6v6l4 2",key:"mmk7yg"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],fr=He("clock",jU);var VU=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],tu=He("file-text",VU);var WU=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}]],ll=He("file",WU);var GU=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]],au=He("globe",GU);var $U=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]],nu=He("image",$U);var XU=[["path",{d:"M12 2v4",key:"3427ic"}],["path",{d:"m16.2 7.8 2.9-2.9",key:"r700ao"}],["path",{d:"M18 12h4",key:"wj9ykh"}],["path",{d:"m16.2 16.2 2.9 2.9",key:"1bxg5t"}],["path",{d:"M12 18v4",key:"jadmvz"}],["path",{d:"m4.9 19.1 2.9-2.9",key:"bwix9q"}],["path",{d:"M2 12h4",key:"j09sii"}],["path",{d:"m4.9 4.9 2.9 2.9",key:"giyufr"}]],ru=He("loader",XU);var KU=[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551",key:"1miecu"}]],sl=He("paperclip",KU);var YU=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],ou=He("square",YU);var ZU=[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z",key:"1ngwbx"}]],Uo=He("wrench",ZU);var QU=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Ga=He("x",QU);var JU=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]],iu=He("zap",JU);var $e=z(he(),1),uO=z(um(),1);var ul=z(he(),1),lu=z(re(),1);function a3(e){return 1-(1-e)**3}function n3({start:e=0,end:t=100,duration:a=1e3,delay:n=0,ease:r=a3,onUpdate:o,onEnd:i}){let l=performance.now()+n;function s(){let u=performance.now()-l,c=Math.min(u/a,1);o(e+(t-e)*r(c)),c<1?requestAnimationFrame(s):i&&i()}setTimeout(()=>requestAnimationFrame(s),n)}var r3=["80% 55%","69% 34%","8% 6%","41% 38%","86% 85%","82% 18%","51% 4%"],o3=[0,1,2,0,1,2,1];function i3(e){let t=[];for(let a=0;a<7;a++){let n=e[Math.min(o3[a],e.length-1)];t.push(`radial-gradient(at ${r3[a]}, ${n} 0px, transparent 50%)`)}return t.push(`linear-gradient(${e[0]} 0 100%)`),t}var l3=({children:e,className:t="",style:a,edgeSensitivity:n=30,backgroundColor:r="#120F17",borderRadius:o=28,coneSpread:i=25,animated:l=!1,colors:s=["#c084fc","#f472b6","#38bdf8"]})=>{let[u,c]=(0,ul.useState)(110),[d,f]=(0,ul.useState)(0),[p,m]=(0,ul.useState)(!1);(0,ul.useEffect)(()=>{if(!l)return;let T=110;m(!0),c(T),n3({ease:C=>C,duration:2e3,onUpdate:C=>{let M=C/100;c(T+360*M);let R=Math.min(M/.1,1),P=M>.85?(1-M)/.15:1;f(Math.min(R,P))},onEnd:()=>m(!1)})},[l]);let x=n+20,S=p?Math.max(0,(d*100-x)/(100-x)):0,y=i3(s).map(T=>`${T} border-box`),b=`conic-gradient(from ${`${u.toFixed(3)}deg`} at center, black ${i}%, transparent ${i+15}%, transparent ${100-i-15}%, black ${100-i}%)`;return(0,lu.jsxs)("div",{className:`ww:relative ww:grid ww:isolate ww:border ${t}`,style:{background:r,borderRadius:typeof o=="number"?`${o}px`:o,transform:"translate3d(0, 0, 0.01px)",...a},children:[(0,lu.jsx)("div",{className:"ww:absolute ww:inset-0 ww:rounded-[inherit] ww:-z-[1]",style:{border:"1px solid transparent",background:[`linear-gradient(${r} 0 100%) padding-box`,"linear-gradient(rgb(255 255 255 / 0%) 0% 100%) border-box",...y].join(", "),opacity:S,maskImage:b,WebkitMaskImage:b,transition:p?"opacity 0.25s ease-out":"opacity 0.75s ease-in-out"}}),(0,lu.jsx)("div",{className:"ww:flex ww:flex-col ww:relative ww:overflow-auto ww:z-[1]",children:e})]})},ef=l3;Xg();Yg();var s3=jC({prefix:"ww"});function q(...e){return s3(tf(e))}var su=z(re(),1);function cl({suggestions:e,isLoading:t,onSelect:a,align:n="start",className:r,...o}){return e.length===0&&!t?null:(0,su.jsx)("div",{className:q("ww:px-4 ww:py-2",r),...o,children:(0,su.jsx)("div",{className:q("ww:mx-auto ww:w-full ww:max-w-3xl ww:flex ww:flex-wrap ww:gap-2",n==="center"&&"ww:justify-center"),children:t?[0,1,2].map(i=>(0,su.jsx)("div",{className:"ww:h-8 ww:rounded-full ww:bg-accent ww:animate-pulse",style:{width:`${60+i*20}px`}},i)):e.map((i,l)=>(0,su.jsx)("button",{type:"button",onClick:()=>a(i),className:q("ww:rounded-full ww:border ww:border-border ww:bg-accent ww:px-3.5 ww:py-1.5 ww:text-sm","ww:text-foreground ww:hover:bg-border ww:hover:border-primary/30","ww:transition-all ww:duration-200 ww:ease-out ww:cursor-pointer","ww:animate-[ww-fade-in_0.2s_ease-out_both]"),style:{animationDelay:`${l*50}ms`},children:i},i))})})}var VC=z(he(),1),WC="(max-width: 639px)";function u3(e){let t=window.matchMedia(WC);return t.addEventListener("change",e),()=>t.removeEventListener("change",e)}function c3(){return window.matchMedia(WC).matches}function d3(){return!1}function GC(){return(0,VC.useSyncExternalStore)(u3,c3,d3)}var af=z(he(),1);function Zg(e,t){return e.find(a=>a.text===t)?.id??null}async function $C(e){let{api:t,token:a,name:n,source:r,sessionId:o,properties:i}=e;if(typeof window>"u"||!t||!a)return;let l=Ks(t);if(l)try{let s=new Date().toISOString(),u=JSON.stringify({sentAt:s,source:{sdk:"@waniwani/sdk",version:"0.1.0"},events:[{id:crypto.randomUUID(),type:"mcp.event",name:n,source:r,timestamp:s,correlation:{visitorId:Zt(),sessionId:o},properties:{...i,url:window.location.href},metadata:{}}]});await fetch(l,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:u,keepalive:!0})}catch{}}async function XC(e){let{api:t,token:a,channelId:n,mode:r,source:o,sessionId:i,promptId:l,origin:s,text:u,index:c}=e;await $C({api:t,token:a,name:"suggestion.clicked",source:o,sessionId:i,properties:{promptId:l,origin:s,text:u,index:c,channelId:n,mode:r}})}function KC(e,t){return t.map(a=>({id:Zg(e,a),text:a}))}async function YC(e){let{api:t,token:a,channelId:n,mode:r,source:o,sessionId:i,prompts:l,origin:s}=e;l.length!==0&&await $C({api:t,token:a,name:"suggestion.shown",source:o,sessionId:i,properties:{prompts:l,count:l.length,origin:s,channelId:n,mode:r}})}function dl(e){let{widgetEvents:t,api:a,token:n,channelId:r,source:o,mode:i,pagePrompts:l}=e,s=(0,af.useRef)(e.getSessionId);s.current=e.getSessionId,(0,af.useEffect)(()=>{if(!(!a||!n))return t.subscribe(u=>{if(u.name==="suggestion.clicked"){let{text:c,origin:d,index:f}=u.properties;XC({api:a,token:n,channelId:r,mode:i,source:o,sessionId:s.current(),promptId:Zg(l??[],c),origin:d,text:c,index:f});return}if(u.name==="suggestions.shown"){let{texts:c,origin:d}=u.properties;YC({api:a,token:n,channelId:r,mode:i,source:o,sessionId:s.current(),prompts:KC(l??[],c),origin:d})}})},[t,a,n,r,o,i,l])}var fl=z(he(),1),f3=80,p3=50,m3=15e3,ZC=500;function pl(e,t=!0){let[a,n]=(0,fl.useState)(""),r=(0,fl.useRef)(void 0);return(0,fl.useEffect)(()=>{if(!t){n("");return}let o=0,i=!1,l=!1,s=()=>{l||(i?(o--,n(e.slice(0,o)),o<=0?(i=!1,r.current=setTimeout(s,ZC)):r.current=setTimeout(s,p3)):(o++,n(e.slice(0,o)),o>=e.length?(i=!0,r.current=setTimeout(s,m3)):r.current=setTimeout(s,f3)))};return r.current=setTimeout(s,ZC),()=>{l=!0,clearTimeout(r.current)}},[e,t]),a}var Sn=z(he(),1);var QC=["en","fr","es"];function ml(e){return QC.includes(e)}function Qg(e){if(e&&ml(e))return e;if(e){let a=e.split("-")[0]?.toLowerCase();if(a&&ml(a))return a}let t=[];if(typeof navigator<"u"&&(navigator.language&&t.push(navigator.language),navigator.languages&&t.push(...navigator.languages)),typeof document<"u"){let a=document.documentElement.getAttribute("lang");a&&t.push(a)}for(let a of t){let n=a.toLowerCase();if(ml(n))return n;let r=n.split("-")[0];if(r&&ml(r))return r}return"en"}var nf={promptInput:{placeholder:"What would you like to know?",uploadFiles:"Upload files",uploadFilesUpTo:"Upload a document, up to {limit}",uploadFilesUpToWithPages:"Upload a document, up to {limit} and {pages} pages",stop:"Stop",submit:"Submit",removeAttachments:"Remove all attachments",removeAttachment:"Remove attachment",uploading:"Uploading\u2026",retry:"Retry",retryUpload:"Retry the upload",uploadFailed:"The upload did not finish.",dropToAttach:"Drop to attach",errorAccept:"{name} is not a file type this chat accepts.",errorTooLarge:"{name} is larger than {limit}.",errorTooMany:"You can attach up to {limit} files."},workingIndicator:{default:"On it\u2026"},reasoning:{thinking:"Thinking\u2026",thoughtBrief:"Thought for a few seconds",thoughtForSeconds:e=>`Thought for ${e} second${e===1?"":"s"}`},chainOfThought:{working:"Working on it\u2026",done:"Thought process"},tool:{copy:"Copy",copied:"Copied",request:"Request",response:"Response",error:"Error"},attachments:{attachmentFallback:"attachment",kindPdf:"PDF",kindImage:"Image",kindFile:"File",fileFallback:"file"},threadMenu:{newChat:"New chat",threadHistory:"Thread history",deleteThread:"Delete thread",noPreviousChats:"No previous chats yet.",hiddenThreads:e=>`${e} older thread${e===1?"":"s"} hidden`},chatQueue:{attachmentFallback:"(attachment)",removeFromQueue:"Remove from queue",queued:e=>`${e} queued`},poweredBy:{label:"AI agent powered by"},aiDisclaimer:{default:"can make mistakes"},exportSession:{saving:"saving...",saved:"saved",error:"error",export:"export",tooltip:"Save scenario to Waniwani"},widgetErrorBoundary:{failedToLoad:"Widget failed to load",retry:"Retry"},launcher:{prompt:"Ask anything\u2026",open:"Open chat",close:"Close chat",minimize:"Minimize"}};var JC={promptInput:{placeholder:"\xBFQu\xE9 te gustar\xEDa saber?",uploadFiles:"Subir archivos",uploadFilesUpTo:"Subir un documento, hasta {limit}",uploadFilesUpToWithPages:"Subir un documento, hasta {limit} y {pages} p\xE1ginas",stop:"Detener",submit:"Enviar",removeAttachments:"Eliminar todos los archivos adjuntos",removeAttachment:"Quitar archivo",uploading:"Subiendo\u2026",retry:"Reintentar",retryUpload:"Reintentar la subida",uploadFailed:"La subida no se complet\xF3.",dropToAttach:"Suelta para adjuntar",errorAccept:"{name} no es un tipo de archivo que acepte este chat.",errorTooLarge:"{name} supera {limit}.",errorTooMany:"Puedes adjuntar hasta {limit} archivos."},workingIndicator:{default:"Un momento\u2026"},reasoning:{thinking:"Pensando\u2026",thoughtBrief:"Pensado durante unos segundos",thoughtForSeconds:e=>`Pensado durante ${e} segundo${e===1?"":"s"}`},chainOfThought:{working:"Estoy en ello\u2026",done:"Razonamiento"},tool:{copy:"Copiar",copied:"Copiado",request:"Solicitud",response:"Respuesta",error:"Error"},attachments:{attachmentFallback:"adjunto",kindPdf:"PDF",kindImage:"Imagen",kindFile:"Archivo",fileFallback:"archivo"},threadMenu:{newChat:"Nueva conversaci\xF3n",threadHistory:"Historial",deleteThread:"Eliminar conversaci\xF3n",noPreviousChats:"A\xFAn no hay conversaciones anteriores.",hiddenThreads:e=>`${e} conversaci\xF3n${e===1?"":"es"} anterior${e===1?"":"es"} oculta${e===1?"":"s"}`},chatQueue:{attachmentFallback:"(adjunto)",removeFromQueue:"Quitar de la cola",queued:e=>`${e} en cola`},poweredBy:{label:"Agente IA con tecnolog\xEDa de"},aiDisclaimer:{default:"puede cometer errores"},exportSession:{saving:"guardando...",saved:"guardado",error:"error",export:"exportar",tooltip:"Guardar escenario en Waniwani"},widgetErrorBoundary:{failedToLoad:"No se pudo cargar el widget",retry:"Reintentar"},launcher:{prompt:"Pregunta lo que quieras\u2026",open:"Abrir chat",close:"Cerrar chat",minimize:"Minimizar"}};var ek={promptInput:{placeholder:"Que souhaitez-vous savoir ?",uploadFiles:"Importer des fichiers",uploadFilesUpTo:"Joindre un document, jusqu'\xE0 {limit}",uploadFilesUpToWithPages:"Envoyer un document, jusqu'\xE0 {limit} et {pages} pages",stop:"Arr\xEAter",submit:"Envoyer",removeAttachments:"Supprimer toutes les pi\xE8ces jointes",removeAttachment:"Retirer la pi\xE8ce jointe",uploading:"Envoi en cours\u2026",retry:"R\xE9essayer",retryUpload:"R\xE9essayer l'envoi",uploadFailed:"L'envoi ne s'est pas termin\xE9.",dropToAttach:"D\xE9posez pour joindre",errorAccept:"{name} n'est pas un type de fichier accept\xE9 par ce chat.",errorTooLarge:"{name} d\xE9passe {limit}.",errorTooMany:"Vous pouvez joindre jusqu'\xE0 {limit} fichiers."},workingIndicator:{default:"Un instant\u2026"},reasoning:{thinking:"R\xE9flexion\u2026",thoughtBrief:"R\xE9flexion pendant quelques secondes",thoughtForSeconds:e=>`R\xE9flexion pendant ${e} seconde${e===1?"":"s"}`},chainOfThought:{working:"Je m'en occupe\u2026",done:"Raisonnement"},tool:{copy:"Copier",copied:"Copi\xE9",request:"Requ\xEAte",response:"R\xE9ponse",error:"Erreur"},attachments:{attachmentFallback:"pi\xE8ce jointe",kindPdf:"PDF",kindImage:"Image",kindFile:"Fichier",fileFallback:"fichier"},threadMenu:{newChat:"Nouvelle conversation",threadHistory:"Historique",deleteThread:"Supprimer la conversation",noPreviousChats:"Aucune conversation pr\xE9c\xE9dente.",hiddenThreads:e=>`${e} conversation${e===1?"":"s"} plus ancienne${e===1?"":"s"} masqu\xE9e${e===1?"":"s"}`},chatQueue:{attachmentFallback:"(pi\xE8ce jointe)",removeFromQueue:"Retirer de la file",queued:e=>`${e} en attente`},poweredBy:{label:"Agent IA propuls\xE9 par"},aiDisclaimer:{default:"peut faire des erreurs"},exportSession:{saving:"enregistrement...",saved:"enregistr\xE9",error:"erreur",export:"exporter",tooltip:"Enregistrer le sc\xE9nario dans Waniwani"},widgetErrorBoundary:{failedToLoad:"\xC9chec du chargement du widget",retry:"R\xE9essayer"},launcher:{prompt:"Posez votre question\u2026",open:"Ouvrir le chat",close:"Fermer le chat",minimize:"R\xE9duire"}};var Jg={en:nf,fr:ek,es:JC};var ak=z(re(),1),tk=(0,Sn.createContext)(null);function h3(e,t){if(!t)return e;let a={...e};for(let n of Object.keys(e)){let r=e[n],o=t[n];o&&typeof r=="object"&&(a[n]={...r,...o})}return a}function Fo({children:e,locale:t,messages:a}){let n=!!(t&&g3(t)),r=n?t:"en",[o,i]=(0,Sn.useState)(r),[l,s]=(0,Sn.useState)(n);(0,Sn.useEffect)(()=>{i(Qg(t)),s(!0)},[t]);let u=(0,Sn.useMemo)(()=>{let c=Jg[o]??Jg["en"];return{locale:o,t:h3(c,a),ready:l}},[o,a,l]);return(0,ak.jsx)(tk.Provider,{value:u,children:e})}function g3(e){return e==="en"||e==="fr"||e==="es"}function ke(){let e=(0,Sn.useContext)(tk);return e||{locale:"en",t:nf,ready:!0}}function ew(e,t){let a=Date.now()-e;if(a<6e4)try{return new Intl.RelativeTimeFormat(t,{numeric:"auto",style:"narrow"}).format(0,"second")}catch{return"just now"}let n,r;a<60*6e4?(n=-Math.floor(a/6e4),r="minute"):a<1440*6e4?(n=-Math.floor(a/(60*6e4)),r="hour"):(n=-Math.floor(a/(1440*6e4)),r="day");try{return new Intl.RelativeTimeFormat(t,{numeric:"auto",style:"short"}).format(n,r)}catch{return`${Math.abs(n)}${r==="minute"?"m":r==="hour"?"h":"d"} ago`}}var ze=z(he(),1);var uu=(e=21)=>crypto.getRandomValues(new Uint8Array(e)).reduce((t,a)=>(a&=63,a<36?t+=a.toString(36):a<62?t+=(a-26).toString(36).toUpperCase():a>62?t+="-":t+="_",t),"");var Ie=z(he(),1);var zo=new Map;function nk(e,t){if(zo.has(e)){URL.revokeObjectURL(t);return}for(zo.set(e,t);zo.size>20;){let a=zo.keys().next();if(a.done)return;let n=zo.get(a.value);zo.delete(a.value),n&&URL.revokeObjectURL(n)}}function rk(e){return zo.get(e)}var ok=z(re(),1),Bn=({className:e,variant:t="default",size:a="default",type:n="button",...r})=>(0,ok.jsx)("button",{type:n,className:q("ww:inline-flex ww:cursor-pointer ww:items-center ww:justify-center ww:rounded-md ww:font-medium ww:transition-colors ww:disabled:pointer-events-none ww:disabled:opacity-50",t==="default"&&"ww:bg-primary ww:text-primary-foreground ww:hover:bg-primary/90",t==="outline"&&"ww:border ww:border-border ww:bg-background ww:hover:bg-accent ww:hover:text-accent-foreground",t==="ghost"&&"ww:hover:bg-accent ww:hover:text-accent-foreground",a==="default"&&"ww:h-9 ww:px-4 ww:py-2 ww:text-sm",a==="sm"&&"ww:h-8 ww:px-3 ww:text-xs",a==="icon"&&"ww:size-9 ww:!rounded-full",a==="icon-sm"&&"ww:size-7 ww:!rounded-full",e),...r});var ik=z(he(),1);var bt=z(re(),1),lk=({files:e,className:t,...a})=>e.length===0?null:(0,bt.jsx)("div",{className:q("ww:flex ww:flex-wrap ww:gap-1.5",t),...a,children:e.map((n,r)=>(0,bt.jsx)(w3,{file:n},r))});function w3({file:e}){let{t}=ke();return e.mediaType?.startsWith("image/")&&e.url?(0,bt.jsx)("img",{src:e.url,alt:e.filename??t.attachments.attachmentFallback,className:"ww:h-16 ww:max-w-32 ww:rounded ww:object-cover"}):(0,bt.jsxs)("span",{className:"ww:inline-flex ww:items-center ww:gap-1.5 ww:rounded ww:bg-background/20 ww:px-2 ww:py-1 ww:text-xs",children:[(0,bt.jsx)(ll,{className:"ww:size-3 ww:shrink-0"}),(0,bt.jsx)("span",{className:"ww:max-w-24 ww:truncate",children:e.filename??t.attachments.fileFallback})]})}function sk(e,t){return e.startsWith("image/")?t.attachments.kindImage:e==="application/pdf"?t.attachments.kindPdf:t.attachments.kindFile}function y3({mediaType:e}){return e.startsWith("image/")?(0,bt.jsx)(nu,{className:"ww:size-5 ww:text-muted-foreground"}):e==="application/pdf"?(0,bt.jsx)(tu,{className:"ww:size-5 ww:text-muted-foreground"}):(0,bt.jsx)(ll,{className:"ww:size-5 ww:text-muted-foreground"})}function tw({filename:e,mediaType:t,previewUrl:a,subtitle:n,tone:r="default",children:o,className:i}){let{t:l}=ke(),s=sk(t,l);return(0,bt.jsxs)("li",{"aria-label":`${e}, ${s}`,className:q("ww:relative ww:flex ww:w-60 ww:max-w-full ww:cursor-default ww:items-center ww:gap-2.5 ww:overflow-hidden ww:rounded-xl ww:border ww:bg-background ww:p-2.5",r==="error"?"ww:border-destructive/50":"ww:border-border",i),children:[(0,bt.jsx)("span",{className:"ww:flex ww:size-10 ww:shrink-0 ww:items-center ww:justify-center ww:overflow-hidden ww:rounded-xl ww:bg-muted",children:a?(0,bt.jsx)("img",{alt:"",className:"ww:size-full ww:object-cover ww:object-center",src:a}):(0,bt.jsx)(y3,{mediaType:t})}),(0,bt.jsxs)("span",{className:"ww:flex ww:min-w-0 ww:flex-col",children:[(0,bt.jsx)("span",{className:"ww:truncate ww:font-medium ww:text-sm",title:e,children:e}),(0,bt.jsx)("span",{className:q("ww:truncate ww:text-xs",r==="error"?"ww:text-destructive":"ww:text-muted-foreground"),children:n??s})]}),o]})}function uk(e){if(typeof e!="object"||e===null)return[];let t=e.documents;return Array.isArray(t)?t.filter(a=>typeof a=="object"&&a!==null&&typeof a.documentId=="string"&&typeof a.filename=="string"&&typeof a.mediaType=="string"):[]}var ck=({documents:e,className:t,...a})=>e.length===0?null:(0,bt.jsx)("ul",{className:q("ww:flex ww:list-none ww:flex-wrap ww:items-end ww:justify-end ww:gap-2 ww:p-0",t),...a,children:e.map((n,r)=>(0,bt.jsx)(x3,{document:n},`${n.documentId}-${r}`))});function x3({document:e}){let{t}=ke(),[a,n]=(0,ik.useState)(!1),r=e.mediaType.startsWith("image/")?rk(e.documentId):void 0;return r&&!a?(0,bt.jsx)("li",{children:(0,bt.jsx)("img",{alt:`${e.filename}, ${sk(e.mediaType,t)}`,className:"ww:max-h-80 ww:max-w-72 ww:rounded-xl ww:border ww:border-border ww:object-contain",onError:()=>n(!0),src:r,title:e.filename})}):(0,bt.jsx)(tw,{filename:e.filename,mediaType:e.mediaType})}var ht=z(re(),1),v3=async e=>{try{let a=await(await fetch(e)).blob();return new Promise(n=>{let r=new FileReader;r.onloadend=()=>n(r.result),r.onerror=()=>n(null),r.readAsDataURL(a)})}catch{return null}},b3=(e,t)=>{if(!t)return!0;let a=t.split(",").map(o=>o.trim().toLowerCase()).filter(Boolean);if(a.length===0)return!0;let n=e.type.toLowerCase(),r=e.name.toLowerCase();return a.some(o=>o.startsWith(".")?r.endsWith(o):o.endsWith("/*")?n.startsWith(o.slice(0,-1)):n===o)},fk=(0,Ie.createContext)(null),rf=()=>{let e=(0,Ie.useContext)(fk);if(!e)throw new Error("usePromptInputAttachments must be used within a PromptInput");return e},pk=({className:e,accept:t,multiple:a,globalDrop:n,maxFiles:r,maxFileSize:o,maxPdfPages:i,attachmentsEnabled:l=!0,upload:s,onDiscard:u,onError:c,onSubmit:d,children:f,...p})=>{let{t:m,locale:x}=ke(),S=(0,Ie.useRef)(null),w=(0,Ie.useRef)(null),[y,h]=(0,Ie.useState)([]),b=(0,Ie.useRef)(y),T=(0,Ie.useRef)(new Map),C=(0,Ie.useRef)(s),M=(0,Ie.useRef)(c),R=(0,Ie.useRef)(u);(0,Ie.useEffect)(()=>{C.current=s,M.current=c,R.current=u},[s,c,u]);let P=(0,Ie.useCallback)(v=>{b.current=v,h(v)},[]),L=(0,Ie.useCallback)(()=>{S.current?.click()},[]),$=(0,Ie.useCallback)((v,K)=>{P(b.current.map(ee=>ee.id===v?{...ee,...K}:ee))},[P]),H=(0,Ie.useCallback)((v,K)=>{let ee=C.current;if(!ee)return;let we=new AbortController,We=ee(K,we.signal,me=>{$(v,{progress:me})}).then(me=>($(v,{status:"ready",progress:1,documentId:me.documentId,error:void 0}),me)).catch(me=>{if(we.signal.aborted)return null;let be=me instanceof Error?me.message:m.promptInput.uploadFailed;return $(v,{status:"failed",error:be}),M.current?.({code:"upload_failed",message:be}),null});T.current.set(v,{file:K,controller:we,done:We})},[$,m]),F=(0,Ie.useCallback)(v=>{let K=[...v];if(!l||K.length===0)return;let ee=(de,Q)=>M.current?.({code:de,message:Q}),we=[];for(let de of K){if(!b3(de,t)){ee("accept",m.promptInput.errorAccept.replace("{name}",de.name));continue}if(o&&de.size>o){ee("max_file_size",m.promptInput.errorTooLarge.replace("{name}",de.name).replace("{limit}",mk(o,x)));continue}we.push(de)}if(we.length===0)return;let We=typeof r=="number"?Math.max(0,r-b.current.length):void 0,me=typeof We=="number"?we.slice(0,We):we;if(me.length<we.length&&ee("max_files",m.promptInput.errorTooMany.replace("{limit}",String(r))),me.length===0)return;let be=!!C.current,le=me.map(de=>({file:de,item:{filename:de.name,id:uu(),mediaType:de.type,type:"file",url:URL.createObjectURL(de),status:be?"uploading":"ready",progress:0}}));P([...b.current,...le.map(de=>de.item)]);for(let de of le)H(de.item.id,de.file)},[r,o,t,l,H,P,m,x]),W=(0,Ie.useCallback)(v=>{let K=T.current.get(v);K&&($(v,{status:"uploading",progress:0,error:void 0}),H(v,K.file))},[$,H]),V=(0,Ie.useCallback)((v,K)=>{T.current.get(v.id)?.controller.abort(),T.current.delete(v.id),v.url&&(!K&&!!v.documentId&&!!v.mediaType?.startsWith("image/")&&v.documentId?nk(v.documentId,v.url):URL.revokeObjectURL(v.url)),K&&v.documentId&&R.current?.({documentId:v.documentId,filename:v.filename??"",mediaType:v.mediaType??""})},[]),N=(0,Ie.useCallback)(v=>{let K=b.current.find(ee=>ee.id===v);K&&V(K,!0),P(b.current.filter(ee=>ee.id!==v))},[V,P]),D=(0,Ie.useCallback)(()=>{for(let v of b.current)V(v,!0);P([])},[V,P]),G=(0,Ie.useRef)(l);(0,Ie.useEffect)(()=>{let v=G.current;G.current=l,v&&!l&&D()},[l,D]);let ue=(0,Ie.useCallback)(()=>{for(let v of b.current)V(v,!1);P([])},[V,P]);(0,Ie.useEffect)(()=>()=>{for(let v of b.current)T.current.get(v.id)?.controller.abort(),v.url&&URL.revokeObjectURL(v.url)},[]);let I=(0,Ie.useCallback)(v=>{v.currentTarget.files&&F(v.currentTarget.files),v.currentTarget.value=""},[F]);(0,Ie.useEffect)(()=>{if(!n)return;let v=ee=>{ee.dataTransfer?.types?.includes("Files")&&ee.preventDefault()},K=ee=>{ee.dataTransfer?.types?.includes("Files")&&ee.preventDefault(),ee.dataTransfer?.files&&ee.dataTransfer.files.length>0&&F(ee.dataTransfer.files)};return document.addEventListener("dragover",v),document.addEventListener("drop",K),()=>{document.removeEventListener("dragover",v),document.removeEventListener("drop",K)}},[F,n]);let Ve=(0,Ie.useCallback)(async v=>{v.preventDefault();let K=v.currentTarget,ee=new FormData(K).get("message")||"",we=new Map;for(;we.size<T.current.size;)await Promise.all([...T.current.entries()].filter(([le])=>!we.has(le)).map(async([le,de])=>{we.set(le,await de.done)}));for(let le of we.keys())T.current.has(le)||we.delete(le);if([...we.values()].some(le=>le===null)){M.current?.({code:"upload_failed",message:m.promptInput.uploadFailed});return}let We=[...we.values()].filter(le=>le!==null),me=C.current?[]:b.current,be=await Promise.all(me.map(async({id:le,status:de,progress:Q,error:Be,...qe})=>{if(qe.url?.startsWith("blob:")){let _e=await v3(qe.url);return{...qe,url:_e??qe.url}}return qe}));try{let le=d({documents:We,files:be,text:ee},v);le instanceof Promise&&await le,K.reset(),ue()}catch{}},[d,ue,m]),et=(0,Ie.useMemo)(()=>({add:F,clear:D,files:y,openFileDialog:L,remove:N,retry:W,maxFileSize:o,maxPdfPages:i}),[y,F,N,W,D,L,o,i]);return(0,ht.jsxs)(fk.Provider,{value:et,children:[(0,ht.jsx)("input",{accept:t,"aria-label":m.promptInput.uploadFiles,className:"ww:hidden",multiple:a,onChange:I,ref:S,title:m.promptInput.uploadFiles,type:"file"}),(0,ht.jsx)("form",{className:q("ww:relative ww:flex ww:w-full ww:flex-col ww:rounded-lg ww:border ww:border-border ww:bg-background",e),onSubmit:Ve,ref:w,...p,children:f})]})},dk=1024*1024;function mk(e,t){let a=e>=dk;return new Intl.NumberFormat(t,{style:"unit",unit:a?"megabyte":"kilobyte",maximumFractionDigits:0}).format(a?e/dk:Math.max(1,e/1024))}var hk=({onChange:e,onKeyDown:t,className:a,placeholder:n,...r})=>{let{t:o}=ke(),i=rf(),[l,s]=(0,Ie.useState)(!1),u=n??o.promptInput.placeholder,c=(0,Ie.useCallback)(f=>{if(t?.(f),!f.defaultPrevented){if(f.key==="Enter"){if(l||f.nativeEvent.isComposing||f.shiftKey)return;f.preventDefault();let{form:p}=f.currentTarget;if(p?.querySelector('[data-submit-blocked="true"]')||p?.querySelector('button[type="submit"]')?.disabled)return;p?.requestSubmit()}if(f.key==="Backspace"&&f.currentTarget.value===""&&i.files.length>0){f.preventDefault();let p=i.files.at(-1);p&&i.remove(p.id)}}},[t,l,i]),d=(0,Ie.useCallback)(f=>{let p=f.clipboardData?.items;if(!p)return;let m=[];for(let x of p)if(x.kind==="file"){let S=x.getAsFile();S&&m.push(S)}m.length>0&&(f.preventDefault(),i.add(m))},[i]);return(0,ht.jsx)("textarea",{className:q("ww:field-sizing-content ww:max-h-48 ww:min-h-0 ww:w-full ww:resize-none ww:border-0 ww:bg-transparent ww:px-3 ww:py-2 ww:text-base ww:sm:text-sm ww:outline-none ww:placeholder:text-muted-foreground",a),name:"message",onCompositionEnd:()=>s(!1),onCompositionStart:()=>s(!0),onKeyDown:c,onPaste:d,placeholder:u,onChange:e,...r})},gk=({className:e,status:t,onStop:a,onClick:n,children:r,disabled:o,...i})=>{let{t:l}=ke(),s=t==="submitted"||t==="streaming",u=s&&a!==void 0,c=(0,ht.jsx)(Nn,{className:"ww:size-4"});t==="submitted"?c=(0,ht.jsx)(ru,{className:"ww:size-4 ww:animate-spin"}):t==="streaming"&&(c=(0,ht.jsx)(ou,{className:"ww:size-4"}));let d=(0,Ie.useCallback)(f=>{if(s&&a){f.preventDefault(),a();return}n?.(f)},[s,a,n]);return(0,ht.jsx)(Bn,{"aria-label":s?l.promptInput.stop:l.promptInput.submit,className:q("ww:bg-foreground ww:text-background ww:hover:bg-foreground ww:rounded-full",e),"data-submit-blocked":o?"true":void 0,disabled:u?!1:o,onClick:d,size:"icon-sm",type:u?"button":"submit",variant:"ghost",...i,children:r??c})},wk=({className:e,children:t,...a})=>{let{t:n,locale:r}=ke(),o=rf();if(o.files.length>0)return(0,ht.jsxs)(Bn,{className:q("ww:group ww:relative",e),onClick:()=>o.clear(),size:"icon-sm",type:"button",variant:"ghost","aria-label":n.promptInput.removeAttachments,...a,children:[(0,ht.jsx)("span",{className:"ww:flex ww:size-5 ww:items-center ww:justify-center ww:rounded-full ww:bg-primary ww:text-[10px] ww:font-medium ww:text-primary-foreground ww:transition-opacity ww:group-hover:opacity-0",children:o.files.length}),(0,ht.jsx)(Ga,{className:"ww:absolute ww:size-4 ww:opacity-0 ww:transition-opacity ww:group-hover:opacity-100"})]});let l=o.maxFileSize?(o.maxPdfPages?n.promptInput.uploadFilesUpToWithPages.replace("{pages}",String(o.maxPdfPages)):n.promptInput.uploadFilesUpTo).replace("{limit}",mk(o.maxFileSize,r)):n.promptInput.uploadFiles;return(0,ht.jsx)(Bn,{"aria-label":l,className:q(e),title:l,onClick:()=>o.openFileDialog(),size:"icon-sm",type:"button",variant:"ghost",...a,children:t??(0,ht.jsx)(sl,{className:"ww:size-4"})})},yk=({className:e,...t})=>{let a=rf();return a.files.length===0?null:(0,ht.jsx)("ul",{className:q("ww:flex ww:list-none ww:flex-wrap ww:gap-2 ww:p-0",e),...t,children:a.files.map(n=>(0,ht.jsx)(S3,{file:n},n.id))})};function S3({file:e}){let{t}=ke(),a=rf(),n=e.status==="failed",r=e.status==="uploading";return(0,ht.jsxs)(tw,{filename:e.filename??t.attachments.fileFallback,mediaType:e.mediaType??"",previewUrl:e.mediaType?.startsWith("image/")?e.url:void 0,subtitle:n?e.error:r?t.promptInput.uploading:void 0,tone:n?"error":"default",children:[n?(0,ht.jsx)("button",{"aria-label":t.promptInput.retryUpload,className:"ww:ml-auto ww:shrink-0 ww:text-destructive ww:text-xs ww:underline ww:underline-offset-2",onClick:()=>a.retry(e.id),type:"button",children:t.promptInput.retry}):null,(0,ht.jsx)("button",{"aria-label":t.promptInput.removeAttachment,className:q("ww:shrink-0 ww:rounded-full ww:p-1 ww:opacity-60 ww:transition-opacity hover:ww:bg-muted hover:ww:opacity-100",n?null:"ww:ml-auto"),onClick:()=>a.remove(e.id),type:"button",children:(0,ht.jsx)(Ga,{className:"ww:size-3.5"})}),r?(0,ht.jsx)("span",{"aria-hidden":!0,className:"ww:absolute ww:bottom-0 ww:left-0 ww:h-0.5 ww:bg-primary ww:transition-[width] ww:duration-200",style:{width:`${Math.round(e.progress*100)}%`}}):null]})}var xk=({enabled:e=!0})=>{let{t}=ke(),[a,n]=(0,Ie.useState)(!1);return(0,Ie.useEffect)(()=>{if(!e)return;let r=0,o=u=>!!u.dataTransfer?.types?.includes("Files"),i=u=>{o(u)&&(r+=1,n(!0))},l=u=>{o(u)&&(r=Math.max(0,r-1),r===0&&n(!1))},s=()=>{r=0,n(!1)};return document.addEventListener("dragenter",i),document.addEventListener("dragleave",l),document.addEventListener("drop",s),()=>{document.removeEventListener("dragenter",i),document.removeEventListener("dragleave",l),document.removeEventListener("drop",s)}},[e]),e&&a?(0,ht.jsx)("div",{className:"ww:pointer-events-none ww:absolute ww:inset-0 ww:z-50 ww:flex ww:items-center ww:justify-center ww:rounded-2xl ww:border-2 ww:border-primary ww:border-dashed ww:bg-background/85",children:(0,ht.jsxs)("span",{className:"ww:flex ww:items-center ww:gap-2 ww:text-sm ww:font-medium",children:[(0,ht.jsx)(sl,{className:"ww:size-4"}),t.promptInput.dropToAttach]})}):null};var bk=z(re(),1);function vk({text:e}){let{t}=ke();return e===!1?null:(0,bk.jsx)("span",{className:"ww:whitespace-nowrap ww:text-[10px] ww:sm:text-[11px] ww:text-muted-foreground ww:opacity-70",children:e||t.aiDisclaimer.default})}var of=z(he(),1);var qo=z(re(),1),Sk=({className:e,...t})=>(0,qo.jsx)("div",{className:q("ww:flex ww:flex-col ww:gap-1 ww:px-3 ww:py-2",e),...t}),Ik=({className:e,...t})=>(0,qo.jsx)("li",{className:q("ww:group ww:flex ww:items-center ww:gap-2 ww:rounded-md ww:px-2 ww:py-1 ww:text-sm ww:transition-colors ww:hover:bg-muted",e),...t}),Ck=({className:e,...t})=>(0,qo.jsx)("span",{className:q("ww:inline-block ww:size-2 ww:shrink-0 ww:rounded-full ww:border ww:border-muted-foreground/50",e),...t}),kk=({className:e,...t})=>(0,qo.jsx)("span",{className:q("ww:line-clamp-1 ww:grow ww:break-words ww:text-muted-foreground",e),...t}),Tk=({className:e,...t})=>(0,qo.jsx)("div",{className:q("ww:flex ww:shrink-0 ww:gap-1 ww:opacity-0 ww:transition-opacity ww:group-hover:opacity-100",e),...t}),Lk=({className:e,...t})=>(0,qo.jsx)(Bn,{className:q("ww:size-auto ww:rounded ww:p-1 ww:text-muted-foreground ww:hover:bg-muted-foreground/10 ww:hover:text-foreground",e),size:"icon",type:"button",variant:"ghost",...t});var sn=z(re(),1),Ek=(0,of.memo)(({message:e,onRemove:t})=>{let{t:a}=ke(),n=(0,of.useCallback)(()=>t(e.id),[t,e.id]);return(0,sn.jsxs)(Ik,{children:[(0,sn.jsx)(Ck,{}),(0,sn.jsx)(kk,{children:e.text||a.chatQueue.attachmentFallback}),(0,sn.jsx)(Tk,{children:(0,sn.jsx)(Lk,{"aria-label":a.chatQueue.removeFromQueue,onClick:n,children:(0,sn.jsx)(Ga,{className:"ww:size-3"})})})]})});Ek.displayName="ChatQueueItem";function Mk({queuedMessages:e,onRemove:t,className:a}){let{t:n}=ke();return e.length===0?null:(0,sn.jsxs)(Sk,{className:q("ww:border-t ww:border-border",a),children:[(0,sn.jsx)("div",{className:"ww:text-[11px] ww:font-medium ww:text-muted-foreground ww:px-2",children:n.chatQueue.queued(e.length)}),(0,sn.jsx)("ul",{children:e.map(r=>(0,sn.jsx)(Ek,{message:r,onRemove:t},r.id))})]})}var _a=z(he(),1);var St=z(he(),1);cp();var l2=z(he(),1);var s2=z(re(),1),H6=({as:e="span",className:t,duration:a=2,style:n,children:r,...o})=>{let i={backgroundImage:"linear-gradient(90deg, var(--ww-color-muted-foreground) 0%, var(--ww-color-muted-foreground) 40%, var(--ww-color-foreground) 50%, var(--ww-color-muted-foreground) 60%, var(--ww-color-muted-foreground) 100%)",backgroundSize:"250% 100%",WebkitBackgroundClip:"text",backgroundClip:"text",color:"transparent",animation:`ww-shimmer ${a}s linear infinite`,...n};return(0,s2.jsx)(e,{"data-waniwani-shimmer":"",className:q("ww:inline-block",t),style:i,...o,children:r})},Tn=(0,l2.memo)(H6);Tn.displayName="Shimmer";var ua=z(re(),1),u2=(0,St.createContext)(null);function c2(){let e=(0,St.useContext)(u2);if(!e)throw new Error("Reasoning components must be used within <Reasoning>");return e}var j6=1e3,V6=1e3,Bu=(0,St.memo)(({className:e,isStreaming:t=!1,open:a,defaultOpen:n,onOpenChange:r,duration:o,children:i,...l})=>{let s=n??t,u=n===!1,c=a!==void 0,[d,f]=(0,St.useState)(s),p=c?a:d,m=(0,St.useCallback)(M=>{c||f(M),r?.(M)},[c,r]),[x,S]=(0,St.useState)(void 0),w=o??x,y=(0,St.useRef)(t),[h,b]=(0,St.useState)(!1),T=(0,St.useRef)(null);(0,St.useEffect)(()=>{t?(y.current=!0,T.current===null&&(T.current=Date.now())):T.current!==null&&(S(Math.ceil((Date.now()-T.current)/V6)),T.current=null)},[t]),(0,St.useEffect)(()=>{t&&!p&&!u&&m(!0)},[t,p,u,m]),(0,St.useEffect)(()=>{if(y.current&&!t&&p&&!h){let M=setTimeout(()=>{m(!1),b(!0)},j6);return()=>clearTimeout(M)}},[t,p,h,m]);let C=(0,St.useMemo)(()=>({isStreaming:t,isOpen:p,setIsOpen:m,duration:w}),[t,p,m,w]);return(0,ua.jsx)(u2.Provider,{value:C,children:(0,ua.jsx)("div",{className:q("ww:mb-4 ww:flex ww:flex-col ww:gap-2",e),"data-state":p?"open":"closed",style:{animation:"ww-fade-in 0.2s ease-out"},...l,children:i})})});Bu.displayName="Reasoning";var Uu=(0,St.memo)(({className:e,children:t,getThinkingMessage:a,hideIcon:n=!1,onClick:r,...o})=>{let{t:i}=ke(),{isStreaming:l,isOpen:s,duration:u,setIsOpen:c}=c2(),f=a??((p,m)=>p||m===0?(0,ua.jsx)(Tn,{duration:1.6,children:i.reasoning.thinking}):m===void 0?(0,ua.jsx)("span",{children:i.reasoning.thoughtBrief}):(0,ua.jsx)("span",{children:i.reasoning.thoughtForSeconds(m)}));return(0,ua.jsx)("button",{type:"button","aria-expanded":s,onClick:p=>{c(!s),r?.(p)},className:q("ww:flex ww:w-full ww:items-center ww:gap-2 ww:text-sm ww:text-muted-foreground ww:transition-colors ww:hover:text-foreground",e),...o,children:t??(0,ua.jsxs)(ua.Fragment,{children:[!n&&(0,ua.jsx)(fr,{className:"ww:size-4 ww:shrink-0"}),f(l,u)]})})});Uu.displayName="ReasoningTrigger";var Fu=(0,St.memo)(({className:e,children:t,...a})=>{let{isOpen:n}=c2();return(0,ua.jsx)("div",{className:q("ww:grid ww:transition-[grid-template-rows,opacity] ww:duration-200 ww:ease-out",n?"ww:grid-rows-[1fr] ww:opacity-100":"ww:grid-rows-[0fr] ww:opacity-0"),children:(0,ua.jsx)("div",{className:"ww:min-h-0 ww:overflow-hidden",children:(0,ua.jsx)("div",{className:q("ww:text-sm ww:text-muted-foreground",e),...a,children:(0,ua.jsx)(Ll,{children:t})})})})});Fu.displayName="ReasoningContent";var Ne=z(re(),1),W6=500,d2=(0,_a.createContext)(null);function f2(){let e=(0,_a.useContext)(d2);if(!e)throw new Error("ChainOfThought components must be used within <ChainOfThought>");return e}function p2({className:e,isWorking:t=!1,activeStep:a,open:n,defaultOpen:r=!1,onOpenChange:o,children:i,...l}){let s=n!==void 0,[u,c]=(0,_a.useState)(r),d=s?n:u,f=(0,_a.useCallback)(S=>{s||c(S),o?.(S)},[s,o]),[p,m]=(0,_a.useState)(!t);(0,_a.useEffect)(()=>{if(t){m(!1);return}let S=setTimeout(()=>m(!0),W6);return()=>clearTimeout(S)},[t]);let x=(0,_a.useMemo)(()=>({open:d,setOpen:f,isWorking:t,settled:p,activeStep:a}),[d,f,t,p,a]);return(0,Ne.jsx)(d2.Provider,{value:x,children:(0,Ne.jsx)("div",{className:q("ww:mb-4 ww:flex ww:flex-col ww:gap-2",e),"data-state":d?"open":"closed",style:{animation:"ww-fade-in 0.2s ease-out"},...l,children:i})})}function m2({className:e,label:t,workingLabel:a,children:n,...r}){let{open:o,setOpen:i,isWorking:l,settled:s,activeStep:u}=f2();if(!s){let c=u?.icon,d=u?.label??a??t??"";return(0,Ne.jsx)("div",{className:q("ww:flex ww:min-h-5 ww:w-full ww:items-center ww:gap-1.5 ww:text-sm ww:text-muted-foreground",e),children:(0,Ne.jsxs)("span",{className:"ww:flex ww:min-w-0 ww:items-center ww:gap-1.5",style:{animation:"ww-fade-in 0.25s ease-out"},children:[c&&(0,Ne.jsx)(c,{className:q("ww:size-4 ww:shrink-0",l&&"ww:animate-pulse")}),(0,Ne.jsx)("span",{className:"ww:truncate",children:l?(0,Ne.jsx)(Tn,{duration:2.6,children:d}):d})]},d)})}return(0,Ne.jsxs)("button",{type:"button",onClick:()=>i(!o),"aria-expanded":o,className:q("ww:flex ww:min-h-5 ww:w-full ww:items-center ww:gap-1.5 ww:text-sm ww:text-muted-foreground ww:transition-colors ww:hover:text-foreground",e),style:{animation:"ww-fade-in 0.25s ease-out"},...r,children:[(0,Ne.jsx)("span",{className:"ww:truncate",children:n??t}),(0,Ne.jsx)(Qr,{className:q("ww:size-4 ww:shrink-0 ww:transition-transform ww:duration-200",o&&"ww:rotate-180")})]})}function h2({className:e,children:t,...a}){let{open:n}=f2();return(0,Ne.jsx)("div",{className:q("ww:grid ww:transition-[grid-template-rows,opacity] ww:duration-200 ww:ease-out",n?"ww:grid-rows-[1fr] ww:opacity-100":"ww:grid-rows-[0fr] ww:opacity-0"),children:(0,Ne.jsx)("div",{className:"ww:min-h-0 ww:overflow-hidden",children:(0,Ne.jsx)("div",{className:q("ww:flex ww:flex-col",e),...a,children:t})})})}function g2({icon:e,isLast:t,running:a,error:n}){return(0,Ne.jsxs)("div",{className:"ww:flex ww:flex-col ww:items-center ww:self-stretch",children:[(0,Ne.jsx)("span",{className:"ww:flex ww:h-5 ww:items-center",children:(0,Ne.jsx)(e,{className:q("ww:size-4 ww:shrink-0",n?"ww:text-destructive":a?"ww:animate-pulse ww:text-foreground":"ww:text-muted-foreground")})}),!t&&(0,Ne.jsx)("span",{className:"ww:w-px ww:flex-1 ww:bg-border"})]})}function Mx({className:e,icon:t,title:a,state:n,isLast:r=!1,children:o,...i}){let l=n==="input-available"||n==="input-streaming",s=n==="output-error",u=o!=null,[c,d]=(0,_a.useState)(!1),f=a??"",p=l?(0,Ne.jsx)(Tn,{duration:1.6,children:f}):(0,Ne.jsx)("span",{className:"ww:truncate",children:f});return(0,Ne.jsxs)("div",{className:q("ww:flex ww:gap-2",e),...i,children:[(0,Ne.jsx)(g2,{icon:t,isLast:r,running:l,error:s}),(0,Ne.jsxs)("div",{className:q("ww:min-w-0 ww:flex-1",!r&&"ww:pb-3"),children:[u?(0,Ne.jsxs)("button",{type:"button",onClick:()=>d(m=>!m),"aria-expanded":c,className:"ww:flex ww:w-full ww:items-center ww:gap-1.5 ww:text-left ww:text-sm ww:text-muted-foreground ww:transition-colors ww:hover:text-foreground",children:[p,(0,Ne.jsx)(Qr,{className:q("ww:size-3.5 ww:shrink-0 ww:transition-transform ww:duration-200",c&&"ww:rotate-180")})]}):(0,Ne.jsx)("div",{className:"ww:flex ww:items-center ww:text-sm ww:text-muted-foreground",children:p}),u&&(0,Ne.jsx)("div",{className:q("ww:grid ww:transition-[grid-template-rows,opacity] ww:duration-200 ww:ease-out",c?"ww:grid-rows-[1fr] ww:opacity-100":"ww:grid-rows-[0fr] ww:opacity-0"),children:(0,Ne.jsx)("div",{className:"ww:min-h-0 ww:overflow-hidden",children:(0,Ne.jsx)("div",{className:"ww:mt-2 ww:space-y-3 ww:rounded-lg ww:border ww:border-border ww:bg-background ww:p-3",children:o})})})]})]})}function w2({isStreaming:e=!1,isLast:t=!1,children:a}){return(0,Ne.jsxs)("div",{className:"ww:flex ww:gap-2",children:[(0,Ne.jsx)(g2,{icon:fr,isLast:t,running:e}),(0,Ne.jsx)("div",{className:q("ww:min-w-0 ww:flex-1",!t&&"ww:pb-3"),children:(0,Ne.jsxs)(Bu,{isStreaming:e,className:"ww:mb-0",children:[(0,Ne.jsx)(Uu,{hideIcon:!0}),(0,Ne.jsx)(Fu,{children:a})]})})]})}var Ax={name:"cjk-noop",type:"cjk",remarkPluginsBefore:[],remarkPluginsAfter:[],remarkPlugins:[]};var y2={name:"shiki-noop",type:"code-highlighter",supportsLanguage:()=>!1,getSupportedLanguages:()=>[],getThemes:()=>["github-light","github-dark"],highlight:()=>null};var b2=z(he(),1);var vr=z(he(),1),G6=5,x2=400;function v2(e,t,a={}){let{msPerChar:n=G6}=a,[r,o]=(0,vr.useState)(t?"":e),i=(0,vr.useRef)(e),l=(0,vr.useRef)(t?0:e.length),s=(0,vr.useRef)(0),u=(0,vr.useRef)(null);return(e.length<l.current||!e.startsWith(r.slice(0,l.current)))&&(l.current=t?0:e.length),i.current=e,(0,vr.useEffect)(()=>{if(!t){u.current!==null&&(cancelAnimationFrame(u.current),u.current=null),l.current=e.length,o(e);return}if(i.current.length-l.current>x2&&(l.current=i.current.length-x2),u.current!==null)return;let d=f=>{let p=i.current;if(l.current>=p.length){u.current=null;return}s.current===0&&(s.current=f);let m=f-s.current;if(m>=n){let x=Math.min(Math.floor(m/n),p.length-l.current);l.current+=x,o(p.slice(0,l.current)),s.current=f}u.current=requestAnimationFrame(d)};return u.current=requestAnimationFrame(d),()=>{u.current!==null&&(cancelAnimationFrame(u.current),u.current=null)}},[e,t,n]),r}var zu=z(re(),1),Rx=({className:e,from:t,children:a,...n})=>(0,zu.jsx)("div",{className:q("ww-message ww:group ww:flex ww:w-full",t==="user"?"ww-message-user is-user ww:ml-auto ww:flex-col ww:items-end ww:[max-width:var(--ww-msg-max-width,80%)]":"ww-message-assistant is-assistant ww:flex-col",e),...n,children:(0,zu.jsx)("div",{className:q("ww:flex ww:min-w-0 ww:flex-col ww:gap-2","ww:w-full"),children:a})}),Dx=({children:e,className:t,...a})=>(0,zu.jsx)("div",{className:q("ww-bubble ww:flex ww:w-fit ww:min-w-0 ww:max-w-full ww:flex-col ww:gap-2 ww:overflow-hidden","ww:[font-size:var(--ww-font-size,1rem)] ww:[line-height:var(--ww-line-height,1.5)]","ww:group-[.is-user]:ml-auto ww:group-[.is-user]:bg-user-bubble ww:group-[.is-user]:[color:var(--ww-color-user-bubble-text)] ww:group-[.is-user]:[border-radius:var(--ww-msg-radius,8px)] ww:group-[.is-user]:[padding:var(--ww-msg-pad-y,12px)_var(--ww-msg-pad-x,16px)]","ww:group-[.is-assistant]:text-foreground",t),...a,children:e}),$6={cjk:Ax,code:y2},X6={cjk:Ax},K6={enabled:!1};function Y6({className:e,linkSafety:t,isStreaming:a,children:n,...r}){let i=v2(typeof n=="string"?n:"",!!a),l=typeof n=="string"?i:n;return(0,zu.jsx)(Ll,{className:q("ww:size-full ww:[&>*:first-child]:mt-0 ww:[&>*:last-child]:mb-0",e),linkSafety:t??K6,plugins:a?X6:$6,...r,children:l})}var hp=(0,b2.memo)(Y6,(e,t)=>e.children===t.children&&e.isStreaming===t.isStreaming);hp.displayName="MessageResponse";var Vt=z(he(),1);function _x(e){if(!(typeof e!="object"||e===null))return e}function S2(e){return _x(e?.ui)}function Ox(e){if(!e)return;let t=S2(e)?.resourceUri;if(typeof t=="string"&&t.length>0)return t;let a=e["ui/resourceUri"];if(typeof a=="string"&&a.length>0)return a;let n=e["openai/outputTemplate"];if(typeof n=="string"&&n.length>0)return n}function qu(e){return S2(e)?.autoHeight===!0}function Px(e){return _x(_x(e)?._meta)}var Te=z(re(),1);function Z6(e,t=80){if(e==null)return String(e);if(typeof e!="object")return String(e).slice(0,t);if(Array.isArray(e))return`Array(${e.length})`;let a=JSON.stringify(e);if(a.length<=t)return a;let n=Object.entries(e),r=[],o=t-2;for(let[i,l]of n){if(o<=8)break;let s=i.length>4?`${i.slice(0,4)}\u2026`:i,u;typeof l=="string"?u=l.length>2?`'${l.slice(0,1)}\u2026`:`'${l}'`:Array.isArray(l)?u=`Array(${l.length})`:typeof l=="object"&&l!==null?u="{\u2026}":u=String(l);let c=`${s}\u2009${u}`;r.push(c),o-=c.length+3}return`{${r.join(", ")}}`}function Q6({text:e,className:t}){let{t:a}=ke(),[n,r]=(0,Vt.useState)(!1),o=(0,Vt.useRef)(null);(0,Vt.useEffect)(()=>()=>{o.current&&clearTimeout(o.current)},[]);let i=(0,Vt.useCallback)(async l=>{l.stopPropagation();try{await navigator.clipboard.writeText(e),r(!0),o.current&&clearTimeout(o.current),o.current=setTimeout(()=>r(!1),2e3)}catch{}},[e]);return(0,Te.jsx)(Bn,{variant:"ghost",size:"sm",onClick:i,className:q("ww:h-auto ww:gap-1 ww:px-1.5 ww:py-0.5 ww:text-xs ww:text-muted-foreground ww:hover:text-foreground",t),children:n?(0,Te.jsxs)(Te.Fragment,{children:[(0,Te.jsx)(Qs,{className:"ww:size-3.5"}),(0,Te.jsx)("span",{children:a.tool.copied})]}):(0,Te.jsxs)(Te.Fragment,{children:[(0,Te.jsx)(eu,{className:"ww:size-3.5"}),(0,Te.jsx)("span",{children:a.tool.copy})]})})}function I2({data:e,label:t,className:a,...n}){let[r,o]=(0,Vt.useState)(!1),i=(0,Vt.useMemo)(()=>JSON.stringify(e,null,2),[e]),l=Z6(e);return(0,Te.jsxs)("div",{className:q("ww:rounded-lg ww:bg-tool-card",a),...n,children:[(0,Te.jsxs)("div",{className:"ww:flex ww:items-center ww:justify-between ww:px-3 ww:pt-2.5 ww:pb-1.5",children:[(0,Te.jsx)("span",{className:"ww:text-xs ww:font-medium ww:text-muted-foreground",children:t}),(0,Te.jsx)(Q6,{text:i})]}),(0,Te.jsxs)("button",{type:"button",onClick:()=>o(s=>!s),className:"ww:flex ww:w-full ww:items-start ww:gap-2 ww:px-3 ww:pb-3 ww:text-left",children:[(0,Te.jsx)(Js,{className:q("ww:mt-0.5 ww:size-3.5 ww:shrink-0 ww:text-muted-foreground ww:transition-transform ww:duration-150",r&&"ww:rotate-90")}),r?(0,Te.jsx)("pre",{className:"ww:overflow-x-auto ww:text-xs ww:font-mono ww:text-foreground ww:whitespace-pre-wrap ww:break-all",children:(0,Te.jsx)("code",{children:i})}):(0,Te.jsx)("span",{className:"ww:truncate ww:text-xs ww:font-mono ww:text-foreground/80",children:l})]})]})}var Nx=(0,Vt.createContext)({open:!1,toggle:()=>{}});function C2({className:e,defaultOpen:t=!1,children:a,...n}){let[r,o]=(0,Vt.useState)(t);return(0,Te.jsx)(Nx.Provider,{value:{open:r,toggle:()=>o(i=>!i)},children:(0,Te.jsx)("div",{className:q("ww:mb-4 ww:w-full",e),"data-state":r?"open":"closed",style:{animation:"ww-fade-in 0.2s ease-out"},...n,children:a})})}function k2({className:e,title:t,state:a,...n}){let{open:r,toggle:o}=(0,Vt.useContext)(Nx),i=a==="input-available"||a==="input-streaming",l=t??"";return(0,Te.jsxs)("button",{type:"button",onClick:o,className:q("ww:flex ww:w-full ww:items-center ww:gap-2 ww:text-sm ww:text-muted-foreground ww:transition-colors ww:hover:text-foreground",e),"aria-expanded":r,...n,children:[(0,Te.jsx)(Uo,{className:"ww:size-4 ww:shrink-0"}),(0,Te.jsx)("span",{className:"ww:truncate",children:i?(0,Te.jsx)(Tn,{duration:1.6,children:l}):l}),(0,Te.jsx)(Qr,{className:q("ww:size-4 ww:shrink-0 ww:transition-transform ww:duration-200",r&&"ww:rotate-180")})]})}function T2({className:e,title:t,state:a,...n}){let r=a==="input-available"||a==="input-streaming",o=t??"";return(0,Te.jsx)("div",{className:q("ww:mb-4 ww:flex ww:items-center ww:gap-2 ww:text-sm ww:text-muted-foreground",e),style:{animation:"ww-fade-in 0.2s ease-out"},...n,children:(0,Te.jsx)("span",{className:"ww:truncate",children:r?(0,Te.jsx)(Tn,{duration:1.6,children:o}):o})})}function L2({className:e,children:t,...a}){let{open:n}=(0,Vt.useContext)(Nx);return(0,Te.jsx)("div",{className:q("ww:grid ww:transition-[grid-template-rows,opacity] ww:duration-200 ww:ease-out",n?"ww:grid-rows-[1fr] ww:opacity-100":"ww:grid-rows-[0fr] ww:opacity-0"),children:(0,Te.jsx)("div",{className:"ww:min-h-0 ww:overflow-hidden",children:(0,Te.jsx)("div",{className:q("ww:mt-2 ww:space-y-3 ww:rounded-lg ww:border ww:border-border ww:bg-background ww:p-3",e),...a,children:t})})})}function Bx({className:e,input:t,debug:a,...n}){let{t:r}=ke(),o=(0,Vt.useMemo)(()=>{if(!a&&typeof t=="object"&&t!==null&&!Array.isArray(t)){let{_meta:i,...l}=t;return l}return t},[t,a]);return(0,Te.jsx)(I2,{data:o,label:r.tool.request,className:e,...n})}function Hu(e,t,a){if(e){let n=Ox(a?.[e]?._meta);if(n)return n}return Ox(Px(t))}function E2(e,t,a){return e&&qu(a?.[e]?._meta)?!0:qu(Px(t))}function Ux({className:e,output:t,errorText:a,debug:n,...r}){let{t:o}=ke(),i=(0,Vt.useMemo)(()=>{if(!n&&typeof t=="object"&&t!==null&&!Array.isArray(t)){let{_meta:l,...s}=t;return s}return t},[t,n]);return t||a?a?(0,Te.jsxs)("div",{className:q("ww:space-y-2",e),...r,children:[(0,Te.jsx)("h4",{className:"ww:text-xs ww:font-medium ww:uppercase ww:tracking-wide ww:text-muted-foreground",children:o.tool.error}),(0,Te.jsx)("div",{className:"ww:rounded-lg ww:bg-destructive/10 ww:p-3 ww:text-xs ww:text-destructive",children:a})]}):(0,Te.jsx)(I2,{data:i,label:o.tool.response,className:e,...r}):null}var ju=z(re(),1);function M2(e){return e.type==="text"||e.type==="reasoning"||e.type==="file"||"toolCallId"in e}function A2(e){return e.parts.some(M2)}function R2(e,t,a){if(t!=="submitted"&&t!=="streaming")return!1;let n=e[e.length-1];return!n||n.role!=="assistant"?!0:!n.parts.some(o=>!(!M2(o)||a?.ignoreToolParts&&"toolCallId"in o||a?.ignoreReasoningParts&&o.type==="reasoning"))}function D2({className:e,...t}){let{t:a}=ke();return(0,ju.jsxs)("div",{"aria-live":"polite",className:q("ww:mb-4 ww:flex ww:w-full ww:items-center ww:gap-2 ww:text-sm ww:text-muted-foreground",e),style:{animation:"ww-fade-in 0.2s ease-out"},...t,children:[(0,ju.jsx)(iu,{className:"ww:size-4 ww:shrink-0"}),(0,ju.jsx)(Tn,{duration:1.6,children:a.workingIndicator.default})]})}var Je=z(he(),1);function ii(e){if(!e)return!1;let t=Array.isArray(e.content)&&e.content.length>0,a=typeof e.structuredContent=="object"&&e.structuredContent!==null&&Object.keys(e.structuredContent).length>0;return t||a}function _2(e,t){return!ii(e)&&!ii(t)?null:ii(e)?ii(t)?{...e.content||t.content?{content:[...e.content??[],...t.content??[]]}:{},...e.structuredContent||t.structuredContent?{structuredContent:{...e.structuredContent??{},...t.structuredContent??{}}}:{}}:{...e.content?{content:[...e.content]}:{},...e.structuredContent?{structuredContent:{...e.structuredContent}}:{}}:{...t?.content?{content:[...t.content]}:{},...t?.structuredContent?{structuredContent:{...t.structuredContent}}:{}}}var br=z(he(),1);var O2=(0,br.createContext)(()=>{});function P2(){return(0,br.useContext)(O2)}var N2=O2.Provider;function J6(e){let t=window.requestIdleCallback;typeof t=="function"?t(e):setTimeout(e,500)}function El(e){let t=(0,br.useRef)(e);t.current=e;let a=(0,br.useRef)(!1);(0,br.useEffect)(()=>{if(!e.painted||a.current)return;a.current=!0;let n=requestAnimationFrame(()=>{let r=t.current;Bo(r.paintMark),J6(()=>MC(r))});return()=>cancelAnimationFrame(n)},[e.painted])}var B2=z(re(),1),e9="/api/mcp/resource",t9=500,a9=0,n9=16,r9="2026-01-26",o9=300,i9=3e3,l9=3,s9=2e3;function u9(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}function c9(e,t,a){return Hu(e,t,a)?!1:t._meta?.["waniwani/autoInjectResultText"]!==!1}function gp({resourceUri:e,toolInput:t,toolResult:a,resourceEndpoint:n=e9,chatSessionId:r,isDark:o=!1,className:i,autoHeight:l=!1,onOpenLink:s,onFollowUp:u,onCallTool:c,onDisplayModeChange:d,isFullscreen:f=!1,toolDefinitions:p}){let m=(0,Je.useRef)(null),x=(0,Je.useRef)(t),S=(0,Je.useRef)(a),w=(0,Je.useRef)({width:0,height:0}),y=(0,Je.useRef)(null),h=(0,Je.useRef)(!1),b=(0,Je.useRef)(0),T=(0,Je.useRef)("inline"),[C,M]=(0,Je.useState)(a9),[R,P]=(0,Je.useState)(void 0),L=(0,Je.useRef)(s),$=(0,Je.useRef)(u),H=(0,Je.useRef)(c),F=(0,Je.useRef)(d),W=(0,Je.useRef)(r),V=(0,Je.useRef)(p);x.current=t,S.current=a,L.current=s,$.current=u,H.current=c,F.current=d,W.current=r,V.current=p;let N=(0,Je.useCallback)(v=>l?Math.max(v+n9,0):Math.min(Math.max(v,50),t9),[l]),D=(0,Je.useMemo)(()=>{let v=n.includes("?")?"&":"?";return`${n}${v}uri=${encodeURIComponent(e)}`},[n,e]),G=P2(),ue=(0,Je.useRef)(null),I=(0,Je.useRef)(void 0);(0,Je.useEffect)(()=>{let v=RC(e,G);return ue.current=v,()=>{clearTimeout(I.current),v.has("initialized")||v.report("timeout",b.current),ue.current=null}},[e,G]);let Ve=(0,Je.useRef)(o);Ve.current=o;let et=(0,Je.useRef)(f);return(0,Je.useEffect)(()=>{et.current=f,w.current.height=-1,y.current&&(y.current.cancel(),y.current=null)},[f]),(0,Je.useEffect)(()=>{if(!h.current)return;let v=m.current;v?.contentWindow&&v.contentWindow.postMessage({jsonrpc:"2.0",method:"ui/notifications/host-context-changed",params:{theme:o?"dark":"light"}},"*")},[o]),(0,Je.useEffect)(()=>{let v=m.current;if(!v)return;let K=!1,ee=!1,we=null,We=null,me=setTimeout(()=>{if(K||ee||b.current>=l9)return;b.current+=1;let de=new URL(v.src);de.searchParams.set("_retry",String(b.current)),v.src=de.toString()},i9),be=de=>{v.contentWindow?.postMessage(de,"*")},le=de=>{if(K||de.source!==v.contentWindow)return;let Q=de.data;if(!Q||typeof Q!="object"||Q.jsonrpc!=="2.0")return;let Be=Q.method,qe=Q.id;if(Be==="ui/initialize"&&qe!=null){ee=!0,ue.current?.mark("initialize"),clearTimeout(me),be({jsonrpc:"2.0",id:qe,result:{protocolVersion:Q.params?.protocolVersion??r9,hostInfo:{name:"Waniwani Chat",version:"1.0.0"},hostCapabilities:{openLinks:{},message:{text:{}},tools:{},updateModelContext:{text:{},structuredContent:{}}},hostContext:{theme:Ve.current?"dark":"light",displayMode:T.current}}});return}if(Be==="ui/notifications/initialized"){h.current=!0,ue.current?.mark("initialized"),I.current=setTimeout(()=>ue.current?.report("ok",b.current),s9);let _e=x.current,Ce=S.current,ye=Ce._meta&&typeof Ce._meta=="object"?Ce._meta:null,Y=u9(W.current),Oe=ye&&typeof ye.waniwani=="object"&&ye.waniwani!==null?ye.waniwani:null,ot=Oe||Y?{...Oe??{},...Y?{sessionId:Y}:{}}:void 0,ba=ye||ot?{...ye??{},...ot?{waniwani:ot}:{}}:void 0;be({jsonrpc:"2.0",method:"ui/notifications/tool-input",params:{arguments:_e}});let Sa=Ce.content??[{type:"text",text:JSON.stringify(Ce)}];be({jsonrpc:"2.0",method:"ui/notifications/tool-result",params:{content:Sa,structuredContent:Ce.structuredContent,_meta:ba,meta:ba}});return}if(Be==="ui/notifications/size-changed"){clearTimeout(I.current),ue.current?.mark("firstSize"),ue.current?.report("ok",b.current);let _e=Q.params,Ce=typeof _e?.height=="number"?_e.height:void 0,ye=typeof _e?.width=="number"?_e.width:void 0,Y=w.current,Oe=Ce!==void 0&&Ce!==Y.height,ot=ye!==void 0&&ye!==Y.width;if(!Oe&&!ot)return;if(Oe&&Ce!==void 0){if(Y.height=Ce,et.current)return;let ba=N(Ce),Sa=v.getBoundingClientRect().height;if(y.current&&(y.current.cancel(),y.current=null),M(ba),v.animate&&Math.abs(Sa-ba)>2){let ra=v.animate([{height:`${Sa}px`},{height:`${ba}px`}],{duration:o9,easing:"ease-out",fill:"forwards"});y.current=ra,ra.onfinish=()=>{y.current===ra&&(ra.cancel(),y.current=null)}}}ot&&l&&ye!==void 0&&(Y.width=ye,P(ye));return}if(Be==="ui/open-link"&&qe!=null){let _e=Q.params?.url;typeof _e=="string"&&(L.current?L.current(_e):window.open(_e,"_blank","noopener,noreferrer")),be({jsonrpc:"2.0",id:qe,result:{}});return}if(Be==="ui/message"&&qe!=null){if($.current&&Q.params){let _e=Q.params,Ce=we;if(we=null,We){clearTimeout(We.timer);let ye=We.text;We=null;let Y=(_e.content??[]).map(Oe=>Oe.text??"").join("").trim();_e={..._e,content:[{type:"text",text:`${Y}
|
|
121
|
+
`||e[t]==="\r");)t-=1;return t>=1&&e[t]==="$"&&e[t-1]==="$"},bx=e=>{let t=0;for(let a=0;a<e.length-1;a+=1)e[a]==="$"&&e[a+1]==="$"&&(t+=1,a+=1);return t},r2=e=>{let t=R6.test(e),a=D6.test(e);if(t||a)return[e];let n=Xa.lex(e,{gfm:!0}),r=[],o=[];for(let i of n){let l=i.raw,s=r.length;if(o.length>0){if(r[s-1]+=l,i.type==="html"){let u=l.match(_6);if(u){let c=u[1];o.at(-1)===c&&o.pop()}}continue}if(i.type==="html"&&i.block){let u=l.match(O6);if(u){let c=u[1];l.includes(`</${c}>`)||o.push(c)}}if(l.trim()==="$$"&&s>0){let u=r[s-1],c=vx(u),d=bx(u);if(c&&d%2===1){r[s-1]=u+l;continue}}if(s>0&&P6(l)){let u=r[s-1],c=vx(u),d=bx(u),f=bx(l);if(c&&d%2===1&&!vx(l)&&f===1){r[s-1]=u+l;continue}}r.push(l)}return r},o2={raw:Uk,sanitize:[hf,{}],harden:[Nk,{allowedImagePrefixes:["*"],allowedLinkPrefixes:["*"],allowedProtocols:["*"],defaultOrigin:void 0,allowDataImages:!0}]},i2={gfm:[zf,{}]},N6=Object.values(o2),B6=Object.values(i2),U6={block:" \u258B",circle:" \u25CF"},F6={shikiTheme:["github-light","github-dark"],controls:!0,isAnimating:!1,mode:"streaming",mermaid:void 0,linkSafety:{enabled:!0}},ya=(0,_.createContext)(F6),Ex=(0,_.memo)(({content:e,shouldParseIncompleteMarkdown:t,index:a,...n})=>(0,E.jsx)(n2,{...n,children:e}),(e,t)=>{if(e.content!==t.content||e.index!==t.index)return!1;if(e.components!==t.components){let a=Object.keys(e.components||{}),n=Object.keys(t.components||{});if(a.length!==n.length||a.some(r=>{var o,i;return((o=e.components)==null?void 0:o[r])!==((i=t.components)==null?void 0:i[r])}))return!1}return!(e.rehypePlugins!==t.rehypePlugins||e.remarkPlugins!==t.remarkPlugins)});Ex.displayName="Block";z6=["github-light","github-dark"],Ll=(0,_.memo)(({children:e,mode:t="streaming",parseIncompleteMarkdown:a=!0,components:n,rehypePlugins:r=N6,remarkPlugins:o=B6,className:i,shikiTheme:l=z6,mermaid:s,controls:u=!0,isAnimating:c=!1,BlockComponent:d=Ex,parseMarkdownIntoBlocksFn:f=r2,caret:p,plugins:m,remend:x,linkSafety:S={enabled:!0},...w})=>{let y=(0,_.useId)(),[h,b]=(0,_.useTransition)(),T=(0,_.useMemo)(()=>typeof e!="string"?"":t==="streaming"&&a?YL(e,x):e,[e,t,a,x]),C=(0,_.useMemo)(()=>f(T),[T,f]),[M,R]=(0,_.useState)(C);(0,_.useEffect)(()=>{t==="streaming"?b(()=>{R(C)}):R(C)},[C,t]);let P=t==="streaming"?M:C,L=(0,_.useMemo)(()=>P.map((N,D)=>`${y}-${D}`),[P.length,y]),$=(0,_.useMemo)(()=>{var N,D;return{shikiTheme:(D=(N=m?.code)==null?void 0:N.getThemes())!=null?D:l,controls:u,isAnimating:c,mode:t,mermaid:s,linkSafety:S}},[l,u,c,t,s,S,m?.code]),H=(0,_.useMemo)(()=>({...T6,...n}),[n]),F=(0,_.useMemo)(()=>{let N=[];return m!=null&&m.cjk&&(N=[...N,...m.cjk.remarkPluginsBefore]),N=[...N,...o],m!=null&&m.cjk&&(N=[...N,...m.cjk.remarkPluginsAfter]),m!=null&&m.math&&(N=[...N,m.math.remarkPlugin]),N},[o,m?.math,m?.cjk]),W=(0,_.useMemo)(()=>m!=null&&m.math?[...r,m.math.rehypePlugin]:r,[r,m?.math]),V=(0,_.useMemo)(()=>p&&c?{"--streamdown-caret":`"${U6[p]}"`}:void 0,[p,c]);return t==="static"?(0,E.jsx)(Sx.Provider,{value:m??null,children:(0,E.jsx)(ya.Provider,{value:$,children:(0,E.jsx)("div",{className:ce("space-y-4 whitespace-normal *:first:mt-0 *:last:mb-0",i),children:(0,E.jsx)(n2,{components:H,rehypePlugins:W,remarkPlugins:F,...w,children:e})})})}):(0,E.jsx)(Sx.Provider,{value:m??null,children:(0,E.jsx)(ya.Provider,{value:$,children:(0,E.jsxs)("div",{className:ce("space-y-4 whitespace-normal *:first:mt-0 *:last:mb-0",p?"*:last:after:inline *:last:after:align-baseline *:last:after:content-(--streamdown-caret)":null,i),style:V,children:[P.length===0&&p&&c&&(0,E.jsx)("span",{}),P.map((N,D)=>(0,E.jsx)(d,{components:H,content:N,index:D,rehypePlugins:W,remarkPlugins:F,shouldParseIncompleteMarkdown:a,...w},L[D]))]})})})},(e,t)=>e.children===t.children&&e.shikiTheme===t.shikiTheme&&e.isAnimating===t.isAnimating&&e.mode===t.mode&&e.plugins===t.plugins&&e.className===t.className&&e.linkSafety===t.linkSafety);Ll.displayName="Streamdown";q6=({children:e,className:t,minZoom:a=.5,maxZoom:n=3,zoomStep:r=.1,showControls:o=!0,initialZoom:i=1,fullscreen:l=!1})=>{let s=(0,_.useRef)(null),u=(0,_.useRef)(null),[c,d]=(0,_.useState)(i),[f,p]=(0,_.useState)({x:0,y:0}),[m,x]=(0,_.useState)(!1),[S,w]=(0,_.useState)({x:0,y:0}),[y,h]=(0,_.useState)({x:0,y:0}),b=(0,_.useCallback)(H=>{d(F=>Math.max(a,Math.min(n,F+H)))},[a,n]),T=(0,_.useCallback)(()=>{b(r)},[b,r]),C=(0,_.useCallback)(()=>{b(-r)},[b,r]),M=(0,_.useCallback)(()=>{d(i),p({x:0,y:0})},[i]),R=(0,_.useCallback)(H=>{H.preventDefault();let F=H.deltaY>0?-r:r;b(F)},[b,r]),P=(0,_.useCallback)(H=>{if(H.button!==0||H.isPrimary===!1)return;x(!0),w({x:H.clientX,y:H.clientY}),h(f);let F=H.currentTarget;F instanceof HTMLElement&&F.setPointerCapture(H.pointerId)},[f]),L=(0,_.useCallback)(H=>{if(!m)return;H.preventDefault();let F=H.clientX-S.x,W=H.clientY-S.y;p({x:y.x+F,y:y.y+W})},[m,S,y]),$=(0,_.useCallback)(H=>{x(!1);let F=H.currentTarget;F instanceof HTMLElement&&F.releasePointerCapture(H.pointerId)},[]);return(0,_.useEffect)(()=>{let H=s.current;if(H)return H.addEventListener("wheel",R,{passive:!1}),()=>{H.removeEventListener("wheel",R)}},[R]),(0,_.useEffect)(()=>{let H=u.current;if(H&&m)return document.body.style.userSelect="none",H.addEventListener("pointermove",L,{passive:!1}),H.addEventListener("pointerup",$),H.addEventListener("pointercancel",$),()=>{document.body.style.userSelect="",H.removeEventListener("pointermove",L),H.removeEventListener("pointerup",$),H.removeEventListener("pointercancel",$)}},[m,L,$]),(0,E.jsxs)("div",{className:ce("relative flex flex-col",l?"h-full w-full":"min-h-28 w-full",t),ref:s,style:{cursor:m?"grabbing":"grab"},children:[o?(0,E.jsxs)("div",{className:ce("absolute z-10 flex flex-col gap-1 rounded-md border border-border bg-background/90 p-1 shadow-sm backdrop-blur-sm",l?"bottom-4 left-4":"bottom-2 left-2"),children:[(0,E.jsx)("button",{className:"flex items-center justify-center rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50",disabled:c>=n,onClick:T,title:"Zoom in",type:"button",children:(0,E.jsx)(n6,{size:16})}),(0,E.jsx)("button",{className:"flex items-center justify-center rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50",disabled:c<=a,onClick:C,title:"Zoom out",type:"button",children:(0,E.jsx)(r6,{size:16})}),(0,E.jsx)("button",{className:"flex items-center justify-center rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",onClick:M,title:"Reset zoom and pan",type:"button",children:(0,E.jsx)(a6,{size:16})})]}):null,(0,E.jsx)("div",{className:ce("flex-1 origin-center transition-transform duration-150 ease-out",l?"flex h-full w-full items-center justify-center":"flex w-full items-center justify-center"),onPointerDown:P,ref:u,role:"application",style:{transform:`translate(${f.x}px, ${f.y}px) scale(${c})`,transformOrigin:"center center",touchAction:"none",willChange:"transform"},children:e})]})},yx=({chart:e,className:t,config:a,fullscreen:n=!1,showControls:r=!0})=>{let[o,i]=(0,_.useState)(null),[l,s]=(0,_.useState)(!1),[u,c]=(0,_.useState)(""),[d,f]=(0,_.useState)(""),[p,m]=(0,_.useState)(0),{mermaid:x}=(0,_.useContext)(ya),S=Tx(),w=x?.errorComponent,{shouldRender:y,containerRef:h}=JH({immediate:n});if((0,_.useEffect)(()=>{if(y){if(!S){i("Mermaid plugin not available. Please add the mermaid plugin to enable diagram rendering.");return}(async()=>{try{i(null),s(!0);let T=S.getMermaid(a),C=e.split("").reduce((P,L)=>(P<<5)-P+L.charCodeAt(0)|0,0),M=`mermaid-${Math.abs(C)}-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,{svg:R}=await T.render(M,e);c(R),f(R)}catch(T){if(!(d||u)){let C=T instanceof Error?T.message:"Failed to render Mermaid chart";i(C)}}finally{s(!1)}})()}},[e,a,p,y,S]),!(y||u||d))return(0,E.jsx)("div",{className:ce("my-4 min-h-[200px]",t),ref:h});if(l&&!u&&!d)return(0,E.jsx)("div",{className:ce("my-4 flex justify-center p-4",t),ref:h,children:(0,E.jsxs)("div",{className:"flex items-center space-x-2 text-muted-foreground",children:[(0,E.jsx)("div",{className:"h-4 w-4 animate-spin rounded-full border-current border-b-2"}),(0,E.jsx)("span",{className:"text-sm",children:"Loading diagram..."})]})});if(o&&!u&&!d)return w?(0,E.jsx)("div",{ref:h,children:(0,E.jsx)(w,{chart:e,error:o,retry:()=>m(C=>C+1)})}):(0,E.jsxs)("div",{className:ce("rounded-lg border border-red-200 bg-red-50 p-4",t),ref:h,children:[(0,E.jsxs)("p",{className:"font-mono text-red-700 text-sm",children:["Mermaid Error: ",o]}),(0,E.jsxs)("details",{className:"mt-2",children:[(0,E.jsx)("summary",{className:"cursor-pointer text-red-600 text-xs",children:"Show Code"}),(0,E.jsx)("pre",{className:"mt-2 overflow-x-auto rounded bg-red-100 p-2 text-red-800 text-xs",children:e})]})]});let b=u||d;return(0,E.jsx)("div",{className:ce("size-full",t),"data-streamdown":"mermaid",ref:h,children:(0,E.jsx)(q6,{className:ce(n?"size-full overflow-hidden":"my-4 overflow-hidden",t),fullscreen:n,maxZoom:3,minZoom:.5,showControls:r,zoomStep:.1,children:(0,E.jsx)("div",{"aria-label":"Mermaid chart",className:ce("flex justify-center",n?"size-full items-center":null),dangerouslySetInnerHTML:{__html:b},role:"img"})})})}});var A_=oa((vse,M_)=>{"use strict";function kV(e,t){if(typeof e!="function")throw new TypeError(`Expected the first argument to be a \`function\`, got \`${typeof e}\`.`);let a,n=0;return function(...o){clearTimeout(a);let i=Date.now(),l=i-n,s=t-l;s<=0?(n=i,e.apply(this,o)):a=setTimeout(()=>{n=Date.now(),e.apply(this,o)},s)}}M_.exports=kV});var Sv=typeof performance>"u"?0:performance.now(),Iv=typeof window<"u"&&!!window.WaniWani?.chat;var di=z(he(),1),Wp=z(Og(),1);var Pg="waniwani/suggestions";function ol(e,t){for(let a of t){let n=e[a];if(typeof n=="string"&&n.length>0)return n}}var NB=["waniwani/sessionId","openai/sessionId","openai/session","sessionId","conversationId","mcp-session-id"],BB=["waniwani/requestId","openai/requestId","requestId","mcp/requestId"],UB=["waniwani/traceId","openai/traceId","traceId","mcp/traceId","openai/requestId","requestId"],FB=["waniwani/userId","openai/userId","externalUserId","userId","actorId"],zB=["waniwani/visitorId","visitorId"],qB=["correlationId","openai/requestId"];function fC(e){return e?ol(e,NB):void 0}function pC(e){return e?ol(e,BB):void 0}function mC(e){return e?ol(e,UB):void 0}function hC(e){return e?ol(e,FB):void 0}function gC(e){return e?ol(e,zB):void 0}function wC(e){return e?ol(e,qB):void 0}var HB=[{key:"openai/sessionId",source:"chatgpt"},{key:"openai/session",source:"chatgpt"}],jB=[{needle:"claude",source:"claude"},{needle:"chatgpt",source:"chatgpt"},{needle:"openai",source:"chatgpt"},{needle:"gemini",source:"gemini"}];function yC(e,t){if(e){let n=e["waniwani/source"];if(typeof n=="string"&&n.length>0)return n;for(let{key:r,source:o}of HB){let i=e[r];if(typeof i=="string"&&i.length>0)return o}}let a=t?.name;if(typeof a=="string"&&a.length>0){let n=a.toLowerCase();for(let{needle:r,source:o}of jB)if(n.includes(r))return o}}var VB="@waniwani/sdk";function xC(e,t={}){let a=t.now??(()=>new Date),n=t.generateId??WB,r=XB(e),o=jd(e.meta),i=jd(e.metadata),l=KB(e,o),s=bn(e.eventId)??n(),u=YB(e.timestamp,a),c=bn(e.source)??yC(o)??t.source??VB,d=Ng(e)?{...e}:void 0,f={...i};return Object.keys(o).length>0&&(f.meta=o),d&&(f.rawLegacy=d),{id:s,type:"mcp.event",name:r,source:c,timestamp:u,correlation:l,properties:GB(e,r),metadata:f,rawLegacy:d}}function WB(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`evt_${crypto.randomUUID()}`:`evt_${Math.random().toString(36).slice(2,10)}_${Date.now().toString(36)}`}function GB(e,t){if(!Ng(e))return jd(e.properties);let a=$B(e,t),n=jd(e.properties);return{...a,...n}}function $B(e,t){switch(t){case"tool.called":{let a={};return bn(e.toolName)&&(a.name=e.toolName),bn(e.toolType)&&(a.type=e.toolType),a}case"link.clicked":{let a={};return bn(e.linkUrl)&&(a.url=e.linkUrl),a}default:return{}}}function XB(e){return Ng(e)?e.eventType:e.event}function KB(e,t){let a=bn(e.requestId)??pC(t),n=bn(e.sessionId)??fC(t),r=bn(e.traceId)??mC(t),o=bn(e.externalUserId)??hC(t),i=bn(e.visitorId)??gC(t),l=bn(e.correlationId)??wC(t)??a,s={};return n&&(s.sessionId=n),r&&(s.traceId=r),a&&(s.requestId=a),l&&(s.correlationId=l),o&&(s.externalUserId=o),i&&(s.visitorId=i),s}function YB(e,t){if(e instanceof Date)return e.toISOString();if(typeof e=="string"){let a=new Date(e);if(!Number.isNaN(a.getTime()))return a.toISOString()}return t().toISOString()}function jd(e){return!e||typeof e!="object"||Array.isArray(e)?{}:e}function bn(e){if(typeof e=="string"&&e.trim().length!==0)return e}function Ng(e){return"eventType"in e}function vC(e){return{priceShown:({amount:t,currency:a,itemId:n,label:r,...o})=>e({event:"price_shown",properties:{amount:t,currency:a,itemId:n,label:r},...o}),pricesCompared:({options:t,...a})=>e({event:"prices_compared",properties:{options:t},...a}),optionSelected:({id:t,amount:a,currency:n,...r})=>e({event:"option_selected",properties:{id:t,amount:a,currency:n},...r}),leadQualified:t=>{let{externalId:a,email:n,name:r,...o}=t??{};return e({event:"lead_qualified",properties:{externalId:a,email:n,name:r},...o})},converted:({amount:t,currency:a,occurredAt:n,...r})=>e({event:"converted",properties:{amount:t,currency:a,occurredAt:n},...r})}}var ZB="/api/mcp/events/v2/batch";var bC="@waniwani/sdk";var QB=new Set([401,403]),JB=new Set([408,425,429,500,502,503,504]),eU=(e,t)=>globalThis.fetch(e,t);function SC(e){return new Bg(e)}var Bg=class{constructor(t){ne(this,"endpointUrl");ne(this,"flushIntervalMs");ne(this,"maxBatchSize");ne(this,"maxBufferSize");ne(this,"maxRetries");ne(this,"retryBaseDelayMs");ne(this,"retryMaxDelayMs");ne(this,"shutdownTimeoutMs");ne(this,"sdkVersion");ne(this,"fetchFn");ne(this,"logger");ne(this,"now");ne(this,"sleep");ne(this,"apiKey");ne(this,"buffer",[]);ne(this,"flushTimer");ne(this,"flushScheduled",!1);ne(this,"flushScheduledTimer");ne(this,"flushInFlight");ne(this,"inFlightCount",0);ne(this,"isStopped",!1);ne(this,"isShuttingDown",!1);this.endpointUrl=nU(t.apiUrl,t.endpointPath??ZB),this.flushIntervalMs=t.flushIntervalMs??1e3,this.maxBatchSize=t.maxBatchSize??20,this.maxBufferSize=t.maxBufferSize??1e3,this.maxRetries=t.maxRetries??3,this.retryBaseDelayMs=t.retryBaseDelayMs??200,this.retryMaxDelayMs=t.retryMaxDelayMs??2e3,this.shutdownTimeoutMs=t.shutdownTimeoutMs??2e3,this.fetchFn=t.fetchFn??eU,this.logger=t.logger??console,this.now=t.now??(()=>new Date),this.sleep=t.sleep??(a=>new Promise(n=>setTimeout(n,a))),this.apiKey=t.apiKey,this.sdkVersion=t.sdkVersion,this.flushIntervalMs>0&&(this.flushTimer=setInterval(()=>{this.flush()},this.flushIntervalMs)),this.registerBrowserTeardown()}enqueue(t){if(this.isStopped||this.isShuttingDown){this.logger.warn("[Waniwani] Tracking transport is stopped, dropping event %s",t.id);return}if(this.buffer.length>=this.maxBufferSize){let a=this.buffer.length-this.maxBufferSize+1;this.buffer.splice(0,a),this.logger.warn("[Waniwani] Tracking buffer overflow, dropped %d oldest event(s)",a)}if(this.buffer.push(t),this.buffer.length>=this.maxBatchSize){this.flush();return}this.scheduleMicroFlush()}pendingEvents(){return this.buffer.length+this.inFlightCount}async flush(){return this.flushInFlight?this.flushInFlight:(this.flushInFlight=this.flushLoop().finally(()=>{this.flushInFlight=void 0}),this.flushInFlight)}async shutdown(t){this.isShuttingDown=!0,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=void 0),this.flushScheduledTimer&&(clearTimeout(this.flushScheduledTimer),this.flushScheduledTimer=void 0,this.flushScheduled=!1);let a=t?.timeoutMs??this.shutdownTimeoutMs,n=this.flush();if(!Number.isFinite(a)||a<=0)return await n,this.isStopped=!0,{timedOut:!1,pendingEvents:this.pendingEvents()};let r=Symbol("shutdown-timeout");return await Promise.race([n.then(()=>"flushed"),this.sleep(a).then(()=>r)])===r?(this.isStopped=!0,{timedOut:!0,pendingEvents:this.pendingEvents()}):(this.isStopped=!0,{timedOut:!1,pendingEvents:this.pendingEvents()})}registerBrowserTeardown(){if(typeof document>"u"||typeof window>"u")return;let t=()=>{document.visibilityState==="hidden"&&this.keepaliveFlush()};document.addEventListener("visibilitychange",t),window.addEventListener("pagehide",()=>this.keepaliveFlush())}keepaliveFlush(){if(this.isStopped||this.buffer.length===0)return;let t=this.buffer.splice(0,this.buffer.length);this.sendKeepaliveChunk(t)}sendKeepaliveChunk(t){let a=JSON.stringify(this.makeBatchRequest(t));if(a.length>6e4&&t.length>1){let n=Math.ceil(t.length/2);this.sendKeepaliveChunk(t.slice(0,n)),this.sendKeepaliveChunk(t.slice(n));return}try{this.fetchFn(this.endpointUrl,{method:"POST",headers:this.requestHeaders(),body:a,keepalive:!0}).catch(()=>{})}catch{}}requestHeaders(){let t={"Content-Type":"application/json","X-WaniWani-SDK":bC};return this.apiKey&&(t.Authorization=`Bearer ${this.apiKey}`),t}scheduleMicroFlush(){this.flushScheduled||(this.flushScheduled=!0,this.flushScheduledTimer=setTimeout(()=>{this.flushScheduledTimer=void 0,this.flushScheduled=!1,this.flush()},0))}async flushLoop(){for(;this.buffer.length>0&&!this.isStopped;){let t=this.buffer.splice(0,this.maxBatchSize);await this.sendBatchWithRetry(t)}}async sendBatchWithRetry(t){let a=0,n=t;for(;n.length>0&&!this.isStopped;){this.inFlightCount=n.length;let r=await this.sendBatchOnce(n);switch(this.inFlightCount=0,r.kind){case"success":return;case"auth":this.stopTransportForAuthFailure(r.status,n.length);return;case"permanent":this.logger.error("[Waniwani] Dropping %d event(s) after permanent failure: %s",n.length,r.reason);return;case"retryable":if(a>=this.maxRetries){this.logger.error("[Waniwani] Dropping %d event(s) after retry exhaustion: %s",n.length,r.reason);return}await this.sleep(this.backoffDelayMs(a)),a+=1;continue;case"partial":if(r.permanent.length>0&&this.logger.error("[Waniwani] Dropping %d event(s) rejected as permanent",r.permanent.length),r.retryable.length===0)return;if(a>=this.maxRetries){this.logger.error("[Waniwani] Dropping %d retryable event(s) after retry exhaustion",r.retryable.length);return}n=r.retryable,await this.sleep(this.backoffDelayMs(a)),a+=1;continue}}}async sendBatchOnce(t){let a;try{a=await this.fetchFn(this.endpointUrl,{method:"POST",headers:this.requestHeaders(),body:JSON.stringify(this.makeBatchRequest(t))})}catch(o){return{kind:"retryable",reason:rU(o)}}if(QB.has(a.status))return{kind:"auth",status:a.status};if(JB.has(a.status))return{kind:"retryable",reason:`HTTP ${a.status}`};if(!a.ok)return{kind:"permanent",reason:`HTTP ${a.status}`};let n=await aU(a);if(!n?.rejected||n.rejected.length===0)return{kind:"success"};let r=this.classifyRejectedEvents(t,n.rejected);return r.retryable.length===0&&r.permanent.length===0?{kind:"success"}:{kind:"partial",retryable:r.retryable,permanent:r.permanent}}makeBatchRequest(t){return{sentAt:this.now().toISOString(),source:{sdk:bC,version:this.sdkVersion??"0.0.0"},events:t}}classifyRejectedEvents(t,a){let n=new Map(t.map(i=>[i.id,i])),r=[],o=[];for(let i of a){let l=n.get(i.eventId);if(l){if(tU(i)){r.push(l);continue}o.push(l)}}return{retryable:r,permanent:o}}backoffDelayMs(t){let a=this.retryBaseDelayMs*2**t;return Math.min(a,this.retryMaxDelayMs)}stopTransportForAuthFailure(t,a){this.isStopped=!0;let n=this.buffer.length;this.buffer.splice(0,n),this.logger.error("[Waniwani] Auth failure (HTTP %d). Stopping tracking transport and dropping %d queued event(s)",t,a+n)}};function tU(e){if(e.retryable===!0)return!0;let t=e.code.toLowerCase();return t.includes("timeout")||t.includes("temporary")||t.includes("unavailable")||t.includes("rate_limit")||t.includes("transient")||t.includes("server")}async function aU(e){let t=await e.text();if(t)try{return JSON.parse(t)}catch{return}}function nU(e,t){let a=e.endsWith("/")?e:`${e}/`,n=t.startsWith("/")?t.slice(1):t;return`${a}${n}`}function rU(e){return e instanceof Error?e.message:String(e)}function IC(e){let{apiUrl:t,endpointPath:a}=oU(e.endpoint),n=SC({apiUrl:t,apiKey:e.token,endpointPath:a,flushIntervalMs:e.flushIntervalMs}),r,o=l=>typeof l=="function"?l():l,i=async l=>{let s=e.identity?.()??{},u=o(e.channelId),c=u===void 0?l.properties:{channelId:u,...l.properties},d=xC({sessionId:s.sessionId,visitorId:s.visitorId,externalUserId:s.externalUserId??r,traceId:s.traceId,...l,properties:c,metadata:{...e.metadata,...l.metadata}},{source:o(e.source)});return n.enqueue(d),{eventId:d.id}};return{track:Object.assign(i,vC(i)),identify(l,s){return r=l,i({event:"user.identified",externalUserId:l,properties:s})},flush:()=>n.flush(),shutdown:l=>n.shutdown(l)}}function oU(e){let t=new URL(e);return{apiUrl:t.origin,endpointPath:`${t.pathname}${t.search}`}}function ma(e,t,a){let[n,r=""]=e.split("?"),o=n.replace(/\/$/,""),i=new URLSearchParams(r);if(a)for(let[s,u]of Object.entries(a))i.set(s,u);let l=i.toString();return`${o}${t}${l?`?${l}`:""}`}var iU="/api/mcp/";function Vd(e,t){let[a=""]=e.split("?"),n="",r=a;try{let o=new URL(a);n=o.origin,r=o.pathname}catch{if(!a.startsWith("/"))return null}return r.startsWith(iU)?`${n}${t}`:null}function lU(){if(typeof window>"u")return!1;try{return window.WANIWANI_DEBUG?!0:!!window.localStorage?.getItem("WANIWANI_DEBUG")}catch{return!1}}function ha(...e){lU()&&console.log("[Waniwani]",...e)}var Ug="waniwani-visitor-id";function sU(){try{if(typeof crypto<"u"){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();if(typeof crypto.getRandomValues=="function"){let e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=Array.from(e,a=>a.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}}}catch{}return`v-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function Zt(){try{let t=localStorage.getItem(Ug);if(t)return t}catch{}let e=sU();try{localStorage.setItem(Ug,e)}catch{}return e}function il(e){let t=typeof e=="string"?e.trim():"";if(!t)return Zt();try{localStorage.setItem(Ug,t)}catch{}return t}function uU(e){return e!=null&&typeof e.then=="function"}function $s(e){let t=!1,a=()=>{t=!0};if(e==null)return a;let n;try{n=typeof e=="function"?e():e}catch{return a}return uU(n)?n.then(r=>{t||il(r??"")},()=>{}):il(n??""),a}var cU="waniwani-memory";var Wa="threads",Wd="by_memoryUserId",dU="by_updatedAt";var kC="memoryUserId",CC="waniwani-memory-user-id",Fg=null;function zg(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}function fU(e,t){if(t<1&&(e.objectStoreNames.contains("ids")||e.createObjectStore("ids")),t<2&&!e.objectStoreNames.contains(Wa)){let a=e.createObjectStore(Wa,{keyPath:"threadId"});a.createIndex(Wd,"memoryUserId",{unique:!1}),a.createIndex(dU,"updatedAt",{unique:!1})}}async function qg(){return new Promise((e,t)=>{let a=indexedDB.open(cU,2);a.onupgradeneeded=n=>{fU(a.result,n.oldVersion)},a.onsuccess=()=>e(a.result),a.onerror=()=>t(a.error)})}async function pU(){return qg()}async function mU(e){return new Promise((t,a)=>{let o=e.transaction("ids","readonly").objectStore("ids").get(kC);o.onsuccess=()=>t(typeof o.result=="string"?o.result:null),o.onerror=()=>a(o.error)})}async function hU(e,t){return new Promise((a,n)=>{let i=e.transaction("ids","readwrite").objectStore("ids").put(t,kC);i.onsuccess=()=>a(),i.onerror=()=>n(i.error)})}async function gU(){if(typeof indexedDB>"u")return null;try{let e=await pU();try{let t=await mU(e);if(t)return t;let a=zg();return await hU(e,a),a}finally{e.close()}}catch{return null}}function wU(){try{let e=localStorage.getItem(CC);if(e)return e;let t=zg();return localStorage.setItem(CC,t),t}catch{return null}}async function TC(){let e=await gU();if(e)return e;let t=wU();return t||(Fg||(Fg=zg()),Fg)}function LC(e,t){return e.match(t)?.[1]??null}function yU(e){let t=[["Edge",/Edg(?:e|A|iOS)?\/(\S+)/],["Opera",/(?:OPR|Opera)\/(\S+)/],["Samsung Internet",/SamsungBrowser\/(\S+)/],["Firefox",/Firefox\/(\S+)/],["Chrome",/Chrome\/(\S+)/],["Safari",/Version\/(\S+).*Safari/]];for(let[a,n]of t){let r=LC(e,n);if(r)return{name:a,version:r}}return null}function xU(e){let t=[["iOS",/(?:iPhone|iPad|iPod).+?OS (\d+[_.\d]*)/],["Android",/Android (\d+[.\d]*)/],["macOS",/Mac OS X (\d+[_.\d]*)/],["Windows",/Windows NT (\d+[.\d]*)/],["ChromeOS",/CrOS \S+ (\d+[.\d]*)/],["Linux",/Linux/]];for(let[a,n]of t){let r=LC(e,n);if(r)return{name:a,version:r.replace(/_/g,".")};if(a==="Linux"&&n.test(e))return{name:a,version:""}}return null}function vU(e){return typeof navigator<"u"&&"userAgentData"in navigator&&navigator.userAgentData?.mobile?"mobile":/iPad|tablet|PlayBook/i.test(e)?"tablet":/Mobi|Android.*Mobile|iPhone|iPod/i.test(e)?"mobile":"desktop"}async function Xs(){let e=navigator.userAgent,t=Zt(),a=await TC();return{userAgent:e,browser:yU(e),os:xU(e),deviceType:vU(e),language:navigator.language,languages:[...navigator.languages],timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,screenWidth:screen.width,screenHeight:screen.height,viewportWidth:window.innerWidth,viewportHeight:window.innerHeight,colorDepth:screen.colorDepth,devicePixelRatio:window.devicePixelRatio??1,touchSupport:"ontouchstart"in window||navigator.maxTouchPoints>0,connectionType:navigator.connection?.effectiveType??"unknown",referrer:document.referrer,visitorId:t,memoryUserId:a}}var bU="0.22.0-beta.2",SU=40,IU=10,CU=6e5;function jg(){return typeof performance>"u"?0:performance.now()}function Vg(e,t){let a={};return{metrics:a,has:n=>n in a,set(n,r){a[n]=r},mark(n,r=jg()){if(!(n in a)){a[n]=r-t;try{performance.mark(`waniwani:${e}:${n}`,{startTime:r})}catch{}}}}}function kU(e){let t={};for(let[a,n]of Object.entries(e)){if(Object.keys(t).length>=SU)break;if(!Number.isFinite(n))continue;let r=Math.round(n);r<0||r>CU||(t[a]=r)}return t}function TU(e){let t={};for(let[a,n]of Object.entries(e)){if(Object.keys(t).length>=IU)break;(typeof n=="string"||typeof n=="boolean")&&(t[a]=n)}return t}function LU(){let e=navigator.connection;if(e)return{effectiveType:e.effectiveType,rtt:e.rtt,downlink:e.downlink,saveData:e.saveData}}function $d(e){let t=e?.Authorization;return typeof t=="string"&&t.startsWith("Bearer ")?t.slice(7):void 0}function EU(e,t,a,n){return{kind:e,sdkVersion:bU,channelId:t.channelId||void 0,sessionId:e==="boot"?void 0:t.sessionId||void 0,visitorId:Zt(),pageHost:window.location.hostname,connection:LU(),tags:TU(a),metrics:kU(n)}}var Hg,Gd=[];function Wg(e){let t=String(e?.chatTimingLogs).trim().toLowerCase()==="true";Hg=t;let a=Gd;if(Gd=[],t)for(let n of a)n()}function Xd(e,t,a,n){let{api:r,token:o}=t;if(!(typeof window>"u"||!r||!o||Hg===!1))try{let i=EU(e,t,a,n),l=()=>{ha("timing",i),fetch(ma(r,"/timing"),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},body:JSON.stringify(i),keepalive:!0}).catch(()=>{})};Hg?l():Gd.length<20&&Gd.push(l)}catch{}}var dr=Vg("boot",0),EC;function Bo(e,t){dr.mark(e,t)}function Kd(e){EC??(EC=e)}var MU=/cdn\.jsdelivr\.net\/npm\/@waniwani\/sdk@[^/]+\/dist\/chat\/embed\.js/,AU=/\/embed\.js(\?|$)/;function RU(){if(typeof performance>"u")return;let e=performance.getEntriesByType("navigation")[0];e?.responseStart&&dr.mark("navTtfb",e.responseStart),e?.domContentLoadedEventEnd&&dr.mark("navDomContentLoaded",e.domContentLoadedEventEnd);let t=performance.getEntriesByType("resource");for(let a of t)MU.test(a.name)?(dr.mark("bundleStart",a.startTime),dr.mark("bundleEnd",a.responseEnd)):AU.test(a.name)&&(dr.mark("loaderStart",a.startTime),dr.mark("loaderEnd",a.responseEnd))}function DU(){if(Iv)return!0;try{return document.querySelectorAll('script[src*="@waniwani/sdk"]').length>1}catch{return!1}}function MC(e){RU(),dr.mark("bundleExecuted",Sv),Xd("boot",e,{configSource:EC,mode:e.mode,secondSdk:DU()},dr.metrics)}var _U=[["text-delta","firstText"],["tool-input-start","firstToolInput"],["tool-output-available","firstToolOutput"]];function AC(e){let t=Vg("turn",jg());t.set("turnIndex",e);let a=!1;return{mark:n=>t.mark(n),instrument(n){if(!n.ok||!n.body||typeof TransformStream>"u")return n;try{let r=new TextDecoder,o=n.body.pipeThrough(new TransformStream({transform(i,l){t.mark("firstChunk");let s=r.decode(i,{stream:!0});for(let[u,c]of _U)!t.has(c)&&s.includes(u)&&t.mark(c);l.enqueue(i)}}));return new Response(o,{status:n.status,statusText:n.statusText,headers:n.headers})}catch{return n}},report(n,r){a||(a=!0,Xd("turn",n,r,t.metrics))}}}function OU(e){let t=e.indexOf("?");return t===-1?e:e.slice(0,t)}function RC(e,t){let a=Vg("widget",jg()),n=!1;return{mark:r=>a.mark(r),has:r=>a.has(r),report(r,o){n||(n=!0,a.set("retries",o),t({widget:OU(e),outcome:r,metrics:a.metrics}))}}}var PU="/api/mcp/events/v2/batch",Gg=new Set;function NU(e,t,a){return`${e}|${t}|${a??""}`}function Ks(e){return Vd(e,PU)}async function DC(e){let{api:t,token:a,channelId:n,mode:r,source:o}=e;if(typeof window>"u"||!t||!a)return;let i=Ks(t);if(!i){ha("page.viewed skipped: the chat api is not a Waniwani endpoint");return}if(!n&&!o){ha("page.viewed skipped: no channelId or source to attribute it");return}let l=NU(t,a,n);if(!Gg.has(l)){Gg.add(l);try{let s=await Xs(),u=new Date().toISOString(),c=JSON.stringify({sentAt:u,source:{sdk:"@waniwani/sdk",version:"0.1.0"},events:[{id:crypto.randomUUID(),type:"mcp.event",name:"page.viewed",source:o,timestamp:u,correlation:{visitorId:s.visitorId},properties:{channelId:n,mode:r,url:window.location.href,referrer:s.referrer,deviceType:s.deviceType,language:s.language,timezone:s.timezone},metadata:{}}]}),d=fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:c,keepalive:!0});Bo("pageViewSent"),await d}catch{Gg.delete(l)}}}function _C(e){let t=Ks(e.api);return t?IC({endpoint:t,token:e.token,channelId:e.channelId,source:e.getSource,identity:()=>({sessionId:e.getSessionId(),visitorId:Zt()})}):Yd("the chat api does not point at a Waniwani event ingest")}function Yd(e){let t=!1,a=async()=>(t||(t=!0,console.warn(`[Waniwani] track() is disabled: ${e}`)),{eventId:""});return{track:Object.assign(a,{priceShown:a,pricesCompared:a,optionSelected:a,leadQualified:a,converted:a}),identify:a,flush:async()=>{},shutdown:async()=>({timedOut:!1,pendingEvents:0})}}var Qd=z(he());var Zd=(...e)=>e.filter((t,a,n)=>!!t&&t.trim()!==""&&n.indexOf(t)===a).join(" ").trim();var OC=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();var PC=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,a,n)=>n?n.toUpperCase():a.toLowerCase());var $g=e=>{let t=PC(e);return t.charAt(0).toUpperCase()+t.slice(1)};var Ys=z(he());var NC={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};var BC=e=>{for(let t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0;return!1};var UC=(0,Ys.forwardRef)(({color:e="currentColor",size:t=24,strokeWidth:a=2,absoluteStrokeWidth:n,className:r="",children:o,iconNode:i,...l},s)=>(0,Ys.createElement)("svg",{ref:s,...NC,width:t,height:t,stroke:e,strokeWidth:n?Number(a)*24/Number(t):a,className:Zd("lucide",r),...!o&&!BC(l)&&{"aria-hidden":"true"},...l},[...i.map(([u,c])=>(0,Ys.createElement)(u,c)),...Array.isArray(o)?o:[o]]));var He=(e,t)=>{let a=(0,Qd.forwardRef)(({className:n,...r},o)=>(0,Qd.createElement)(UC,{ref:o,iconNode:t,className:Zd(`lucide-${OC($g(e))}`,`lucide-${e}`,n),...r}));return a.displayName=$g(e),a};var BU=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],Zs=He("arrow-down",BU);var UU=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],Nn=He("arrow-up",UU);var FU=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Qs=He("check",FU);var zU=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Qr=He("chevron-down",zU);var qU=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],Js=He("chevron-right",qU);var HU=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2",key:"4jdomd"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v4",key:"3hqy98"}],["path",{d:"M21 14H11",key:"1bme5i"}],["path",{d:"m15 10-4 4 4 4",key:"5dvupr"}]],eu=He("clipboard-copy",HU);var jU=[["path",{d:"M12 6v6l4 2",key:"mmk7yg"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],fr=He("clock",jU);var VU=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],tu=He("file-text",VU);var WU=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}]],ll=He("file",WU);var GU=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]],au=He("globe",GU);var $U=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]],nu=He("image",$U);var XU=[["path",{d:"M12 2v4",key:"3427ic"}],["path",{d:"m16.2 7.8 2.9-2.9",key:"r700ao"}],["path",{d:"M18 12h4",key:"wj9ykh"}],["path",{d:"m16.2 16.2 2.9 2.9",key:"1bxg5t"}],["path",{d:"M12 18v4",key:"jadmvz"}],["path",{d:"m4.9 19.1 2.9-2.9",key:"bwix9q"}],["path",{d:"M2 12h4",key:"j09sii"}],["path",{d:"m4.9 4.9 2.9 2.9",key:"giyufr"}]],ru=He("loader",XU);var KU=[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551",key:"1miecu"}]],sl=He("paperclip",KU);var YU=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],ou=He("square",YU);var ZU=[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z",key:"1ngwbx"}]],Uo=He("wrench",ZU);var QU=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Ga=He("x",QU);var JU=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]],iu=He("zap",JU);var $e=z(he(),1),uO=z(um(),1);var ul=z(he(),1),lu=z(re(),1);function a3(e){return 1-(1-e)**3}function n3({start:e=0,end:t=100,duration:a=1e3,delay:n=0,ease:r=a3,onUpdate:o,onEnd:i}){let l=performance.now()+n;function s(){let u=performance.now()-l,c=Math.min(u/a,1);o(e+(t-e)*r(c)),c<1?requestAnimationFrame(s):i&&i()}setTimeout(()=>requestAnimationFrame(s),n)}var r3=["80% 55%","69% 34%","8% 6%","41% 38%","86% 85%","82% 18%","51% 4%"],o3=[0,1,2,0,1,2,1];function i3(e){let t=[];for(let a=0;a<7;a++){let n=e[Math.min(o3[a],e.length-1)];t.push(`radial-gradient(at ${r3[a]}, ${n} 0px, transparent 50%)`)}return t.push(`linear-gradient(${e[0]} 0 100%)`),t}var l3=({children:e,className:t="",style:a,edgeSensitivity:n=30,backgroundColor:r="#120F17",borderRadius:o=28,coneSpread:i=25,animated:l=!1,colors:s=["#c084fc","#f472b6","#38bdf8"]})=>{let[u,c]=(0,ul.useState)(110),[d,f]=(0,ul.useState)(0),[p,m]=(0,ul.useState)(!1);(0,ul.useEffect)(()=>{if(!l)return;let T=110;m(!0),c(T),n3({ease:C=>C,duration:2e3,onUpdate:C=>{let M=C/100;c(T+360*M);let R=Math.min(M/.1,1),P=M>.85?(1-M)/.15:1;f(Math.min(R,P))},onEnd:()=>m(!1)})},[l]);let x=n+20,S=p?Math.max(0,(d*100-x)/(100-x)):0,y=i3(s).map(T=>`${T} border-box`),b=`conic-gradient(from ${`${u.toFixed(3)}deg`} at center, black ${i}%, transparent ${i+15}%, transparent ${100-i-15}%, black ${100-i}%)`;return(0,lu.jsxs)("div",{className:`ww:relative ww:grid ww:isolate ww:border ${t}`,style:{background:r,borderRadius:typeof o=="number"?`${o}px`:o,transform:"translate3d(0, 0, 0.01px)",...a},children:[(0,lu.jsx)("div",{className:"ww:absolute ww:inset-0 ww:rounded-[inherit] ww:-z-[1]",style:{border:"1px solid transparent",background:[`linear-gradient(${r} 0 100%) padding-box`,"linear-gradient(rgb(255 255 255 / 0%) 0% 100%) border-box",...y].join(", "),opacity:S,maskImage:b,WebkitMaskImage:b,transition:p?"opacity 0.25s ease-out":"opacity 0.75s ease-in-out"}}),(0,lu.jsx)("div",{className:"ww:flex ww:flex-col ww:relative ww:overflow-auto ww:z-[1]",children:e})]})},ef=l3;Xg();Yg();var s3=jC({prefix:"ww"});function q(...e){return s3(tf(e))}var su=z(re(),1);function cl({suggestions:e,isLoading:t,onSelect:a,align:n="start",className:r,...o}){return e.length===0&&!t?null:(0,su.jsx)("div",{className:q("ww:px-4 ww:py-2",r),...o,children:(0,su.jsx)("div",{className:q("ww:mx-auto ww:w-full ww:max-w-3xl ww:flex ww:flex-wrap ww:gap-2",n==="center"&&"ww:justify-center"),children:t?[0,1,2].map(i=>(0,su.jsx)("div",{className:"ww:h-8 ww:rounded-full ww:bg-accent ww:animate-pulse",style:{width:`${60+i*20}px`}},i)):e.map((i,l)=>(0,su.jsx)("button",{type:"button",onClick:()=>a(i),className:q("ww:rounded-full ww:border ww:border-border ww:bg-accent ww:px-3.5 ww:py-1.5 ww:text-sm","ww:text-foreground ww:hover:bg-border ww:hover:border-primary/30","ww:transition-all ww:duration-200 ww:ease-out ww:cursor-pointer","ww:animate-[ww-fade-in_0.2s_ease-out_both]"),style:{animationDelay:`${l*50}ms`},children:i},i))})})}var VC=z(he(),1),WC="(max-width: 639px)";function u3(e){let t=window.matchMedia(WC);return t.addEventListener("change",e),()=>t.removeEventListener("change",e)}function c3(){return window.matchMedia(WC).matches}function d3(){return!1}function GC(){return(0,VC.useSyncExternalStore)(u3,c3,d3)}var af=z(he(),1);function Zg(e,t){return e.find(a=>a.text===t)?.id??null}async function $C(e){let{api:t,token:a,name:n,source:r,sessionId:o,properties:i}=e;if(typeof window>"u"||!t||!a)return;let l=Ks(t);if(l)try{let s=new Date().toISOString(),u=JSON.stringify({sentAt:s,source:{sdk:"@waniwani/sdk",version:"0.1.0"},events:[{id:crypto.randomUUID(),type:"mcp.event",name:n,source:r,timestamp:s,correlation:{visitorId:Zt(),sessionId:o},properties:{...i,url:window.location.href},metadata:{}}]});await fetch(l,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:u,keepalive:!0})}catch{}}async function XC(e){let{api:t,token:a,channelId:n,mode:r,source:o,sessionId:i,promptId:l,origin:s,text:u,index:c}=e;await $C({api:t,token:a,name:"suggestion.clicked",source:o,sessionId:i,properties:{promptId:l,origin:s,text:u,index:c,channelId:n,mode:r}})}function KC(e,t){return t.map(a=>({id:Zg(e,a),text:a}))}async function YC(e){let{api:t,token:a,channelId:n,mode:r,source:o,sessionId:i,prompts:l,origin:s}=e;l.length!==0&&await $C({api:t,token:a,name:"suggestion.shown",source:o,sessionId:i,properties:{prompts:l,count:l.length,origin:s,channelId:n,mode:r}})}function dl(e){let{widgetEvents:t,api:a,token:n,channelId:r,source:o,mode:i,pagePrompts:l}=e,s=(0,af.useRef)(e.getSessionId);s.current=e.getSessionId,(0,af.useEffect)(()=>{if(!(!a||!n))return t.subscribe(u=>{if(u.name==="suggestion.clicked"){let{text:c,origin:d,index:f}=u.properties;XC({api:a,token:n,channelId:r,mode:i,source:o,sessionId:s.current(),promptId:Zg(l??[],c),origin:d,text:c,index:f});return}if(u.name==="suggestions.shown"){let{texts:c,origin:d}=u.properties;YC({api:a,token:n,channelId:r,mode:i,source:o,sessionId:s.current(),prompts:KC(l??[],c),origin:d})}})},[t,a,n,r,o,i,l])}var fl=z(he(),1),f3=80,p3=50,m3=15e3,ZC=500;function pl(e,t=!0){let[a,n]=(0,fl.useState)(""),r=(0,fl.useRef)(void 0);return(0,fl.useEffect)(()=>{if(!t){n("");return}let o=0,i=!1,l=!1,s=()=>{l||(i?(o--,n(e.slice(0,o)),o<=0?(i=!1,r.current=setTimeout(s,ZC)):r.current=setTimeout(s,p3)):(o++,n(e.slice(0,o)),o>=e.length?(i=!0,r.current=setTimeout(s,m3)):r.current=setTimeout(s,f3)))};return r.current=setTimeout(s,ZC),()=>{l=!0,clearTimeout(r.current)}},[e,t]),a}var Sn=z(he(),1);var QC=["en","fr","es"];function ml(e){return QC.includes(e)}function Qg(e){if(e&&ml(e))return e;if(e){let a=e.split("-")[0]?.toLowerCase();if(a&&ml(a))return a}let t=[];if(typeof navigator<"u"&&(navigator.language&&t.push(navigator.language),navigator.languages&&t.push(...navigator.languages)),typeof document<"u"){let a=document.documentElement.getAttribute("lang");a&&t.push(a)}for(let a of t){let n=a.toLowerCase();if(ml(n))return n;let r=n.split("-")[0];if(r&&ml(r))return r}return"en"}var nf={promptInput:{placeholder:"What would you like to know?",uploadFiles:"Upload files",uploadFilesUpTo:"Upload a document, up to {limit}",uploadFilesUpToWithPages:"Upload a document, up to {limit} and {pages} pages",stop:"Stop",submit:"Submit",removeAttachments:"Remove all attachments",removeAttachment:"Remove attachment",uploading:"Uploading\u2026",retry:"Retry",retryUpload:"Retry the upload",uploadFailed:"The upload did not finish.",dropToAttach:"Drop to attach",errorAccept:"{name} is not a file type this chat accepts.",errorTooLarge:"{name} is larger than {limit}.",errorTooMany:"You can attach up to {limit} files."},workingIndicator:{default:"On it\u2026"},reasoning:{thinking:"Thinking\u2026",thoughtBrief:"Thought for a few seconds",thoughtForSeconds:e=>`Thought for ${e} second${e===1?"":"s"}`},chainOfThought:{working:"Working on it\u2026",done:"Thought process"},tool:{copy:"Copy",copied:"Copied",request:"Request",response:"Response",error:"Error"},attachments:{attachmentFallback:"attachment",kindPdf:"PDF",kindImage:"Image",kindFile:"File",fileFallback:"file"},threadMenu:{newChat:"New chat",threadHistory:"Thread history",deleteThread:"Delete thread",noPreviousChats:"No previous chats yet.",hiddenThreads:e=>`${e} older thread${e===1?"":"s"} hidden`},chatQueue:{attachmentFallback:"(attachment)",removeFromQueue:"Remove from queue",queued:e=>`${e} queued`},poweredBy:{label:"AI agent powered by"},aiDisclaimer:{default:"can make mistakes"},exportSession:{saving:"saving...",saved:"saved",error:"error",export:"export",tooltip:"Save scenario to Waniwani"},widgetErrorBoundary:{failedToLoad:"Widget failed to load",retry:"Retry"},launcher:{prompt:"Ask anything\u2026",open:"Open chat",close:"Close chat",minimize:"Minimize"}};var JC={promptInput:{placeholder:"\xBFQu\xE9 te gustar\xEDa saber?",uploadFiles:"Subir archivos",uploadFilesUpTo:"Subir un documento, hasta {limit}",uploadFilesUpToWithPages:"Subir un documento, hasta {limit} y {pages} p\xE1ginas",stop:"Detener",submit:"Enviar",removeAttachments:"Eliminar todos los archivos adjuntos",removeAttachment:"Quitar archivo",uploading:"Subiendo\u2026",retry:"Reintentar",retryUpload:"Reintentar la subida",uploadFailed:"La subida no se complet\xF3.",dropToAttach:"Suelta para adjuntar",errorAccept:"{name} no es un tipo de archivo que acepte este chat.",errorTooLarge:"{name} supera {limit}.",errorTooMany:"Puedes adjuntar hasta {limit} archivos."},workingIndicator:{default:"Un momento\u2026"},reasoning:{thinking:"Pensando\u2026",thoughtBrief:"Pensado durante unos segundos",thoughtForSeconds:e=>`Pensado durante ${e} segundo${e===1?"":"s"}`},chainOfThought:{working:"Estoy en ello\u2026",done:"Razonamiento"},tool:{copy:"Copiar",copied:"Copiado",request:"Solicitud",response:"Respuesta",error:"Error"},attachments:{attachmentFallback:"adjunto",kindPdf:"PDF",kindImage:"Imagen",kindFile:"Archivo",fileFallback:"archivo"},threadMenu:{newChat:"Nueva conversaci\xF3n",threadHistory:"Historial",deleteThread:"Eliminar conversaci\xF3n",noPreviousChats:"A\xFAn no hay conversaciones anteriores.",hiddenThreads:e=>`${e} conversaci\xF3n${e===1?"":"es"} anterior${e===1?"":"es"} oculta${e===1?"":"s"}`},chatQueue:{attachmentFallback:"(adjunto)",removeFromQueue:"Quitar de la cola",queued:e=>`${e} en cola`},poweredBy:{label:"Agente IA con tecnolog\xEDa de"},aiDisclaimer:{default:"puede cometer errores"},exportSession:{saving:"guardando...",saved:"guardado",error:"error",export:"exportar",tooltip:"Guardar escenario en Waniwani"},widgetErrorBoundary:{failedToLoad:"No se pudo cargar el widget",retry:"Reintentar"},launcher:{prompt:"Pregunta lo que quieras\u2026",open:"Abrir chat",close:"Cerrar chat",minimize:"Minimizar"}};var ek={promptInput:{placeholder:"Que souhaitez-vous savoir ?",uploadFiles:"Importer des fichiers",uploadFilesUpTo:"Joindre un document, jusqu'\xE0 {limit}",uploadFilesUpToWithPages:"Envoyer un document, jusqu'\xE0 {limit} et {pages} pages",stop:"Arr\xEAter",submit:"Envoyer",removeAttachments:"Supprimer toutes les pi\xE8ces jointes",removeAttachment:"Retirer la pi\xE8ce jointe",uploading:"Envoi en cours\u2026",retry:"R\xE9essayer",retryUpload:"R\xE9essayer l'envoi",uploadFailed:"L'envoi ne s'est pas termin\xE9.",dropToAttach:"D\xE9posez pour joindre",errorAccept:"{name} n'est pas un type de fichier accept\xE9 par ce chat.",errorTooLarge:"{name} d\xE9passe {limit}.",errorTooMany:"Vous pouvez joindre jusqu'\xE0 {limit} fichiers."},workingIndicator:{default:"Un instant\u2026"},reasoning:{thinking:"R\xE9flexion\u2026",thoughtBrief:"R\xE9flexion pendant quelques secondes",thoughtForSeconds:e=>`R\xE9flexion pendant ${e} seconde${e===1?"":"s"}`},chainOfThought:{working:"Je m'en occupe\u2026",done:"Raisonnement"},tool:{copy:"Copier",copied:"Copi\xE9",request:"Requ\xEAte",response:"R\xE9ponse",error:"Erreur"},attachments:{attachmentFallback:"pi\xE8ce jointe",kindPdf:"PDF",kindImage:"Image",kindFile:"Fichier",fileFallback:"fichier"},threadMenu:{newChat:"Nouvelle conversation",threadHistory:"Historique",deleteThread:"Supprimer la conversation",noPreviousChats:"Aucune conversation pr\xE9c\xE9dente.",hiddenThreads:e=>`${e} conversation${e===1?"":"s"} plus ancienne${e===1?"":"s"} masqu\xE9e${e===1?"":"s"}`},chatQueue:{attachmentFallback:"(pi\xE8ce jointe)",removeFromQueue:"Retirer de la file",queued:e=>`${e} en attente`},poweredBy:{label:"Agent IA propuls\xE9 par"},aiDisclaimer:{default:"peut faire des erreurs"},exportSession:{saving:"enregistrement...",saved:"enregistr\xE9",error:"erreur",export:"exporter",tooltip:"Enregistrer le sc\xE9nario dans Waniwani"},widgetErrorBoundary:{failedToLoad:"\xC9chec du chargement du widget",retry:"R\xE9essayer"},launcher:{prompt:"Posez votre question\u2026",open:"Ouvrir le chat",close:"Fermer le chat",minimize:"R\xE9duire"}};var Jg={en:nf,fr:ek,es:JC};var ak=z(re(),1),tk=(0,Sn.createContext)(null);function h3(e,t){if(!t)return e;let a={...e};for(let n of Object.keys(e)){let r=e[n],o=t[n];o&&typeof r=="object"&&(a[n]={...r,...o})}return a}function Fo({children:e,locale:t,messages:a}){let n=!!(t&&g3(t)),r=n?t:"en",[o,i]=(0,Sn.useState)(r),[l,s]=(0,Sn.useState)(n);(0,Sn.useEffect)(()=>{i(Qg(t)),s(!0)},[t]);let u=(0,Sn.useMemo)(()=>{let c=Jg[o]??Jg["en"];return{locale:o,t:h3(c,a),ready:l}},[o,a,l]);return(0,ak.jsx)(tk.Provider,{value:u,children:e})}function g3(e){return e==="en"||e==="fr"||e==="es"}function ke(){let e=(0,Sn.useContext)(tk);return e||{locale:"en",t:nf,ready:!0}}function ew(e,t){let a=Date.now()-e;if(a<6e4)try{return new Intl.RelativeTimeFormat(t,{numeric:"auto",style:"narrow"}).format(0,"second")}catch{return"just now"}let n,r;a<60*6e4?(n=-Math.floor(a/6e4),r="minute"):a<1440*6e4?(n=-Math.floor(a/(60*6e4)),r="hour"):(n=-Math.floor(a/(1440*6e4)),r="day");try{return new Intl.RelativeTimeFormat(t,{numeric:"auto",style:"short"}).format(n,r)}catch{return`${Math.abs(n)}${r==="minute"?"m":r==="hour"?"h":"d"} ago`}}var ze=z(he(),1);var uu=(e=21)=>crypto.getRandomValues(new Uint8Array(e)).reduce((t,a)=>(a&=63,a<36?t+=a.toString(36):a<62?t+=(a-26).toString(36).toUpperCase():a>62?t+="-":t+="_",t),"");var Ie=z(he(),1);var zo=new Map;function nk(e,t){if(zo.has(e)){URL.revokeObjectURL(t);return}for(zo.set(e,t);zo.size>20;){let a=zo.keys().next();if(a.done)return;let n=zo.get(a.value);zo.delete(a.value),n&&URL.revokeObjectURL(n)}}function rk(e){return zo.get(e)}var ok=z(re(),1),Bn=({className:e,variant:t="default",size:a="default",type:n="button",...r})=>(0,ok.jsx)("button",{type:n,className:q("ww:inline-flex ww:cursor-pointer ww:items-center ww:justify-center ww:rounded-md ww:font-medium ww:transition-colors ww:disabled:pointer-events-none ww:disabled:opacity-50",t==="default"&&"ww:bg-primary ww:text-primary-foreground ww:hover:bg-primary/90",t==="outline"&&"ww:border ww:border-border ww:bg-background ww:hover:bg-accent ww:hover:text-accent-foreground",t==="ghost"&&"ww:hover:bg-accent ww:hover:text-accent-foreground",a==="default"&&"ww:h-9 ww:px-4 ww:py-2 ww:text-sm",a==="sm"&&"ww:h-8 ww:px-3 ww:text-xs",a==="icon"&&"ww:size-9 ww:!rounded-full",a==="icon-sm"&&"ww:size-7 ww:!rounded-full",e),...r});var ik=z(he(),1);var bt=z(re(),1),lk=({files:e,className:t,...a})=>e.length===0?null:(0,bt.jsx)("div",{className:q("ww:flex ww:flex-wrap ww:gap-1.5",t),...a,children:e.map((n,r)=>(0,bt.jsx)(w3,{file:n},r))});function w3({file:e}){let{t}=ke();return e.mediaType?.startsWith("image/")&&e.url?(0,bt.jsx)("img",{src:e.url,alt:e.filename??t.attachments.attachmentFallback,className:"ww:h-16 ww:max-w-32 ww:rounded ww:object-cover"}):(0,bt.jsxs)("span",{className:"ww:inline-flex ww:items-center ww:gap-1.5 ww:rounded ww:bg-background/20 ww:px-2 ww:py-1 ww:text-xs",children:[(0,bt.jsx)(ll,{className:"ww:size-3 ww:shrink-0"}),(0,bt.jsx)("span",{className:"ww:max-w-24 ww:truncate",children:e.filename??t.attachments.fileFallback})]})}function sk(e,t){return e.startsWith("image/")?t.attachments.kindImage:e==="application/pdf"?t.attachments.kindPdf:t.attachments.kindFile}function y3({mediaType:e}){return e.startsWith("image/")?(0,bt.jsx)(nu,{className:"ww:size-5 ww:text-muted-foreground"}):e==="application/pdf"?(0,bt.jsx)(tu,{className:"ww:size-5 ww:text-muted-foreground"}):(0,bt.jsx)(ll,{className:"ww:size-5 ww:text-muted-foreground"})}function tw({filename:e,mediaType:t,previewUrl:a,subtitle:n,tone:r="default",children:o,className:i}){let{t:l}=ke(),s=sk(t,l);return(0,bt.jsxs)("li",{"aria-label":`${e}, ${s}`,className:q("ww:relative ww:flex ww:w-60 ww:max-w-full ww:cursor-default ww:items-center ww:gap-2.5 ww:overflow-hidden ww:rounded-xl ww:border ww:bg-background ww:p-2.5",r==="error"?"ww:border-destructive/50":"ww:border-border",i),children:[(0,bt.jsx)("span",{className:"ww:flex ww:size-10 ww:shrink-0 ww:items-center ww:justify-center ww:overflow-hidden ww:rounded-xl ww:bg-muted",children:a?(0,bt.jsx)("img",{alt:"",className:"ww:size-full ww:object-cover ww:object-center",src:a}):(0,bt.jsx)(y3,{mediaType:t})}),(0,bt.jsxs)("span",{className:"ww:flex ww:min-w-0 ww:flex-col",children:[(0,bt.jsx)("span",{className:"ww:truncate ww:font-medium ww:text-sm",title:e,children:e}),(0,bt.jsx)("span",{className:q("ww:truncate ww:text-xs",r==="error"?"ww:text-destructive":"ww:text-muted-foreground"),children:n??s})]}),o]})}function uk(e){if(typeof e!="object"||e===null)return[];let t=e.documents;return Array.isArray(t)?t.filter(a=>typeof a=="object"&&a!==null&&typeof a.documentId=="string"&&typeof a.filename=="string"&&typeof a.mediaType=="string"):[]}var ck=({documents:e,className:t,...a})=>e.length===0?null:(0,bt.jsx)("ul",{className:q("ww:flex ww:list-none ww:flex-wrap ww:items-end ww:justify-end ww:gap-2 ww:p-0",t),...a,children:e.map((n,r)=>(0,bt.jsx)(x3,{document:n},`${n.documentId}-${r}`))});function x3({document:e}){let{t}=ke(),[a,n]=(0,ik.useState)(!1),r=e.mediaType.startsWith("image/")?rk(e.documentId):void 0;return r&&!a?(0,bt.jsx)("li",{children:(0,bt.jsx)("img",{alt:`${e.filename}, ${sk(e.mediaType,t)}`,className:"ww:max-h-80 ww:max-w-72 ww:rounded-xl ww:border ww:border-border ww:object-contain",onError:()=>n(!0),src:r,title:e.filename})}):(0,bt.jsx)(tw,{filename:e.filename,mediaType:e.mediaType})}var ht=z(re(),1),v3=async e=>{try{let a=await(await fetch(e)).blob();return new Promise(n=>{let r=new FileReader;r.onloadend=()=>n(r.result),r.onerror=()=>n(null),r.readAsDataURL(a)})}catch{return null}},b3=(e,t)=>{if(!t)return!0;let a=t.split(",").map(o=>o.trim().toLowerCase()).filter(Boolean);if(a.length===0)return!0;let n=e.type.toLowerCase(),r=e.name.toLowerCase();return a.some(o=>o.startsWith(".")?r.endsWith(o):o.endsWith("/*")?n.startsWith(o.slice(0,-1)):n===o)},fk=(0,Ie.createContext)(null),rf=()=>{let e=(0,Ie.useContext)(fk);if(!e)throw new Error("usePromptInputAttachments must be used within a PromptInput");return e},pk=({className:e,accept:t,multiple:a,globalDrop:n,maxFiles:r,maxFileSize:o,maxPdfPages:i,attachmentsEnabled:l=!0,upload:s,onDiscard:u,onError:c,onSubmit:d,children:f,...p})=>{let{t:m,locale:x}=ke(),S=(0,Ie.useRef)(null),w=(0,Ie.useRef)(null),[y,h]=(0,Ie.useState)([]),b=(0,Ie.useRef)(y),T=(0,Ie.useRef)(new Map),C=(0,Ie.useRef)(s),M=(0,Ie.useRef)(c),R=(0,Ie.useRef)(u);(0,Ie.useEffect)(()=>{C.current=s,M.current=c,R.current=u},[s,c,u]);let P=(0,Ie.useCallback)(v=>{b.current=v,h(v)},[]),L=(0,Ie.useCallback)(()=>{S.current?.click()},[]),$=(0,Ie.useCallback)((v,K)=>{P(b.current.map(ee=>ee.id===v?{...ee,...K}:ee))},[P]),H=(0,Ie.useCallback)((v,K)=>{let ee=C.current;if(!ee)return;let we=new AbortController,We=ee(K,we.signal,me=>{$(v,{progress:me})}).then(me=>($(v,{status:"ready",progress:1,documentId:me.documentId,error:void 0}),me)).catch(me=>{if(we.signal.aborted)return null;let be=me instanceof Error?me.message:m.promptInput.uploadFailed;return $(v,{status:"failed",error:be}),M.current?.({code:"upload_failed",message:be}),null});T.current.set(v,{file:K,controller:we,done:We})},[$,m]),F=(0,Ie.useCallback)(v=>{let K=[...v];if(!l||K.length===0)return;let ee=(de,Q)=>M.current?.({code:de,message:Q}),we=[];for(let de of K){if(!b3(de,t)){ee("accept",m.promptInput.errorAccept.replace("{name}",de.name));continue}if(o&&de.size>o){ee("max_file_size",m.promptInput.errorTooLarge.replace("{name}",de.name).replace("{limit}",mk(o,x)));continue}we.push(de)}if(we.length===0)return;let We=typeof r=="number"?Math.max(0,r-b.current.length):void 0,me=typeof We=="number"?we.slice(0,We):we;if(me.length<we.length&&ee("max_files",m.promptInput.errorTooMany.replace("{limit}",String(r))),me.length===0)return;let be=!!C.current,le=me.map(de=>({file:de,item:{filename:de.name,id:uu(),mediaType:de.type,type:"file",url:URL.createObjectURL(de),status:be?"uploading":"ready",progress:0}}));P([...b.current,...le.map(de=>de.item)]);for(let de of le)H(de.item.id,de.file)},[r,o,t,l,H,P,m,x]),W=(0,Ie.useCallback)(v=>{let K=T.current.get(v);K&&($(v,{status:"uploading",progress:0,error:void 0}),H(v,K.file))},[$,H]),V=(0,Ie.useCallback)((v,K)=>{T.current.get(v.id)?.controller.abort(),T.current.delete(v.id),v.url&&(!K&&!!v.documentId&&!!v.mediaType?.startsWith("image/")&&v.documentId?nk(v.documentId,v.url):URL.revokeObjectURL(v.url)),K&&v.documentId&&R.current?.({documentId:v.documentId,filename:v.filename??"",mediaType:v.mediaType??""})},[]),N=(0,Ie.useCallback)(v=>{let K=b.current.find(ee=>ee.id===v);K&&V(K,!0),P(b.current.filter(ee=>ee.id!==v))},[V,P]),D=(0,Ie.useCallback)(()=>{for(let v of b.current)V(v,!0);P([])},[V,P]),G=(0,Ie.useRef)(l);(0,Ie.useEffect)(()=>{let v=G.current;G.current=l,v&&!l&&D()},[l,D]);let ue=(0,Ie.useCallback)(()=>{for(let v of b.current)V(v,!1);P([])},[V,P]);(0,Ie.useEffect)(()=>()=>{for(let v of b.current)T.current.get(v.id)?.controller.abort(),v.url&&URL.revokeObjectURL(v.url)},[]);let I=(0,Ie.useCallback)(v=>{v.currentTarget.files&&F(v.currentTarget.files),v.currentTarget.value=""},[F]);(0,Ie.useEffect)(()=>{if(!n)return;let v=ee=>{ee.dataTransfer?.types?.includes("Files")&&ee.preventDefault()},K=ee=>{ee.dataTransfer?.types?.includes("Files")&&ee.preventDefault(),ee.dataTransfer?.files&&ee.dataTransfer.files.length>0&&F(ee.dataTransfer.files)};return document.addEventListener("dragover",v),document.addEventListener("drop",K),()=>{document.removeEventListener("dragover",v),document.removeEventListener("drop",K)}},[F,n]);let Ve=(0,Ie.useCallback)(async v=>{v.preventDefault();let K=v.currentTarget,ee=new FormData(K).get("message")||"",we=new Map;for(;we.size<T.current.size;)await Promise.all([...T.current.entries()].filter(([le])=>!we.has(le)).map(async([le,de])=>{we.set(le,await de.done)}));for(let le of we.keys())T.current.has(le)||we.delete(le);if([...we.values()].some(le=>le===null)){M.current?.({code:"upload_failed",message:m.promptInput.uploadFailed});return}let We=[...we.values()].filter(le=>le!==null),me=C.current?[]:b.current,be=await Promise.all(me.map(async({id:le,status:de,progress:Q,error:Be,...qe})=>{if(qe.url?.startsWith("blob:")){let _e=await v3(qe.url);return{...qe,url:_e??qe.url}}return qe}));try{let le=d({documents:We,files:be,text:ee},v);le instanceof Promise&&await le,K.reset(),ue()}catch{}},[d,ue,m]),et=(0,Ie.useMemo)(()=>({add:F,clear:D,files:y,openFileDialog:L,remove:N,retry:W,maxFileSize:o,maxPdfPages:i}),[y,F,N,W,D,L,o,i]);return(0,ht.jsxs)(fk.Provider,{value:et,children:[(0,ht.jsx)("input",{accept:t,"aria-label":m.promptInput.uploadFiles,className:"ww:hidden",multiple:a,onChange:I,ref:S,title:m.promptInput.uploadFiles,type:"file"}),(0,ht.jsx)("form",{className:q("ww:relative ww:flex ww:w-full ww:flex-col ww:rounded-lg ww:border ww:border-border ww:bg-background",e),onSubmit:Ve,ref:w,...p,children:f})]})},dk=1024*1024;function mk(e,t){let a=e>=dk;return new Intl.NumberFormat(t,{style:"unit",unit:a?"megabyte":"kilobyte",maximumFractionDigits:0}).format(a?e/dk:Math.max(1,e/1024))}var hk=({onChange:e,onKeyDown:t,className:a,placeholder:n,...r})=>{let{t:o}=ke(),i=rf(),[l,s]=(0,Ie.useState)(!1),u=n??o.promptInput.placeholder,c=(0,Ie.useCallback)(f=>{if(t?.(f),!f.defaultPrevented){if(f.key==="Enter"){if(l||f.nativeEvent.isComposing||f.shiftKey)return;f.preventDefault();let{form:p}=f.currentTarget;if(p?.querySelector('[data-submit-blocked="true"]')||p?.querySelector('button[type="submit"]')?.disabled)return;p?.requestSubmit()}if(f.key==="Backspace"&&f.currentTarget.value===""&&i.files.length>0){f.preventDefault();let p=i.files.at(-1);p&&i.remove(p.id)}}},[t,l,i]),d=(0,Ie.useCallback)(f=>{let p=f.clipboardData?.items;if(!p)return;let m=[];for(let x of p)if(x.kind==="file"){let S=x.getAsFile();S&&m.push(S)}m.length>0&&(f.preventDefault(),i.add(m))},[i]);return(0,ht.jsx)("textarea",{className:q("ww:field-sizing-content ww:max-h-48 ww:min-h-0 ww:w-full ww:resize-none ww:border-0 ww:bg-transparent ww:px-3 ww:py-2 ww:text-base ww:sm:text-sm ww:outline-none ww:placeholder:text-muted-foreground",a),name:"message",onCompositionEnd:()=>s(!1),onCompositionStart:()=>s(!0),onKeyDown:c,onPaste:d,placeholder:u,onChange:e,...r})},gk=({className:e,status:t,onStop:a,onClick:n,children:r,disabled:o,...i})=>{let{t:l}=ke(),s=t==="submitted"||t==="streaming",u=s&&a!==void 0,c=(0,ht.jsx)(Nn,{className:"ww:size-4"});t==="submitted"?c=(0,ht.jsx)(ru,{className:"ww:size-4 ww:animate-spin"}):t==="streaming"&&(c=(0,ht.jsx)(ou,{className:"ww:size-4"}));let d=(0,Ie.useCallback)(f=>{if(s&&a){f.preventDefault(),a();return}n?.(f)},[s,a,n]);return(0,ht.jsx)(Bn,{"aria-label":s?l.promptInput.stop:l.promptInput.submit,className:q("ww:bg-foreground ww:text-background ww:hover:bg-foreground ww:rounded-full",e),"data-submit-blocked":o?"true":void 0,disabled:u?!1:o,onClick:d,size:"icon-sm",type:u?"button":"submit",variant:"ghost",...i,children:r??c})},wk=({className:e,children:t,...a})=>{let{t:n,locale:r}=ke(),o=rf();if(o.files.length>0)return(0,ht.jsxs)(Bn,{className:q("ww:group ww:relative",e),onClick:()=>o.clear(),size:"icon-sm",type:"button",variant:"ghost","aria-label":n.promptInput.removeAttachments,...a,children:[(0,ht.jsx)("span",{className:"ww:flex ww:size-5 ww:items-center ww:justify-center ww:rounded-full ww:bg-primary ww:text-[10px] ww:font-medium ww:text-primary-foreground ww:transition-opacity ww:group-hover:opacity-0",children:o.files.length}),(0,ht.jsx)(Ga,{className:"ww:absolute ww:size-4 ww:opacity-0 ww:transition-opacity ww:group-hover:opacity-100"})]});let l=o.maxFileSize?(o.maxPdfPages?n.promptInput.uploadFilesUpToWithPages.replace("{pages}",String(o.maxPdfPages)):n.promptInput.uploadFilesUpTo).replace("{limit}",mk(o.maxFileSize,r)):n.promptInput.uploadFiles;return(0,ht.jsx)(Bn,{"aria-label":l,className:q(e),title:l,onClick:()=>o.openFileDialog(),size:"icon-sm",type:"button",variant:"ghost",...a,children:t??(0,ht.jsx)(sl,{className:"ww:size-4"})})},yk=({className:e,...t})=>{let a=rf();return a.files.length===0?null:(0,ht.jsx)("ul",{className:q("ww:flex ww:list-none ww:flex-wrap ww:gap-2 ww:p-0",e),...t,children:a.files.map(n=>(0,ht.jsx)(S3,{file:n},n.id))})};function S3({file:e}){let{t}=ke(),a=rf(),n=e.status==="failed",r=e.status==="uploading";return(0,ht.jsxs)(tw,{filename:e.filename??t.attachments.fileFallback,mediaType:e.mediaType??"",previewUrl:e.mediaType?.startsWith("image/")?e.url:void 0,subtitle:n?e.error:r?t.promptInput.uploading:void 0,tone:n?"error":"default",children:[n?(0,ht.jsx)("button",{"aria-label":t.promptInput.retryUpload,className:"ww:ml-auto ww:shrink-0 ww:text-destructive ww:text-xs ww:underline ww:underline-offset-2",onClick:()=>a.retry(e.id),type:"button",children:t.promptInput.retry}):null,(0,ht.jsx)("button",{"aria-label":t.promptInput.removeAttachment,className:q("ww:shrink-0 ww:rounded-full ww:p-1 ww:opacity-60 ww:transition-opacity hover:ww:bg-muted hover:ww:opacity-100",n?null:"ww:ml-auto"),onClick:()=>a.remove(e.id),type:"button",children:(0,ht.jsx)(Ga,{className:"ww:size-3.5"})}),r?(0,ht.jsx)("span",{"aria-hidden":!0,className:"ww:absolute ww:bottom-0 ww:left-0 ww:h-0.5 ww:bg-primary ww:transition-[width] ww:duration-200",style:{width:`${Math.round(e.progress*100)}%`}}):null]})}var xk=({enabled:e=!0})=>{let{t}=ke(),[a,n]=(0,Ie.useState)(!1);return(0,Ie.useEffect)(()=>{if(!e)return;let r=0,o=u=>!!u.dataTransfer?.types?.includes("Files"),i=u=>{o(u)&&(r+=1,n(!0))},l=u=>{o(u)&&(r=Math.max(0,r-1),r===0&&n(!1))},s=()=>{r=0,n(!1)};return document.addEventListener("dragenter",i),document.addEventListener("dragleave",l),document.addEventListener("drop",s),()=>{document.removeEventListener("dragenter",i),document.removeEventListener("dragleave",l),document.removeEventListener("drop",s)}},[e]),e&&a?(0,ht.jsx)("div",{className:"ww:pointer-events-none ww:absolute ww:inset-0 ww:z-50 ww:flex ww:items-center ww:justify-center ww:rounded-2xl ww:border-2 ww:border-primary ww:border-dashed ww:bg-background/85",children:(0,ht.jsxs)("span",{className:"ww:flex ww:items-center ww:gap-2 ww:text-sm ww:font-medium",children:[(0,ht.jsx)(sl,{className:"ww:size-4"}),t.promptInput.dropToAttach]})}):null};var bk=z(re(),1);function vk({text:e}){let{t}=ke();return e===!1?null:(0,bk.jsx)("span",{className:"ww:whitespace-nowrap ww:text-[10px] ww:sm:text-[11px] ww:text-muted-foreground ww:opacity-70",children:e||t.aiDisclaimer.default})}var of=z(he(),1);var qo=z(re(),1),Sk=({className:e,...t})=>(0,qo.jsx)("div",{className:q("ww:flex ww:flex-col ww:gap-1 ww:px-3 ww:py-2",e),...t}),Ik=({className:e,...t})=>(0,qo.jsx)("li",{className:q("ww:group ww:flex ww:items-center ww:gap-2 ww:rounded-md ww:px-2 ww:py-1 ww:text-sm ww:transition-colors ww:hover:bg-muted",e),...t}),Ck=({className:e,...t})=>(0,qo.jsx)("span",{className:q("ww:inline-block ww:size-2 ww:shrink-0 ww:rounded-full ww:border ww:border-muted-foreground/50",e),...t}),kk=({className:e,...t})=>(0,qo.jsx)("span",{className:q("ww:line-clamp-1 ww:grow ww:break-words ww:text-muted-foreground",e),...t}),Tk=({className:e,...t})=>(0,qo.jsx)("div",{className:q("ww:flex ww:shrink-0 ww:gap-1 ww:opacity-0 ww:transition-opacity ww:group-hover:opacity-100",e),...t}),Lk=({className:e,...t})=>(0,qo.jsx)(Bn,{className:q("ww:size-auto ww:rounded ww:p-1 ww:text-muted-foreground ww:hover:bg-muted-foreground/10 ww:hover:text-foreground",e),size:"icon",type:"button",variant:"ghost",...t});var sn=z(re(),1),Ek=(0,of.memo)(({message:e,onRemove:t})=>{let{t:a}=ke(),n=(0,of.useCallback)(()=>t(e.id),[t,e.id]);return(0,sn.jsxs)(Ik,{children:[(0,sn.jsx)(Ck,{}),(0,sn.jsx)(kk,{children:e.text||a.chatQueue.attachmentFallback}),(0,sn.jsx)(Tk,{children:(0,sn.jsx)(Lk,{"aria-label":a.chatQueue.removeFromQueue,onClick:n,children:(0,sn.jsx)(Ga,{className:"ww:size-3"})})})]})});Ek.displayName="ChatQueueItem";function Mk({queuedMessages:e,onRemove:t,className:a}){let{t:n}=ke();return e.length===0?null:(0,sn.jsxs)(Sk,{className:q("ww:border-t ww:border-border",a),children:[(0,sn.jsx)("div",{className:"ww:text-[11px] ww:font-medium ww:text-muted-foreground ww:px-2",children:n.chatQueue.queued(e.length)}),(0,sn.jsx)("ul",{children:e.map(r=>(0,sn.jsx)(Ek,{message:r,onRemove:t},r.id))})]})}var _a=z(he(),1);var St=z(he(),1);cp();var l2=z(he(),1);var s2=z(re(),1),H6=({as:e="span",className:t,duration:a=2,style:n,children:r,...o})=>{let i={backgroundImage:"linear-gradient(90deg, var(--ww-color-muted-foreground) 0%, var(--ww-color-muted-foreground) 40%, var(--ww-color-foreground) 50%, var(--ww-color-muted-foreground) 60%, var(--ww-color-muted-foreground) 100%)",backgroundSize:"250% 100%",WebkitBackgroundClip:"text",backgroundClip:"text",color:"transparent",animation:`ww-shimmer ${a}s linear infinite`,...n};return(0,s2.jsx)(e,{"data-waniwani-shimmer":"",className:q("ww:inline-block",t),style:i,...o,children:r})},Tn=(0,l2.memo)(H6);Tn.displayName="Shimmer";var ua=z(re(),1),u2=(0,St.createContext)(null);function c2(){let e=(0,St.useContext)(u2);if(!e)throw new Error("Reasoning components must be used within <Reasoning>");return e}var j6=1e3,V6=1e3,Bu=(0,St.memo)(({className:e,isStreaming:t=!1,open:a,defaultOpen:n,onOpenChange:r,duration:o,children:i,...l})=>{let s=n??t,u=n===!1,c=a!==void 0,[d,f]=(0,St.useState)(s),p=c?a:d,m=(0,St.useCallback)(M=>{c||f(M),r?.(M)},[c,r]),[x,S]=(0,St.useState)(void 0),w=o??x,y=(0,St.useRef)(t),[h,b]=(0,St.useState)(!1),T=(0,St.useRef)(null);(0,St.useEffect)(()=>{t?(y.current=!0,T.current===null&&(T.current=Date.now())):T.current!==null&&(S(Math.ceil((Date.now()-T.current)/V6)),T.current=null)},[t]),(0,St.useEffect)(()=>{t&&!p&&!u&&m(!0)},[t,p,u,m]),(0,St.useEffect)(()=>{if(y.current&&!t&&p&&!h){let M=setTimeout(()=>{m(!1),b(!0)},j6);return()=>clearTimeout(M)}},[t,p,h,m]);let C=(0,St.useMemo)(()=>({isStreaming:t,isOpen:p,setIsOpen:m,duration:w}),[t,p,m,w]);return(0,ua.jsx)(u2.Provider,{value:C,children:(0,ua.jsx)("div",{className:q("ww:mb-4 ww:flex ww:flex-col ww:gap-2",e),"data-state":p?"open":"closed",style:{animation:"ww-fade-in 0.2s ease-out"},...l,children:i})})});Bu.displayName="Reasoning";var Uu=(0,St.memo)(({className:e,children:t,getThinkingMessage:a,hideIcon:n=!1,onClick:r,...o})=>{let{t:i}=ke(),{isStreaming:l,isOpen:s,duration:u,setIsOpen:c}=c2(),f=a??((p,m)=>p||m===0?(0,ua.jsx)(Tn,{duration:1.6,children:i.reasoning.thinking}):m===void 0?(0,ua.jsx)("span",{children:i.reasoning.thoughtBrief}):(0,ua.jsx)("span",{children:i.reasoning.thoughtForSeconds(m)}));return(0,ua.jsx)("button",{type:"button","aria-expanded":s,onClick:p=>{c(!s),r?.(p)},className:q("ww:flex ww:w-full ww:items-center ww:gap-2 ww:text-sm ww:text-muted-foreground ww:transition-colors ww:hover:text-foreground",e),...o,children:t??(0,ua.jsxs)(ua.Fragment,{children:[!n&&(0,ua.jsx)(fr,{className:"ww:size-4 ww:shrink-0"}),f(l,u)]})})});Uu.displayName="ReasoningTrigger";var Fu=(0,St.memo)(({className:e,children:t,...a})=>{let{isOpen:n}=c2();return(0,ua.jsx)("div",{className:q("ww:grid ww:transition-[grid-template-rows,opacity] ww:duration-200 ww:ease-out",n?"ww:grid-rows-[1fr] ww:opacity-100":"ww:grid-rows-[0fr] ww:opacity-0"),children:(0,ua.jsx)("div",{className:"ww:min-h-0 ww:overflow-hidden",children:(0,ua.jsx)("div",{className:q("ww:text-sm ww:text-muted-foreground",e),...a,children:(0,ua.jsx)(Ll,{children:t})})})})});Fu.displayName="ReasoningContent";var Ne=z(re(),1),W6=500,d2=(0,_a.createContext)(null);function f2(){let e=(0,_a.useContext)(d2);if(!e)throw new Error("ChainOfThought components must be used within <ChainOfThought>");return e}function p2({className:e,isWorking:t=!1,activeStep:a,open:n,defaultOpen:r=!1,onOpenChange:o,children:i,...l}){let s=n!==void 0,[u,c]=(0,_a.useState)(r),d=s?n:u,f=(0,_a.useCallback)(S=>{s||c(S),o?.(S)},[s,o]),[p,m]=(0,_a.useState)(!t);(0,_a.useEffect)(()=>{if(t){m(!1);return}let S=setTimeout(()=>m(!0),W6);return()=>clearTimeout(S)},[t]);let x=(0,_a.useMemo)(()=>({open:d,setOpen:f,isWorking:t,settled:p,activeStep:a}),[d,f,t,p,a]);return(0,Ne.jsx)(d2.Provider,{value:x,children:(0,Ne.jsx)("div",{className:q("ww:mb-4 ww:flex ww:flex-col ww:gap-2",e),"data-state":d?"open":"closed",style:{animation:"ww-fade-in 0.2s ease-out"},...l,children:i})})}function m2({className:e,label:t,workingLabel:a,children:n,...r}){let{open:o,setOpen:i,isWorking:l,settled:s,activeStep:u}=f2();if(!s){let c=u?.icon,d=u?.label??a??t??"";return(0,Ne.jsx)("div",{className:q("ww:flex ww:min-h-5 ww:w-full ww:items-center ww:gap-1.5 ww:text-sm ww:text-muted-foreground",e),children:(0,Ne.jsxs)("span",{className:"ww:flex ww:min-w-0 ww:items-center ww:gap-1.5",style:{animation:"ww-fade-in 0.25s ease-out"},children:[c&&(0,Ne.jsx)(c,{className:q("ww:size-4 ww:shrink-0",l&&"ww:animate-pulse")}),(0,Ne.jsx)("span",{className:"ww:truncate",children:l?(0,Ne.jsx)(Tn,{duration:2.6,children:d}):d})]},d)})}return(0,Ne.jsxs)("button",{type:"button",onClick:()=>i(!o),"aria-expanded":o,className:q("ww:flex ww:min-h-5 ww:w-full ww:items-center ww:gap-1.5 ww:text-sm ww:text-muted-foreground ww:transition-colors ww:hover:text-foreground",e),style:{animation:"ww-fade-in 0.25s ease-out"},...r,children:[(0,Ne.jsx)("span",{className:"ww:truncate",children:n??t}),(0,Ne.jsx)(Qr,{className:q("ww:size-4 ww:shrink-0 ww:transition-transform ww:duration-200",o&&"ww:rotate-180")})]})}function h2({className:e,children:t,...a}){let{open:n}=f2();return(0,Ne.jsx)("div",{className:q("ww:grid ww:transition-[grid-template-rows,opacity] ww:duration-200 ww:ease-out",n?"ww:grid-rows-[1fr] ww:opacity-100":"ww:grid-rows-[0fr] ww:opacity-0"),children:(0,Ne.jsx)("div",{className:"ww:min-h-0 ww:overflow-hidden",children:(0,Ne.jsx)("div",{className:q("ww:flex ww:flex-col",e),...a,children:t})})})}function g2({icon:e,isLast:t,running:a,error:n}){return(0,Ne.jsxs)("div",{className:"ww:flex ww:flex-col ww:items-center ww:self-stretch",children:[(0,Ne.jsx)("span",{className:"ww:flex ww:h-5 ww:items-center",children:(0,Ne.jsx)(e,{className:q("ww:size-4 ww:shrink-0",n?"ww:text-destructive":a?"ww:animate-pulse ww:text-foreground":"ww:text-muted-foreground")})}),!t&&(0,Ne.jsx)("span",{className:"ww:w-px ww:flex-1 ww:bg-border"})]})}function Mx({className:e,icon:t,title:a,state:n,isLast:r=!1,children:o,...i}){let l=n==="input-available"||n==="input-streaming",s=n==="output-error",u=o!=null,[c,d]=(0,_a.useState)(!1),f=a??"",p=l?(0,Ne.jsx)(Tn,{duration:1.6,children:f}):(0,Ne.jsx)("span",{className:"ww:truncate",children:f});return(0,Ne.jsxs)("div",{className:q("ww:flex ww:gap-2",e),...i,children:[(0,Ne.jsx)(g2,{icon:t,isLast:r,running:l,error:s}),(0,Ne.jsxs)("div",{className:q("ww:min-w-0 ww:flex-1",!r&&"ww:pb-3"),children:[u?(0,Ne.jsxs)("button",{type:"button",onClick:()=>d(m=>!m),"aria-expanded":c,className:"ww:flex ww:w-full ww:items-center ww:gap-1.5 ww:text-left ww:text-sm ww:text-muted-foreground ww:transition-colors ww:hover:text-foreground",children:[p,(0,Ne.jsx)(Qr,{className:q("ww:size-3.5 ww:shrink-0 ww:transition-transform ww:duration-200",c&&"ww:rotate-180")})]}):(0,Ne.jsx)("div",{className:"ww:flex ww:items-center ww:text-sm ww:text-muted-foreground",children:p}),u&&(0,Ne.jsx)("div",{className:q("ww:grid ww:transition-[grid-template-rows,opacity] ww:duration-200 ww:ease-out",c?"ww:grid-rows-[1fr] ww:opacity-100":"ww:grid-rows-[0fr] ww:opacity-0"),children:(0,Ne.jsx)("div",{className:"ww:min-h-0 ww:overflow-hidden",children:(0,Ne.jsx)("div",{className:"ww:mt-2 ww:space-y-3 ww:rounded-lg ww:border ww:border-border ww:bg-background ww:p-3",children:o})})})]})]})}function w2({isStreaming:e=!1,isLast:t=!1,children:a}){return(0,Ne.jsxs)("div",{className:"ww:flex ww:gap-2",children:[(0,Ne.jsx)(g2,{icon:fr,isLast:t,running:e}),(0,Ne.jsx)("div",{className:q("ww:min-w-0 ww:flex-1",!t&&"ww:pb-3"),children:(0,Ne.jsxs)(Bu,{isStreaming:e,className:"ww:mb-0",children:[(0,Ne.jsx)(Uu,{hideIcon:!0}),(0,Ne.jsx)(Fu,{children:a})]})})]})}var Ax={name:"cjk-noop",type:"cjk",remarkPluginsBefore:[],remarkPluginsAfter:[],remarkPlugins:[]};var y2={name:"shiki-noop",type:"code-highlighter",supportsLanguage:()=>!1,getSupportedLanguages:()=>[],getThemes:()=>["github-light","github-dark"],highlight:()=>null};var b2=z(he(),1);var vr=z(he(),1),G6=5,x2=400;function v2(e,t,a={}){let{msPerChar:n=G6}=a,[r,o]=(0,vr.useState)(t?"":e),i=(0,vr.useRef)(e),l=(0,vr.useRef)(t?0:e.length),s=(0,vr.useRef)(0),u=(0,vr.useRef)(null);return(e.length<l.current||!e.startsWith(r.slice(0,l.current)))&&(l.current=t?0:e.length),i.current=e,(0,vr.useEffect)(()=>{if(!t){u.current!==null&&(cancelAnimationFrame(u.current),u.current=null),l.current=e.length,o(e);return}if(i.current.length-l.current>x2&&(l.current=i.current.length-x2),u.current!==null)return;let d=f=>{let p=i.current;if(l.current>=p.length){u.current=null;return}s.current===0&&(s.current=f);let m=f-s.current;if(m>=n){let x=Math.min(Math.floor(m/n),p.length-l.current);l.current+=x,o(p.slice(0,l.current)),s.current=f}u.current=requestAnimationFrame(d)};return u.current=requestAnimationFrame(d),()=>{u.current!==null&&(cancelAnimationFrame(u.current),u.current=null)}},[e,t,n]),r}var zu=z(re(),1),Rx=({className:e,from:t,children:a,...n})=>(0,zu.jsx)("div",{className:q("ww-message ww:group ww:flex ww:w-full",t==="user"?"ww-message-user is-user ww:ml-auto ww:flex-col ww:items-end ww:[max-width:var(--ww-msg-max-width,80%)]":"ww-message-assistant is-assistant ww:flex-col",e),...n,children:(0,zu.jsx)("div",{className:q("ww:flex ww:min-w-0 ww:flex-col ww:gap-2","ww:w-full"),children:a})}),Dx=({children:e,className:t,...a})=>(0,zu.jsx)("div",{className:q("ww-bubble ww:flex ww:w-fit ww:min-w-0 ww:max-w-full ww:flex-col ww:gap-2 ww:overflow-hidden","ww:[font-size:var(--ww-font-size,1rem)] ww:[line-height:var(--ww-line-height,1.5)]","ww:group-[.is-user]:ml-auto ww:group-[.is-user]:bg-user-bubble ww:group-[.is-user]:[color:var(--ww-color-user-bubble-text)] ww:group-[.is-user]:[border-radius:var(--ww-msg-radius,8px)] ww:group-[.is-user]:[padding:var(--ww-msg-pad-y,12px)_var(--ww-msg-pad-x,16px)]","ww:group-[.is-assistant]:text-foreground",t),...a,children:e}),$6={cjk:Ax,code:y2},X6={cjk:Ax},K6={enabled:!1};function Y6({className:e,linkSafety:t,isStreaming:a,children:n,...r}){let i=v2(typeof n=="string"?n:"",!!a),l=typeof n=="string"?i:n;return(0,zu.jsx)(Ll,{className:q("ww:size-full ww:[&>*:first-child]:mt-0 ww:[&>*:last-child]:mb-0",e),linkSafety:t??K6,plugins:a?X6:$6,...r,children:l})}var hp=(0,b2.memo)(Y6,(e,t)=>e.children===t.children&&e.isStreaming===t.isStreaming);hp.displayName="MessageResponse";var Vt=z(he(),1);function _x(e){if(!(typeof e!="object"||e===null))return e}function S2(e){return _x(e?.ui)}function Ox(e){if(!e)return;let t=S2(e)?.resourceUri;if(typeof t=="string"&&t.length>0)return t;let a=e["ui/resourceUri"];if(typeof a=="string"&&a.length>0)return a;let n=e["openai/outputTemplate"];if(typeof n=="string"&&n.length>0)return n}function qu(e){return S2(e)?.autoHeight===!0}function Px(e){return _x(_x(e)?._meta)}var Te=z(re(),1);function Z6(e,t=80){if(e==null)return String(e);if(typeof e!="object")return String(e).slice(0,t);if(Array.isArray(e))return`Array(${e.length})`;let a=JSON.stringify(e);if(a.length<=t)return a;let n=Object.entries(e),r=[],o=t-2;for(let[i,l]of n){if(o<=8)break;let s=i.length>4?`${i.slice(0,4)}\u2026`:i,u;typeof l=="string"?u=l.length>2?`'${l.slice(0,1)}\u2026`:`'${l}'`:Array.isArray(l)?u=`Array(${l.length})`:typeof l=="object"&&l!==null?u="{\u2026}":u=String(l);let c=`${s}\u2009${u}`;r.push(c),o-=c.length+3}return`{${r.join(", ")}}`}function Q6({text:e,className:t}){let{t:a}=ke(),[n,r]=(0,Vt.useState)(!1),o=(0,Vt.useRef)(null);(0,Vt.useEffect)(()=>()=>{o.current&&clearTimeout(o.current)},[]);let i=(0,Vt.useCallback)(async l=>{l.stopPropagation();try{await navigator.clipboard.writeText(e),r(!0),o.current&&clearTimeout(o.current),o.current=setTimeout(()=>r(!1),2e3)}catch{}},[e]);return(0,Te.jsx)(Bn,{variant:"ghost",size:"sm",onClick:i,className:q("ww:h-auto ww:gap-1 ww:px-1.5 ww:py-0.5 ww:text-xs ww:text-muted-foreground ww:hover:text-foreground",t),children:n?(0,Te.jsxs)(Te.Fragment,{children:[(0,Te.jsx)(Qs,{className:"ww:size-3.5"}),(0,Te.jsx)("span",{children:a.tool.copied})]}):(0,Te.jsxs)(Te.Fragment,{children:[(0,Te.jsx)(eu,{className:"ww:size-3.5"}),(0,Te.jsx)("span",{children:a.tool.copy})]})})}function I2({data:e,label:t,className:a,...n}){let[r,o]=(0,Vt.useState)(!1),i=(0,Vt.useMemo)(()=>JSON.stringify(e,null,2),[e]),l=Z6(e);return(0,Te.jsxs)("div",{className:q("ww:rounded-lg ww:bg-tool-card",a),...n,children:[(0,Te.jsxs)("div",{className:"ww:flex ww:items-center ww:justify-between ww:px-3 ww:pt-2.5 ww:pb-1.5",children:[(0,Te.jsx)("span",{className:"ww:text-xs ww:font-medium ww:text-muted-foreground",children:t}),(0,Te.jsx)(Q6,{text:i})]}),(0,Te.jsxs)("button",{type:"button",onClick:()=>o(s=>!s),className:"ww:flex ww:w-full ww:items-start ww:gap-2 ww:px-3 ww:pb-3 ww:text-left",children:[(0,Te.jsx)(Js,{className:q("ww:mt-0.5 ww:size-3.5 ww:shrink-0 ww:text-muted-foreground ww:transition-transform ww:duration-150",r&&"ww:rotate-90")}),r?(0,Te.jsx)("pre",{className:"ww:overflow-x-auto ww:text-xs ww:font-mono ww:text-foreground ww:whitespace-pre-wrap ww:break-all",children:(0,Te.jsx)("code",{children:i})}):(0,Te.jsx)("span",{className:"ww:truncate ww:text-xs ww:font-mono ww:text-foreground/80",children:l})]})]})}var Nx=(0,Vt.createContext)({open:!1,toggle:()=>{}});function C2({className:e,defaultOpen:t=!1,children:a,...n}){let[r,o]=(0,Vt.useState)(t);return(0,Te.jsx)(Nx.Provider,{value:{open:r,toggle:()=>o(i=>!i)},children:(0,Te.jsx)("div",{className:q("ww:mb-4 ww:w-full",e),"data-state":r?"open":"closed",style:{animation:"ww-fade-in 0.2s ease-out"},...n,children:a})})}function k2({className:e,title:t,state:a,...n}){let{open:r,toggle:o}=(0,Vt.useContext)(Nx),i=a==="input-available"||a==="input-streaming",l=t??"";return(0,Te.jsxs)("button",{type:"button",onClick:o,className:q("ww:flex ww:w-full ww:items-center ww:gap-2 ww:text-sm ww:text-muted-foreground ww:transition-colors ww:hover:text-foreground",e),"aria-expanded":r,...n,children:[(0,Te.jsx)(Uo,{className:"ww:size-4 ww:shrink-0"}),(0,Te.jsx)("span",{className:"ww:truncate",children:i?(0,Te.jsx)(Tn,{duration:1.6,children:l}):l}),(0,Te.jsx)(Qr,{className:q("ww:size-4 ww:shrink-0 ww:transition-transform ww:duration-200",r&&"ww:rotate-180")})]})}function T2({className:e,title:t,state:a,...n}){let r=a==="input-available"||a==="input-streaming",o=t??"";return(0,Te.jsx)("div",{className:q("ww:mb-4 ww:flex ww:items-center ww:gap-2 ww:text-sm ww:text-muted-foreground",e),style:{animation:"ww-fade-in 0.2s ease-out"},...n,children:(0,Te.jsx)("span",{className:"ww:truncate",children:r?(0,Te.jsx)(Tn,{duration:1.6,children:o}):o})})}function L2({className:e,children:t,...a}){let{open:n}=(0,Vt.useContext)(Nx);return(0,Te.jsx)("div",{className:q("ww:grid ww:transition-[grid-template-rows,opacity] ww:duration-200 ww:ease-out",n?"ww:grid-rows-[1fr] ww:opacity-100":"ww:grid-rows-[0fr] ww:opacity-0"),children:(0,Te.jsx)("div",{className:"ww:min-h-0 ww:overflow-hidden",children:(0,Te.jsx)("div",{className:q("ww:mt-2 ww:space-y-3 ww:rounded-lg ww:border ww:border-border ww:bg-background ww:p-3",e),...a,children:t})})})}function Bx({className:e,input:t,debug:a,...n}){let{t:r}=ke(),o=(0,Vt.useMemo)(()=>{if(!a&&typeof t=="object"&&t!==null&&!Array.isArray(t)){let{_meta:i,...l}=t;return l}return t},[t,a]);return(0,Te.jsx)(I2,{data:o,label:r.tool.request,className:e,...n})}function Hu(e,t,a){if(e){let n=Ox(a?.[e]?._meta);if(n)return n}return Ox(Px(t))}function E2(e,t,a){return e&&qu(a?.[e]?._meta)?!0:qu(Px(t))}function Ux({className:e,output:t,errorText:a,debug:n,...r}){let{t:o}=ke(),i=(0,Vt.useMemo)(()=>{if(!n&&typeof t=="object"&&t!==null&&!Array.isArray(t)){let{_meta:l,...s}=t;return s}return t},[t,n]);return t||a?a?(0,Te.jsxs)("div",{className:q("ww:space-y-2",e),...r,children:[(0,Te.jsx)("h4",{className:"ww:text-xs ww:font-medium ww:uppercase ww:tracking-wide ww:text-muted-foreground",children:o.tool.error}),(0,Te.jsx)("div",{className:"ww:rounded-lg ww:bg-destructive/10 ww:p-3 ww:text-xs ww:text-destructive",children:a})]}):(0,Te.jsx)(I2,{data:i,label:o.tool.response,className:e,...r}):null}var ju=z(re(),1);function M2(e){return e.type==="text"||e.type==="reasoning"||e.type==="file"||"toolCallId"in e}function A2(e){return e.parts.some(M2)}function R2(e,t,a){if(t!=="submitted"&&t!=="streaming")return!1;let n=e[e.length-1];return!n||n.role!=="assistant"?!0:!n.parts.some(o=>!(!M2(o)||a?.ignoreToolParts&&"toolCallId"in o||a?.ignoreReasoningParts&&o.type==="reasoning"))}function D2({className:e,...t}){let{t:a}=ke();return(0,ju.jsxs)("div",{"aria-live":"polite",className:q("ww:mb-4 ww:flex ww:w-full ww:items-center ww:gap-2 ww:text-sm ww:text-muted-foreground",e),style:{animation:"ww-fade-in 0.2s ease-out"},...t,children:[(0,ju.jsx)(iu,{className:"ww:size-4 ww:shrink-0"}),(0,ju.jsx)(Tn,{duration:1.6,children:a.workingIndicator.default})]})}var Je=z(he(),1);function ii(e){if(!e)return!1;let t=Array.isArray(e.content)&&e.content.length>0,a=typeof e.structuredContent=="object"&&e.structuredContent!==null&&Object.keys(e.structuredContent).length>0;return t||a}function _2(e,t){return!ii(e)&&!ii(t)?null:ii(e)?ii(t)?{...e.content||t.content?{content:[...e.content??[],...t.content??[]]}:{},...e.structuredContent||t.structuredContent?{structuredContent:{...e.structuredContent??{},...t.structuredContent??{}}}:{}}:{...e.content?{content:[...e.content]}:{},...e.structuredContent?{structuredContent:{...e.structuredContent}}:{}}:{...t?.content?{content:[...t.content]}:{},...t?.structuredContent?{structuredContent:{...t.structuredContent}}:{}}}var br=z(he(),1);var O2=(0,br.createContext)(()=>{});function P2(){return(0,br.useContext)(O2)}var N2=O2.Provider;function J6(e){let t=window.requestIdleCallback;typeof t=="function"?t(e):setTimeout(e,500)}function El(e){let t=(0,br.useRef)(e);t.current=e;let a=(0,br.useRef)(!1);(0,br.useEffect)(()=>{if(!e.painted||a.current)return;a.current=!0;let n=requestAnimationFrame(()=>{let r=t.current;Bo(r.paintMark),J6(()=>MC(r))});return()=>cancelAnimationFrame(n)},[e.painted])}var B2=z(re(),1),e9="/api/mcp/resource",t9=500,a9=0,n9=16,r9="2026-01-26",o9=300,i9=3e3,l9=3,s9=2e3;function u9(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}function c9(e,t,a){return Hu(e,t,a)?!1:t._meta?.["waniwani/autoInjectResultText"]!==!1}function gp({resourceUri:e,toolInput:t,toolResult:a,resourceEndpoint:n=e9,chatSessionId:r,isDark:o=!1,className:i,autoHeight:l=!1,onOpenLink:s,onFollowUp:u,onCallTool:c,onDisplayModeChange:d,isFullscreen:f=!1,toolDefinitions:p}){let m=(0,Je.useRef)(null),x=(0,Je.useRef)(t),S=(0,Je.useRef)(a),w=(0,Je.useRef)({width:0,height:0}),y=(0,Je.useRef)(null),h=(0,Je.useRef)(!1),b=(0,Je.useRef)(0),T=(0,Je.useRef)("inline"),[C,M]=(0,Je.useState)(a9),[R,P]=(0,Je.useState)(void 0),L=(0,Je.useRef)(s),$=(0,Je.useRef)(u),H=(0,Je.useRef)(c),F=(0,Je.useRef)(d),W=(0,Je.useRef)(r),V=(0,Je.useRef)(p);x.current=t,S.current=a,L.current=s,$.current=u,H.current=c,F.current=d,W.current=r,V.current=p;let N=(0,Je.useCallback)(v=>l?Math.max(v+n9,0):Math.min(Math.max(v,50),t9),[l]),D=(0,Je.useMemo)(()=>{let v=n.includes("?")?"&":"?";return`${n}${v}uri=${encodeURIComponent(e)}`},[n,e]),G=P2(),ue=(0,Je.useRef)(null),I=(0,Je.useRef)(void 0);(0,Je.useEffect)(()=>{let v=RC(e,G);return ue.current=v,()=>{clearTimeout(I.current),v.has("initialized")||v.report("timeout",b.current),ue.current=null}},[e,G]);let Ve=(0,Je.useRef)(o);Ve.current=o;let et=(0,Je.useRef)(f);return(0,Je.useEffect)(()=>{et.current=f,w.current.height=-1,y.current&&(y.current.cancel(),y.current=null)},[f]),(0,Je.useEffect)(()=>{if(!h.current)return;let v=m.current;v?.contentWindow&&v.contentWindow.postMessage({jsonrpc:"2.0",method:"ui/notifications/host-context-changed",params:{theme:o?"dark":"light"}},"*")},[o]),(0,Je.useEffect)(()=>{let v=m.current;if(!v)return;let K=!1,ee=!1,we=null,We=null,me=setTimeout(()=>{if(K||ee||b.current>=l9)return;b.current+=1;let de=new URL(v.src);de.searchParams.set("_retry",String(b.current)),v.src=de.toString()},i9),be=de=>{v.contentWindow?.postMessage(de,"*")},le=de=>{if(K||de.source!==v.contentWindow)return;let Q=de.data;if(!Q||typeof Q!="object"||Q.jsonrpc!=="2.0")return;let Be=Q.method,qe=Q.id;if(Be==="ui/initialize"&&qe!=null){ee=!0,ue.current?.mark("initialize"),clearTimeout(me),be({jsonrpc:"2.0",id:qe,result:{protocolVersion:Q.params?.protocolVersion??r9,hostInfo:{name:"Waniwani Chat",version:"1.0.0"},hostCapabilities:{openLinks:{},message:{text:{}},tools:{},updateModelContext:{text:{},structuredContent:{}}},hostContext:{theme:Ve.current?"dark":"light",displayMode:T.current}}});return}if(Be==="ui/notifications/initialized"){h.current=!0,ue.current?.mark("initialized"),I.current=setTimeout(()=>ue.current?.report("ok",b.current),s9);let _e=x.current,Ce=S.current,ye=Ce._meta&&typeof Ce._meta=="object"?Ce._meta:null,Y=u9(W.current),Oe=ye&&typeof ye.waniwani=="object"&&ye.waniwani!==null?ye.waniwani:null,ot=Oe||Y?{...Oe??{},...Y?{sessionId:Y}:{}}:void 0,ba=ye||ot?{...ye??{},...ot?{waniwani:ot}:{}}:void 0;be({jsonrpc:"2.0",method:"ui/notifications/tool-input",params:{arguments:_e}});let Sa=Ce.content??[{type:"text",text:JSON.stringify(Ce)}];be({jsonrpc:"2.0",method:"ui/notifications/tool-result",params:{content:Sa,structuredContent:Ce.structuredContent,_meta:ba,meta:ba}});return}if(Be==="ui/notifications/size-changed"){clearTimeout(I.current),ue.current?.mark("firstSize"),ue.current?.report("ok",b.current);let _e=Q.params,Ce=typeof _e?.height=="number"?_e.height:void 0,ye=typeof _e?.width=="number"?_e.width:void 0,Y=w.current,Oe=Ce!==void 0&&Ce!==Y.height,ot=ye!==void 0&&ye!==Y.width;if(!Oe&&!ot)return;if(Oe&&Ce!==void 0){if(Y.height=Ce,et.current)return;let ba=N(Ce),Sa=v.getBoundingClientRect().height;if(y.current&&(y.current.cancel(),y.current=null),M(ba),v.animate&&Math.abs(Sa-ba)>2){let ra=v.animate([{height:`${Sa}px`},{height:`${ba}px`}],{duration:o9,easing:"ease-out",fill:"forwards"});y.current=ra,ra.onfinish=()=>{y.current===ra&&(ra.cancel(),y.current=null)}}}ot&&l&&ye!==void 0&&(Y.width=ye,P(ye));return}if(Be==="ui/open-link"&&qe!=null){let _e=Q.params?.url;typeof _e=="string"&&(L.current?L.current(_e):window.open(_e,"_blank","noopener,noreferrer")),be({jsonrpc:"2.0",id:qe,result:{}});return}if(Be==="ui/message"&&qe!=null){if($.current&&Q.params){let _e=Q.params,Ce=we;if(we=null,We){clearTimeout(We.timer);let ye=We.text;We=null;let Y=(_e.content??[]).map(Oe=>Oe.text??"").join("").trim();_e={..._e,content:[{type:"text",text:`${Y}
|
|
122
122
|
|
|
123
123
|
${ye}`}]}}$.current({..._e,...Ce?{modelContext:Ce}:{}})}be({jsonrpc:"2.0",id:qe,result:{}});return}if(Be==="ui/update-model-context"&&qe!=null){we=_2(we,Q.params),be({jsonrpc:"2.0",id:qe,result:{}});return}if(Be==="tools/call"&&qe!=null){let _e=H.current;if(!_e){be({jsonrpc:"2.0",id:qe,error:{code:-32601,message:"tools/call not supported"}});return}let Ce=Q.params?.name;_e({name:Ce,arguments:Q.params?.arguments??{}}).then(ye=>{be({jsonrpc:"2.0",id:qe,result:ye});let Y=ye.content?.map(Oe=>Oe.text??"").join("").trim();Y&&c9(Ce,ye,V.current)&&(We&&clearTimeout(We.timer),We={text:Y,timer:setTimeout(()=>{if(K)return;let Oe=we;we=null,We=null,$.current?.({role:"user",content:[{type:"text",text:Y}],...Oe?{modelContext:Oe}:{}})},500)})}).catch(ye=>{let Y=ye instanceof Error?ye.message:"Tool call failed";be({jsonrpc:"2.0",id:qe,error:{code:-32e3,message:Y}})});return}if(Be==="ui/request-display-mode"&&qe!=null){let _e=Q.params?.mode,Ce=_e==="fullscreen"||_e==="inline"||_e==="pip"?_e:"inline";T.current=Ce,be({jsonrpc:"2.0",id:qe,result:{mode:Ce}}),be({jsonrpc:"2.0",method:"ui/notifications/host-context-changed",params:{displayMode:Ce}}),F.current?.(Ce);return}if(Be==="ui/resource-teardown"&&qe!=null){be({jsonrpc:"2.0",id:qe,result:{}});return}Be==="ping"&&qe!=null&&be({jsonrpc:"2.0",id:qe,result:{}})};return window.addEventListener("message",le),()=>{K=!0,clearTimeout(me),We&&clearTimeout(We.timer),window.removeEventListener("message",le)}},[l,N]),(0,B2.jsx)("iframe",{ref:m,src:D,onLoad:()=>ue.current?.mark("iframeLoad"),sandbox:"allow-scripts allow-forms allow-same-origin allow-popups allow-popups-to-escape-sandbox",className:q(!f&&"ww:rounded-md ww:border ww:border-border",i),style:{height:f?"100%":C,minWidth:f||!R?void 0:`min(${R}px, 100%)`,width:"100%",border:"none",colorScheme:o?"dark":"auto"},title:"MCP App"})}var uo=z(re(),1);function U2({icon:e,title:t,description:a,suggestions:n,onSuggestionSelect:r}){return(0,uo.jsxs)("div",{className:"ww:flex ww:flex-col ww:items-center ww:justify-center ww:py-12 ww:px-6 ww:text-center ww:min-h-full",children:[e&&(0,uo.jsx)("div",{className:"ww:mb-4 ww:flex ww:items-center ww:justify-center ww:size-12 ww:rounded-xl ww:bg-foreground ww:text-background",children:e}),(0,uo.jsx)("h2",{className:"ww:text-lg ww:font-semibold ww:text-foreground",children:t}),a&&(0,uo.jsx)("p",{className:"ww:mt-1 ww:text-sm ww:text-muted-foreground ww:max-w-sm",children:a}),n&&n.length>0&&(0,uo.jsx)("div",{className:"ww:mt-6 ww:w-full ww:max-w-md ww:flex ww:flex-col ww:gap-2",children:n.map((o,i)=>(0,uo.jsx)("button",{type:"button",onClick:()=>r?.(o),className:q("ww:w-full ww:text-left ww:rounded-xl ww:border ww:border-border ww:bg-background ww:px-4 ww:py-3 ww:text-sm","ww:text-foreground ww:hover:bg-accent ww:hover:border-primary/30","ww:transition-all ww:duration-200 ww:ease-out ww:cursor-pointer","ww:animate-[ww-fade-in_0.2s_ease-out_both]"),style:{animationDelay:`${i*50}ms`},children:o},o))})]})}var F2=z(he(),1);var Ml=z(re(),1);function d9({onRetry:e}){let{t}=ke();return(0,Ml.jsxs)("div",{className:"ww:flex ww:items-center ww:justify-between ww:rounded-md ww:border ww:border-border ww:bg-muted/50 ww:px-4 ww:py-3 ww:text-sm ww:text-muted-foreground",children:[(0,Ml.jsx)("span",{children:t.widgetErrorBoundary.failedToLoad}),(0,Ml.jsx)("button",{type:"button",onClick:e,className:"ww:text-xs ww:font-medium ww:text-primary ww:hover:underline",children:t.widgetErrorBoundary.retry})]})}var wp=class extends F2.Component{constructor(){super(...arguments);ne(this,"state",{hasError:!1})}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(a){console.warn("[Waniwani] Widget failed to render:",a.message)}render(){return this.state.hasError?(0,Ml.jsx)(d9,{onRetry:()=>this.setState({hasError:!1})}):this.props.children}};var Le=z(re(),1);function Fx(e){return e?e.replace(/[-_]/g," ").replace(/^\w/,t=>t.toUpperCase()):"Tool"}function z2(e){return e&&/search|find|lookup|query|web|browse|google/i.test(e)?au:Uo}function q2({messages:e,status:t,welcomeMessage:a,welcome:n,onSuggestionSelect:r,resourceEndpoint:o,chatSessionId:i,isDark:l,onFollowUp:s,onCallTool:u,onWidgetDisplayModeChange:c,fullscreenToolCallId:d,debug:f,showToolCalls:p=!0,toolDefinitions:m,messageClassNames:x}){let{t:S}=ke(),w=e[e.length-1],y=e.length>0,h=d!=null,b=!h&&R2(e,t,{ignoreToolParts:p===!1,ignoreReasoningParts:p===!1});return(0,Le.jsxs)(Le.Fragment,{children:[!h&&(!y&&n?(0,Le.jsx)(U2,{...n,onSuggestionSelect:r}):a&&(0,Le.jsx)(Rx,{from:"assistant",children:(0,Le.jsx)(Dx,{children:(0,Le.jsx)(hp,{children:a})})})),e.map(T=>{let C=T.parts.filter(N=>N.type==="text"),M=T.parts.filter(N=>N.type==="reasoning"),R=T.parts.filter(N=>N.type==="file"),P=uk(T.metadata),L=T.parts.filter(N=>"toolCallId"in N),$=T.parts.filter(N=>N.type==="reasoning"||"toolCallId"in N),H=T===w&&T.role==="assistant",F=C.length>0,W=h?L.some(N=>N.toolCallId===d):!1,V=p!==!1&&!W&&$.length>=2;return h&&!W?(0,Le.jsx)("div",{style:{display:"none"}},T.id):T.role==="assistant"&&!A2(T)?(0,Le.jsx)("div",{style:{display:"none"}},T.id):p===!1&&T.role==="assistant"&&!F&&R.length===0&&L.every(N=>{let D="output"in N?N.output:void 0;return D===void 0||!o||!Hu(N.toolName,D,m)})?(0,Le.jsx)("div",{style:{display:"none"}},T.id):(0,Le.jsxs)(Rx,{from:T.role,className:x?.message,children:[p!==!1&&!W&&!V&&M.map((N,D)=>(0,Le.jsxs)(Bu,{isStreaming:N.state==="streaming",children:[(0,Le.jsx)(Uu,{}),(0,Le.jsx)(Fu,{children:N.text})]},`reasoning-${T.id}-${D}`)),V&&(()=>{let N=$[$.length-1],D=N.type==="reasoning"?{icon:fr,label:S.reasoning.thinking}:{icon:z2(N.toolName),label:N.title??Fx(N.toolName)};return(0,Le.jsxs)(p2,{isWorking:H&&(t==="streaming"||t==="submitted"),activeStep:D,children:[(0,Le.jsx)(m2,{workingLabel:S.chainOfThought.working,label:S.chainOfThought.done}),(0,Le.jsx)(h2,{children:$.map((G,ue)=>{let I=ue===$.length-1;if(G.type==="reasoning")return(0,Le.jsx)(w2,{isStreaming:G.state==="streaming",isLast:I,children:G.text},`reasoning-${T.id}-${ue}`);let Ve=G.title??Fx(G.toolName),et=z2(G.toolName);if(p==="titles-only")return(0,Le.jsx)(Mx,{icon:et,title:Ve,state:G.state,isLast:I},G.toolCallId);let v="output"in G?G.output:void 0;return(0,Le.jsxs)(Mx,{icon:et,title:Ve,state:G.state,isLast:I,children:[(0,Le.jsx)(Bx,{input:G.input,debug:f}),v!==void 0&&(0,Le.jsx)(Ux,{output:v,errorText:"errorText"in G?G.errorText:void 0,debug:f})]},G.toolCallId)})})]})})(),p!==!1&&!W&&!V&&L.length===1&&(()=>{let N=L[0],D=N.title??Fx(N.toolName);if(p==="titles-only")return(0,Le.jsx)(T2,{title:D,state:N.state});let G="output"in N?N.output:void 0;return(0,Le.jsxs)(C2,{children:[(0,Le.jsx)(k2,{title:D,state:N.state}),(0,Le.jsxs)(L2,{children:[(0,Le.jsx)(Bx,{input:N.input,debug:f}),G!==void 0&&(0,Le.jsx)(Ux,{output:G,errorText:"errorText"in N?N.errorText:void 0,debug:f})]})]})})(),L.map(N=>{let D="output"in N?N.output:void 0,G=Hu(N.toolName,D,m),ue=E2(N.toolName,D,m),I=N.toolCallId===d;return G&&o&&D!==void 0?(0,Le.jsx)("div",{style:I?{position:"absolute",inset:0,zIndex:10,display:"flex",flexDirection:"column",overflow:"hidden",background:"var(--ww-color-background)"}:void 0,children:G&&o&&D!==void 0&&(0,Le.jsx)(wp,{children:(0,Le.jsx)(gp,{isFullscreen:I,resourceUri:G,toolInput:N.input??{},toolResult:{content:D.content,structuredContent:D.structuredContent,_meta:D._meta},resourceEndpoint:o,chatSessionId:i,isDark:l,autoHeight:ue,toolDefinitions:m,onFollowUp:s,onCallTool:u,onDisplayModeChange:c?Ve=>c(Ve,{toolCallId:N.toolCallId,resourceUri:G,toolInput:N.input??{},toolResult:{content:D.content,structuredContent:D.structuredContent,_meta:D._meta},autoHeight:ue}):void 0})})},N.toolCallId):null}),!W&&P.length>0&&(0,Le.jsx)(ck,{documents:P}),!W&&(0,Le.jsx)("div",{children:(0,Le.jsxs)(Dx,{className:q(T.role==="user"?x?.userBubble:x?.assistantBubble),children:[R.length>0&&(0,Le.jsx)(lk,{files:R}),F?C.map((N,D)=>{let G=H&&t==="streaming"&&D===C.length-1;return(0,Le.jsx)(hp,{isStreaming:G,children:N.type==="text"?N.text:""},`${T.id}-${D}`)}):null]})})]},T.id)}),b&&(0,Le.jsx)(D2,{})]})}var Vu=z(re(),1),f9="https://app.waniwani.ai/assets/waniwani-logo.svg",p9="https://waniwani.ai";function H2(){let{t:e}=ke();return(0,Vu.jsxs)("a",{href:p9,target:"_blank",rel:"noopener noreferrer",className:"ww:flex ww:items-center ww:gap-1.5 ww:whitespace-nowrap ww:text-[10px] ww:sm:text-[11px] ww:text-muted-foreground ww:opacity-70 hover:ww:opacity-100 ww:transition-opacity",children:[(0,Vu.jsx)("span",{children:e.poweredBy.label}),(0,Vu.jsx)("img",{src:f9,alt:"Waniwani",width:72,height:10,"data-waniwani-logo":"",className:"ww:h-2.5 ww:w-auto"})]})}var Al=z(he(),1);var Ke=z(re(),1),j2=20;function m9({label:e}){return(0,Ke.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",role:"img","aria-label":e,children:[(0,Ke.jsx)("title",{children:e}),(0,Ke.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,Ke.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function h9({label:e}){return(0,Ke.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",role:"img","aria-label":e,children:[(0,Ke.jsx)("title",{children:e}),(0,Ke.jsx)("path",{d:"M3 12a9 9 0 1 0 3-6.7"}),(0,Ke.jsx)("polyline",{points:"3 4 3 9 8 9"}),(0,Ke.jsx)("line",{x1:"12",y1:"7",x2:"12",y2:"12"}),(0,Ke.jsx)("line",{x1:"12",y1:"12",x2:"15",y2:"14"})]})}function g9({label:e}){return(0,Ke.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",role:"img","aria-label":e,children:[(0,Ke.jsx)("title",{children:e}),(0,Ke.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,Ke.jsx)("path",{d:"M19 6l-2 14a2 2 0 0 1-2 2H9a2 2 0 0 1-2-2L5 6"}),(0,Ke.jsx)("path",{d:"M10 11v6"}),(0,Ke.jsx)("path",{d:"M14 11v6"})]})}function V2({threads:e,activeThreadId:t,onNewThread:a,onSelectThread:n,onDeleteThread:r}){let{locale:o,t:i}=ke(),[l,s]=(0,Al.useState)(!1),u=(0,Al.useRef)(null);(0,Al.useEffect)(()=>{if(!l)return;let f=p=>{let m=u.current;m&&(p.composedPath().includes(m)||s(!1))};return document.addEventListener("mousedown",f),()=>document.removeEventListener("mousedown",f)},[l]);let c=e.slice(0,j2),d=Math.max(0,e.length-j2);return(0,Ke.jsxs)("div",{ref:u,className:"ww:relative ww:flex ww:items-center ww:gap-1",children:[(0,Ke.jsx)("button",{type:"button",onClick:a,title:i.threadMenu.newChat,"aria-label":i.threadMenu.newChat,className:"ww:p-1.5 ww:rounded-md ww:text-muted-foreground hover:ww:text-foreground hover:ww:bg-foreground/5 ww:transition-colors ww:cursor-pointer",children:(0,Ke.jsx)(m9,{label:i.threadMenu.newChat})}),(0,Ke.jsx)("button",{type:"button",onClick:()=>s(f=>!f),title:i.threadMenu.threadHistory,"aria-label":i.threadMenu.threadHistory,"aria-expanded":l,className:"ww:p-1.5 ww:rounded-md ww:text-muted-foreground hover:ww:text-foreground hover:ww:bg-foreground/5 ww:transition-colors ww:cursor-pointer",children:(0,Ke.jsx)(h9,{label:i.threadMenu.threadHistory})}),l&&(0,Ke.jsxs)("div",{role:"menu",className:"ww:absolute ww:right-0 ww:top-full ww:mt-1 ww:w-72 ww:max-h-80 ww:overflow-y-auto ww:rounded-lg ww:border ww:border-border ww:bg-background ww:shadow-lg ww:z-50",children:[c.length===0&&(0,Ke.jsx)("div",{className:"ww:px-3 ww:py-3 ww:text-xs ww:text-muted-foreground",children:i.threadMenu.noPreviousChats}),c.map(f=>{let p=f.threadId===t,m=Date.parse(f.updatedAt);return(0,Ke.jsxs)("div",{className:`ww:flex ww:items-center ww:gap-2 ww:px-3 ww:py-2 ww:text-xs hover:ww:bg-foreground/5 ${p?"ww:bg-foreground/5":""}`,children:[(0,Ke.jsxs)("button",{type:"button",onClick:()=>{n(f.threadId),s(!1)},className:"ww:flex-1 ww:min-w-0 ww:text-left ww:cursor-pointer",children:[(0,Ke.jsx)("div",{className:"ww:truncate ww:text-foreground ww:font-medium",children:f.title}),(0,Ke.jsx)("div",{className:"ww:text-[10px] ww:text-muted-foreground",children:Number.isNaN(m)?"":ew(m,o)})]}),(0,Ke.jsx)("button",{type:"button",onClick:x=>{x.stopPropagation(),r(f.threadId)},title:i.threadMenu.deleteThread,"aria-label":i.threadMenu.deleteThread,className:"ww:p-1 ww:rounded ww:text-muted-foreground hover:ww:text-foreground hover:ww:bg-foreground/10 ww:transition-colors ww:cursor-pointer",children:(0,Ke.jsx)(g9,{label:i.threadMenu.deleteThread})})]},f.threadId)}),d>0&&(0,Ke.jsx)("div",{className:"ww:px-3 ww:py-2 ww:text-[10px] ww:text-muted-foreground ww:border-t ww:border-border",children:i.threadMenu.hiddenThreads(d)})]})]})}var yp=z(he(),1);function Rl(e){let t=new Set;return{subscribe(a){return t.add(a),()=>{t.delete(a)}},emit(a){let{sessionId:n,...r}=a,o=a.name==="session.started"?a.properties.sessionId:void 0,i={...r,mode:e.mode,sessionId:Object.hasOwn(a,"sessionId")?n:o??e.getSessionId?.(),timestamp:Date.now()};for(let l of[...t])try{l(i)}catch(s){console.warn("[Waniwani] onEvent subscriber threw:",s)}}}}function W2(){return{subscribe(){return()=>{}},emit(){}}}var G2=(0,yp.createContext)(W2());function xp(){return(0,yp.useContext)(G2)}var Dl=G2.Provider;var vp=z(he(),1);function $2(e){let t=(0,vp.useRef)(e);return t.current=e,(0,vp.useCallback)(async a=>{let{api:n,headers:r,onCallTool:o,sessionId:i}=t.current;if(o)return o(a);let l=ma(n??"/api/waniwani","/tool"),s=typeof i=="string"&&i.trim().length>0?i.trim():void 0,u=await fetch(l,{method:"POST",headers:{"Content-Type":"application/json",...s?{"X-Session-Id":s}:{},...r},body:JSON.stringify(a)});if(!u.ok)throw new Error(`Tool call failed: ${u.status} ${u.statusText}`);return u.json()},[])}var pn=z(he(),1);var SD="vercel.ai.error",w9=Symbol.for(SD),X2,K2,Fe=class ID extends(K2=Error,X2=w9,K2){constructor({name:t,message:a,cause:n}){super(a),this[X2]=!0,this.name=t,this.cause=n}static isInstance(t){return ID.hasMarker(t,SD)}static hasMarker(t,a){let n=Symbol.for(a);return t!=null&&typeof t=="object"&&n in t&&typeof t[n]=="boolean"&&t[n]===!0}},CD="AI_APICallError",kD=`vercel.ai.error.${CD}`,y9=Symbol.for(kD),Y2,Z2,Vie=class extends(Z2=Fe,Y2=y9,Z2){constructor({message:e,url:t,requestBodyValues:a,statusCode:n,responseHeaders:r,responseBody:o,cause:i,isRetryable:l=n!=null&&(n===408||n===409||n===429||n>=500),data:s}){super({name:CD,message:e,cause:i}),this[Y2]=!0,this.url=t,this.requestBodyValues=a,this.statusCode=n,this.responseHeaders=r,this.responseBody=o,this.isRetryable=l,this.data=s}static isInstance(e){return Fe.hasMarker(e,kD)}},TD="AI_EmptyResponseBodyError",LD=`vercel.ai.error.${TD}`,x9=Symbol.for(LD),Q2,J2,Wie=class extends(J2=Fe,Q2=x9,J2){constructor({message:e="Empty response body"}={}){super({name:TD,message:e}),this[Q2]=!0}static isInstance(e){return Fe.hasMarker(e,LD)}};function ED(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var MD="AI_InvalidArgumentError",AD=`vercel.ai.error.${MD}`,v9=Symbol.for(AD),eD,tD,RD=class extends(tD=Fe,eD=v9,tD){constructor({message:e,cause:t,argument:a}){super({name:MD,message:e,cause:t}),this[eD]=!0,this.argument=a}static isInstance(e){return Fe.hasMarker(e,AD)}},DD="AI_InvalidPromptError",_D=`vercel.ai.error.${DD}`,b9=Symbol.for(_D),aD,nD,Gie=class extends(nD=Fe,aD=b9,nD){constructor({prompt:e,message:t,cause:a}){super({name:DD,message:`Invalid prompt: ${t}`,cause:a}),this[aD]=!0,this.prompt=e}static isInstance(e){return Fe.hasMarker(e,_D)}},OD="AI_InvalidResponseDataError",PD=`vercel.ai.error.${OD}`,S9=Symbol.for(PD),rD,oD,$ie=class extends(oD=Fe,rD=S9,oD){constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:OD,message:t}),this[rD]=!0,this.data=e}static isInstance(e){return Fe.hasMarker(e,PD)}},ND="AI_JSONParseError",BD=`vercel.ai.error.${ND}`,I9=Symbol.for(BD),iD,lD,qx=class extends(lD=Fe,iD=I9,lD){constructor({text:e,cause:t}){super({name:ND,message:`JSON parsing failed: Text: ${e}.
|
|
124
124
|
Error message: ${ED(t)}`,cause:t}),this[iD]=!0,this.text=e}static isInstance(e){return Fe.hasMarker(e,BD)}},UD="AI_LoadAPIKeyError",FD=`vercel.ai.error.${UD}`,C9=Symbol.for(FD),sD,uD,Xie=class extends(uD=Fe,sD=C9,uD){constructor({message:e}){super({name:UD,message:e}),this[sD]=!0}static isInstance(e){return Fe.hasMarker(e,FD)}},zD="AI_LoadSettingError",qD=`vercel.ai.error.${zD}`,k9=Symbol.for(qD),cD,dD,Kie=class extends(dD=Fe,cD=k9,dD){constructor({message:e}){super({name:zD,message:e}),this[cD]=!0}static isInstance(e){return Fe.hasMarker(e,qD)}},HD="AI_NoContentGeneratedError",jD=`vercel.ai.error.${HD}`,T9=Symbol.for(jD),fD,pD,Yie=class extends(pD=Fe,fD=T9,pD){constructor({message:e="No content generated."}={}){super({name:HD,message:e}),this[fD]=!0}static isInstance(e){return Fe.hasMarker(e,jD)}},VD="AI_NoSuchModelError",WD=`vercel.ai.error.${VD}`,L9=Symbol.for(WD),mD,hD,Zie=class extends(hD=Fe,mD=L9,hD){constructor({errorName:e=VD,modelId:t,modelType:a,message:n=`No such ${a}: ${t}`}){super({name:e,message:n}),this[mD]=!0,this.modelId=t,this.modelType=a}static isInstance(e){return Fe.hasMarker(e,WD)}},GD="AI_TooManyEmbeddingValuesForCallError",$D=`vercel.ai.error.${GD}`,E9=Symbol.for($D),gD,wD,Qie=class extends(wD=Fe,gD=E9,wD){constructor(e){super({name:GD,message:`Too many values for a single embedding call. The ${e.provider} model "${e.modelId}" can only embed up to ${e.maxEmbeddingsPerCall} values per call, but ${e.values.length} values were provided.`}),this[gD]=!0,this.provider=e.provider,this.modelId=e.modelId,this.maxEmbeddingsPerCall=e.maxEmbeddingsPerCall,this.values=e.values}static isInstance(e){return Fe.hasMarker(e,$D)}},XD="AI_TypeValidationError",KD=`vercel.ai.error.${XD}`,M9=Symbol.for(KD),yD,xD,qn=class zx extends(xD=Fe,yD=M9,xD){constructor({value:t,cause:a,context:n}){let r="Type validation failed";if(n?.field&&(r+=` for ${n.field}`),n?.entityName||n?.entityId){r+=" (";let o=[];n.entityName&&o.push(n.entityName),n.entityId&&o.push(`id: "${n.entityId}"`),r+=o.join(", "),r+=")"}super({name:XD,message:`${r}: Value: ${JSON.stringify(t)}.
|