@waniwani/sdk 0.22.0-beta.4 → 0.22.0-beta.5
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 +11 -11
- package/dist/chat/index.js.map +1 -1
- package/package.json +1 -1
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
|
`)},bx=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("")},x6=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=>bx(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?bx(l[u]):"";n[r]=`| ${s.join(" | ")} |`,r+=1}else{let s=l.map(u=>bx(u));n[r]=`| ${s.join(" | ")} |`,r+=1}return n.join(`
|
|
119
119
|
`)},v6=({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=_R(y),b=m==="csv"?OR(h):y6(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?Tx:Lx;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]})},b6=({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=_R(f),m=u==="csv"?OR(p):x6(p);Ll(`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)(mp,{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]})},S6=({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)(v6,{}),(0,E.jsx)(b6,{})]}):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})})]}),I6=(0,_.lazy)(()=>Promise.resolve().then(()=>(xR(),yR)).then(e=>({default:e.CodeBlock}))),C6=(0,_.lazy)(()=>Promise.resolve().then(()=>(SR(),bR)).then(e=>({default:e.Mermaid}))),k6=/language-([^\s]+)/;kx=(e,t)=>typeof e=="boolean"?e:e[t]!==!1,fp=(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},Mx=(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));Mx.displayName="MarkdownOl";PR=(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&&hp(e.node,t.node));PR.displayName="MarkdownLi";NR=(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));NR.displayName="MarkdownUl";BR=(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));BR.displayName="MarkdownHr";UR=(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));UR.displayName="MarkdownStrong";T6=({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)(f6,{...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})},FR=(0,_.memo)(T6,(e,t)=>Lt(e,t)&&e.href===t.href);FR.displayName="MarkdownA";zR=(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));zR.displayName="MarkdownH1";qR=(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));qR.displayName="MarkdownH2";HR=(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));HR.displayName="MarkdownH3";jR=(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));jR.displayName="MarkdownH4";VR=(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));VR.displayName="MarkdownH5";WR=(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));WR.displayName="MarkdownH6";GR=(0,_.memo)(({children:e,className:t,node:a,...n})=>{let{controls:r}=(0,_.useContext)(ya),o=kx(r,"table");return(0,E.jsx)(S6,{className:t,showControls:o,...n,children:e})},(e,t)=>Lt(e,t));GR.displayName="MarkdownTable";$R=(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));$R.displayName="MarkdownThead";XR=(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));XR.displayName="MarkdownTbody";KR=(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));KR.displayName="MarkdownTr";YR=(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));YR.displayName="MarkdownTh";ZR=(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));ZR.displayName="MarkdownTd";QR=(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));QR.displayName="MarkdownBlockquote";JR=(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));JR.displayName="MarkdownSup";e2=(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));e2.displayName="MarkdownSub";t2=(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===Mx){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));t2.displayName="MarkdownSection";L6=({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=Ex();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(k6),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=kx(u,"mermaid"),S=fp(u,"download"),w=fp(u,"copy"),y=fp(u,"fullscreen"),h=fp(u,"panZoom"),b=x&&(S||w||y);return(0,E.jsx)(_.Suspense,{fallback:(0,E.jsx)(TR,{}),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)(m6,{chart:p,config:s?.config}):null,w?(0,E.jsx)(CR,{code:p}):null,y?(0,E.jsx)(w6,{chart:p,config:s?.config}):null]}):null,(0,E.jsx)(C6,{chart:p,config:s?.config,showControls:h})]})})}let m=kx(u,"code");return(0,E.jsx)(_.Suspense,{fallback:(0,E.jsx)(TR,{}),children:(0,E.jsx)(I6,{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)(l6,{code:p,language:f}),(0,E.jsx)(CR,{})]}):null})})},a2=(0,_.memo)(L6,(e,t)=>e.className===t.className&&hp(e.node,t.node));a2.displayName="MarkdownCode";n2=(0,_.memo)(u6,(e,t)=>e.className===t.className&&hp(e.node,t.node));n2.displayName="MarkdownImg";r2=(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));r2.displayName="MarkdownParagraph";E6={ol:Mx,li:PR,ul:NR,hr:BR,strong:UR,a:FR,h1:zR,h2:qR,h3:HR,h4:jR,h5:VR,h6:WR,table:GR,thead:$R,tbody:XR,tr:KR,th:YR,td:ZR,blockquote:QR,code:a2,img:n2,pre:({children:e})=>e,sup:JR,sub:e2,p:r2,section:t2},LR=[],ER={allowDangerousHtml:!0},pp=new WeakMap,M6=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=pp.get(m);S||(S=m.name,pp.set(m,S)),d+=S}else d+=String(m);d+=":",d+=JSON.stringify(x)}else if(typeof p=="function"){let m=pp.get(p);m||(m=p.name,pp.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()}},MR=new M6,o2=e=>{let t=A6(e),a=e.children||"";return D6(t.runSync(t.parse(a),a),e)},A6=e=>{let t=MR.get(e);if(t)return t;let a=R6(e);return MR.set(e,a),a},R6=e=>{let t=e.rehypePlugins||LR,a=e.remarkPlugins||LR,n=e.remarkRehypeOptions?{...ER,...e.remarkRehypeOptions}:ER;return ix().use(Yf).use(a).use(ep,n).use(t)},D6=(e,t)=>Fy(e,{Fragment:E.Fragment,components:t.components,ignoreInvalidStyle:!0,jsx:E.jsx,jsxs:E.jsxs,passKeys:!0,passNode:!0}),_6=/\[\^[^\]\s]{1,200}\](?!:)/,O6=/\[\^[^\]\s]{1,200}\]:/,P6=/<\/(\w+)>/,N6=/<(\w+)[\s>]/,Sx=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]==="$"},B6=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]==="$"},Ix=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},i2=e=>{let t=_6.test(e),a=O6.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(P6);if(u){let c=u[1];o.at(-1)===c&&o.pop()}}continue}if(i.type==="html"&&i.block){let u=l.match(N6);if(u){let c=u[1];l.includes(`</${c}>`)||o.push(c)}}if(l.trim()==="$$"&&s>0){let u=r[s-1],c=Sx(u),d=Ix(u);if(c&&d%2===1){r[s-1]=u+l;continue}}if(s>0&&B6(l)){let u=r[s-1],c=Sx(u),d=Ix(u),f=Ix(l);if(c&&d%2===1&&!Sx(l)&&f===1){r[s-1]=u+l;continue}}r.push(l)}return r},l2={raw:zk,sanitize:[gf,{}],harden:[Uk,{allowedImagePrefixes:["*"],allowedLinkPrefixes:["*"],allowedProtocols:["*"],defaultOrigin:void 0,allowDataImages:!0}]},s2={gfm:[qf,{}]},U6=Object.values(l2),F6=Object.values(s2),z6={block:" \u258B",circle:" \u25CF"},q6={shikiTheme:["github-light","github-dark"],controls:!0,isAnimating:!1,mode:"streaming",mermaid:void 0,linkSafety:{enabled:!0}},ya=(0,_.createContext)(q6),Ax=(0,_.memo)(({content:e,shouldParseIncompleteMarkdown:t,index:a,...n})=>(0,E.jsx)(o2,{...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)});Ax.displayName="Block";H6=["github-light","github-dark"],El=(0,_.memo)(({children:e,mode:t="streaming",parseIncompleteMarkdown:a=!0,components:n,rehypePlugins:r=U6,remarkPlugins:o=F6,className:i,shikiTheme:l=H6,mermaid:s,controls:u=!0,isAnimating:c=!1,BlockComponent:d=Ax,parseMarkdownIntoBlocksFn:f=i2,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?QL(e,x):e,[e,t,a,x]),C=(0,_.useMemo)(()=>f(T),[T,f]),[M,D]=(0,_.useState)(C);(0,_.useEffect)(()=>{t==="streaming"?b(()=>{D(C)}):D(C)},[C,t]);let P=t==="streaming"?M:C,L=(0,_.useMemo)(()=>P.map((N,R)=>`${y}-${R}`),[P.length,y]),$=(0,_.useMemo)(()=>{var N,R;return{shikiTheme:(R=(N=m?.code)==null?void 0:N.getThemes())!=null?R:l,controls:u,isAnimating:c,mode:t,mermaid:s,linkSafety:S}},[l,u,c,t,s,S,m?.code]),H=(0,_.useMemo)(()=>({...E6,...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":`"${z6[p]}"`}:void 0,[p,c]);return t==="static"?(0,E.jsx)(Cx.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)(o2,{components:H,rehypePlugins:W,remarkPlugins:F,...w,children:e})})})}):(0,E.jsx)(Cx.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,R)=>(0,E.jsx)(d,{components:H,content:N,index:R,rehypePlugins:W,remarkPlugins:F,shouldParseIncompleteMarkdown:a,...w},L[R]))]})})})},(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);El.displayName="Streamdown";j6=({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]),D=(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",D,{passive:!1}),()=>{H.removeEventListener("wheel",D)}},[D]),(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)(o6,{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)(i6,{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)(r6,{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})]})},vx=({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=Ex(),w=x?.errorComponent,{shouldRender:y,containerRef:h}=t6({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:D}=await T.render(M,e);c(D),f(D)}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)(j6,{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 D_=oa((kse,R_)=>{"use strict";function LV(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)}}R_.exports=LV});var Cv=typeof performance>"u"?0:performance.now(),kv=typeof window<"u"&&!!window.WaniWani?.chat;var fi=z(he(),1),$p=z(Ng(),1);var Bg="waniwani/suggestions";function il(e,t){for(let a of t){let n=e[a];if(typeof n=="string"&&n.length>0)return n}}var UB=["waniwani/sessionId","openai/sessionId","openai/session","sessionId","conversationId","mcp-session-id"],FB=["waniwani/requestId","openai/requestId","requestId","mcp/requestId"],zB=["waniwani/traceId","openai/traceId","traceId","mcp/traceId","openai/requestId","requestId"],qB=["waniwani/userId","openai/userId","externalUserId","userId","actorId"],HB=["waniwani/visitorId","visitorId"],jB=["correlationId","openai/requestId"];function mC(e){return e?il(e,UB):void 0}function hC(e){return e?il(e,FB):void 0}function gC(e){return e?il(e,zB):void 0}function wC(e){return e?il(e,qB):void 0}function yC(e){return e?il(e,HB):void 0}function xC(e){return e?il(e,jB):void 0}var VB=[{key:"openai/sessionId",source:"chatgpt"},{key:"openai/session",source:"chatgpt"}],WB=[{needle:"claude",source:"claude"},{needle:"chatgpt",source:"chatgpt"},{needle:"openai",source:"chatgpt"},{needle:"gemini",source:"gemini"}];function vC(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 VB){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 WB)if(n.includes(r))return o}}var GB="@waniwani/sdk";function bC(e,t={}){let a=t.now??(()=>new Date),n=t.generateId??$B,r=YB(e),o=Vd(e.meta),i=Vd(e.metadata),l=ZB(e,o),s=bn(e.eventId)??n(),u=QB(e.timestamp,a),c=bn(e.source)??vC(o)??t.source??GB,d=Ug(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:XB(e,r),metadata:f,rawLegacy:d}}function $B(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`evt_${crypto.randomUUID()}`:`evt_${Math.random().toString(36).slice(2,10)}_${Date.now().toString(36)}`}function XB(e,t){if(!Ug(e))return Vd(e.properties);let a=KB(e,t),n=Vd(e.properties);return{...a,...n}}function KB(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 YB(e){return Ug(e)?e.eventType:e.event}function ZB(e,t){let a=bn(e.requestId)??hC(t),n=bn(e.sessionId)??mC(t),r=bn(e.traceId)??gC(t),o=bn(e.externalUserId)??wC(t),i=bn(e.visitorId)??yC(t),l=bn(e.correlationId)??xC(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 QB(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 Vd(e){return!e||typeof e!="object"||Array.isArray(e)?{}:e}function bn(e){if(typeof e=="string"&&e.trim().length!==0)return e}function Ug(e){return"eventType"in e}function SC(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 JB="/api/mcp/events/v2/batch";var IC="@waniwani/sdk";var eU=new Set([401,403]),tU=new Set([408,425,429,500,502,503,504]),aU=(e,t)=>globalThis.fetch(e,t);function CC(e){return new Fg(e)}var Fg=class{constructor(t){re(this,"endpointUrl");re(this,"flushIntervalMs");re(this,"maxBatchSize");re(this,"maxBufferSize");re(this,"maxRetries");re(this,"retryBaseDelayMs");re(this,"retryMaxDelayMs");re(this,"shutdownTimeoutMs");re(this,"sdkVersion");re(this,"fetchFn");re(this,"logger");re(this,"now");re(this,"sleep");re(this,"apiKey");re(this,"buffer",[]);re(this,"flushTimer");re(this,"flushScheduled",!1);re(this,"flushScheduledTimer");re(this,"flushInFlight");re(this,"inFlightCount",0);re(this,"isStopped",!1);re(this,"isShuttingDown",!1);this.endpointUrl=oU(t.apiUrl,t.endpointPath??JB),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??aU,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":IC};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:iU(o)}}if(eU.has(a.status))return{kind:"auth",status:a.status};if(tU.has(a.status))return{kind:"retryable",reason:`HTTP ${a.status}`};if(!a.ok)return{kind:"permanent",reason:`HTTP ${a.status}`};let n=await rU(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:IC,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(nU(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 nU(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 rU(e){let t=await e.text();if(t)try{return JSON.parse(t)}catch{return}}function oU(e,t){let a=e.endsWith("/")?e:`${e}/`,n=t.startsWith("/")?t.slice(1):t;return`${a}${n}`}function iU(e){return e instanceof Error?e.message:String(e)}function kC(e){let{apiUrl:t,endpointPath:a}=lU(e.endpoint),n=CC({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=bC({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,SC(i)),identify(l,s){return r=l,i({event:"user.identified",externalUserId:l,properties:s})},flush:()=>n.flush(),shutdown:l=>n.shutdown(l)}}function lU(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 sU="/api/mcp/";function Wd(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(sU)?`${n}${t}`:null}function uU(){if(typeof window>"u")return!1;try{return window.WANIWANI_DEBUG?!0:!!window.localStorage?.getItem("WANIWANI_DEBUG")}catch{return!1}}function ha(...e){uU()&&console.log("[Waniwani]",...e)}var zg="waniwani-visitor-id";function cU(){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(zg);if(t)return t}catch{}let e=cU();try{localStorage.setItem(zg,e)}catch{}return e}function ll(e){let t=typeof e=="string"?e.trim():"";if(!t)return Zt();try{localStorage.setItem(zg,t)}catch{}return t}function dU(e){return e!=null&&typeof e.then=="function"}function Xs(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 dU(n)?n.then(r=>{t||ll(r??"")},()=>{}):ll(n??""),a}var fU="waniwani-memory";var Wa="threads",Gd="by_memoryUserId",pU="by_updatedAt";var LC="memoryUserId",TC="waniwani-memory-user-id",qg=null;function Hg(){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 mU(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(Gd,"memoryUserId",{unique:!1}),a.createIndex(pU,"updatedAt",{unique:!1})}}async function jg(){return new Promise((e,t)=>{let a=indexedDB.open(fU,2);a.onupgradeneeded=n=>{mU(a.result,n.oldVersion)},a.onsuccess=()=>e(a.result),a.onerror=()=>t(a.error)})}async function hU(){return jg()}async function gU(e){return new Promise((t,a)=>{let o=e.transaction("ids","readonly").objectStore("ids").get(LC);o.onsuccess=()=>t(typeof o.result=="string"?o.result:null),o.onerror=()=>a(o.error)})}async function wU(e,t){return new Promise((a,n)=>{let i=e.transaction("ids","readwrite").objectStore("ids").put(t,LC);i.onsuccess=()=>a(),i.onerror=()=>n(i.error)})}async function yU(){if(typeof indexedDB>"u")return null;try{let e=await hU();try{let t=await gU(e);if(t)return t;let a=Hg();return await wU(e,a),a}finally{e.close()}}catch{return null}}function xU(){try{let e=localStorage.getItem(TC);if(e)return e;let t=Hg();return localStorage.setItem(TC,t),t}catch{return null}}async function EC(){let e=await yU();if(e)return e;let t=xU();return t||(qg||(qg=Hg()),qg)}function MC(e,t){return e.match(t)?.[1]??null}function vU(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=MC(e,n);if(r)return{name:a,version:r}}return null}function bU(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=MC(e,n);if(r)return{name:a,version:r.replace(/_/g,".")};if(a==="Linux"&&n.test(e))return{name:a,version:""}}return null}function SU(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 Ks(){let e=navigator.userAgent,t=Zt(),a=await EC();return{userAgent:e,browser:vU(e),os:bU(e),deviceType:SU(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 IU="0.22.0-beta.4",CU=40,kU=10,TU=6e5;function Wg(){return typeof performance>"u"?0:performance.now()}function Gg(e,t){let a={};return{metrics:a,has:n=>n in a,set(n,r){a[n]=r},mark(n,r=Wg()){if(!(n in a)){a[n]=r-t;try{performance.mark(`waniwani:${e}:${n}`,{startTime:r})}catch{}}}}}function LU(e){let t={};for(let[a,n]of Object.entries(e)){if(Object.keys(t).length>=CU)break;if(!Number.isFinite(n))continue;let r=Math.round(n);r<0||r>TU||(t[a]=r)}return t}function EU(e){let t={};for(let[a,n]of Object.entries(e)){if(Object.keys(t).length>=kU)break;(typeof n=="string"||typeof n=="boolean")&&(t[a]=n)}return t}function MU(){let e=navigator.connection;if(e)return{effectiveType:e.effectiveType,rtt:e.rtt,downlink:e.downlink,saveData:e.saveData}}function Xd(e){let t=e?.Authorization;return typeof t=="string"&&t.startsWith("Bearer ")?t.slice(7):void 0}function AU(e,t,a,n){return{kind:e,sdkVersion:IU,channelId:t.channelId||void 0,sessionId:e==="boot"?void 0:t.sessionId||void 0,visitorId:Zt(),pageHost:window.location.hostname,connection:MU(),tags:EU(a),metrics:LU(n)}}var Vg,$d=[];function $g(e){let t=String(e?.chatTimingLogs).trim().toLowerCase()==="true";Vg=t;let a=$d;if($d=[],t)for(let n of a)n()}function Kd(e,t,a,n){let{api:r,token:o}=t;if(!(typeof window>"u"||!r||!o||Vg===!1))try{let i=AU(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(()=>{})};Vg?l():$d.length<20&&$d.push(l)}catch{}}var dr=Gg("boot",0),AC;function Uo(e,t){dr.mark(e,t)}function Yd(e){AC??(AC=e)}var RU=/cdn\.jsdelivr\.net\/npm\/@waniwani\/sdk@[^/]+\/dist\/chat\/embed\.js/,DU=/\/embed\.js(\?|$)/;function _U(){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)RU.test(a.name)?(dr.mark("bundleStart",a.startTime),dr.mark("bundleEnd",a.responseEnd)):DU.test(a.name)&&(dr.mark("loaderStart",a.startTime),dr.mark("loaderEnd",a.responseEnd))}function OU(){if(kv)return!0;try{return document.querySelectorAll('script[src*="@waniwani/sdk"]').length>1}catch{return!1}}function RC(e){_U(),dr.mark("bundleExecuted",Cv),Kd("boot",e,{configSource:AC,mode:e.mode,secondSdk:OU()},dr.metrics)}var PU=[["text-delta","firstText"],["tool-input-start","firstToolInput"],["tool-output-available","firstToolOutput"]];function DC(e){let t=Gg("turn",Wg());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 PU)!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,Kd("turn",n,r,t.metrics))}}}function NU(e){let t=e.indexOf("?");return t===-1?e:e.slice(0,t)}function _C(e,t){let a=Gg("widget",Wg()),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:NU(e),outcome:r,metrics:a.metrics}))}}}var BU="/api/mcp/events/v2/batch",Xg=new Set;function UU(e,t,a){return`${e}|${t}|${a??""}`}function Ys(e){return Wd(e,BU)}async function OC(e){let{api:t,token:a,channelId:n,mode:r,source:o}=e;if(typeof window>"u"||!t||!a)return;let i=Ys(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=UU(t,a,n);if(!Xg.has(l)){Xg.add(l);try{let s=await Ks(),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});Uo("pageViewSent"),await d}catch{Xg.delete(l)}}}function PC(e){let t=Ys(e.api);return t?kC({endpoint:t,token:e.token,channelId:e.channelId,source:e.getSource,identity:()=>({sessionId:e.getSessionId(),visitorId:Zt()})}):Zd("the chat api does not point at a Waniwani event ingest")}function Zd(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 Jd=z(he());var Qd=(...e)=>e.filter((t,a,n)=>!!t&&t.trim()!==""&&n.indexOf(t)===a).join(" ").trim();var NC=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();var BC=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,a,n)=>n?n.toUpperCase():a.toLowerCase());var Kg=e=>{let t=BC(e);return t.charAt(0).toUpperCase()+t.slice(1)};var Zs=z(he());var UC={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 FC=e=>{for(let t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0;return!1};var zC=(0,Zs.forwardRef)(({color:e="currentColor",size:t=24,strokeWidth:a=2,absoluteStrokeWidth:n,className:r="",children:o,iconNode:i,...l},s)=>(0,Zs.createElement)("svg",{ref:s,...UC,width:t,height:t,stroke:e,strokeWidth:n?Number(a)*24/Number(t):a,className:Qd("lucide",r),...!o&&!FC(l)&&{"aria-hidden":"true"},...l},[...i.map(([u,c])=>(0,Zs.createElement)(u,c)),...Array.isArray(o)?o:[o]]));var He=(e,t)=>{let a=(0,Jd.forwardRef)(({className:n,...r},o)=>(0,Jd.createElement)(zC,{ref:o,iconNode:t,className:Qd(`lucide-${NC(Kg(e))}`,`lucide-${e}`,n),...r}));return a.displayName=Kg(e),a};var FU=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],Qs=He("arrow-down",FU);var zU=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],Nn=He("arrow-up",zU);var qU=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Js=He("check",qU);var HU=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Qr=He("chevron-down",HU);var jU=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],eu=He("chevron-right",jU);var VU=[["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"}]],tu=He("clipboard-copy",VU);var WU=[["path",{d:"M12 6v6l4 2",key:"mmk7yg"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],fr=He("clock",WU);var GU=[["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"}]],au=He("file-text",GU);var $U=[["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"}]],sl=He("file",$U);var XU=[["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"}]],nu=He("globe",XU);var KU=[["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"}]],ru=He("image",KU);var YU=[["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"}]],ou=He("loader",YU);var ZU=[["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"}]],ul=He("paperclip",ZU);var QU=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],iu=He("square",QU);var JU=[["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"}]],Fo=He("wrench",JU);var e3=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Ga=He("x",e3);var t3=[["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"}]],lu=He("zap",t3);var $e=z(he(),1),dO=z(dm(),1);var cl=z(he(),1),su=z(ae(),1);function r3(e){return 1-(1-e)**3}function o3({start:e=0,end:t=100,duration:a=1e3,delay:n=0,ease:r=r3,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 i3=["80% 55%","69% 34%","8% 6%","41% 38%","86% 85%","82% 18%","51% 4%"],l3=[0,1,2,0,1,2,1];function s3(e){let t=[];for(let a=0;a<7;a++){let n=e[Math.min(l3[a],e.length-1)];t.push(`radial-gradient(at ${i3[a]}, ${n} 0px, transparent 50%)`)}return t.push(`linear-gradient(${e[0]} 0 100%)`),t}var u3=({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,cl.useState)(110),[d,f]=(0,cl.useState)(0),[p,m]=(0,cl.useState)(!1);(0,cl.useEffect)(()=>{if(!l)return;let T=110;m(!0),c(T),o3({ease:C=>C,duration:2e3,onUpdate:C=>{let M=C/100;c(T+360*M);let D=Math.min(M/.1,1),P=M>.85?(1-M)/.15:1;f(Math.min(D,P))},onEnd:()=>m(!1)})},[l]);let x=n+20,S=p?Math.max(0,(d*100-x)/(100-x)):0,y=s3(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,su.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,su.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,su.jsx)("div",{className:"ww:flex ww:flex-col ww:relative ww:overflow-auto ww:z-[1]",children:e})]})},tf=u3;Yg();Qg();var c3=WC({prefix:"ww"});function q(...e){return c3(af(e))}var uu=z(ae(),1);function dl({suggestions:e,isLoading:t,onSelect:a,align:n="start",className:r,...o}){return e.length===0&&!t?null:(0,uu.jsx)("div",{className:q("ww:px-4 ww:py-2",r),...o,children:(0,uu.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,uu.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,uu.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 GC=z(he(),1),$C="(max-width: 639px)";function d3(e){let t=window.matchMedia($C);return t.addEventListener("change",e),()=>t.removeEventListener("change",e)}function f3(){return window.matchMedia($C).matches}function p3(){return!1}function XC(){return(0,GC.useSyncExternalStore)(d3,f3,p3)}var nf=z(he(),1);function Jg(e,t){return e.find(a=>a.text===t)?.id??null}async function KC(e){let{api:t,token:a,name:n,source:r,sessionId:o,properties:i}=e;if(typeof window>"u"||!t||!a)return;let l=Ys(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 YC(e){let{api:t,token:a,channelId:n,mode:r,source:o,sessionId:i,promptId:l,origin:s,text:u,index:c}=e;await KC({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 ZC(e,t){return t.map(a=>({id:Jg(e,a),text:a}))}async function QC(e){let{api:t,token:a,channelId:n,mode:r,source:o,sessionId:i,prompts:l,origin:s}=e;l.length!==0&&await KC({api:t,token:a,name:"suggestion.shown",source:o,sessionId:i,properties:{prompts:l,count:l.length,origin:s,channelId:n,mode:r}})}function fl(e){let{widgetEvents:t,api:a,token:n,channelId:r,source:o,mode:i,pagePrompts:l}=e,s=(0,nf.useRef)(e.getSessionId);s.current=e.getSessionId,(0,nf.useEffect)(()=>{if(!(!a||!n))return t.subscribe(u=>{if(u.name==="suggestion.clicked"){let{text:c,origin:d,index:f}=u.properties;YC({api:a,token:n,channelId:r,mode:i,source:o,sessionId:s.current(),promptId:Jg(l??[],c),origin:d,text:c,index:f});return}if(u.name==="suggestions.shown"){let{texts:c,origin:d}=u.properties;QC({api:a,token:n,channelId:r,mode:i,source:o,sessionId:s.current(),prompts:ZC(l??[],c),origin:d})}})},[t,a,n,r,o,i,l])}var pl=z(he(),1),m3=80,h3=50,g3=15e3,JC=500;function ml(e,t=!0){let[a,n]=(0,pl.useState)(""),r=(0,pl.useRef)(void 0);return(0,pl.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,JC)):r.current=setTimeout(s,h3)):(o++,n(e.slice(0,o)),o>=e.length?(i=!0,r.current=setTimeout(s,g3)):r.current=setTimeout(s,m3)))};return r.current=setTimeout(s,JC),()=>{l=!0,clearTimeout(r.current)}},[e,t]),a}var Sn=z(he(),1);var ek=["en","fr","es"];function hl(e){return ek.includes(e)}function ew(e){if(e&&hl(e))return e;if(e){let a=e.split("-")[0]?.toLowerCase();if(a&&hl(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(hl(n))return n;let r=n.split("-")[0];if(r&&hl(r))return r}return"en"}var rf={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 tk={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 ak={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 tw={en:rf,fr:ak,es:tk};var rk=z(ae(),1),nk=(0,Sn.createContext)(null);function w3(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 zo({children:e,locale:t,messages:a}){let n=!!(t&&y3(t)),r=n?t:"en",[o,i]=(0,Sn.useState)(r),[l,s]=(0,Sn.useState)(n);(0,Sn.useEffect)(()=>{i(ew(t)),s(!0)},[t]);let u=(0,Sn.useMemo)(()=>{let c=tw[o]??tw["en"];return{locale:o,t:w3(c,a),ready:l}},[o,a,l]);return(0,rk.jsx)(nk.Provider,{value:u,children:e})}function y3(e){return e==="en"||e==="fr"||e==="es"}function Ie(){let e=(0,Sn.useContext)(nk);return e||{locale:"en",t:rf,ready:!0}}function aw(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 cu=(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 Ce=z(he(),1);var qo=new Map;function ok(e,t){if(qo.has(e)){URL.revokeObjectURL(t);return}for(qo.set(e,t);qo.size>20;){let a=qo.keys().next();if(a.done)return;let n=qo.get(a.value);qo.delete(a.value),n&&URL.revokeObjectURL(n)}}function ik(e){return qo.get(e)}var lk=z(ae(),1),Bn=({className:e,variant:t="default",size:a="default",type:n="button",...r})=>(0,lk.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 sk=z(he(),1);var bt=z(ae(),1),uk=({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)(x3,{file:n},r))});function x3({file:e}){let{t}=Ie();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)(sl,{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 ck(e,t){return e.startsWith("image/")?t.attachments.kindImage:e==="application/pdf"?t.attachments.kindPdf:t.attachments.kindFile}function v3({mediaType:e}){return e.startsWith("image/")?(0,bt.jsx)(ru,{className:"ww:size-5 ww:text-muted-foreground"}):e==="application/pdf"?(0,bt.jsx)(au,{className:"ww:size-5 ww:text-muted-foreground"}):(0,bt.jsx)(sl,{className:"ww:size-5 ww:text-muted-foreground"})}function nw({filename:e,mediaType:t,previewUrl:a,subtitle:n,tone:r="default",children:o,className:i}){let{t:l}=Ie(),s=ck(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)(v3,{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 dk(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 fk=({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)(b3,{document:n},`${n.documentId}-${r}`))});function b3({document:e}){let{t}=Ie(),[a,n]=(0,sk.useState)(!1),r=e.mediaType.startsWith("image/")?ik(e.documentId):void 0;return r&&!a?(0,bt.jsx)("li",{children:(0,bt.jsx)("img",{alt:`${e.filename}, ${ck(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)(nw,{filename:e.filename,mediaType:e.mediaType})}var ht=z(ae(),1),S3=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}},I3=(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)},mk=(0,Ce.createContext)(null),of=()=>{let e=(0,Ce.useContext)(mk);if(!e)throw new Error("usePromptInputAttachments must be used within a PromptInput");return e},hk=({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}=Ie(),S=(0,Ce.useRef)(null),w=(0,Ce.useRef)(null),[y,h]=(0,Ce.useState)([]),b=(0,Ce.useRef)(y),T=(0,Ce.useRef)(new Map),C=(0,Ce.useRef)(s),M=(0,Ce.useRef)(c),D=(0,Ce.useRef)(u);(0,Ce.useEffect)(()=>{C.current=s,M.current=c,D.current=u},[s,c,u]);let P=(0,Ce.useCallback)(v=>{b.current=v,h(v)},[]),L=(0,Ce.useCallback)(()=>{S.current?.click()},[]),$=(0,Ce.useCallback)((v,K)=>{P(b.current.map(ee=>ee.id===v?{...ee,...K}:ee))},[P]),H=(0,Ce.useCallback)((v,K)=>{let ee=C.current;if(!ee)return;let we=new AbortController,Ge=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 ye=me instanceof Error?me.message:m.promptInput.uploadFailed;return $(v,{status:"failed",error:ye}),M.current?.({code:"upload_failed",message:ye}),null});T.current.set(v,{file:K,controller:we,done:Ge})},[$,m]),F=(0,Ce.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(!I3(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}",gk(o,x)));continue}we.push(de)}if(we.length===0)return;let Ge=typeof r=="number"?Math.max(0,r-b.current.length):void 0,me=typeof Ge=="number"?we.slice(0,Ge):we;if(me.length<we.length&&ee("max_files",m.promptInput.errorTooMany.replace("{limit}",String(r))),me.length===0)return;let ye=!!C.current,le=me.map(de=>({file:de,item:{filename:de.name,id:cu(),mediaType:de.type,type:"file",url:URL.createObjectURL(de),status:ye?"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,Ce.useCallback)(v=>{let K=T.current.get(v);K&&($(v,{status:"uploading",progress:0,error:void 0}),H(v,K.file))},[$,H]),V=(0,Ce.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?ok(v.documentId,v.url):URL.revokeObjectURL(v.url)),K&&v.documentId&&D.current?.({documentId:v.documentId,filename:v.filename??"",mediaType:v.mediaType??""})},[]),N=(0,Ce.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]),R=(0,Ce.useCallback)(()=>{for(let v of b.current)V(v,!0);P([])},[V,P]),G=(0,Ce.useRef)(l);(0,Ce.useEffect)(()=>{let v=G.current;G.current=l,v&&!l&&R()},[l,R]);let ue=(0,Ce.useCallback)(()=>{for(let v of b.current)V(v,!1);P([])},[V,P]);(0,Ce.useEffect)(()=>()=>{for(let v of b.current)T.current.get(v.id)?.controller.abort(),v.url&&URL.revokeObjectURL(v.url)},[]);let I=(0,Ce.useCallback)(v=>{v.currentTarget.files&&F(v.currentTarget.files),v.currentTarget.value=""},[F]);(0,Ce.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 We=(0,Ce.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 Ge=[...we.values()].filter(le=>le!==null),me=C.current?[]:b.current,ye=await Promise.all(me.map(async({id:le,status:de,progress:Q,error:Be,...qe})=>{if(qe.url?.startsWith("blob:")){let _e=await S3(qe.url);return{...qe,url:_e??qe.url}}return qe}));try{let le=d({documents:Ge,files:ye,text:ee},v);le instanceof Promise&&await le,K.reset(),ue()}catch{}},[d,ue,m]),Je=(0,Ce.useMemo)(()=>({add:F,clear:R,files:y,openFileDialog:L,remove:N,retry:W,maxFileSize:o,maxPdfPages:i}),[y,F,N,W,R,L,o,i]);return(0,ht.jsxs)(mk.Provider,{value:Je,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:We,ref:w,...p,children:f})]})},pk=1024*1024;function gk(e,t){let a=e>=pk;return new Intl.NumberFormat(t,{style:"unit",unit:a?"megabyte":"kilobyte",maximumFractionDigits:0}).format(a?e/pk:Math.max(1,e/1024))}var wk=({onChange:e,onKeyDown:t,className:a,placeholder:n,...r})=>{let{t:o}=Ie(),i=of(),[l,s]=(0,Ce.useState)(!1),u=n??o.promptInput.placeholder,c=(0,Ce.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,Ce.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})},yk=({className:e,status:t,onStop:a,onClick:n,children:r,disabled:o,...i})=>{let{t:l}=Ie(),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)(ou,{className:"ww:size-4 ww:animate-spin"}):t==="streaming"&&(c=(0,ht.jsx)(iu,{className:"ww:size-4"}));let d=(0,Ce.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})},xk=({className:e,children:t,...a})=>{let{t:n,locale:r}=Ie(),o=of();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}",gk(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)(ul,{className:"ww:size-4"})})},vk=({className:e,...t})=>{let a=of();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)(C3,{file:n},n.id))})};function C3({file:e}){let{t}=Ie(),a=of(),n=e.status==="failed",r=e.status==="uploading";return(0,ht.jsxs)(nw,{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 bk=({enabled:e=!0})=>{let{t}=Ie(),[a,n]=(0,Ce.useState)(!1);return(0,Ce.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)(ul,{className:"ww:size-4"}),t.promptInput.dropToAttach]})}):null};var Ik=z(ae(),1);function Sk({text:e}){let{t}=Ie();return e===!1?null:(0,Ik.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 lf=z(he(),1);var Ho=z(ae(),1),Ck=({className:e,...t})=>(0,Ho.jsx)("div",{className:q("ww:flex ww:flex-col ww:gap-1 ww:px-3 ww:py-2",e),...t}),kk=({className:e,...t})=>(0,Ho.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}),Tk=({className:e,...t})=>(0,Ho.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}),Lk=({className:e,...t})=>(0,Ho.jsx)("span",{className:q("ww:line-clamp-1 ww:grow ww:break-words ww:text-muted-foreground",e),...t}),Ek=({className:e,...t})=>(0,Ho.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}),Mk=({className:e,...t})=>(0,Ho.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(ae(),1),Ak=(0,lf.memo)(({message:e,onRemove:t})=>{let{t:a}=Ie(),n=(0,lf.useCallback)(()=>t(e.id),[t,e.id]);return(0,sn.jsxs)(kk,{children:[(0,sn.jsx)(Tk,{}),(0,sn.jsx)(Lk,{children:e.text||a.chatQueue.attachmentFallback}),(0,sn.jsx)(Ek,{children:(0,sn.jsx)(Mk,{"aria-label":a.chatQueue.removeFromQueue,onClick:n,children:(0,sn.jsx)(Ga,{className:"ww:size-3"})})})]})});Ak.displayName="ChatQueueItem";function Rk({queuedMessages:e,onRemove:t,className:a}){let{t:n}=Ie();return e.length===0?null:(0,sn.jsxs)(Ck,{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)(Ak,{message:r,onRemove:t},r.id))})]})}var _a=z(he(),1);var St=z(he(),1);dp();var u2=z(he(),1);var c2=z(ae(),1),V6=({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,c2.jsx)(e,{"data-waniwani-shimmer":"",className:q("ww:inline-block",t),style:i,...o,children:r})},Tn=(0,u2.memo)(V6);Tn.displayName="Shimmer";var ua=z(ae(),1),d2=(0,St.createContext)(null);function f2(){let e=(0,St.useContext)(d2);if(!e)throw new Error("Reasoning components must be used within <Reasoning>");return e}var W6=1e3,G6=1e3,Uu=(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)/G6)),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)},W6);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)(d2.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})})});Uu.displayName="Reasoning";var Fu=(0,St.memo)(({className:e,children:t,getThinkingMessage:a,hideIcon:n=!1,onClick:r,...o})=>{let{t:i}=Ie(),{isStreaming:l,isOpen:s,duration:u,setIsOpen:c}=f2(),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)]})})});Fu.displayName="ReasoningTrigger";var zu=(0,St.memo)(({className:e,children:t,...a})=>{let{isOpen:n}=f2();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)(El,{children:t})})})})});zu.displayName="ReasoningContent";var Ne=z(ae(),1),$6=500,p2=(0,_a.createContext)(null);function m2(){let e=(0,_a.useContext)(p2);if(!e)throw new Error("ChainOfThought components must be used within <ChainOfThought>");return e}function h2({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),$6);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)(p2.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 g2({className:e,label:t,workingLabel:a,children:n,...r}){let{open:o,setOpen:i,isWorking:l,settled:s,activeStep:u}=m2();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 w2({className:e,children:t,...a}){let{open:n}=m2();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 y2({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 Rx({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)(y2,{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 x2({isStreaming:e=!1,isLast:t=!1,children:a}){return(0,Ne.jsxs)("div",{className:"ww:flex ww:gap-2",children:[(0,Ne.jsx)(y2,{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)(Uu,{isStreaming:e,className:"ww:mb-0",children:[(0,Ne.jsx)(Fu,{hideIcon:!0}),(0,Ne.jsx)(zu,{children:a})]})})]})}var Dx={name:"cjk-noop",type:"cjk",remarkPluginsBefore:[],remarkPluginsAfter:[],remarkPlugins:[]};var v2={name:"shiki-noop",type:"code-highlighter",supportsLanguage:()=>!1,getSupportedLanguages:()=>[],getThemes:()=>["github-light","github-dark"],highlight:()=>null};var I2=z(he(),1);var vr=z(he(),1),X6=5,b2=400;function S2(e,t,a={}){let{msPerChar:n=X6}=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>b2&&(l.current=i.current.length-b2),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 qu=z(ae(),1),_x=({className:e,from:t,children:a,...n})=>(0,qu.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,qu.jsx)("div",{className:q("ww:flex ww:min-w-0 ww:flex-col ww:gap-2","ww:w-full"),children:a})}),Ox=({children:e,className:t,...a})=>(0,qu.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}),K6={cjk:Dx,code:v2},Y6={cjk:Dx},Z6={enabled:!1};function Q6({className:e,linkSafety:t,isStreaming:a,children:n,...r}){let i=S2(typeof n=="string"?n:"",!!a),l=typeof n=="string"?i:n;return(0,qu.jsx)(El,{className:q("ww:size-full ww:[&>*:first-child]:mt-0 ww:[&>*:last-child]:mb-0",e),linkSafety:t??Z6,plugins:a?Y6:K6,...r,children:l})}var gp=(0,I2.memo)(Q6,(e,t)=>e.children===t.children&&e.isStreaming===t.isStreaming);gp.displayName="MessageResponse";var Vt=z(he(),1);function Px(e){if(!(typeof e!="object"||e===null))return e}function C2(e){return Px(e?.ui)}function Nx(e){if(!e)return;let t=C2(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 Hu(e){return C2(e)?.autoHeight===!0}function Bx(e){return Px(Px(e)?._meta)}var Te=z(ae(),1);function J6(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 e9({text:e,className:t}){let{t:a}=Ie(),[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)(Js,{className:"ww:size-3.5"}),(0,Te.jsx)("span",{children:a.tool.copied})]}):(0,Te.jsxs)(Te.Fragment,{children:[(0,Te.jsx)(tu,{className:"ww:size-3.5"}),(0,Te.jsx)("span",{children:a.tool.copy})]})})}function k2({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=J6(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)(e9,{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)(eu,{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 Ux=(0,Vt.createContext)({open:!1,toggle:()=>{}});function T2({className:e,defaultOpen:t=!1,children:a,...n}){let[r,o]=(0,Vt.useState)(t);return(0,Te.jsx)(Ux.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 L2({className:e,title:t,state:a,...n}){let{open:r,toggle:o}=(0,Vt.useContext)(Ux),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)(Fo,{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 E2({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 M2({className:e,children:t,...a}){let{open:n}=(0,Vt.useContext)(Ux);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 Fx({className:e,input:t,debug:a,...n}){let{t:r}=Ie(),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)(k2,{data:o,label:r.tool.request,className:e,...n})}function ju(e,t,a){if(e){let n=Nx(a?.[e]?._meta);if(n)return n}return Nx(Bx(t))}function A2(e,t,a){return e&&Hu(a?.[e]?._meta)?!0:Hu(Bx(t))}function zx({className:e,output:t,errorText:a,debug:n,...r}){let{t:o}=Ie(),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)(k2,{data:i,label:o.tool.response,className:e,...r}):null}var Vu=z(ae(),1);function R2(e){return e.type==="text"||e.type==="reasoning"||e.type==="file"||"toolCallId"in e}function D2(e){return e.parts.some(R2)}function _2(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=>!(!R2(o)||a?.ignoreToolParts&&"toolCallId"in o||a?.ignoreReasoningParts&&o.type==="reasoning"))}function O2({className:e,...t}){let{t:a}=Ie();return(0,Vu.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,Vu.jsx)(lu,{className:"ww:size-4 ww:shrink-0"}),(0,Vu.jsx)(Tn,{duration:1.6,children:a.workingIndicator.default})]})}var Qe=z(he(),1);function li(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 P2(e,t){return!li(e)&&!li(t)?null:li(e)?li(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 N2=(0,br.createContext)(()=>{});function B2(){return(0,br.useContext)(N2)}var U2=N2.Provider;function t9(e){let t=window.requestIdleCallback;typeof t=="function"?t(e):setTimeout(e,500)}function Ml(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;Uo(r.paintMark),t9(()=>RC(r))});return()=>cancelAnimationFrame(n)},[e.painted])}var F2=z(ae(),1),a9="/api/mcp/resource",n9=500,r9=0,o9=16,i9="2026-01-26",l9=300,s9=3e3,u9=3,c9=2e3;function d9(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}function f9(e,t,a){return ju(e,t,a)?!1:t._meta?.["waniwani/autoInjectResultText"]!==!1}function wp({resourceUri:e,toolInput:t,toolResult:a,resourceEndpoint:n=a9,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,Qe.useRef)(null),x=(0,Qe.useRef)(t),S=(0,Qe.useRef)(a),w=(0,Qe.useRef)({width:0,height:0}),y=(0,Qe.useRef)(null),h=(0,Qe.useRef)(!1),b=(0,Qe.useRef)(0),T=(0,Qe.useRef)("inline"),[C,M]=(0,Qe.useState)(r9),[D,P]=(0,Qe.useState)(void 0),L=(0,Qe.useRef)(s),$=(0,Qe.useRef)(u),H=(0,Qe.useRef)(c),F=(0,Qe.useRef)(d),W=(0,Qe.useRef)(r),V=(0,Qe.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,Qe.useCallback)(v=>l?Math.max(v+o9,0):Math.min(Math.max(v,50),n9),[l]),R=(0,Qe.useMemo)(()=>{let v=n.includes("?")?"&":"?";return`${n}${v}uri=${encodeURIComponent(e)}`},[n,e]),G=B2(),ue=(0,Qe.useRef)(null),I=(0,Qe.useRef)(void 0);(0,Qe.useEffect)(()=>{let v=_C(e,G);return ue.current=v,()=>{clearTimeout(I.current),v.has("initialized")||v.report("timeout",b.current),ue.current=null}},[e,G]);let We=(0,Qe.useRef)(o);We.current=o;let Je=(0,Qe.useRef)(f);return(0,Qe.useEffect)(()=>{Je.current=f,w.current.height=-1,y.current&&(y.current.cancel(),y.current=null)},[f]),(0,Qe.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,Qe.useEffect)(()=>{let v=m.current;if(!v)return;let K=!1,ee=!1,we=null,Ge=null,me=setTimeout(()=>{if(K||ee||b.current>=u9)return;b.current+=1;let de=new URL(v.src);de.searchParams.set("_retry",String(b.current)),v.src=de.toString()},s9),ye=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),ye({jsonrpc:"2.0",id:qe,result:{protocolVersion:Q.params?.protocolVersion??i9,hostInfo:{name:"Waniwani Chat",version:"1.0.0"},hostCapabilities:{openLinks:{},message:{text:{}},tools:{},updateModelContext:{text:{},structuredContent:{}}},hostContext:{theme:We.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),c9);let _e=x.current,ke=S.current,xe=ke._meta&&typeof ke._meta=="object"?ke._meta:null,Y=d9(W.current),Oe=xe&&typeof xe.waniwani=="object"&&xe.waniwani!==null?xe.waniwani:null,rt=Oe||Y?{...Oe??{},...Y?{sessionId:Y}:{}}:void 0,ba=xe||rt?{...xe??{},...rt?{waniwani:rt}:{}}:void 0;ye({jsonrpc:"2.0",method:"ui/notifications/tool-input",params:{arguments:_e}});let Sa=ke.content??[{type:"text",text:JSON.stringify(ke)}];ye({jsonrpc:"2.0",method:"ui/notifications/tool-result",params:{content:Sa,structuredContent:ke.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,ke=typeof _e?.height=="number"?_e.height:void 0,xe=typeof _e?.width=="number"?_e.width:void 0,Y=w.current,Oe=ke!==void 0&&ke!==Y.height,rt=xe!==void 0&&xe!==Y.width;if(!Oe&&!rt)return;if(Oe&&ke!==void 0){if(Y.height=ke,Je.current)return;let ba=N(ke),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:l9,easing:"ease-out",fill:"forwards"});y.current=ra,ra.onfinish=()=>{y.current===ra&&(ra.cancel(),y.current=null)}}}rt&&l&&xe!==void 0&&(Y.width=xe,P(xe));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")),ye({jsonrpc:"2.0",id:qe,result:{}});return}if(Be==="ui/message"&&qe!=null){if($.current&&Q.params){let _e=Q.params,ke=we;if(we=null,Ge){clearTimeout(Ge.timer);let xe=Ge.text;Ge=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]==="$"},Ix=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},i2=e=>{let t=_6.test(e),a=O6.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(P6);if(u){let c=u[1];o.at(-1)===c&&o.pop()}}continue}if(i.type==="html"&&i.block){let u=l.match(N6);if(u){let c=u[1];l.includes(`</${c}>`)||o.push(c)}}if(l.trim()==="$$"&&s>0){let u=r[s-1],c=Sx(u),d=Ix(u);if(c&&d%2===1){r[s-1]=u+l;continue}}if(s>0&&B6(l)){let u=r[s-1],c=Sx(u),d=Ix(u),f=Ix(l);if(c&&d%2===1&&!Sx(l)&&f===1){r[s-1]=u+l;continue}}r.push(l)}return r},l2={raw:zk,sanitize:[gf,{}],harden:[Uk,{allowedImagePrefixes:["*"],allowedLinkPrefixes:["*"],allowedProtocols:["*"],defaultOrigin:void 0,allowDataImages:!0}]},s2={gfm:[qf,{}]},U6=Object.values(l2),F6=Object.values(s2),z6={block:" \u258B",circle:" \u25CF"},q6={shikiTheme:["github-light","github-dark"],controls:!0,isAnimating:!1,mode:"streaming",mermaid:void 0,linkSafety:{enabled:!0}},ya=(0,_.createContext)(q6),Ax=(0,_.memo)(({content:e,shouldParseIncompleteMarkdown:t,index:a,...n})=>(0,E.jsx)(o2,{...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)});Ax.displayName="Block";H6=["github-light","github-dark"],El=(0,_.memo)(({children:e,mode:t="streaming",parseIncompleteMarkdown:a=!0,components:n,rehypePlugins:r=U6,remarkPlugins:o=F6,className:i,shikiTheme:l=H6,mermaid:s,controls:u=!0,isAnimating:c=!1,BlockComponent:d=Ax,parseMarkdownIntoBlocksFn:f=i2,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?QL(e,x):e,[e,t,a,x]),C=(0,_.useMemo)(()=>f(T),[T,f]),[M,D]=(0,_.useState)(C);(0,_.useEffect)(()=>{t==="streaming"?b(()=>{D(C)}):D(C)},[C,t]);let P=t==="streaming"?M:C,L=(0,_.useMemo)(()=>P.map((N,R)=>`${y}-${R}`),[P.length,y]),$=(0,_.useMemo)(()=>{var N,R;return{shikiTheme:(R=(N=m?.code)==null?void 0:N.getThemes())!=null?R:l,controls:u,isAnimating:c,mode:t,mermaid:s,linkSafety:S}},[l,u,c,t,s,S,m?.code]),H=(0,_.useMemo)(()=>({...E6,...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":`"${z6[p]}"`}:void 0,[p,c]);return t==="static"?(0,E.jsx)(Cx.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)(o2,{components:H,rehypePlugins:W,remarkPlugins:F,...w,children:e})})})}):(0,E.jsx)(Cx.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,R)=>(0,E.jsx)(d,{components:H,content:N,index:R,rehypePlugins:W,remarkPlugins:F,shouldParseIncompleteMarkdown:a,...w},L[R]))]})})})},(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);El.displayName="Streamdown";j6=({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]),D=(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",D,{passive:!1}),()=>{H.removeEventListener("wheel",D)}},[D]),(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)(o6,{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)(i6,{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)(r6,{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})]})},vx=({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=Ex(),w=x?.errorComponent,{shouldRender:y,containerRef:h}=t6({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:D}=await T.render(M,e);c(D),f(D)}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)(j6,{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 D_=oa((kse,R_)=>{"use strict";function LV(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)}}R_.exports=LV});var Cv=typeof performance>"u"?0:performance.now(),kv=typeof window<"u"&&!!window.WaniWani?.chat;var fi=z(he(),1),$p=z(Ng(),1);var Bg="waniwani/suggestions";function il(e,t){for(let a of t){let n=e[a];if(typeof n=="string"&&n.length>0)return n}}var UB=["waniwani/sessionId","openai/sessionId","openai/session","sessionId","conversationId","mcp-session-id"],FB=["waniwani/requestId","openai/requestId","requestId","mcp/requestId"],zB=["waniwani/traceId","openai/traceId","traceId","mcp/traceId","openai/requestId","requestId"],qB=["waniwani/userId","openai/userId","externalUserId","userId","actorId"],HB=["waniwani/visitorId","visitorId"],jB=["correlationId","openai/requestId"];function mC(e){return e?il(e,UB):void 0}function hC(e){return e?il(e,FB):void 0}function gC(e){return e?il(e,zB):void 0}function wC(e){return e?il(e,qB):void 0}function yC(e){return e?il(e,HB):void 0}function xC(e){return e?il(e,jB):void 0}var VB=[{key:"openai/sessionId",source:"chatgpt"},{key:"openai/session",source:"chatgpt"}],WB=[{needle:"claude",source:"claude"},{needle:"chatgpt",source:"chatgpt"},{needle:"openai",source:"chatgpt"},{needle:"gemini",source:"gemini"}];function vC(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 VB){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 WB)if(n.includes(r))return o}}var GB="@waniwani/sdk";function bC(e,t={}){let a=t.now??(()=>new Date),n=t.generateId??$B,r=YB(e),o=Vd(e.meta),i=Vd(e.metadata),l=ZB(e,o),s=bn(e.eventId)??n(),u=QB(e.timestamp,a),c=bn(e.source)??vC(o)??t.source??GB,d=Ug(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:XB(e,r),metadata:f,rawLegacy:d}}function $B(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`evt_${crypto.randomUUID()}`:`evt_${Math.random().toString(36).slice(2,10)}_${Date.now().toString(36)}`}function XB(e,t){if(!Ug(e))return Vd(e.properties);let a=KB(e,t),n=Vd(e.properties);return{...a,...n}}function KB(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 YB(e){return Ug(e)?e.eventType:e.event}function ZB(e,t){let a=bn(e.requestId)??hC(t),n=bn(e.sessionId)??mC(t),r=bn(e.traceId)??gC(t),o=bn(e.externalUserId)??wC(t),i=bn(e.visitorId)??yC(t),l=bn(e.correlationId)??xC(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 QB(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 Vd(e){return!e||typeof e!="object"||Array.isArray(e)?{}:e}function bn(e){if(typeof e=="string"&&e.trim().length!==0)return e}function Ug(e){return"eventType"in e}function SC(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 JB="/api/mcp/events/v2/batch";var IC="@waniwani/sdk";var eU=new Set([401,403]),tU=new Set([408,425,429,500,502,503,504]),aU=(e,t)=>globalThis.fetch(e,t);function CC(e){return new Fg(e)}var Fg=class{constructor(t){re(this,"endpointUrl");re(this,"flushIntervalMs");re(this,"maxBatchSize");re(this,"maxBufferSize");re(this,"maxRetries");re(this,"retryBaseDelayMs");re(this,"retryMaxDelayMs");re(this,"shutdownTimeoutMs");re(this,"sdkVersion");re(this,"fetchFn");re(this,"logger");re(this,"now");re(this,"sleep");re(this,"apiKey");re(this,"buffer",[]);re(this,"flushTimer");re(this,"flushScheduled",!1);re(this,"flushScheduledTimer");re(this,"flushInFlight");re(this,"inFlightCount",0);re(this,"isStopped",!1);re(this,"isShuttingDown",!1);this.endpointUrl=oU(t.apiUrl,t.endpointPath??JB),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??aU,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":IC};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:iU(o)}}if(eU.has(a.status))return{kind:"auth",status:a.status};if(tU.has(a.status))return{kind:"retryable",reason:`HTTP ${a.status}`};if(!a.ok)return{kind:"permanent",reason:`HTTP ${a.status}`};let n=await rU(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:IC,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(nU(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 nU(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 rU(e){let t=await e.text();if(t)try{return JSON.parse(t)}catch{return}}function oU(e,t){let a=e.endsWith("/")?e:`${e}/`,n=t.startsWith("/")?t.slice(1):t;return`${a}${n}`}function iU(e){return e instanceof Error?e.message:String(e)}function kC(e){let{apiUrl:t,endpointPath:a}=lU(e.endpoint),n=CC({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=bC({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,SC(i)),identify(l,s){return r=l,i({event:"user.identified",externalUserId:l,properties:s})},flush:()=>n.flush(),shutdown:l=>n.shutdown(l)}}function lU(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 sU="/api/mcp/";function Wd(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(sU)?`${n}${t}`:null}function uU(){if(typeof window>"u")return!1;try{return window.WANIWANI_DEBUG?!0:!!window.localStorage?.getItem("WANIWANI_DEBUG")}catch{return!1}}function ha(...e){uU()&&console.log("[Waniwani]",...e)}var zg="waniwani-visitor-id";function cU(){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(zg);if(t)return t}catch{}let e=cU();try{localStorage.setItem(zg,e)}catch{}return e}function ll(e){let t=typeof e=="string"?e.trim():"";if(!t)return Zt();try{localStorage.setItem(zg,t)}catch{}return t}function dU(e){return e!=null&&typeof e.then=="function"}function Xs(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 dU(n)?n.then(r=>{t||ll(r??"")},()=>{}):ll(n??""),a}var fU="waniwani-memory";var Wa="threads",Gd="by_memoryUserId",pU="by_updatedAt";var LC="memoryUserId",TC="waniwani-memory-user-id",qg=null;function Hg(){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 mU(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(Gd,"memoryUserId",{unique:!1}),a.createIndex(pU,"updatedAt",{unique:!1})}}async function jg(){return new Promise((e,t)=>{let a=indexedDB.open(fU,2);a.onupgradeneeded=n=>{mU(a.result,n.oldVersion)},a.onsuccess=()=>e(a.result),a.onerror=()=>t(a.error)})}async function hU(){return jg()}async function gU(e){return new Promise((t,a)=>{let o=e.transaction("ids","readonly").objectStore("ids").get(LC);o.onsuccess=()=>t(typeof o.result=="string"?o.result:null),o.onerror=()=>a(o.error)})}async function wU(e,t){return new Promise((a,n)=>{let i=e.transaction("ids","readwrite").objectStore("ids").put(t,LC);i.onsuccess=()=>a(),i.onerror=()=>n(i.error)})}async function yU(){if(typeof indexedDB>"u")return null;try{let e=await hU();try{let t=await gU(e);if(t)return t;let a=Hg();return await wU(e,a),a}finally{e.close()}}catch{return null}}function xU(){try{let e=localStorage.getItem(TC);if(e)return e;let t=Hg();return localStorage.setItem(TC,t),t}catch{return null}}async function EC(){let e=await yU();if(e)return e;let t=xU();return t||(qg||(qg=Hg()),qg)}function MC(e,t){return e.match(t)?.[1]??null}function vU(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=MC(e,n);if(r)return{name:a,version:r}}return null}function bU(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=MC(e,n);if(r)return{name:a,version:r.replace(/_/g,".")};if(a==="Linux"&&n.test(e))return{name:a,version:""}}return null}function SU(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 Ks(){let e=navigator.userAgent,t=Zt(),a=await EC();return{userAgent:e,browser:vU(e),os:bU(e),deviceType:SU(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 IU="0.22.0-beta.5",CU=40,kU=10,TU=6e5;function Wg(){return typeof performance>"u"?0:performance.now()}function Gg(e,t){let a={};return{metrics:a,has:n=>n in a,set(n,r){a[n]=r},mark(n,r=Wg()){if(!(n in a)){a[n]=r-t;try{performance.mark(`waniwani:${e}:${n}`,{startTime:r})}catch{}}}}}function LU(e){let t={};for(let[a,n]of Object.entries(e)){if(Object.keys(t).length>=CU)break;if(!Number.isFinite(n))continue;let r=Math.round(n);r<0||r>TU||(t[a]=r)}return t}function EU(e){let t={};for(let[a,n]of Object.entries(e)){if(Object.keys(t).length>=kU)break;(typeof n=="string"||typeof n=="boolean")&&(t[a]=n)}return t}function MU(){let e=navigator.connection;if(e)return{effectiveType:e.effectiveType,rtt:e.rtt,downlink:e.downlink,saveData:e.saveData}}function Xd(e){let t=e?.Authorization;return typeof t=="string"&&t.startsWith("Bearer ")?t.slice(7):void 0}function AU(e,t,a,n){return{kind:e,sdkVersion:IU,channelId:t.channelId||void 0,sessionId:e==="boot"?void 0:t.sessionId||void 0,visitorId:Zt(),pageHost:window.location.hostname,connection:MU(),tags:EU(a),metrics:LU(n)}}var Vg,$d=[];function $g(e){let t=String(e?.chatTimingLogs).trim().toLowerCase()==="true";Vg=t;let a=$d;if($d=[],t)for(let n of a)n()}function Kd(e,t,a,n){let{api:r,token:o}=t;if(!(typeof window>"u"||!r||!o||Vg===!1))try{let i=AU(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(()=>{})};Vg?l():$d.length<20&&$d.push(l)}catch{}}var dr=Gg("boot",0),AC;function Uo(e,t){dr.mark(e,t)}function Yd(e){AC??(AC=e)}var RU=/cdn\.jsdelivr\.net\/npm\/@waniwani\/sdk@[^/]+\/dist\/chat\/embed\.js/,DU=/\/embed\.js(\?|$)/;function _U(){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)RU.test(a.name)?(dr.mark("bundleStart",a.startTime),dr.mark("bundleEnd",a.responseEnd)):DU.test(a.name)&&(dr.mark("loaderStart",a.startTime),dr.mark("loaderEnd",a.responseEnd))}function OU(){if(kv)return!0;try{return document.querySelectorAll('script[src*="@waniwani/sdk"]').length>1}catch{return!1}}function RC(e){_U(),dr.mark("bundleExecuted",Cv),Kd("boot",e,{configSource:AC,mode:e.mode,secondSdk:OU()},dr.metrics)}var PU=[["text-delta","firstText"],["tool-input-start","firstToolInput"],["tool-output-available","firstToolOutput"]];function DC(e){let t=Gg("turn",Wg());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 PU)!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,Kd("turn",n,r,t.metrics))}}}function NU(e){let t=e.indexOf("?");return t===-1?e:e.slice(0,t)}function _C(e,t){let a=Gg("widget",Wg()),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:NU(e),outcome:r,metrics:a.metrics}))}}}var BU="/api/mcp/events/v2/batch",Xg=new Set;function UU(e,t,a){return`${e}|${t}|${a??""}`}function Ys(e){return Wd(e,BU)}async function OC(e){let{api:t,token:a,channelId:n,mode:r,source:o}=e;if(typeof window>"u"||!t||!a)return;let i=Ys(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=UU(t,a,n);if(!Xg.has(l)){Xg.add(l);try{let s=await Ks(),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});Uo("pageViewSent"),await d}catch{Xg.delete(l)}}}function PC(e){let t=Ys(e.api);return t?kC({endpoint:t,token:e.token,channelId:e.channelId,source:e.getSource,identity:()=>({sessionId:e.getSessionId(),visitorId:Zt()})}):Zd("the chat api does not point at a Waniwani event ingest")}function Zd(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 Jd=z(he());var Qd=(...e)=>e.filter((t,a,n)=>!!t&&t.trim()!==""&&n.indexOf(t)===a).join(" ").trim();var NC=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();var BC=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,a,n)=>n?n.toUpperCase():a.toLowerCase());var Kg=e=>{let t=BC(e);return t.charAt(0).toUpperCase()+t.slice(1)};var Zs=z(he());var UC={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 FC=e=>{for(let t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0;return!1};var zC=(0,Zs.forwardRef)(({color:e="currentColor",size:t=24,strokeWidth:a=2,absoluteStrokeWidth:n,className:r="",children:o,iconNode:i,...l},s)=>(0,Zs.createElement)("svg",{ref:s,...UC,width:t,height:t,stroke:e,strokeWidth:n?Number(a)*24/Number(t):a,className:Qd("lucide",r),...!o&&!FC(l)&&{"aria-hidden":"true"},...l},[...i.map(([u,c])=>(0,Zs.createElement)(u,c)),...Array.isArray(o)?o:[o]]));var He=(e,t)=>{let a=(0,Jd.forwardRef)(({className:n,...r},o)=>(0,Jd.createElement)(zC,{ref:o,iconNode:t,className:Qd(`lucide-${NC(Kg(e))}`,`lucide-${e}`,n),...r}));return a.displayName=Kg(e),a};var FU=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],Qs=He("arrow-down",FU);var zU=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],Nn=He("arrow-up",zU);var qU=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Js=He("check",qU);var HU=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Qr=He("chevron-down",HU);var jU=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],eu=He("chevron-right",jU);var VU=[["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"}]],tu=He("clipboard-copy",VU);var WU=[["path",{d:"M12 6v6l4 2",key:"mmk7yg"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],fr=He("clock",WU);var GU=[["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"}]],au=He("file-text",GU);var $U=[["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"}]],sl=He("file",$U);var XU=[["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"}]],nu=He("globe",XU);var KU=[["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"}]],ru=He("image",KU);var YU=[["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"}]],ou=He("loader",YU);var ZU=[["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"}]],ul=He("paperclip",ZU);var QU=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],iu=He("square",QU);var JU=[["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"}]],Fo=He("wrench",JU);var e3=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Ga=He("x",e3);var t3=[["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"}]],lu=He("zap",t3);var $e=z(he(),1),dO=z(dm(),1);var cl=z(he(),1),su=z(ae(),1);function r3(e){return 1-(1-e)**3}function o3({start:e=0,end:t=100,duration:a=1e3,delay:n=0,ease:r=r3,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 i3=["80% 55%","69% 34%","8% 6%","41% 38%","86% 85%","82% 18%","51% 4%"],l3=[0,1,2,0,1,2,1];function s3(e){let t=[];for(let a=0;a<7;a++){let n=e[Math.min(l3[a],e.length-1)];t.push(`radial-gradient(at ${i3[a]}, ${n} 0px, transparent 50%)`)}return t.push(`linear-gradient(${e[0]} 0 100%)`),t}var u3=({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,cl.useState)(110),[d,f]=(0,cl.useState)(0),[p,m]=(0,cl.useState)(!1);(0,cl.useEffect)(()=>{if(!l)return;let T=110;m(!0),c(T),o3({ease:C=>C,duration:2e3,onUpdate:C=>{let M=C/100;c(T+360*M);let D=Math.min(M/.1,1),P=M>.85?(1-M)/.15:1;f(Math.min(D,P))},onEnd:()=>m(!1)})},[l]);let x=n+20,S=p?Math.max(0,(d*100-x)/(100-x)):0,y=s3(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,su.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,su.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,su.jsx)("div",{className:"ww:flex ww:flex-col ww:relative ww:overflow-auto ww:z-[1]",children:e})]})},tf=u3;Yg();Qg();var c3=WC({prefix:"ww"});function q(...e){return c3(af(e))}var uu=z(ae(),1);function dl({suggestions:e,isLoading:t,onSelect:a,align:n="start",className:r,...o}){return e.length===0&&!t?null:(0,uu.jsx)("div",{className:q("ww:px-4 ww:py-2",r),...o,children:(0,uu.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,uu.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,uu.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 GC=z(he(),1),$C="(max-width: 639px)";function d3(e){let t=window.matchMedia($C);return t.addEventListener("change",e),()=>t.removeEventListener("change",e)}function f3(){return window.matchMedia($C).matches}function p3(){return!1}function XC(){return(0,GC.useSyncExternalStore)(d3,f3,p3)}var nf=z(he(),1);function Jg(e,t){return e.find(a=>a.text===t)?.id??null}async function KC(e){let{api:t,token:a,name:n,source:r,sessionId:o,properties:i}=e;if(typeof window>"u"||!t||!a)return;let l=Ys(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 YC(e){let{api:t,token:a,channelId:n,mode:r,source:o,sessionId:i,promptId:l,origin:s,text:u,index:c}=e;await KC({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 ZC(e,t){return t.map(a=>({id:Jg(e,a),text:a}))}async function QC(e){let{api:t,token:a,channelId:n,mode:r,source:o,sessionId:i,prompts:l,origin:s}=e;l.length!==0&&await KC({api:t,token:a,name:"suggestion.shown",source:o,sessionId:i,properties:{prompts:l,count:l.length,origin:s,channelId:n,mode:r}})}function fl(e){let{widgetEvents:t,api:a,token:n,channelId:r,source:o,mode:i,pagePrompts:l}=e,s=(0,nf.useRef)(e.getSessionId);s.current=e.getSessionId,(0,nf.useEffect)(()=>{if(!(!a||!n))return t.subscribe(u=>{if(u.name==="suggestion.clicked"){let{text:c,origin:d,index:f}=u.properties;YC({api:a,token:n,channelId:r,mode:i,source:o,sessionId:s.current(),promptId:Jg(l??[],c),origin:d,text:c,index:f});return}if(u.name==="suggestions.shown"){let{texts:c,origin:d}=u.properties;QC({api:a,token:n,channelId:r,mode:i,source:o,sessionId:s.current(),prompts:ZC(l??[],c),origin:d})}})},[t,a,n,r,o,i,l])}var pl=z(he(),1),m3=80,h3=50,g3=15e3,JC=500;function ml(e,t=!0){let[a,n]=(0,pl.useState)(""),r=(0,pl.useRef)(void 0);return(0,pl.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,JC)):r.current=setTimeout(s,h3)):(o++,n(e.slice(0,o)),o>=e.length?(i=!0,r.current=setTimeout(s,g3)):r.current=setTimeout(s,m3)))};return r.current=setTimeout(s,JC),()=>{l=!0,clearTimeout(r.current)}},[e,t]),a}var Sn=z(he(),1);var ek=["en","fr","es"];function hl(e){return ek.includes(e)}function ew(e){if(e&&hl(e))return e;if(e){let a=e.split("-")[0]?.toLowerCase();if(a&&hl(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(hl(n))return n;let r=n.split("-")[0];if(r&&hl(r))return r}return"en"}var rf={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 tk={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 ak={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 tw={en:rf,fr:ak,es:tk};var rk=z(ae(),1),nk=(0,Sn.createContext)(null);function w3(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 zo({children:e,locale:t,messages:a}){let n=!!(t&&y3(t)),r=n?t:"en",[o,i]=(0,Sn.useState)(r),[l,s]=(0,Sn.useState)(n);(0,Sn.useEffect)(()=>{i(ew(t)),s(!0)},[t]);let u=(0,Sn.useMemo)(()=>{let c=tw[o]??tw["en"];return{locale:o,t:w3(c,a),ready:l}},[o,a,l]);return(0,rk.jsx)(nk.Provider,{value:u,children:e})}function y3(e){return e==="en"||e==="fr"||e==="es"}function Ie(){let e=(0,Sn.useContext)(nk);return e||{locale:"en",t:rf,ready:!0}}function aw(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 cu=(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 Ce=z(he(),1);var qo=new Map;function ok(e,t){if(qo.has(e)){URL.revokeObjectURL(t);return}for(qo.set(e,t);qo.size>20;){let a=qo.keys().next();if(a.done)return;let n=qo.get(a.value);qo.delete(a.value),n&&URL.revokeObjectURL(n)}}function ik(e){return qo.get(e)}var lk=z(ae(),1),Bn=({className:e,variant:t="default",size:a="default",type:n="button",...r})=>(0,lk.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 sk=z(he(),1);var bt=z(ae(),1),uk=({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)(x3,{file:n},r))});function x3({file:e}){let{t}=Ie();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)(sl,{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 ck(e,t){return e.startsWith("image/")?t.attachments.kindImage:e==="application/pdf"?t.attachments.kindPdf:t.attachments.kindFile}function v3({mediaType:e}){return e.startsWith("image/")?(0,bt.jsx)(ru,{className:"ww:size-5 ww:text-muted-foreground"}):e==="application/pdf"?(0,bt.jsx)(au,{className:"ww:size-5 ww:text-muted-foreground"}):(0,bt.jsx)(sl,{className:"ww:size-5 ww:text-muted-foreground"})}function nw({filename:e,mediaType:t,previewUrl:a,subtitle:n,tone:r="default",children:o,className:i}){let{t:l}=Ie(),s=ck(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)(v3,{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 dk(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 fk=({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)(b3,{document:n},`${n.documentId}-${r}`))});function b3({document:e}){let{t}=Ie(),[a,n]=(0,sk.useState)(!1),r=e.mediaType.startsWith("image/")?ik(e.documentId):void 0;return r&&!a?(0,bt.jsx)("li",{children:(0,bt.jsx)("img",{alt:`${e.filename}, ${ck(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)(nw,{filename:e.filename,mediaType:e.mediaType})}var ht=z(ae(),1),S3=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}},I3=(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)},mk=(0,Ce.createContext)(null),of=()=>{let e=(0,Ce.useContext)(mk);if(!e)throw new Error("usePromptInputAttachments must be used within a PromptInput");return e},hk=({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}=Ie(),S=(0,Ce.useRef)(null),w=(0,Ce.useRef)(null),[y,h]=(0,Ce.useState)([]),b=(0,Ce.useRef)(y),T=(0,Ce.useRef)(new Map),C=(0,Ce.useRef)(s),M=(0,Ce.useRef)(c),D=(0,Ce.useRef)(u);(0,Ce.useEffect)(()=>{C.current=s,M.current=c,D.current=u},[s,c,u]);let P=(0,Ce.useCallback)(v=>{b.current=v,h(v)},[]),L=(0,Ce.useCallback)(()=>{S.current?.click()},[]),$=(0,Ce.useCallback)((v,K)=>{P(b.current.map(ee=>ee.id===v?{...ee,...K}:ee))},[P]),H=(0,Ce.useCallback)((v,K)=>{let ee=C.current;if(!ee)return;let we=new AbortController,Ge=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 ye=me instanceof Error?me.message:m.promptInput.uploadFailed;return $(v,{status:"failed",error:ye}),M.current?.({code:"upload_failed",message:ye}),null});T.current.set(v,{file:K,controller:we,done:Ge})},[$,m]),F=(0,Ce.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(!I3(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}",gk(o,x)));continue}we.push(de)}if(we.length===0)return;let Ge=typeof r=="number"?Math.max(0,r-b.current.length):void 0,me=typeof Ge=="number"?we.slice(0,Ge):we;if(me.length<we.length&&ee("max_files",m.promptInput.errorTooMany.replace("{limit}",String(r))),me.length===0)return;let ye=!!C.current,le=me.map(de=>({file:de,item:{filename:de.name,id:cu(),mediaType:de.type,type:"file",url:URL.createObjectURL(de),status:ye?"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,Ce.useCallback)(v=>{let K=T.current.get(v);K&&($(v,{status:"uploading",progress:0,error:void 0}),H(v,K.file))},[$,H]),V=(0,Ce.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?ok(v.documentId,v.url):URL.revokeObjectURL(v.url)),K&&v.documentId&&D.current?.({documentId:v.documentId,filename:v.filename??"",mediaType:v.mediaType??""})},[]),N=(0,Ce.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]),R=(0,Ce.useCallback)(()=>{for(let v of b.current)V(v,!0);P([])},[V,P]),G=(0,Ce.useRef)(l);(0,Ce.useEffect)(()=>{let v=G.current;G.current=l,v&&!l&&R()},[l,R]);let ue=(0,Ce.useCallback)(()=>{for(let v of b.current)V(v,!1);P([])},[V,P]);(0,Ce.useEffect)(()=>()=>{for(let v of b.current)T.current.get(v.id)?.controller.abort(),v.url&&URL.revokeObjectURL(v.url)},[]);let I=(0,Ce.useCallback)(v=>{v.currentTarget.files&&F(v.currentTarget.files),v.currentTarget.value=""},[F]);(0,Ce.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 We=(0,Ce.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 Ge=[...we.values()].filter(le=>le!==null),me=C.current?[]:b.current,ye=await Promise.all(me.map(async({id:le,status:de,progress:Q,error:Be,...qe})=>{if(qe.url?.startsWith("blob:")){let _e=await S3(qe.url);return{...qe,url:_e??qe.url}}return qe}));try{let le=d({documents:Ge,files:ye,text:ee},v);le instanceof Promise&&await le,K.reset(),ue()}catch{}},[d,ue,m]),Je=(0,Ce.useMemo)(()=>({add:F,clear:R,files:y,openFileDialog:L,remove:N,retry:W,maxFileSize:o,maxPdfPages:i}),[y,F,N,W,R,L,o,i]);return(0,ht.jsxs)(mk.Provider,{value:Je,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:We,ref:w,...p,children:f})]})},pk=1024*1024;function gk(e,t){let a=e>=pk;return new Intl.NumberFormat(t,{style:"unit",unit:a?"megabyte":"kilobyte",maximumFractionDigits:0}).format(a?e/pk:Math.max(1,e/1024))}var wk=({onChange:e,onKeyDown:t,className:a,placeholder:n,...r})=>{let{t:o}=Ie(),i=of(),[l,s]=(0,Ce.useState)(!1),u=n??o.promptInput.placeholder,c=(0,Ce.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,Ce.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})},yk=({className:e,status:t,onStop:a,onClick:n,children:r,disabled:o,...i})=>{let{t:l}=Ie(),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)(ou,{className:"ww:size-4 ww:animate-spin"}):t==="streaming"&&(c=(0,ht.jsx)(iu,{className:"ww:size-4"}));let d=(0,Ce.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})},xk=({className:e,children:t,...a})=>{let{t:n,locale:r}=Ie(),o=of();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}",gk(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)(ul,{className:"ww:size-4"})})},vk=({className:e,...t})=>{let a=of();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)(C3,{file:n},n.id))})};function C3({file:e}){let{t}=Ie(),a=of(),n=e.status==="failed",r=e.status==="uploading";return(0,ht.jsxs)(nw,{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 bk=({enabled:e=!0})=>{let{t}=Ie(),[a,n]=(0,Ce.useState)(!1);return(0,Ce.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)(ul,{className:"ww:size-4"}),t.promptInput.dropToAttach]})}):null};var Ik=z(ae(),1);function Sk({text:e}){let{t}=Ie();return e===!1?null:(0,Ik.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 lf=z(he(),1);var Ho=z(ae(),1),Ck=({className:e,...t})=>(0,Ho.jsx)("div",{className:q("ww:flex ww:flex-col ww:gap-1 ww:px-3 ww:py-2",e),...t}),kk=({className:e,...t})=>(0,Ho.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}),Tk=({className:e,...t})=>(0,Ho.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}),Lk=({className:e,...t})=>(0,Ho.jsx)("span",{className:q("ww:line-clamp-1 ww:grow ww:break-words ww:text-muted-foreground",e),...t}),Ek=({className:e,...t})=>(0,Ho.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}),Mk=({className:e,...t})=>(0,Ho.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(ae(),1),Ak=(0,lf.memo)(({message:e,onRemove:t})=>{let{t:a}=Ie(),n=(0,lf.useCallback)(()=>t(e.id),[t,e.id]);return(0,sn.jsxs)(kk,{children:[(0,sn.jsx)(Tk,{}),(0,sn.jsx)(Lk,{children:e.text||a.chatQueue.attachmentFallback}),(0,sn.jsx)(Ek,{children:(0,sn.jsx)(Mk,{"aria-label":a.chatQueue.removeFromQueue,onClick:n,children:(0,sn.jsx)(Ga,{className:"ww:size-3"})})})]})});Ak.displayName="ChatQueueItem";function Rk({queuedMessages:e,onRemove:t,className:a}){let{t:n}=Ie();return e.length===0?null:(0,sn.jsxs)(Ck,{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)(Ak,{message:r,onRemove:t},r.id))})]})}var _a=z(he(),1);var St=z(he(),1);dp();var u2=z(he(),1);var c2=z(ae(),1),V6=({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,c2.jsx)(e,{"data-waniwani-shimmer":"",className:q("ww:inline-block",t),style:i,...o,children:r})},Tn=(0,u2.memo)(V6);Tn.displayName="Shimmer";var ua=z(ae(),1),d2=(0,St.createContext)(null);function f2(){let e=(0,St.useContext)(d2);if(!e)throw new Error("Reasoning components must be used within <Reasoning>");return e}var W6=1e3,G6=1e3,Uu=(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)/G6)),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)},W6);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)(d2.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})})});Uu.displayName="Reasoning";var Fu=(0,St.memo)(({className:e,children:t,getThinkingMessage:a,hideIcon:n=!1,onClick:r,...o})=>{let{t:i}=Ie(),{isStreaming:l,isOpen:s,duration:u,setIsOpen:c}=f2(),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)]})})});Fu.displayName="ReasoningTrigger";var zu=(0,St.memo)(({className:e,children:t,...a})=>{let{isOpen:n}=f2();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)(El,{children:t})})})})});zu.displayName="ReasoningContent";var Ne=z(ae(),1),$6=500,p2=(0,_a.createContext)(null);function m2(){let e=(0,_a.useContext)(p2);if(!e)throw new Error("ChainOfThought components must be used within <ChainOfThought>");return e}function h2({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),$6);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)(p2.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 g2({className:e,label:t,workingLabel:a,children:n,...r}){let{open:o,setOpen:i,isWorking:l,settled:s,activeStep:u}=m2();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 w2({className:e,children:t,...a}){let{open:n}=m2();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 y2({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 Rx({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)(y2,{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 x2({isStreaming:e=!1,isLast:t=!1,children:a}){return(0,Ne.jsxs)("div",{className:"ww:flex ww:gap-2",children:[(0,Ne.jsx)(y2,{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)(Uu,{isStreaming:e,className:"ww:mb-0",children:[(0,Ne.jsx)(Fu,{hideIcon:!0}),(0,Ne.jsx)(zu,{children:a})]})})]})}var Dx={name:"cjk-noop",type:"cjk",remarkPluginsBefore:[],remarkPluginsAfter:[],remarkPlugins:[]};var v2={name:"shiki-noop",type:"code-highlighter",supportsLanguage:()=>!1,getSupportedLanguages:()=>[],getThemes:()=>["github-light","github-dark"],highlight:()=>null};var I2=z(he(),1);var vr=z(he(),1),X6=5,b2=400;function S2(e,t,a={}){let{msPerChar:n=X6}=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>b2&&(l.current=i.current.length-b2),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 qu=z(ae(),1),_x=({className:e,from:t,children:a,...n})=>(0,qu.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,qu.jsx)("div",{className:q("ww:flex ww:min-w-0 ww:flex-col ww:gap-2","ww:w-full"),children:a})}),Ox=({children:e,className:t,...a})=>(0,qu.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}),K6={cjk:Dx,code:v2},Y6={cjk:Dx},Z6={enabled:!1};function Q6({className:e,linkSafety:t,isStreaming:a,children:n,...r}){let i=S2(typeof n=="string"?n:"",!!a),l=typeof n=="string"?i:n;return(0,qu.jsx)(El,{className:q("ww:size-full ww:[&>*:first-child]:mt-0 ww:[&>*:last-child]:mb-0",e),linkSafety:t??Z6,plugins:a?Y6:K6,...r,children:l})}var gp=(0,I2.memo)(Q6,(e,t)=>e.children===t.children&&e.isStreaming===t.isStreaming);gp.displayName="MessageResponse";var Vt=z(he(),1);function Px(e){if(!(typeof e!="object"||e===null))return e}function C2(e){return Px(e?.ui)}function Nx(e){if(!e)return;let t=C2(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 Hu(e){return C2(e)?.autoHeight===!0}function Bx(e){return Px(Px(e)?._meta)}var Te=z(ae(),1);function J6(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 e9({text:e,className:t}){let{t:a}=Ie(),[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)(Js,{className:"ww:size-3.5"}),(0,Te.jsx)("span",{children:a.tool.copied})]}):(0,Te.jsxs)(Te.Fragment,{children:[(0,Te.jsx)(tu,{className:"ww:size-3.5"}),(0,Te.jsx)("span",{children:a.tool.copy})]})})}function k2({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=J6(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)(e9,{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)(eu,{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 Ux=(0,Vt.createContext)({open:!1,toggle:()=>{}});function T2({className:e,defaultOpen:t=!1,children:a,...n}){let[r,o]=(0,Vt.useState)(t);return(0,Te.jsx)(Ux.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 L2({className:e,title:t,state:a,...n}){let{open:r,toggle:o}=(0,Vt.useContext)(Ux),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)(Fo,{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 E2({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 M2({className:e,children:t,...a}){let{open:n}=(0,Vt.useContext)(Ux);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 Fx({className:e,input:t,debug:a,...n}){let{t:r}=Ie(),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)(k2,{data:o,label:r.tool.request,className:e,...n})}function ju(e,t,a){if(e){let n=Nx(a?.[e]?._meta);if(n)return n}return Nx(Bx(t))}function A2(e,t,a){return e&&Hu(a?.[e]?._meta)?!0:Hu(Bx(t))}function zx({className:e,output:t,errorText:a,debug:n,...r}){let{t:o}=Ie(),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)(k2,{data:i,label:o.tool.response,className:e,...r}):null}var Vu=z(ae(),1);function R2(e){return e.type==="text"||e.type==="reasoning"||e.type==="file"||"toolCallId"in e}function D2(e){return e.parts.some(R2)}function _2(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=>!(!R2(o)||a?.ignoreToolParts&&"toolCallId"in o||a?.ignoreReasoningParts&&o.type==="reasoning"))}function O2({className:e,...t}){let{t:a}=Ie();return(0,Vu.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,Vu.jsx)(lu,{className:"ww:size-4 ww:shrink-0"}),(0,Vu.jsx)(Tn,{duration:1.6,children:a.workingIndicator.default})]})}var Qe=z(he(),1);function li(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 P2(e,t){return!li(e)&&!li(t)?null:li(e)?li(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 N2=(0,br.createContext)(()=>{});function B2(){return(0,br.useContext)(N2)}var U2=N2.Provider;function t9(e){let t=window.requestIdleCallback;typeof t=="function"?t(e):setTimeout(e,500)}function Ml(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;Uo(r.paintMark),t9(()=>RC(r))});return()=>cancelAnimationFrame(n)},[e.painted])}var F2=z(ae(),1),a9="/api/mcp/resource",n9=500,r9=0,o9=16,i9="2026-01-26",l9=300,s9=3e3,u9=3,c9=2e3;function d9(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}function f9(e,t,a){return ju(e,t,a)?!1:t._meta?.["waniwani/autoInjectResultText"]!==!1}function wp({resourceUri:e,toolInput:t,toolResult:a,resourceEndpoint:n=a9,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,Qe.useRef)(null),x=(0,Qe.useRef)(t),S=(0,Qe.useRef)(a),w=(0,Qe.useRef)({width:0,height:0}),y=(0,Qe.useRef)(null),h=(0,Qe.useRef)(!1),b=(0,Qe.useRef)(0),T=(0,Qe.useRef)("inline"),[C,M]=(0,Qe.useState)(r9),[D,P]=(0,Qe.useState)(void 0),L=(0,Qe.useRef)(s),$=(0,Qe.useRef)(u),H=(0,Qe.useRef)(c),F=(0,Qe.useRef)(d),W=(0,Qe.useRef)(r),V=(0,Qe.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,Qe.useCallback)(v=>l?Math.max(v+o9,0):Math.min(Math.max(v,50),n9),[l]),R=(0,Qe.useMemo)(()=>{let v=n.includes("?")?"&":"?";return`${n}${v}uri=${encodeURIComponent(e)}`},[n,e]),G=B2(),ue=(0,Qe.useRef)(null),I=(0,Qe.useRef)(void 0);(0,Qe.useEffect)(()=>{let v=_C(e,G);return ue.current=v,()=>{clearTimeout(I.current),v.has("initialized")||v.report("timeout",b.current),ue.current=null}},[e,G]);let We=(0,Qe.useRef)(o);We.current=o;let Je=(0,Qe.useRef)(f);return(0,Qe.useEffect)(()=>{Je.current=f,w.current.height=-1,y.current&&(y.current.cancel(),y.current=null)},[f]),(0,Qe.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,Qe.useEffect)(()=>{let v=m.current;if(!v)return;let K=!1,ee=!1,we=null,Ge=null,me=setTimeout(()=>{if(K||ee||b.current>=u9)return;b.current+=1;let de=new URL(v.src);de.searchParams.set("_retry",String(b.current)),v.src=de.toString()},s9),ye=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),ye({jsonrpc:"2.0",id:qe,result:{protocolVersion:Q.params?.protocolVersion??i9,hostInfo:{name:"Waniwani Chat",version:"1.0.0"},hostCapabilities:{openLinks:{},message:{text:{}},tools:{},updateModelContext:{text:{},structuredContent:{}}},hostContext:{theme:We.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),c9);let _e=x.current,ke=S.current,xe=ke._meta&&typeof ke._meta=="object"?ke._meta:null,Y=d9(W.current),Oe=xe&&typeof xe.waniwani=="object"&&xe.waniwani!==null?xe.waniwani:null,rt=Oe||Y?{...Oe??{},...Y?{sessionId:Y}:{}}:void 0,ba=xe||rt?{...xe??{},...rt?{waniwani:rt}:{}}:void 0;ye({jsonrpc:"2.0",method:"ui/notifications/tool-input",params:{arguments:_e}});let Sa=ke.content??[{type:"text",text:JSON.stringify(ke)}];ye({jsonrpc:"2.0",method:"ui/notifications/tool-result",params:{content:Sa,structuredContent:ke.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,ke=typeof _e?.height=="number"?_e.height:void 0,xe=typeof _e?.width=="number"?_e.width:void 0,Y=w.current,Oe=ke!==void 0&&ke!==Y.height,rt=xe!==void 0&&xe!==Y.width;if(!Oe&&!rt)return;if(Oe&&ke!==void 0){if(Y.height=ke,Je.current)return;let ba=N(ke),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:l9,easing:"ease-out",fill:"forwards"});y.current=ra,ra.onfinish=()=>{y.current===ra&&(ra.cancel(),y.current=null)}}}rt&&l&&xe!==void 0&&(Y.width=xe,P(xe));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")),ye({jsonrpc:"2.0",id:qe,result:{}});return}if(Be==="ui/message"&&qe!=null){if($.current&&Q.params){let _e=Q.params,ke=we;if(we=null,Ge){clearTimeout(Ge.timer);let xe=Ge.text;Ge=null;let Y=(_e.content??[]).map(Oe=>Oe.text??"").join("").trim();_e={..._e,content:[{type:"text",text:`${Y}
|
|
122
122
|
|
|
123
123
|
${xe}`}]}}$.current({..._e,...ke?{modelContext:ke}:{}})}ye({jsonrpc:"2.0",id:qe,result:{}});return}if(Be==="ui/update-model-context"&&qe!=null){we=P2(we,Q.params),ye({jsonrpc:"2.0",id:qe,result:{}});return}if(Be==="tools/call"&&qe!=null){let _e=H.current;if(!_e){ye({jsonrpc:"2.0",id:qe,error:{code:-32601,message:"tools/call not supported"}});return}let ke=Q.params?.name;_e({name:ke,arguments:Q.params?.arguments??{}}).then(xe=>{ye({jsonrpc:"2.0",id:qe,result:xe});let Y=xe.content?.map(Oe=>Oe.text??"").join("").trim();Y&&f9(ke,xe,V.current)&&(Ge&&clearTimeout(Ge.timer),Ge={text:Y,timer:setTimeout(()=>{if(K)return;let Oe=we;we=null,Ge=null,$.current?.({role:"user",content:[{type:"text",text:Y}],...Oe?{modelContext:Oe}:{}})},500)})}).catch(xe=>{let Y=xe instanceof Error?xe.message:"Tool call failed";ye({jsonrpc:"2.0",id:qe,error:{code:-32e3,message:Y}})});return}if(Be==="ui/request-display-mode"&&qe!=null){let _e=Q.params?.mode,ke=_e==="fullscreen"||_e==="inline"||_e==="pip"?_e:"inline";T.current=ke,ye({jsonrpc:"2.0",id:qe,result:{mode:ke}}),ye({jsonrpc:"2.0",method:"ui/notifications/host-context-changed",params:{displayMode:ke}}),F.current?.(ke);return}if(Be==="ui/resource-teardown"&&qe!=null){ye({jsonrpc:"2.0",id:qe,result:{}});return}Be==="ping"&&qe!=null&&ye({jsonrpc:"2.0",id:qe,result:{}})};return window.addEventListener("message",le),()=>{K=!0,clearTimeout(me),Ge&&clearTimeout(Ge.timer),window.removeEventListener("message",le)}},[l,N]),(0,F2.jsx)("iframe",{ref:m,src:R,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||!D?void 0:`min(${D}px, 100%)`,width:"100%",border:"none",colorScheme:o?"dark":"auto"},title:"MCP App"})}var uo=z(ae(),1);function z2({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 q2=z(he(),1);var Al=z(ae(),1);function p9({onRetry:e}){let{t}=Ie();return(0,Al.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,Al.jsx)("span",{children:t.widgetErrorBoundary.failedToLoad}),(0,Al.jsx)("button",{type:"button",onClick:e,className:"ww:text-xs ww:font-medium ww:text-primary ww:hover:underline",children:t.widgetErrorBoundary.retry})]})}var yp=class extends q2.Component{constructor(){super(...arguments);re(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,Al.jsx)(p9,{onRetry:()=>this.setState({hasError:!1})}):this.props.children}};var Le=z(ae(),1);function qx(e){return e?e.replace(/[-_]/g," ").replace(/^\w/,t=>t.toUpperCase()):"Tool"}function H2(e){return e&&/search|find|lookup|query|web|browse|google/i.test(e)?nu:Fo}function j2({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}=Ie(),w=e[e.length-1],y=e.length>0,h=d!=null,b=!h&&_2(e,t,{ignoreToolParts:p===!1,ignoreReasoningParts:p===!1});return(0,Le.jsxs)(Le.Fragment,{children:[!h&&(!y&&n?(0,Le.jsx)(z2,{...n,onSuggestionSelect:r}):a&&(0,Le.jsx)(_x,{from:"assistant",children:(0,Le.jsx)(Ox,{children:(0,Le.jsx)(gp,{children:a})})})),e.map(T=>{let C=T.parts.filter(N=>N.type==="text"),M=T.parts.filter(N=>N.type==="reasoning"),D=T.parts.filter(N=>N.type==="file"),P=dk(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"&&!D2(T)?(0,Le.jsx)("div",{style:{display:"none"}},T.id):p===!1&&T.role==="assistant"&&!F&&D.length===0&&L.every(N=>{let R="output"in N?N.output:void 0;return R===void 0||!o||!ju(N.toolName,R,m)})?(0,Le.jsx)("div",{style:{display:"none"}},T.id):(0,Le.jsxs)(_x,{from:T.role,className:x?.message,children:[p!==!1&&!W&&!V&&M.map((N,R)=>(0,Le.jsxs)(Uu,{isStreaming:N.state==="streaming",children:[(0,Le.jsx)(Fu,{}),(0,Le.jsx)(zu,{children:N.text})]},`reasoning-${T.id}-${R}`)),V&&(()=>{let N=$[$.length-1],R=N.type==="reasoning"?{icon:fr,label:S.reasoning.thinking}:{icon:H2(N.toolName),label:N.title??qx(N.toolName)};return(0,Le.jsxs)(h2,{isWorking:H&&(t==="streaming"||t==="submitted"),activeStep:R,children:[(0,Le.jsx)(g2,{workingLabel:S.chainOfThought.working,label:S.chainOfThought.done}),(0,Le.jsx)(w2,{children:$.map((G,ue)=>{let I=ue===$.length-1;if(G.type==="reasoning")return(0,Le.jsx)(x2,{isStreaming:G.state==="streaming",isLast:I,children:G.text},`reasoning-${T.id}-${ue}`);let We=G.title??qx(G.toolName),Je=H2(G.toolName);if(p==="titles-only")return(0,Le.jsx)(Rx,{icon:Je,title:We,state:G.state,isLast:I},G.toolCallId);let v="output"in G?G.output:void 0;return(0,Le.jsxs)(Rx,{icon:Je,title:We,state:G.state,isLast:I,children:[(0,Le.jsx)(Fx,{input:G.input,debug:f}),v!==void 0&&(0,Le.jsx)(zx,{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],R=N.title??qx(N.toolName);if(p==="titles-only")return(0,Le.jsx)(E2,{title:R,state:N.state});let G="output"in N?N.output:void 0;return(0,Le.jsxs)(T2,{children:[(0,Le.jsx)(L2,{title:R,state:N.state}),(0,Le.jsxs)(M2,{children:[(0,Le.jsx)(Fx,{input:N.input,debug:f}),G!==void 0&&(0,Le.jsx)(zx,{output:G,errorText:"errorText"in N?N.errorText:void 0,debug:f})]})]})})(),L.map(N=>{let R="output"in N?N.output:void 0,G=ju(N.toolName,R,m),ue=A2(N.toolName,R,m),I=N.toolCallId===d;return G&&o&&R!==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&&R!==void 0&&(0,Le.jsx)(yp,{children:(0,Le.jsx)(wp,{isFullscreen:I,resourceUri:G,toolInput:N.input??{},toolResult:{content:R.content,structuredContent:R.structuredContent,_meta:R._meta},resourceEndpoint:o,chatSessionId:i,isDark:l,autoHeight:ue,toolDefinitions:m,onFollowUp:s,onCallTool:u,onDisplayModeChange:c?We=>c(We,{toolCallId:N.toolCallId,resourceUri:G,toolInput:N.input??{},toolResult:{content:R.content,structuredContent:R.structuredContent,_meta:R._meta},autoHeight:ue}):void 0})})},N.toolCallId):null}),!W&&P.length>0&&(0,Le.jsx)(fk,{documents:P}),!W&&(0,Le.jsx)("div",{children:(0,Le.jsxs)(Ox,{className:q(T.role==="user"?x?.userBubble:x?.assistantBubble),children:[D.length>0&&(0,Le.jsx)(uk,{files:D}),F?C.map((N,R)=>{let G=H&&t==="streaming"&&R===C.length-1;return(0,Le.jsx)(gp,{isStreaming:G,children:N.type==="text"?N.text:""},`${T.id}-${R}`)}):null]})})]},T.id)}),b&&(0,Le.jsx)(O2,{})]})}var co=z(ae(),1);function m9({label:e}){return(0,co.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,co.jsx)("title",{children:e}),(0,co.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,co.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function xp({onClick:e}){let{t}=Ie();return(0,co.jsx)("button",{type:"button",onClick:e,title:t.threadMenu.newChat,"aria-label":t.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,co.jsx)(m9,{label:t.threadMenu.newChat})})}var Wu=z(ae(),1),h9="https://app.waniwani.ai/assets/waniwani-logo.svg",g9="https://waniwani.ai";function V2(){let{t:e}=Ie();return(0,Wu.jsxs)("a",{href:g9,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,Wu.jsx)("span",{children:e.poweredBy.label}),(0,Wu.jsx)("img",{src:h9,alt:"Waniwani",width:72,height:10,"data-waniwani-logo":"",className:"ww:h-2.5 ww:w-auto"})]})}var Rl=z(he(),1);var ut=z(ae(),1),W2=20;function w9({label:e}){return(0,ut.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,ut.jsx)("title",{children:e}),(0,ut.jsx)("path",{d:"M3 12a9 9 0 1 0 3-6.7"}),(0,ut.jsx)("polyline",{points:"3 4 3 9 8 9"}),(0,ut.jsx)("line",{x1:"12",y1:"7",x2:"12",y2:"12"}),(0,ut.jsx)("line",{x1:"12",y1:"12",x2:"15",y2:"14"})]})}function y9({label:e}){return(0,ut.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,ut.jsx)("title",{children:e}),(0,ut.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,ut.jsx)("path",{d:"M19 6l-2 14a2 2 0 0 1-2 2H9a2 2 0 0 1-2-2L5 6"}),(0,ut.jsx)("path",{d:"M10 11v6"}),(0,ut.jsx)("path",{d:"M14 11v6"})]})}function G2({threads:e,activeThreadId:t,onNewThread:a,onSelectThread:n,onDeleteThread:r}){let{locale:o,t:i}=Ie(),[l,s]=(0,Rl.useState)(!1),u=(0,Rl.useRef)(null);(0,Rl.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,W2),d=Math.max(0,e.length-W2);return(0,ut.jsxs)("div",{ref:u,className:"ww:relative ww:flex ww:items-center ww:gap-1",children:[(0,ut.jsx)(xp,{onClick:a}),(0,ut.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,ut.jsx)(w9,{label:i.threadMenu.threadHistory})}),l&&(0,ut.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,ut.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,ut.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,ut.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,ut.jsx)("div",{className:"ww:truncate ww:text-foreground ww:font-medium",children:f.title}),(0,ut.jsx)("div",{className:"ww:text-[10px] ww:text-muted-foreground",children:Number.isNaN(m)?"":aw(m,o)})]}),(0,ut.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,ut.jsx)(y9,{label:i.threadMenu.deleteThread})})]},f.threadId)}),d>0&&(0,ut.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 vp=z(he(),1);function Dl(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 $2(){return{subscribe(){return()=>{}},emit(){}}}var X2=(0,vp.createContext)($2());function bp(){return(0,vp.useContext)(X2)}var _l=X2.Provider;var Sp=z(he(),1);function K2(e){let t=(0,Sp.useRef)(e);return t.current=e,(0,Sp.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 CD="vercel.ai.error",x9=Symbol.for(CD),Y2,Z2,Fe=class kD extends(Z2=Error,Y2=x9,Z2){constructor({name:t,message:a,cause:n}){super(a),this[Y2]=!0,this.name=t,this.cause=n}static isInstance(t){return kD.hasMarker(t,CD)}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}},TD="AI_APICallError",LD=`vercel.ai.error.${TD}`,v9=Symbol.for(LD),Q2,J2,Kie=class extends(J2=Fe,Q2=v9,J2){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:TD,message:e,cause:i}),this[Q2]=!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,LD)}},ED="AI_EmptyResponseBodyError",MD=`vercel.ai.error.${ED}`,b9=Symbol.for(MD),eD,tD,Yie=class extends(tD=Fe,eD=b9,tD){constructor({message:e="Empty response body"}={}){super({name:ED,message:e}),this[eD]=!0}static isInstance(e){return Fe.hasMarker(e,MD)}};function AD(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var RD="AI_InvalidArgumentError",DD=`vercel.ai.error.${RD}`,S9=Symbol.for(DD),aD,nD,_D=class extends(nD=Fe,aD=S9,nD){constructor({message:e,cause:t,argument:a}){super({name:RD,message:e,cause:t}),this[aD]=!0,this.argument=a}static isInstance(e){return Fe.hasMarker(e,DD)}},OD="AI_InvalidPromptError",PD=`vercel.ai.error.${OD}`,I9=Symbol.for(PD),rD,oD,Zie=class extends(oD=Fe,rD=I9,oD){constructor({prompt:e,message:t,cause:a}){super({name:OD,message:`Invalid prompt: ${t}`,cause:a}),this[rD]=!0,this.prompt=e}static isInstance(e){return Fe.hasMarker(e,PD)}},ND="AI_InvalidResponseDataError",BD=`vercel.ai.error.${ND}`,C9=Symbol.for(BD),iD,lD,Qie=class extends(lD=Fe,iD=C9,lD){constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:ND,message:t}),this[iD]=!0,this.data=e}static isInstance(e){return Fe.hasMarker(e,BD)}},UD="AI_JSONParseError",FD=`vercel.ai.error.${UD}`,k9=Symbol.for(FD),sD,uD,jx=class extends(uD=Fe,sD=k9,uD){constructor({text:e,cause:t}){super({name:UD,message:`JSON parsing failed: Text: ${e}.
|
|
124
124
|
Error message: ${AD(t)}`,cause:t}),this[sD]=!0,this.text=e}static isInstance(e){return Fe.hasMarker(e,FD)}},zD="AI_LoadAPIKeyError",qD=`vercel.ai.error.${zD}`,T9=Symbol.for(qD),cD,dD,Jie=class extends(dD=Fe,cD=T9,dD){constructor({message:e}){super({name:zD,message:e}),this[cD]=!0}static isInstance(e){return Fe.hasMarker(e,qD)}},HD="AI_LoadSettingError",jD=`vercel.ai.error.${HD}`,L9=Symbol.for(jD),fD,pD,ele=class extends(pD=Fe,fD=L9,pD){constructor({message:e}){super({name:HD,message:e}),this[fD]=!0}static isInstance(e){return Fe.hasMarker(e,jD)}},VD="AI_NoContentGeneratedError",WD=`vercel.ai.error.${VD}`,E9=Symbol.for(WD),mD,hD,tle=class extends(hD=Fe,mD=E9,hD){constructor({message:e="No content generated."}={}){super({name:VD,message:e}),this[mD]=!0}static isInstance(e){return Fe.hasMarker(e,WD)}},GD="AI_NoSuchModelError",$D=`vercel.ai.error.${GD}`,M9=Symbol.for($D),gD,wD,ale=class extends(wD=Fe,gD=M9,wD){constructor({errorName:e=GD,modelId:t,modelType:a,message:n=`No such ${a}: ${t}`}){super({name:e,message:n}),this[gD]=!0,this.modelId=t,this.modelType=a}static isInstance(e){return Fe.hasMarker(e,$D)}},XD="AI_TooManyEmbeddingValuesForCallError",KD=`vercel.ai.error.${XD}`,A9=Symbol.for(KD),yD,xD,nle=class extends(xD=Fe,yD=A9,xD){constructor(e){super({name:XD,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[yD]=!0,this.provider=e.provider,this.modelId=e.modelId,this.maxEmbeddingsPerCall=e.maxEmbeddingsPerCall,this.values=e.values}static isInstance(e){return Fe.hasMarker(e,KD)}},YD="AI_TypeValidationError",ZD=`vercel.ai.error.${YD}`,R9=Symbol.for(ZD),vD,bD,qn=class Hx extends(bD=Fe,vD=R9,bD){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:YD,message:`${r}: Value: ${JSON.stringify(t)}.
|