@waniwani/sdk 0.22.1 → 0.23.0
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 +2 -2
- package/dist/chat/embed.js.map +1 -1
- package/dist/chat/index.js +1 -1
- package/dist/chat/index.js.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/mcp/index.d.ts +22 -24
- package/dist/mcp/index.js +5 -5
- package/dist/mcp/index.js.map +1 -1
- package/dist/mcp/react/skybridge.js.map +1 -1
- package/dist/mcp/react.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
|
`)},PS=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("")},uK=e=>{let{headers:t,rows:a}=e;if(t.length===0)return"";let n=new Array(a.length+2),r=0,o=t.map(s=>PS(s));n[r]=`| ${o.join(" | ")} |`,r+=1;let i=new Array(t.length);for(let s=0;s<t.length;s+=1)i[s]="---";n[r]=`| ${i.join(" | ")} |`,r+=1;for(let s of a)if(s.length<t.length){let l=new Array(t.length);for(let u=0;u<t.length;u+=1)l[u]=u<s.length?PS(s[u]):"";n[r]=`| ${l.join(" | ")} |`,r+=1}else{let l=s.map(u=>PS(u));n[r]=`| ${l.join(" | ")} |`,r+=1}return n.join(`
|
|
119
119
|
`)},cK=({children:e,className:t,onCopy:a,onError:n,timeout:r=2e3})=>{let[o,i]=(0,N.useState)(!1),[s,l]=(0,N.useState)(!1),u=(0,N.useRef)(null),c=(0,N.useRef)(0),{isAnimating:d}=(0,N.useContext)(qa),p=async h=>{var v,I;if(typeof window>"u"||!((v=navigator?.clipboard)!=null&&v.write)){n?.(new Error("Clipboard API not available"));return}try{let y=(I=u.current)==null?void 0:I.closest('[data-streamdown="table-wrapper"]'),w=y?.querySelector("table");if(!w){n?.(new Error("Table not found"));return}let g=VN(w),S=h==="csv"?$N(g):lK(g),E=new ClipboardItem({"text/plain":new Blob([S],{type:"text/plain"}),"text/html":new Blob([w.outerHTML],{type:"text/html"})});await navigator.clipboard.write([E]),l(!0),i(!1),a?.(h),c.current=window.setTimeout(()=>l(!1),r)}catch(y){n?.(y)}};(0,N.useEffect)(()=>{let h=v=>{let I=v.composedPath();u.current&&!I.includes(u.current)&&i(!1)};return document.addEventListener("mousedown",h),()=>{document.removeEventListener("mousedown",h),window.clearTimeout(c.current)}},[]);let m=s?zS:FS;return(0,M.jsxs)("div",{className:"relative",ref:u,children:[(0,M.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,M.jsx)(m,{size:14})}),o?(0,M.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,M.jsx)("button",{className:"w-full px-3 py-2 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>p("csv"),title:"Copy table as CSV",type:"button",children:"CSV"}),(0,M.jsx)("button",{className:"w-full px-3 py-2 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>p("tsv"),title:"Copy table as TSV",type:"button",children:"TSV"})]}):null]})},dK=({children:e,className:t,onDownload:a,onError:n})=>{let[r,o]=(0,N.useState)(!1),i=(0,N.useRef)(null),{isAnimating:s}=(0,N.useContext)(qa),l=u=>{var c;try{let d=(c=i.current)==null?void 0:c.closest('[data-streamdown="table-wrapper"]'),p=d?.querySelector("table");if(!p){n?.(new Error("Table not found"));return}let m=VN(p),h=u==="csv"?$N(m):uK(m);tu(`table.${u==="csv"?"csv":"md"}`,h,u==="csv"?"text/csv":"text/markdown"),o(!1),a?.(u)}catch(d){n?.(d)}};return(0,N.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,M.jsxs)("div",{className:"relative",ref:i,children:[(0,M.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:s,onClick:()=>o(!r),title:"Download table",type:"button",children:e??(0,M.jsx)(Lh,{size:14})}),r?(0,M.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,M.jsx)("button",{className:"w-full px-3 py-2 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>l("csv"),title:"Download table as CSV",type:"button",children:"CSV"}),(0,M.jsx)("button",{className:"w-full px-3 py-2 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>l("markdown"),title:"Download table as Markdown",type:"button",children:"Markdown"})]}):null]})},fK=({children:e,className:t,showControls:a,...n})=>(0,M.jsxs)("div",{className:"my-4 flex flex-col space-y-2","data-streamdown":"table-wrapper",children:[a?(0,M.jsxs)("div",{className:"flex items-center justify-end gap-1",children:[(0,M.jsx)(cK,{}),(0,M.jsx)(dK,{})]}):null,(0,M.jsx)("div",{className:"overflow-x-auto",children:(0,M.jsx)("table",{className:Ce("w-full border-collapse border border-border",t),"data-streamdown":"table",...n,children:e})})]}),pK=(0,N.lazy)(()=>Promise.resolve().then(()=>(MN(),AN)).then(e=>({default:e.CodeBlock}))),mK=(0,N.lazy)(()=>Promise.resolve().then(()=>(_N(),DN)).then(e=>({default:e.Mermaid}))),hK=/language-([^\s]+)/;BS=(e,t)=>typeof e=="boolean"?e:e[t]!==!1,kh=(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},HS=(0,N.memo)(({children:e,className:t,node:a,...n})=>(0,M.jsx)("ol",{className:Ce("list-inside list-decimal whitespace-normal [li_&]:pl-6",t),"data-streamdown":"ordered-list",...n,children:e}),(e,t)=>Wt(e,t));HS.displayName="MarkdownOl";WN=(0,N.memo)(({children:e,className:t,node:a,...n})=>(0,M.jsx)("li",{className:Ce("py-1 [&>p]:inline",t),"data-streamdown":"list-item",...n,children:e}),(e,t)=>e.className===t.className&&Eh(e.node,t.node));WN.displayName="MarkdownLi";GN=(0,N.memo)(({children:e,className:t,node:a,...n})=>(0,M.jsx)("ul",{className:Ce("list-inside list-disc whitespace-normal [li_&]:pl-6",t),"data-streamdown":"unordered-list",...n,children:e}),(e,t)=>Wt(e,t));GN.displayName="MarkdownUl";XN=(0,N.memo)(({className:e,node:t,...a})=>(0,M.jsx)("hr",{className:Ce("my-6 border-border",e),"data-streamdown":"horizontal-rule",...a}),(e,t)=>Wt(e,t));XN.displayName="MarkdownHr";KN=(0,N.memo)(({children:e,className:t,node:a,...n})=>(0,M.jsx)("span",{className:Ce("font-semibold",t),"data-streamdown":"strong",...n,children:e}),(e,t)=>Wt(e,t));KN.displayName="MarkdownStrong";gK=({children:e,className:t,href:a,node:n,...r})=>{let{linkSafety:o}=(0,N.useContext)(qa),[i,s]=(0,N.useState)(!1),l=a==="streamdown:incomplete-link",u=(0,N.useCallback)(async m=>{if(!(!(o!=null&&o.enabled&&a)||l)){if(m.preventDefault(),o.onLinkCheck&&await o.onLinkCheck(a)){window.open(a,"_blank","noreferrer");return}s(!0)}},[o,a,l]),c=(0,N.useCallback)(()=>{a&&window.open(a,"_blank","noreferrer")},[a]),d=(0,N.useCallback)(()=>{s(!1)},[]),p={url:a??"",isOpen:i,onClose:d,onConfirm:c};return o!=null&&o.enabled&&a?(0,M.jsxs)(M.Fragment,{children:[(0,M.jsx)("button",{className:Ce("wrap-anywhere appearance-none text-left font-medium text-primary underline",t),"data-incomplete":l,"data-streamdown":"link",onClick:u,type:"button",children:e}),o.renderModal?o.renderModal(p):(0,M.jsx)(aK,{...p})]}):(0,M.jsx)("a",{className:Ce("wrap-anywhere font-medium text-primary underline",t),"data-incomplete":l,"data-streamdown":"link",href:a,rel:"noreferrer",target:"_blank",...r,children:e})},YN=(0,N.memo)(gK,(e,t)=>Wt(e,t)&&e.href===t.href);YN.displayName="MarkdownA";ZN=(0,N.memo)(({children:e,className:t,node:a,...n})=>(0,M.jsx)("h1",{className:Ce("mt-6 mb-2 font-semibold text-3xl",t),"data-streamdown":"heading-1",...n,children:e}),(e,t)=>Wt(e,t));ZN.displayName="MarkdownH1";JN=(0,N.memo)(({children:e,className:t,node:a,...n})=>(0,M.jsx)("h2",{className:Ce("mt-6 mb-2 font-semibold text-2xl",t),"data-streamdown":"heading-2",...n,children:e}),(e,t)=>Wt(e,t));JN.displayName="MarkdownH2";QN=(0,N.memo)(({children:e,className:t,node:a,...n})=>(0,M.jsx)("h3",{className:Ce("mt-6 mb-2 font-semibold text-xl",t),"data-streamdown":"heading-3",...n,children:e}),(e,t)=>Wt(e,t));QN.displayName="MarkdownH3";eU=(0,N.memo)(({children:e,className:t,node:a,...n})=>(0,M.jsx)("h4",{className:Ce("mt-6 mb-2 font-semibold text-lg",t),"data-streamdown":"heading-4",...n,children:e}),(e,t)=>Wt(e,t));eU.displayName="MarkdownH4";tU=(0,N.memo)(({children:e,className:t,node:a,...n})=>(0,M.jsx)("h5",{className:Ce("mt-6 mb-2 font-semibold text-base",t),"data-streamdown":"heading-5",...n,children:e}),(e,t)=>Wt(e,t));tU.displayName="MarkdownH5";aU=(0,N.memo)(({children:e,className:t,node:a,...n})=>(0,M.jsx)("h6",{className:Ce("mt-6 mb-2 font-semibold text-sm",t),"data-streamdown":"heading-6",...n,children:e}),(e,t)=>Wt(e,t));aU.displayName="MarkdownH6";nU=(0,N.memo)(({children:e,className:t,node:a,...n})=>{let{controls:r}=(0,N.useContext)(qa),o=BS(r,"table");return(0,M.jsx)(fK,{className:t,showControls:o,...n,children:e})},(e,t)=>Wt(e,t));nU.displayName="MarkdownTable";rU=(0,N.memo)(({children:e,className:t,node:a,...n})=>(0,M.jsx)("thead",{className:Ce("bg-muted/80",t),"data-streamdown":"table-header",...n,children:e}),(e,t)=>Wt(e,t));rU.displayName="MarkdownThead";oU=(0,N.memo)(({children:e,className:t,node:a,...n})=>(0,M.jsx)("tbody",{className:Ce("divide-y divide-border bg-muted/40",t),"data-streamdown":"table-body",...n,children:e}),(e,t)=>Wt(e,t));oU.displayName="MarkdownTbody";iU=(0,N.memo)(({children:e,className:t,node:a,...n})=>(0,M.jsx)("tr",{className:Ce("border-border border-b",t),"data-streamdown":"table-row",...n,children:e}),(e,t)=>Wt(e,t));iU.displayName="MarkdownTr";sU=(0,N.memo)(({children:e,className:t,node:a,...n})=>(0,M.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)=>Wt(e,t));sU.displayName="MarkdownTh";lU=(0,N.memo)(({children:e,className:t,node:a,...n})=>(0,M.jsx)("td",{className:Ce("px-4 py-2 text-sm",t),"data-streamdown":"table-cell",...n,children:e}),(e,t)=>Wt(e,t));lU.displayName="MarkdownTd";uU=(0,N.memo)(({children:e,className:t,node:a,...n})=>(0,M.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)=>Wt(e,t));uU.displayName="MarkdownBlockquote";cU=(0,N.memo)(({children:e,className:t,node:a,...n})=>(0,M.jsx)("sup",{className:Ce("text-sm",t),"data-streamdown":"superscript",...n,children:e}),(e,t)=>Wt(e,t));cU.displayName="MarkdownSup";dU=(0,N.memo)(({children:e,className:t,node:a,...n})=>(0,M.jsx)("sub",{className:Ce("text-sm",t),"data-streamdown":"subscript",...n,children:e}),(e,t)=>Wt(e,t));dU.displayName="MarkdownSub";fU=(0,N.memo)(({children:e,className:t,node:a,...n})=>{if("data-footnotes"in n){let r=i=>{var s,l;if(!(0,N.isValidElement)(i))return!1;let u=Array.isArray(i.props.children)?i.props.children:[i.props.children],c=!1,d=!1;for(let p of u)if(p){if(typeof p=="string")p.trim()!==""&&(c=!0);else if((0,N.isValidElement)(p))if(((s=p.props)==null?void 0:s["data-footnote-backref"])!==void 0)d=!0;else{let m=Array.isArray(p.props.children)?p.props.children:[p.props.children];for(let h of m){if(typeof h=="string"&&h.trim()!==""){c=!0;break}if((0,N.isValidElement)(h)&&((l=h.props)==null?void 0:l["data-footnote-backref"])===void 0){c=!0;break}}}}return d&&!c},o=Array.isArray(e)?e.map(i=>{if(!(0,N.isValidElement)(i))return i;if(i.type===HS){let s=(Array.isArray(i.props.children)?i.props.children:[i.props.children]).filter(l=>!r(l));return s.length===0?null:{...i,props:{...i.props,children:s}}}return i}):e;return(Array.isArray(o)?o.some(i=>i!==null):o!==null)?(0,M.jsx)("section",{className:t,...n,children:o}):null}return(0,M.jsx)("section",{className:t,...n,children:e})},(e,t)=>Wt(e,t));fU.displayName="MarkdownSection";yK=({node:e,className:t,children:a,...n})=>{var r,o,i;let s=((r=e?.position)==null?void 0:r.start.line)===((o=e?.position)==null?void 0:o.end.line),{mermaid:l,controls:u}=(0,N.useContext)(qa),c=qS();if(s)return(0,M.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(hK),p=(i=d?.at(1))!=null?i:"",m="";if((0,N.isValidElement)(a)&&a.props&&typeof a.props=="object"&&"children"in a.props&&typeof a.props.children=="string"?m=a.props.children:typeof a=="string"&&(m=a),p==="mermaid"&&c){let v=BS(u,"mermaid"),I=kh(u,"download"),y=kh(u,"copy"),w=kh(u,"fullscreen"),g=kh(u,"panZoom"),S=v&&(I||y||w);return(0,M.jsx)(N.Suspense,{fallback:(0,M.jsx)(UN,{}),children:(0,M.jsxs)("div",{className:Ce("group relative my-4 h-auto rounded-xl border p-4",t),"data-streamdown":"mermaid-block",children:[S?(0,M.jsxs)("div",{className:"flex items-center justify-end gap-2",children:[I?(0,M.jsx)(rK,{chart:m,config:l?.config}):null,y?(0,M.jsx)(ON,{code:m}):null,w?(0,M.jsx)(sK,{chart:m,config:l?.config}):null]}):null,(0,M.jsx)(mK,{chart:m,config:l?.config,showControls:g})]})})}let h=BS(u,"code");return(0,M.jsx)(N.Suspense,{fallback:(0,M.jsx)(UN,{}),children:(0,M.jsx)(pK,{className:Ce("overflow-x-auto border-border border-t",t),code:m,language:p,children:h?(0,M.jsxs)(M.Fragment,{children:[(0,M.jsx)(ZX,{code:m,language:p}),(0,M.jsx)(ON,{})]}):null})})},pU=(0,N.memo)(yK,(e,t)=>e.className===t.className&&Eh(e.node,t.node));pU.displayName="MarkdownCode";mU=(0,N.memo)(QX,(e,t)=>e.className===t.className&&Eh(e.node,t.node));mU.displayName="MarkdownImg";hU=(0,N.memo)(({children:e,className:t,node:a,...n})=>{var r,o;let i=(Array.isArray(e)?e:[e]).filter(s=>s!=null&&s!=="");if(i.length===1&&(0,N.isValidElement)(i[0])){let s=i[0].props.node,l=s?.tagName;if(l==="img")return(0,M.jsx)(M.Fragment,{children:e});if(l==="code"&&((r=s?.position)==null?void 0:r.start.line)!==((o=s?.position)==null?void 0:o.end.line))return(0,M.jsx)(M.Fragment,{children:e})}return(0,M.jsx)("p",{className:t,...n,children:e})},(e,t)=>Wt(e,t));hU.displayName="MarkdownParagraph";wK={ol:HS,li:WN,ul:GN,hr:XN,strong:KN,a:YN,h1:ZN,h2:JN,h3:QN,h4:eU,h5:tU,h6:aU,table:nU,thead:rU,tbody:oU,tr:iU,th:sU,td:lU,blockquote:uU,code:pU,img:mU,pre:({children:e})=>e,sup:cU,sub:dU,p:hU,section:fU},BN=[],zN={allowDangerousHtml:!0},Th=new WeakMap,vK=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 p=0;p<c.length;p+=1){let m=c[p];if(p>0&&(d+=","),Array.isArray(m)){let[h,v]=m;if(typeof h=="function"){let I=Th.get(h);I||(I=h.name,Th.set(h,I)),d+=I}else d+=String(h);d+=":",d+=JSON.stringify(v)}else if(typeof m=="function"){let h=Th.get(m);h||(h=m.name,Th.set(m,h)),d+=h}else d+=String(m)}return d},i=o(a),s=o(n),l=r?JSON.stringify(r):"",u=`${s}::${i}::${l}`;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()}},FN=new vK,gU=e=>{let t=xK(e),a=e.children||"";return SK(t.runSync(t.parse(a),a),e)},xK=e=>{let t=FN.get(e);if(t)return t;let a=bK(e);return FN.set(e,a),a},bK=e=>{let t=e.rehypePlugins||BN,a=e.remarkPlugins||BN,n=e.remarkRehypeOptions?{...zN,...e.remarkRehypeOptions}:zN;return vS().use(uh).use(a).use(ph,n).use(t)},SK=(e,t)=>Jb(e,{Fragment:M.Fragment,components:t.components,ignoreInvalidStyle:!0,jsx:M.jsx,jsxs:M.jsxs,passKeys:!0,passNode:!0}),IK=/\[\^[^\]\s]{1,200}\](?!:)/,CK=/\[\^[^\]\s]{1,200}\]:/,kK=/<\/(\w+)>/,TK=/<(\w+)[\s>]/,OS=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]==="$"},LK=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]==="$"},NS=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},yU=e=>{let t=IK.test(e),a=CK.test(e);if(t||a)return[e];let n=Sn.lex(e,{gfm:!0}),r=[],o=[];for(let i of n){let s=i.raw,l=r.length;if(o.length>0){if(r[l-1]+=s,i.type==="html"){let u=s.match(kK);if(u){let c=u[1];o.at(-1)===c&&o.pop()}}continue}if(i.type==="html"&&i.block){let u=s.match(TK);if(u){let c=u[1];s.includes(`</${c}>`)||o.push(c)}}if(s.trim()==="$$"&&l>0){let u=r[l-1],c=OS(u),d=NS(u);if(c&&d%2===1){r[l-1]=u+s;continue}}if(l>0&&LK(s)){let u=r[l-1],c=OS(u),d=NS(u),p=NS(s);if(c&&d%2===1&&!OS(s)&&p===1){r[l-1]=u+s;continue}}r.push(s)}return r},wU={raw:ZM,sanitize:[Am,{}],harden:[KM,{allowedImagePrefixes:["*"],allowedLinkPrefixes:["*"],allowedProtocols:["*"],defaultOrigin:void 0,allowDataImages:!0}]},vU={gfm:[eh,{}]},EK=Object.values(wU),AK=Object.values(vU),MK={block:" \u258B",circle:" \u25CF"},RK={shikiTheme:["github-light","github-dark"],controls:!0,isAnimating:!1,mode:"streaming",mermaid:void 0,linkSafety:{enabled:!0}},qa=(0,N.createContext)(RK),jS=(0,N.memo)(({content:e,shouldParseIncompleteMarkdown:t,index:a,...n})=>(0,M.jsx)(gU,{...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)});jS.displayName="Block";DK=["github-light","github-dark"],au=(0,N.memo)(({children:e,mode:t="streaming",parseIncompleteMarkdown:a=!0,components:n,rehypePlugins:r=EK,remarkPlugins:o=AK,className:i,shikiTheme:s=DK,mermaid:l,controls:u=!0,isAnimating:c=!1,BlockComponent:d=jS,parseMarkdownIntoBlocksFn:p=yU,caret:m,plugins:h,remend:v,linkSafety:I={enabled:!0},...y})=>{let w=(0,N.useId)(),[g,S]=(0,N.useTransition)(),E=(0,N.useMemo)(()=>typeof e!="string"?"":t==="streaming"&&a?u_(e,v):e,[e,t,a,v]),T=(0,N.useMemo)(()=>p(E),[E,p]),[R,O]=(0,N.useState)(T);(0,N.useEffect)(()=>{t==="streaming"?S(()=>{O(T)}):O(T)},[T,t]);let U=t==="streaming"?R:T,A=(0,N.useMemo)(()=>U.map((B,P)=>`${w}-${P}`),[U.length,w]),Q=(0,N.useMemo)(()=>{var B,P;return{shikiTheme:(P=(B=h?.code)==null?void 0:B.getThemes())!=null?P:s,controls:u,isAnimating:c,mode:t,mermaid:l,linkSafety:I}},[s,u,c,t,l,I,h?.code]),$=(0,N.useMemo)(()=>({...wK,...n}),[n]),H=(0,N.useMemo)(()=>{let B=[];return h!=null&&h.cjk&&(B=[...B,...h.cjk.remarkPluginsBefore]),B=[...B,...o],h!=null&&h.cjk&&(B=[...B,...h.cjk.remarkPluginsAfter]),h!=null&&h.math&&(B=[...B,h.math.remarkPlugin]),B},[o,h?.math,h?.cjk]),Z=(0,N.useMemo)(()=>h!=null&&h.math?[...r,h.math.rehypePlugin]:r,[r,h?.math]),X=(0,N.useMemo)(()=>m&&c?{"--streamdown-caret":`"${MK[m]}"`}:void 0,[m,c]);return t==="static"?(0,M.jsx)(US.Provider,{value:h??null,children:(0,M.jsx)(qa.Provider,{value:Q,children:(0,M.jsx)("div",{className:Ce("space-y-4 whitespace-normal *:first:mt-0 *:last:mb-0",i),children:(0,M.jsx)(gU,{components:$,rehypePlugins:Z,remarkPlugins:H,...y,children:e})})})}):(0,M.jsx)(US.Provider,{value:h??null,children:(0,M.jsx)(qa.Provider,{value:Q,children:(0,M.jsxs)("div",{className:Ce("space-y-4 whitespace-normal *:first:mt-0 *:last:mb-0",m?"*:last:after:inline *:last:after:align-baseline *:last:after:content-(--streamdown-caret)":null,i),style:X,children:[U.length===0&&m&&c&&(0,M.jsx)("span",{}),U.map((B,P)=>(0,M.jsx)(d,{components:$,content:B,index:P,rehypePlugins:Z,remarkPlugins:H,shouldParseIncompleteMarkdown:a,...y},A[P]))]})})})},(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);au.displayName="Streamdown";_K=({children:e,className:t,minZoom:a=.5,maxZoom:n=3,zoomStep:r=.1,showControls:o=!0,initialZoom:i=1,fullscreen:s=!1})=>{let l=(0,N.useRef)(null),u=(0,N.useRef)(null),[c,d]=(0,N.useState)(i),[p,m]=(0,N.useState)({x:0,y:0}),[h,v]=(0,N.useState)(!1),[I,y]=(0,N.useState)({x:0,y:0}),[w,g]=(0,N.useState)({x:0,y:0}),S=(0,N.useCallback)($=>{d(H=>Math.max(a,Math.min(n,H+$)))},[a,n]),E=(0,N.useCallback)(()=>{S(r)},[S,r]),T=(0,N.useCallback)(()=>{S(-r)},[S,r]),R=(0,N.useCallback)(()=>{d(i),m({x:0,y:0})},[i]),O=(0,N.useCallback)($=>{$.preventDefault();let H=$.deltaY>0?-r:r;S(H)},[S,r]),U=(0,N.useCallback)($=>{if($.button!==0||$.isPrimary===!1)return;v(!0),y({x:$.clientX,y:$.clientY}),g(p);let H=$.currentTarget;H instanceof HTMLElement&&H.setPointerCapture($.pointerId)},[p]),A=(0,N.useCallback)($=>{if(!h)return;$.preventDefault();let H=$.clientX-I.x,Z=$.clientY-I.y;m({x:w.x+H,y:w.y+Z})},[h,I,w]),Q=(0,N.useCallback)($=>{v(!1);let H=$.currentTarget;H instanceof HTMLElement&&H.releasePointerCapture($.pointerId)},[]);return(0,N.useEffect)(()=>{let $=l.current;if($)return $.addEventListener("wheel",O,{passive:!1}),()=>{$.removeEventListener("wheel",O)}},[O]),(0,N.useEffect)(()=>{let $=u.current;if($&&h)return document.body.style.userSelect="none",$.addEventListener("pointermove",A,{passive:!1}),$.addEventListener("pointerup",Q),$.addEventListener("pointercancel",Q),()=>{document.body.style.userSelect="",$.removeEventListener("pointermove",A),$.removeEventListener("pointerup",Q),$.removeEventListener("pointercancel",Q)}},[h,A,Q]),(0,M.jsxs)("div",{className:Ce("relative flex flex-col",s?"h-full w-full":"min-h-28 w-full",t),ref:l,style:{cursor:h?"grabbing":"grab"},children:[o?(0,M.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",s?"bottom-4 left-4":"bottom-2 left-2"),children:[(0,M.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:E,title:"Zoom in",type:"button",children:(0,M.jsx)(KX,{size:16})}),(0,M.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:T,title:"Zoom out",type:"button",children:(0,M.jsx)(YX,{size:16})}),(0,M.jsx)("button",{className:"flex items-center justify-center rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",onClick:R,title:"Reset zoom and pan",type:"button",children:(0,M.jsx)(XX,{size:16})})]}):null,(0,M.jsx)("div",{className:Ce("flex-1 origin-center transition-transform duration-150 ease-out",s?"flex h-full w-full items-center justify-center":"flex w-full items-center justify-center"),onPointerDown:U,ref:u,role:"application",style:{transform:`translate(${p.x}px, ${p.y}px) scale(${c})`,transformOrigin:"center center",touchAction:"none",willChange:"transform"},children:e})]})},_S=({chart:e,className:t,config:a,fullscreen:n=!1,showControls:r=!0})=>{let[o,i]=(0,N.useState)(null),[s,l]=(0,N.useState)(!1),[u,c]=(0,N.useState)(""),[d,p]=(0,N.useState)(""),[m,h]=(0,N.useState)(0),{mermaid:v}=(0,N.useContext)(qa),I=qS(),y=v?.errorComponent,{shouldRender:w,containerRef:g}=$X({immediate:n});if((0,N.useEffect)(()=>{if(w){if(!I){i("Mermaid plugin not available. Please add the mermaid plugin to enable diagram rendering.");return}(async()=>{try{i(null),l(!0);let E=I.getMermaid(a),T=e.split("").reduce((U,A)=>(U<<5)-U+A.charCodeAt(0)|0,0),R=`mermaid-${Math.abs(T)}-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,{svg:O}=await E.render(R,e);c(O),p(O)}catch(E){if(!(d||u)){let T=E instanceof Error?E.message:"Failed to render Mermaid chart";i(T)}}finally{l(!1)}})()}},[e,a,m,w,I]),!(w||u||d))return(0,M.jsx)("div",{className:Ce("my-4 min-h-[200px]",t),ref:g});if(s&&!u&&!d)return(0,M.jsx)("div",{className:Ce("my-4 flex justify-center p-4",t),ref:g,children:(0,M.jsxs)("div",{className:"flex items-center space-x-2 text-muted-foreground",children:[(0,M.jsx)("div",{className:"h-4 w-4 animate-spin rounded-full border-current border-b-2"}),(0,M.jsx)("span",{className:"text-sm",children:"Loading diagram..."})]})});if(o&&!u&&!d)return y?(0,M.jsx)("div",{ref:g,children:(0,M.jsx)(y,{chart:e,error:o,retry:()=>h(T=>T+1)})}):(0,M.jsxs)("div",{className:Ce("rounded-lg border border-red-200 bg-red-50 p-4",t),ref:g,children:[(0,M.jsxs)("p",{className:"font-mono text-red-700 text-sm",children:["Mermaid Error: ",o]}),(0,M.jsxs)("details",{className:"mt-2",children:[(0,M.jsx)("summary",{className:"cursor-pointer text-red-600 text-xs",children:"Show Code"}),(0,M.jsx)("pre",{className:"mt-2 overflow-x-auto rounded bg-red-100 p-2 text-red-800 text-xs",children:e})]})]});let S=u||d;return(0,M.jsx)("div",{className:Ce("size-full",t),"data-streamdown":"mermaid",ref:g,children:(0,M.jsx)(_K,{className:Ce(n?"size-full overflow-hidden":"my-4 overflow-hidden",t),fullscreen:n,maxZoom:3,minZoom:.5,showControls:r,zoomStep:.1,children:(0,M.jsx)("div",{"aria-label":"Mermaid chart",className:Ce("flex justify-center",n?"size-full items-center":null),dangerouslySetInnerHTML:{__html:S},role:"img"})})})}});var lB=Ca((Xve,sB)=>{"use strict";function cY(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(),s=i-n,l=t-s;l<=0?(n=i,e.apply(this,o)):a=setTimeout(()=>{n=Date.now(),e.apply(this,o)},l)}}sB.exports=cY});var xI=typeof performance>"u"?0:performance.now(),bI=typeof window<"u"&&!!window.WaniWani?.chat;var Cs=j(Ee(),1),Zh=j(qw(),1);var Hw="waniwani/suggestions";function yl(e,t){for(let a of t){let n=e[a];if(typeof n=="string"&&n.length>0)return n}}var hq=["waniwani/sessionId","openai/sessionId","openai/session","sessionId","conversationId","mcp-session-id"],gq=["waniwani/requestId","openai/requestId","requestId","mcp/requestId"],yq=["waniwani/traceId","openai/traceId","traceId","mcp/traceId","openai/requestId","requestId"],wq=["waniwani/userId","openai/userId","externalUserId","userId","actorId"],vq=["waniwani/visitorId","visitorId"],xq=["correlationId","openai/requestId"];function c1(e){return e?yl(e,hq):void 0}function d1(e){return e?yl(e,gq):void 0}function f1(e){return e?yl(e,yq):void 0}function p1(e){return e?yl(e,wq):void 0}function m1(e){return e?yl(e,vq):void 0}function h1(e){return e?yl(e,xq):void 0}var bq=[{key:"openai/sessionId",source:"chatgpt"},{key:"openai/session",source:"chatgpt"}],Sq=[{needle:"claude",source:"claude"},{needle:"chatgpt",source:"chatgpt"},{needle:"openai",source:"chatgpt"},{needle:"gemini",source:"gemini"}];function g1(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 bq){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 Sq)if(n.includes(r))return o}}var Iq="@waniwani/sdk";function y1(e,t={}){let a=t.now??(()=>new Date),n=t.generateId??Cq,r=Lq(e),o=zp(e.meta),i=zp(e.metadata),s=Eq(e,o),l=Xn(e.eventId)??n(),u=Aq(e.timestamp,a),c=Xn(e.source)??g1(o)??t.source??Iq,d=jw(e)?{...e}:void 0,p={...i};return Object.keys(o).length>0&&(p.meta=o),d&&(p.rawLegacy=d),{id:l,type:"mcp.event",name:r,source:c,timestamp:u,correlation:s,properties:kq(e,r),metadata:p,rawLegacy:d}}function Cq(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`evt_${crypto.randomUUID()}`:`evt_${Math.random().toString(36).slice(2,10)}_${Date.now().toString(36)}`}function kq(e,t){if(!jw(e))return zp(e.properties);let a=Tq(e,t),n=zp(e.properties);return{...a,...n}}function Tq(e,t){switch(t){case"tool.called":{let a={};return Xn(e.toolName)&&(a.name=e.toolName),Xn(e.toolType)&&(a.type=e.toolType),a}case"link.clicked":{let a={};return Xn(e.linkUrl)&&(a.url=e.linkUrl),a}default:return{}}}function Lq(e){return jw(e)?e.eventType:e.event}function Eq(e,t){let a=Xn(e.requestId)??d1(t),n=Xn(e.sessionId)??c1(t),r=Xn(e.traceId)??f1(t),o=Xn(e.externalUserId)??p1(t),i=Xn(e.visitorId)??m1(t),s=Xn(e.correlationId)??h1(t)??a,l={};return n&&(l.sessionId=n),r&&(l.traceId=r),a&&(l.requestId=a),s&&(l.correlationId=s),o&&(l.externalUserId=o),i&&(l.visitorId=i),l}function Aq(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 zp(e){return!e||typeof e!="object"||Array.isArray(e)?{}:e}function Xn(e){if(typeof e=="string"&&e.trim().length!==0)return e}function jw(e){return"eventType"in e}function w1(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 Mq="/api/mcp/events/v2/batch";var v1="@waniwani/sdk";var Rq=new Set([401,403]),Dq=new Set([408,425,429,500,502,503,504]),_q=(e,t)=>globalThis.fetch(e,t);function x1(e){return new Vw(e)}var Vw=class{constructor(t){K(this,"endpointUrl");K(this,"flushIntervalMs");K(this,"maxBatchSize");K(this,"maxBufferSize");K(this,"maxRetries");K(this,"retryBaseDelayMs");K(this,"retryMaxDelayMs");K(this,"shutdownTimeoutMs");K(this,"sdkVersion");K(this,"fetchFn");K(this,"logger");K(this,"now");K(this,"sleep");K(this,"apiKey");K(this,"buffer",[]);K(this,"flushTimer");K(this,"flushScheduled",!1);K(this,"flushScheduledTimer");K(this,"flushInFlight");K(this,"inFlightCount",0);K(this,"isStopped",!1);K(this,"isShuttingDown",!1);this.endpointUrl=Nq(t.apiUrl,t.endpointPath??Mq),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??_q,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":v1};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:Uq(o)}}if(Rq.has(a.status))return{kind:"auth",status:a.status};if(Dq.has(a.status))return{kind:"retryable",reason:`HTTP ${a.status}`};if(!a.ok)return{kind:"permanent",reason:`HTTP ${a.status}`};let n=await Oq(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:v1,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 s=n.get(i.eventId);if(s){if(Pq(i)){r.push(s);continue}o.push(s)}}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 Pq(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 Oq(e){let t=await e.text();if(t)try{return JSON.parse(t)}catch{return}}function Nq(e,t){let a=e.endsWith("/")?e:`${e}/`,n=t.startsWith("/")?t.slice(1):t;return`${a}${n}`}function Uq(e){return e instanceof Error?e.message:String(e)}function b1(e){let{apiUrl:t,endpointPath:a}=Bq(e.endpoint),n=x1({apiUrl:t,apiKey:e.token,endpointPath:a,flushIntervalMs:e.flushIntervalMs}),r,o=s=>typeof s=="function"?s():s,i=async s=>{let l=e.identity?.()??{},u=o(e.channelId),c=u===void 0?s.properties:{channelId:u,...s.properties},d=y1({sessionId:l.sessionId,visitorId:l.visitorId,externalUserId:l.externalUserId??r,traceId:l.traceId,...s,properties:c,metadata:{...e.metadata,...s.metadata}},{source:o(e.source)});return n.enqueue(d),{eventId:d.id}};return{track:Object.assign(i,w1(i)),identify(s,l){return r=s,i({event:"user.identified",externalUserId:s,properties:l})},flush:()=>n.flush(),shutdown:s=>n.shutdown(s)}}function Bq(e){let t=new URL(e);return{apiUrl:t.origin,endpointPath:`${t.pathname}${t.search}`}}function Na(e,t,a){let[n,r=""]=e.split("?"),o=n.replace(/\/$/,""),i=new URLSearchParams(r);if(a)for(let[l,u]of Object.entries(a))i.set(l,u);let s=i.toString();return`${o}${t}${s?`?${s}`:""}`}var zq="/api/mcp/";function Fp(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(zq)?`${n}${t}`:null}function Fq(){if(typeof window>"u")return!1;try{return window.WANIWANI_DEBUG?!0:!!window.localStorage?.getItem("WANIWANI_DEBUG")}catch{return!1}}function Ua(...e){Fq()&&console.log("[Waniwani]",...e)}var $w="waniwani-visitor-id";function qq(){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 ma(){try{let t=localStorage.getItem($w);if(t)return t}catch{}let e=qq();try{localStorage.setItem($w,e)}catch{}return e}function wl(e){let t=typeof e=="string"?e.trim():"";if(!t)return ma();try{localStorage.setItem($w,t)}catch{}return t}function Hq(e){return e!=null&&typeof e.then=="function"}function Sc(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 Hq(n)?n.then(r=>{t||wl(r??"")},()=>{}):wl(n??""),a}var jq="waniwani-memory";var yn="threads",qp="by_memoryUserId",Vq="by_updatedAt";var I1="memoryUserId",S1="waniwani-memory-user-id",Ww=null;function Gw(){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 $q(e,t){if(t<1&&(e.objectStoreNames.contains("ids")||e.createObjectStore("ids")),t<2&&!e.objectStoreNames.contains(yn)){let a=e.createObjectStore(yn,{keyPath:"threadId"});a.createIndex(qp,"memoryUserId",{unique:!1}),a.createIndex(Vq,"updatedAt",{unique:!1})}}async function Xw(){return new Promise((e,t)=>{let a=indexedDB.open(jq,2);a.onupgradeneeded=n=>{$q(a.result,n.oldVersion)},a.onsuccess=()=>e(a.result),a.onerror=()=>t(a.error)})}async function Wq(){return Xw()}async function Gq(e){return new Promise((t,a)=>{let o=e.transaction("ids","readonly").objectStore("ids").get(I1);o.onsuccess=()=>t(typeof o.result=="string"?o.result:null),o.onerror=()=>a(o.error)})}async function Xq(e,t){return new Promise((a,n)=>{let i=e.transaction("ids","readwrite").objectStore("ids").put(t,I1);i.onsuccess=()=>a(),i.onerror=()=>n(i.error)})}async function Kq(){if(typeof indexedDB>"u")return null;try{let e=await Wq();try{let t=await Gq(e);if(t)return t;let a=Gw();return await Xq(e,a),a}finally{e.close()}}catch{return null}}function Yq(){try{let e=localStorage.getItem(S1);if(e)return e;let t=Gw();return localStorage.setItem(S1,t),t}catch{return null}}async function C1(){let e=await Kq();if(e)return e;let t=Yq();return t||(Ww||(Ww=Gw()),Ww)}function k1(e,t){return e.match(t)?.[1]??null}function Zq(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=k1(e,n);if(r)return{name:a,version:r}}return null}function Jq(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=k1(e,n);if(r)return{name:a,version:r.replace(/_/g,".")};if(a==="Linux"&&n.test(e))return{name:a,version:""}}return null}function Qq(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 Ic(){let e=navigator.userAgent,t=ma(),a=await C1();return{userAgent:e,browser:Zq(e),os:Jq(e),deviceType:Qq(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 e4="0.22.1",t4=40,a4=10,n4=6e5;function Yw(){return typeof performance>"u"?0:performance.now()}function Zw(e,t){let a={};return{metrics:a,has:n=>n in a,set(n,r){a[n]=r},mark(n,r=Yw()){if(!(n in a)){a[n]=r-t;try{performance.mark(`waniwani:${e}:${n}`,{startTime:r})}catch{}}}}}function r4(e){let t={};for(let[a,n]of Object.entries(e)){if(Object.keys(t).length>=t4)break;if(!Number.isFinite(n))continue;let r=Math.round(n);r<0||r>n4||(t[a]=r)}return t}function o4(e){let t={};for(let[a,n]of Object.entries(e)){if(Object.keys(t).length>=a4)break;(typeof n=="string"||typeof n=="boolean")&&(t[a]=n)}return t}function i4(){let e=navigator.connection;if(e)return{effectiveType:e.effectiveType,rtt:e.rtt,downlink:e.downlink,saveData:e.saveData}}function jp(e){let t=e?.Authorization;return typeof t=="string"&&t.startsWith("Bearer ")?t.slice(7):void 0}function s4(e,t,a,n){return{kind:e,sdkVersion:e4,channelId:t.channelId||void 0,sessionId:e==="boot"?void 0:t.sessionId||void 0,visitorId:ma(),pageHost:window.location.hostname,connection:i4(),tags:o4(a),metrics:r4(n)}}var Kw,Hp=[];function Jw(e){let t=String(e?.chatTimingLogs).trim().toLowerCase()==="true";Kw=t;let a=Hp;if(Hp=[],t)for(let n of a)n()}function Vp(e,t,a,n){let{api:r,token:o}=t;if(!(typeof window>"u"||!r||!o||Kw===!1))try{let i=s4(e,t,a,n),s=()=>{Ua("timing",i),fetch(Na(r,"/timing"),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},body:JSON.stringify(i),keepalive:!0}).catch(()=>{})};Kw?s():Hp.length<20&&Hp.push(s)}catch{}}var Wr=Zw("boot",0),T1;function Di(e,t){Wr.mark(e,t)}function $p(e){T1??(T1=e)}var l4=/cdn\.jsdelivr\.net\/npm\/@waniwani\/sdk@[^/]+\/dist\/chat\/embed\.js/,u4=/\/embed\.js(\?|$)/;function c4(){if(typeof performance>"u")return;let e=performance.getEntriesByType("navigation")[0];e?.responseStart&&Wr.mark("navTtfb",e.responseStart),e?.domContentLoadedEventEnd&&Wr.mark("navDomContentLoaded",e.domContentLoadedEventEnd);let t=performance.getEntriesByType("resource");for(let a of t)l4.test(a.name)?(Wr.mark("bundleStart",a.startTime),Wr.mark("bundleEnd",a.responseEnd)):u4.test(a.name)&&(Wr.mark("loaderStart",a.startTime),Wr.mark("loaderEnd",a.responseEnd))}function d4(){if(bI)return!0;try{return document.querySelectorAll('script[src*="@waniwani/sdk"]').length>1}catch{return!1}}function L1(e){c4(),Wr.mark("bundleExecuted",xI),Vp("boot",e,{configSource:T1,mode:e.mode,secondSdk:d4()},Wr.metrics)}var f4=[["text-delta","firstText"],["tool-input-start","firstToolInput"],["tool-output-available","firstToolOutput"]];function E1(e){let t=Zw("turn",Yw());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,s){t.mark("firstChunk");let l=r.decode(i,{stream:!0});for(let[u,c]of f4)!t.has(c)&&l.includes(u)&&t.mark(c);s.enqueue(i)}}));return new Response(o,{status:n.status,statusText:n.statusText,headers:n.headers})}catch{return n}},report(n,r){a||(a=!0,Vp("turn",n,r,t.metrics))}}}function p4(e){let t=e.indexOf("?");return t===-1?e:e.slice(0,t)}function A1(e,t){let a=Zw("widget",Yw()),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:p4(e),outcome:r,metrics:a.metrics}))}}}var m4="/api/mcp/events/v2/batch",Qw=new Set;function h4(e,t,a){return`${e}|${t}|${a??""}`}function Cc(e){return Fp(e,m4)}async function M1(e){let{api:t,token:a,channelId:n,mode:r,source:o}=e;if(typeof window>"u"||!t||!a)return;let i=Cc(t);if(!i){Ua("page.viewed skipped: the chat api is not a Waniwani endpoint");return}if(!n&&!o){Ua("page.viewed skipped: no channelId or source to attribute it");return}let s=h4(t,a,n);if(!Qw.has(s)){Qw.add(s);try{let l=await Ic(),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:l.visitorId},properties:{channelId:n,mode:r,url:window.location.href,referrer:l.referrer,deviceType:l.deviceType,language:l.language,timezone:l.timezone},metadata:{}}]}),d=fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:c,keepalive:!0});Di("pageViewSent"),await d}catch{Qw.delete(s)}}}function R1(e){let t=Cc(e.api);return t?b1({endpoint:t,token:e.token,channelId:e.channelId,source:e.getSource,identity:()=>({sessionId:e.getSessionId(),visitorId:ma()})}):Wp("the chat api does not point at a Waniwani event ingest")}function Wp(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 Xp=j(Ee());var Gp=(...e)=>e.filter((t,a,n)=>!!t&&t.trim()!==""&&n.indexOf(t)===a).join(" ").trim();var D1=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();var _1=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,a,n)=>n?n.toUpperCase():a.toLowerCase());var ev=e=>{let t=_1(e);return t.charAt(0).toUpperCase()+t.slice(1)};var kc=j(Ee());var P1={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 O1=e=>{for(let t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0;return!1};var N1=(0,kc.forwardRef)(({color:e="currentColor",size:t=24,strokeWidth:a=2,absoluteStrokeWidth:n,className:r="",children:o,iconNode:i,...s},l)=>(0,kc.createElement)("svg",{ref:l,...P1,width:t,height:t,stroke:e,strokeWidth:n?Number(a)*24/Number(t):a,className:Gp("lucide",r),...!o&&!O1(s)&&{"aria-hidden":"true"},...s},[...i.map(([u,c])=>(0,kc.createElement)(u,c)),...Array.isArray(o)?o:[o]]));var tt=(e,t)=>{let a=(0,Xp.forwardRef)(({className:n,...r},o)=>(0,Xp.createElement)(N1,{ref:o,iconNode:t,className:Gp(`lucide-${D1(ev(e))}`,`lucide-${e}`,n),...r}));return a.displayName=ev(e),a};var g4=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],Tc=tt("arrow-down",g4);var y4=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],pr=tt("arrow-up",y4);var w4=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Lc=tt("check",w4);var v4=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],zo=tt("chevron-down",v4);var x4=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],Ec=tt("chevron-right",x4);var b4=[["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"}]],Ac=tt("clipboard-copy",b4);var S4=[["path",{d:"M12 6v6l4 2",key:"mmk7yg"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],Gr=tt("clock",S4);var I4=[["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"}]],Mc=tt("file-text",I4);var C4=[["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"}]],vl=tt("file",C4);var k4=[["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"}]],Rc=tt("globe",k4);var T4=[["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"}]],Dc=tt("image",T4);var L4=[["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"}]],_c=tt("loader",L4);var E4=[["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"}]],xl=tt("paperclip",E4);var A4=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],Pc=tt("square",A4);var M4=[["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"}]],_i=tt("wrench",M4);var R4=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],wn=tt("x",R4);var D4=[["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"}]],Oc=tt("zap",D4);var rt=j(Ee(),1),qB=j(gg(),1);var bl=j(Ee(),1),Nc=j(me(),1);function O4(e){return 1-(1-e)**3}function N4({start:e=0,end:t=100,duration:a=1e3,delay:n=0,ease:r=O4,onUpdate:o,onEnd:i}){let s=performance.now()+n;function l(){let u=performance.now()-s,c=Math.min(u/a,1);o(e+(t-e)*r(c)),c<1?requestAnimationFrame(l):i&&i()}setTimeout(()=>requestAnimationFrame(l),n)}var U4=["80% 55%","69% 34%","8% 6%","41% 38%","86% 85%","82% 18%","51% 4%"],B4=[0,1,2,0,1,2,1];function z4(e){let t=[];for(let a=0;a<7;a++){let n=e[Math.min(B4[a],e.length-1)];t.push(`radial-gradient(at ${U4[a]}, ${n} 0px, transparent 50%)`)}return t.push(`linear-gradient(${e[0]} 0 100%)`),t}var F4=({children:e,className:t="",style:a,edgeSensitivity:n=30,backgroundColor:r="#120F17",borderRadius:o=28,coneSpread:i=25,animated:s=!1,colors:l=["#c084fc","#f472b6","#38bdf8"]})=>{let[u,c]=(0,bl.useState)(110),[d,p]=(0,bl.useState)(0),[m,h]=(0,bl.useState)(!1);(0,bl.useEffect)(()=>{if(!s)return;let E=110;h(!0),c(E),N4({ease:T=>T,duration:2e3,onUpdate:T=>{let R=T/100;c(E+360*R);let O=Math.min(R/.1,1),U=R>.85?(1-R)/.15:1;p(Math.min(O,U))},onEnd:()=>h(!1)})},[s]);let v=n+20,I=m?Math.max(0,(d*100-v)/(100-v)):0,w=z4(l).map(E=>`${E} border-box`),S=`conic-gradient(from ${`${u.toFixed(3)}deg`} at center, black ${i}%, transparent ${i+15}%, transparent ${100-i-15}%, black ${100-i}%)`;return(0,Nc.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,Nc.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",...w].join(", "),opacity:I,maskImage:S,WebkitMaskImage:S,transition:m?"opacity 0.25s ease-out":"opacity 0.75s ease-in-out"}}),(0,Nc.jsx)("div",{className:"ww:flex ww:flex-col ww:relative ww:overflow-auto ww:z-[1]",children:e})]})},Yp=F4;tv();nv();var q4=q1({prefix:"ww"});function V(...e){return q4(Zp(e))}var Uc=j(me(),1);function Sl({suggestions:e,isLoading:t,onSelect:a,align:n="start",className:r,...o}){return e.length===0&&!t?null:(0,Uc.jsx)("div",{className:V("ww:px-4 ww:py-2",r),...o,children:(0,Uc.jsx)("div",{className:V("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,Uc.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,s)=>(0,Uc.jsx)("button",{type:"button",onClick:()=>a(i),className:V("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:`${s*50}ms`},children:i},i))})})}var gm=j(Ee(),1);var gL="vercel.ai.error",H4=Symbol.for(gL),H1,j1,Je=class yL extends(j1=Error,H1=H4,j1){constructor({name:t,message:a,cause:n}){super(a),this[H1]=!0,this.name=t,this.cause=n}static isInstance(t){return yL.hasMarker(t,gL)}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}},wL="AI_APICallError",vL=`vercel.ai.error.${wL}`,j4=Symbol.for(vL),V1,$1,GQ=class extends($1=Je,V1=j4,$1){constructor({message:e,url:t,requestBodyValues:a,statusCode:n,responseHeaders:r,responseBody:o,cause:i,isRetryable:s=n!=null&&(n===408||n===409||n===429||n>=500),data:l}){super({name:wL,message:e,cause:i}),this[V1]=!0,this.url=t,this.requestBodyValues=a,this.statusCode=n,this.responseHeaders=r,this.responseBody=o,this.isRetryable=s,this.data=l}static isInstance(e){return Je.hasMarker(e,vL)}},xL="AI_EmptyResponseBodyError",bL=`vercel.ai.error.${xL}`,V4=Symbol.for(bL),W1,G1,XQ=class extends(G1=Je,W1=V4,G1){constructor({message:e="Empty response body"}={}){super({name:xL,message:e}),this[W1]=!0}static isInstance(e){return Je.hasMarker(e,bL)}};function SL(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var IL="AI_InvalidArgumentError",CL=`vercel.ai.error.${IL}`,$4=Symbol.for(CL),X1,K1,kL=class extends(K1=Je,X1=$4,K1){constructor({message:e,cause:t,argument:a}){super({name:IL,message:e,cause:t}),this[X1]=!0,this.argument=a}static isInstance(e){return Je.hasMarker(e,CL)}},TL="AI_InvalidPromptError",LL=`vercel.ai.error.${TL}`,W4=Symbol.for(LL),Y1,Z1,KQ=class extends(Z1=Je,Y1=W4,Z1){constructor({prompt:e,message:t,cause:a}){super({name:TL,message:`Invalid prompt: ${t}`,cause:a}),this[Y1]=!0,this.prompt=e}static isInstance(e){return Je.hasMarker(e,LL)}},EL="AI_InvalidResponseDataError",AL=`vercel.ai.error.${EL}`,G4=Symbol.for(AL),J1,Q1,YQ=class extends(Q1=Je,J1=G4,Q1){constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:EL,message:t}),this[J1]=!0,this.data=e}static isInstance(e){return Je.hasMarker(e,AL)}},ML="AI_JSONParseError",RL=`vercel.ai.error.${ML}`,X4=Symbol.for(RL),eL,tL,ov=class extends(tL=Je,eL=X4,tL){constructor({text:e,cause:t}){super({name:ML,message:`JSON parsing failed: Text: ${e}.
|
|
121
|
+
`||e[t]==="\r");)t-=1;return t>=1&&e[t]==="$"&&e[t-1]==="$"},NS=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},yU=e=>{let t=IK.test(e),a=CK.test(e);if(t||a)return[e];let n=Sn.lex(e,{gfm:!0}),r=[],o=[];for(let i of n){let s=i.raw,l=r.length;if(o.length>0){if(r[l-1]+=s,i.type==="html"){let u=s.match(kK);if(u){let c=u[1];o.at(-1)===c&&o.pop()}}continue}if(i.type==="html"&&i.block){let u=s.match(TK);if(u){let c=u[1];s.includes(`</${c}>`)||o.push(c)}}if(s.trim()==="$$"&&l>0){let u=r[l-1],c=OS(u),d=NS(u);if(c&&d%2===1){r[l-1]=u+s;continue}}if(l>0&&LK(s)){let u=r[l-1],c=OS(u),d=NS(u),p=NS(s);if(c&&d%2===1&&!OS(s)&&p===1){r[l-1]=u+s;continue}}r.push(s)}return r},wU={raw:ZM,sanitize:[Am,{}],harden:[KM,{allowedImagePrefixes:["*"],allowedLinkPrefixes:["*"],allowedProtocols:["*"],defaultOrigin:void 0,allowDataImages:!0}]},vU={gfm:[eh,{}]},EK=Object.values(wU),AK=Object.values(vU),MK={block:" \u258B",circle:" \u25CF"},RK={shikiTheme:["github-light","github-dark"],controls:!0,isAnimating:!1,mode:"streaming",mermaid:void 0,linkSafety:{enabled:!0}},qa=(0,N.createContext)(RK),jS=(0,N.memo)(({content:e,shouldParseIncompleteMarkdown:t,index:a,...n})=>(0,M.jsx)(gU,{...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)});jS.displayName="Block";DK=["github-light","github-dark"],au=(0,N.memo)(({children:e,mode:t="streaming",parseIncompleteMarkdown:a=!0,components:n,rehypePlugins:r=EK,remarkPlugins:o=AK,className:i,shikiTheme:s=DK,mermaid:l,controls:u=!0,isAnimating:c=!1,BlockComponent:d=jS,parseMarkdownIntoBlocksFn:p=yU,caret:m,plugins:h,remend:v,linkSafety:I={enabled:!0},...y})=>{let w=(0,N.useId)(),[g,S]=(0,N.useTransition)(),E=(0,N.useMemo)(()=>typeof e!="string"?"":t==="streaming"&&a?u_(e,v):e,[e,t,a,v]),T=(0,N.useMemo)(()=>p(E),[E,p]),[R,O]=(0,N.useState)(T);(0,N.useEffect)(()=>{t==="streaming"?S(()=>{O(T)}):O(T)},[T,t]);let U=t==="streaming"?R:T,A=(0,N.useMemo)(()=>U.map((B,P)=>`${w}-${P}`),[U.length,w]),Q=(0,N.useMemo)(()=>{var B,P;return{shikiTheme:(P=(B=h?.code)==null?void 0:B.getThemes())!=null?P:s,controls:u,isAnimating:c,mode:t,mermaid:l,linkSafety:I}},[s,u,c,t,l,I,h?.code]),$=(0,N.useMemo)(()=>({...wK,...n}),[n]),H=(0,N.useMemo)(()=>{let B=[];return h!=null&&h.cjk&&(B=[...B,...h.cjk.remarkPluginsBefore]),B=[...B,...o],h!=null&&h.cjk&&(B=[...B,...h.cjk.remarkPluginsAfter]),h!=null&&h.math&&(B=[...B,h.math.remarkPlugin]),B},[o,h?.math,h?.cjk]),Z=(0,N.useMemo)(()=>h!=null&&h.math?[...r,h.math.rehypePlugin]:r,[r,h?.math]),X=(0,N.useMemo)(()=>m&&c?{"--streamdown-caret":`"${MK[m]}"`}:void 0,[m,c]);return t==="static"?(0,M.jsx)(US.Provider,{value:h??null,children:(0,M.jsx)(qa.Provider,{value:Q,children:(0,M.jsx)("div",{className:Ce("space-y-4 whitespace-normal *:first:mt-0 *:last:mb-0",i),children:(0,M.jsx)(gU,{components:$,rehypePlugins:Z,remarkPlugins:H,...y,children:e})})})}):(0,M.jsx)(US.Provider,{value:h??null,children:(0,M.jsx)(qa.Provider,{value:Q,children:(0,M.jsxs)("div",{className:Ce("space-y-4 whitespace-normal *:first:mt-0 *:last:mb-0",m?"*:last:after:inline *:last:after:align-baseline *:last:after:content-(--streamdown-caret)":null,i),style:X,children:[U.length===0&&m&&c&&(0,M.jsx)("span",{}),U.map((B,P)=>(0,M.jsx)(d,{components:$,content:B,index:P,rehypePlugins:Z,remarkPlugins:H,shouldParseIncompleteMarkdown:a,...y},A[P]))]})})})},(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);au.displayName="Streamdown";_K=({children:e,className:t,minZoom:a=.5,maxZoom:n=3,zoomStep:r=.1,showControls:o=!0,initialZoom:i=1,fullscreen:s=!1})=>{let l=(0,N.useRef)(null),u=(0,N.useRef)(null),[c,d]=(0,N.useState)(i),[p,m]=(0,N.useState)({x:0,y:0}),[h,v]=(0,N.useState)(!1),[I,y]=(0,N.useState)({x:0,y:0}),[w,g]=(0,N.useState)({x:0,y:0}),S=(0,N.useCallback)($=>{d(H=>Math.max(a,Math.min(n,H+$)))},[a,n]),E=(0,N.useCallback)(()=>{S(r)},[S,r]),T=(0,N.useCallback)(()=>{S(-r)},[S,r]),R=(0,N.useCallback)(()=>{d(i),m({x:0,y:0})},[i]),O=(0,N.useCallback)($=>{$.preventDefault();let H=$.deltaY>0?-r:r;S(H)},[S,r]),U=(0,N.useCallback)($=>{if($.button!==0||$.isPrimary===!1)return;v(!0),y({x:$.clientX,y:$.clientY}),g(p);let H=$.currentTarget;H instanceof HTMLElement&&H.setPointerCapture($.pointerId)},[p]),A=(0,N.useCallback)($=>{if(!h)return;$.preventDefault();let H=$.clientX-I.x,Z=$.clientY-I.y;m({x:w.x+H,y:w.y+Z})},[h,I,w]),Q=(0,N.useCallback)($=>{v(!1);let H=$.currentTarget;H instanceof HTMLElement&&H.releasePointerCapture($.pointerId)},[]);return(0,N.useEffect)(()=>{let $=l.current;if($)return $.addEventListener("wheel",O,{passive:!1}),()=>{$.removeEventListener("wheel",O)}},[O]),(0,N.useEffect)(()=>{let $=u.current;if($&&h)return document.body.style.userSelect="none",$.addEventListener("pointermove",A,{passive:!1}),$.addEventListener("pointerup",Q),$.addEventListener("pointercancel",Q),()=>{document.body.style.userSelect="",$.removeEventListener("pointermove",A),$.removeEventListener("pointerup",Q),$.removeEventListener("pointercancel",Q)}},[h,A,Q]),(0,M.jsxs)("div",{className:Ce("relative flex flex-col",s?"h-full w-full":"min-h-28 w-full",t),ref:l,style:{cursor:h?"grabbing":"grab"},children:[o?(0,M.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",s?"bottom-4 left-4":"bottom-2 left-2"),children:[(0,M.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:E,title:"Zoom in",type:"button",children:(0,M.jsx)(KX,{size:16})}),(0,M.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:T,title:"Zoom out",type:"button",children:(0,M.jsx)(YX,{size:16})}),(0,M.jsx)("button",{className:"flex items-center justify-center rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",onClick:R,title:"Reset zoom and pan",type:"button",children:(0,M.jsx)(XX,{size:16})})]}):null,(0,M.jsx)("div",{className:Ce("flex-1 origin-center transition-transform duration-150 ease-out",s?"flex h-full w-full items-center justify-center":"flex w-full items-center justify-center"),onPointerDown:U,ref:u,role:"application",style:{transform:`translate(${p.x}px, ${p.y}px) scale(${c})`,transformOrigin:"center center",touchAction:"none",willChange:"transform"},children:e})]})},_S=({chart:e,className:t,config:a,fullscreen:n=!1,showControls:r=!0})=>{let[o,i]=(0,N.useState)(null),[s,l]=(0,N.useState)(!1),[u,c]=(0,N.useState)(""),[d,p]=(0,N.useState)(""),[m,h]=(0,N.useState)(0),{mermaid:v}=(0,N.useContext)(qa),I=qS(),y=v?.errorComponent,{shouldRender:w,containerRef:g}=$X({immediate:n});if((0,N.useEffect)(()=>{if(w){if(!I){i("Mermaid plugin not available. Please add the mermaid plugin to enable diagram rendering.");return}(async()=>{try{i(null),l(!0);let E=I.getMermaid(a),T=e.split("").reduce((U,A)=>(U<<5)-U+A.charCodeAt(0)|0,0),R=`mermaid-${Math.abs(T)}-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,{svg:O}=await E.render(R,e);c(O),p(O)}catch(E){if(!(d||u)){let T=E instanceof Error?E.message:"Failed to render Mermaid chart";i(T)}}finally{l(!1)}})()}},[e,a,m,w,I]),!(w||u||d))return(0,M.jsx)("div",{className:Ce("my-4 min-h-[200px]",t),ref:g});if(s&&!u&&!d)return(0,M.jsx)("div",{className:Ce("my-4 flex justify-center p-4",t),ref:g,children:(0,M.jsxs)("div",{className:"flex items-center space-x-2 text-muted-foreground",children:[(0,M.jsx)("div",{className:"h-4 w-4 animate-spin rounded-full border-current border-b-2"}),(0,M.jsx)("span",{className:"text-sm",children:"Loading diagram..."})]})});if(o&&!u&&!d)return y?(0,M.jsx)("div",{ref:g,children:(0,M.jsx)(y,{chart:e,error:o,retry:()=>h(T=>T+1)})}):(0,M.jsxs)("div",{className:Ce("rounded-lg border border-red-200 bg-red-50 p-4",t),ref:g,children:[(0,M.jsxs)("p",{className:"font-mono text-red-700 text-sm",children:["Mermaid Error: ",o]}),(0,M.jsxs)("details",{className:"mt-2",children:[(0,M.jsx)("summary",{className:"cursor-pointer text-red-600 text-xs",children:"Show Code"}),(0,M.jsx)("pre",{className:"mt-2 overflow-x-auto rounded bg-red-100 p-2 text-red-800 text-xs",children:e})]})]});let S=u||d;return(0,M.jsx)("div",{className:Ce("size-full",t),"data-streamdown":"mermaid",ref:g,children:(0,M.jsx)(_K,{className:Ce(n?"size-full overflow-hidden":"my-4 overflow-hidden",t),fullscreen:n,maxZoom:3,minZoom:.5,showControls:r,zoomStep:.1,children:(0,M.jsx)("div",{"aria-label":"Mermaid chart",className:Ce("flex justify-center",n?"size-full items-center":null),dangerouslySetInnerHTML:{__html:S},role:"img"})})})}});var lB=Ca((Xve,sB)=>{"use strict";function cY(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(),s=i-n,l=t-s;l<=0?(n=i,e.apply(this,o)):a=setTimeout(()=>{n=Date.now(),e.apply(this,o)},l)}}sB.exports=cY});var xI=typeof performance>"u"?0:performance.now(),bI=typeof window<"u"&&!!window.WaniWani?.chat;var Cs=j(Ee(),1),Zh=j(qw(),1);var Hw="waniwani/suggestions";function yl(e,t){for(let a of t){let n=e[a];if(typeof n=="string"&&n.length>0)return n}}var hq=["waniwani/sessionId","openai/sessionId","openai/session","sessionId","conversationId","mcp-session-id"],gq=["waniwani/requestId","openai/requestId","requestId","mcp/requestId"],yq=["waniwani/traceId","openai/traceId","traceId","mcp/traceId","openai/requestId","requestId"],wq=["waniwani/userId","openai/userId","externalUserId","userId","actorId"],vq=["waniwani/visitorId","visitorId"],xq=["correlationId","openai/requestId"];function c1(e){return e?yl(e,hq):void 0}function d1(e){return e?yl(e,gq):void 0}function f1(e){return e?yl(e,yq):void 0}function p1(e){return e?yl(e,wq):void 0}function m1(e){return e?yl(e,vq):void 0}function h1(e){return e?yl(e,xq):void 0}var bq=[{key:"openai/sessionId",source:"chatgpt"},{key:"openai/session",source:"chatgpt"}],Sq=[{needle:"claude",source:"claude"},{needle:"chatgpt",source:"chatgpt"},{needle:"openai",source:"chatgpt"},{needle:"gemini",source:"gemini"}];function g1(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 bq){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 Sq)if(n.includes(r))return o}}var Iq="@waniwani/sdk";function y1(e,t={}){let a=t.now??(()=>new Date),n=t.generateId??Cq,r=Lq(e),o=zp(e.meta),i=zp(e.metadata),s=Eq(e,o),l=Xn(e.eventId)??n(),u=Aq(e.timestamp,a),c=Xn(e.source)??g1(o)??t.source??Iq,d=jw(e)?{...e}:void 0,p={...i};return Object.keys(o).length>0&&(p.meta=o),d&&(p.rawLegacy=d),{id:l,type:"mcp.event",name:r,source:c,timestamp:u,correlation:s,properties:kq(e,r),metadata:p,rawLegacy:d}}function Cq(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`evt_${crypto.randomUUID()}`:`evt_${Math.random().toString(36).slice(2,10)}_${Date.now().toString(36)}`}function kq(e,t){if(!jw(e))return zp(e.properties);let a=Tq(e,t),n=zp(e.properties);return{...a,...n}}function Tq(e,t){switch(t){case"tool.called":{let a={};return Xn(e.toolName)&&(a.name=e.toolName),Xn(e.toolType)&&(a.type=e.toolType),a}case"link.clicked":{let a={};return Xn(e.linkUrl)&&(a.url=e.linkUrl),a}default:return{}}}function Lq(e){return jw(e)?e.eventType:e.event}function Eq(e,t){let a=Xn(e.requestId)??d1(t),n=Xn(e.sessionId)??c1(t),r=Xn(e.traceId)??f1(t),o=Xn(e.externalUserId)??p1(t),i=Xn(e.visitorId)??m1(t),s=Xn(e.correlationId)??h1(t)??a,l={};return n&&(l.sessionId=n),r&&(l.traceId=r),a&&(l.requestId=a),s&&(l.correlationId=s),o&&(l.externalUserId=o),i&&(l.visitorId=i),l}function Aq(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 zp(e){return!e||typeof e!="object"||Array.isArray(e)?{}:e}function Xn(e){if(typeof e=="string"&&e.trim().length!==0)return e}function jw(e){return"eventType"in e}function w1(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 Mq="/api/mcp/events/v2/batch";var v1="@waniwani/sdk";var Rq=new Set([401,403]),Dq=new Set([408,425,429,500,502,503,504]),_q=(e,t)=>globalThis.fetch(e,t);function x1(e){return new Vw(e)}var Vw=class{constructor(t){K(this,"endpointUrl");K(this,"flushIntervalMs");K(this,"maxBatchSize");K(this,"maxBufferSize");K(this,"maxRetries");K(this,"retryBaseDelayMs");K(this,"retryMaxDelayMs");K(this,"shutdownTimeoutMs");K(this,"sdkVersion");K(this,"fetchFn");K(this,"logger");K(this,"now");K(this,"sleep");K(this,"apiKey");K(this,"buffer",[]);K(this,"flushTimer");K(this,"flushScheduled",!1);K(this,"flushScheduledTimer");K(this,"flushInFlight");K(this,"inFlightCount",0);K(this,"isStopped",!1);K(this,"isShuttingDown",!1);this.endpointUrl=Nq(t.apiUrl,t.endpointPath??Mq),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??_q,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":v1};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:Uq(o)}}if(Rq.has(a.status))return{kind:"auth",status:a.status};if(Dq.has(a.status))return{kind:"retryable",reason:`HTTP ${a.status}`};if(!a.ok)return{kind:"permanent",reason:`HTTP ${a.status}`};let n=await Oq(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:v1,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 s=n.get(i.eventId);if(s){if(Pq(i)){r.push(s);continue}o.push(s)}}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 Pq(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 Oq(e){let t=await e.text();if(t)try{return JSON.parse(t)}catch{return}}function Nq(e,t){let a=e.endsWith("/")?e:`${e}/`,n=t.startsWith("/")?t.slice(1):t;return`${a}${n}`}function Uq(e){return e instanceof Error?e.message:String(e)}function b1(e){let{apiUrl:t,endpointPath:a}=Bq(e.endpoint),n=x1({apiUrl:t,apiKey:e.token,endpointPath:a,flushIntervalMs:e.flushIntervalMs}),r,o=s=>typeof s=="function"?s():s,i=async s=>{let l=e.identity?.()??{},u=o(e.channelId),c=u===void 0?s.properties:{channelId:u,...s.properties},d=y1({sessionId:l.sessionId,visitorId:l.visitorId,externalUserId:l.externalUserId??r,traceId:l.traceId,...s,properties:c,metadata:{...e.metadata,...s.metadata}},{source:o(e.source)});return n.enqueue(d),{eventId:d.id}};return{track:Object.assign(i,w1(i)),identify(s,l){return r=s,i({event:"user.identified",externalUserId:s,properties:l})},flush:()=>n.flush(),shutdown:s=>n.shutdown(s)}}function Bq(e){let t=new URL(e);return{apiUrl:t.origin,endpointPath:`${t.pathname}${t.search}`}}function Na(e,t,a){let[n,r=""]=e.split("?"),o=n.replace(/\/$/,""),i=new URLSearchParams(r);if(a)for(let[l,u]of Object.entries(a))i.set(l,u);let s=i.toString();return`${o}${t}${s?`?${s}`:""}`}var zq="/api/mcp/";function Fp(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(zq)?`${n}${t}`:null}function Fq(){if(typeof window>"u")return!1;try{return window.WANIWANI_DEBUG?!0:!!window.localStorage?.getItem("WANIWANI_DEBUG")}catch{return!1}}function Ua(...e){Fq()&&console.log("[Waniwani]",...e)}var $w="waniwani-visitor-id";function qq(){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 ma(){try{let t=localStorage.getItem($w);if(t)return t}catch{}let e=qq();try{localStorage.setItem($w,e)}catch{}return e}function wl(e){let t=typeof e=="string"?e.trim():"";if(!t)return ma();try{localStorage.setItem($w,t)}catch{}return t}function Hq(e){return e!=null&&typeof e.then=="function"}function Sc(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 Hq(n)?n.then(r=>{t||wl(r??"")},()=>{}):wl(n??""),a}var jq="waniwani-memory";var yn="threads",qp="by_memoryUserId",Vq="by_updatedAt";var I1="memoryUserId",S1="waniwani-memory-user-id",Ww=null;function Gw(){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 $q(e,t){if(t<1&&(e.objectStoreNames.contains("ids")||e.createObjectStore("ids")),t<2&&!e.objectStoreNames.contains(yn)){let a=e.createObjectStore(yn,{keyPath:"threadId"});a.createIndex(qp,"memoryUserId",{unique:!1}),a.createIndex(Vq,"updatedAt",{unique:!1})}}async function Xw(){return new Promise((e,t)=>{let a=indexedDB.open(jq,2);a.onupgradeneeded=n=>{$q(a.result,n.oldVersion)},a.onsuccess=()=>e(a.result),a.onerror=()=>t(a.error)})}async function Wq(){return Xw()}async function Gq(e){return new Promise((t,a)=>{let o=e.transaction("ids","readonly").objectStore("ids").get(I1);o.onsuccess=()=>t(typeof o.result=="string"?o.result:null),o.onerror=()=>a(o.error)})}async function Xq(e,t){return new Promise((a,n)=>{let i=e.transaction("ids","readwrite").objectStore("ids").put(t,I1);i.onsuccess=()=>a(),i.onerror=()=>n(i.error)})}async function Kq(){if(typeof indexedDB>"u")return null;try{let e=await Wq();try{let t=await Gq(e);if(t)return t;let a=Gw();return await Xq(e,a),a}finally{e.close()}}catch{return null}}function Yq(){try{let e=localStorage.getItem(S1);if(e)return e;let t=Gw();return localStorage.setItem(S1,t),t}catch{return null}}async function C1(){let e=await Kq();if(e)return e;let t=Yq();return t||(Ww||(Ww=Gw()),Ww)}function k1(e,t){return e.match(t)?.[1]??null}function Zq(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=k1(e,n);if(r)return{name:a,version:r}}return null}function Jq(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=k1(e,n);if(r)return{name:a,version:r.replace(/_/g,".")};if(a==="Linux"&&n.test(e))return{name:a,version:""}}return null}function Qq(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 Ic(){let e=navigator.userAgent,t=ma(),a=await C1();return{userAgent:e,browser:Zq(e),os:Jq(e),deviceType:Qq(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 e4="0.23.0",t4=40,a4=10,n4=6e5;function Yw(){return typeof performance>"u"?0:performance.now()}function Zw(e,t){let a={};return{metrics:a,has:n=>n in a,set(n,r){a[n]=r},mark(n,r=Yw()){if(!(n in a)){a[n]=r-t;try{performance.mark(`waniwani:${e}:${n}`,{startTime:r})}catch{}}}}}function r4(e){let t={};for(let[a,n]of Object.entries(e)){if(Object.keys(t).length>=t4)break;if(!Number.isFinite(n))continue;let r=Math.round(n);r<0||r>n4||(t[a]=r)}return t}function o4(e){let t={};for(let[a,n]of Object.entries(e)){if(Object.keys(t).length>=a4)break;(typeof n=="string"||typeof n=="boolean")&&(t[a]=n)}return t}function i4(){let e=navigator.connection;if(e)return{effectiveType:e.effectiveType,rtt:e.rtt,downlink:e.downlink,saveData:e.saveData}}function jp(e){let t=e?.Authorization;return typeof t=="string"&&t.startsWith("Bearer ")?t.slice(7):void 0}function s4(e,t,a,n){return{kind:e,sdkVersion:e4,channelId:t.channelId||void 0,sessionId:e==="boot"?void 0:t.sessionId||void 0,visitorId:ma(),pageHost:window.location.hostname,connection:i4(),tags:o4(a),metrics:r4(n)}}var Kw,Hp=[];function Jw(e){let t=String(e?.chatTimingLogs).trim().toLowerCase()==="true";Kw=t;let a=Hp;if(Hp=[],t)for(let n of a)n()}function Vp(e,t,a,n){let{api:r,token:o}=t;if(!(typeof window>"u"||!r||!o||Kw===!1))try{let i=s4(e,t,a,n),s=()=>{Ua("timing",i),fetch(Na(r,"/timing"),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},body:JSON.stringify(i),keepalive:!0}).catch(()=>{})};Kw?s():Hp.length<20&&Hp.push(s)}catch{}}var Wr=Zw("boot",0),T1;function Di(e,t){Wr.mark(e,t)}function $p(e){T1??(T1=e)}var l4=/cdn\.jsdelivr\.net\/npm\/@waniwani\/sdk@[^/]+\/dist\/chat\/embed\.js/,u4=/\/embed\.js(\?|$)/;function c4(){if(typeof performance>"u")return;let e=performance.getEntriesByType("navigation")[0];e?.responseStart&&Wr.mark("navTtfb",e.responseStart),e?.domContentLoadedEventEnd&&Wr.mark("navDomContentLoaded",e.domContentLoadedEventEnd);let t=performance.getEntriesByType("resource");for(let a of t)l4.test(a.name)?(Wr.mark("bundleStart",a.startTime),Wr.mark("bundleEnd",a.responseEnd)):u4.test(a.name)&&(Wr.mark("loaderStart",a.startTime),Wr.mark("loaderEnd",a.responseEnd))}function d4(){if(bI)return!0;try{return document.querySelectorAll('script[src*="@waniwani/sdk"]').length>1}catch{return!1}}function L1(e){c4(),Wr.mark("bundleExecuted",xI),Vp("boot",e,{configSource:T1,mode:e.mode,secondSdk:d4()},Wr.metrics)}var f4=[["text-delta","firstText"],["tool-input-start","firstToolInput"],["tool-output-available","firstToolOutput"]];function E1(e){let t=Zw("turn",Yw());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,s){t.mark("firstChunk");let l=r.decode(i,{stream:!0});for(let[u,c]of f4)!t.has(c)&&l.includes(u)&&t.mark(c);s.enqueue(i)}}));return new Response(o,{status:n.status,statusText:n.statusText,headers:n.headers})}catch{return n}},report(n,r){a||(a=!0,Vp("turn",n,r,t.metrics))}}}function p4(e){let t=e.indexOf("?");return t===-1?e:e.slice(0,t)}function A1(e,t){let a=Zw("widget",Yw()),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:p4(e),outcome:r,metrics:a.metrics}))}}}var m4="/api/mcp/events/v2/batch",Qw=new Set;function h4(e,t,a){return`${e}|${t}|${a??""}`}function Cc(e){return Fp(e,m4)}async function M1(e){let{api:t,token:a,channelId:n,mode:r,source:o}=e;if(typeof window>"u"||!t||!a)return;let i=Cc(t);if(!i){Ua("page.viewed skipped: the chat api is not a Waniwani endpoint");return}if(!n&&!o){Ua("page.viewed skipped: no channelId or source to attribute it");return}let s=h4(t,a,n);if(!Qw.has(s)){Qw.add(s);try{let l=await Ic(),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:l.visitorId},properties:{channelId:n,mode:r,url:window.location.href,referrer:l.referrer,deviceType:l.deviceType,language:l.language,timezone:l.timezone},metadata:{}}]}),d=fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:c,keepalive:!0});Di("pageViewSent"),await d}catch{Qw.delete(s)}}}function R1(e){let t=Cc(e.api);return t?b1({endpoint:t,token:e.token,channelId:e.channelId,source:e.getSource,identity:()=>({sessionId:e.getSessionId(),visitorId:ma()})}):Wp("the chat api does not point at a Waniwani event ingest")}function Wp(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 Xp=j(Ee());var Gp=(...e)=>e.filter((t,a,n)=>!!t&&t.trim()!==""&&n.indexOf(t)===a).join(" ").trim();var D1=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();var _1=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,a,n)=>n?n.toUpperCase():a.toLowerCase());var ev=e=>{let t=_1(e);return t.charAt(0).toUpperCase()+t.slice(1)};var kc=j(Ee());var P1={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 O1=e=>{for(let t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0;return!1};var N1=(0,kc.forwardRef)(({color:e="currentColor",size:t=24,strokeWidth:a=2,absoluteStrokeWidth:n,className:r="",children:o,iconNode:i,...s},l)=>(0,kc.createElement)("svg",{ref:l,...P1,width:t,height:t,stroke:e,strokeWidth:n?Number(a)*24/Number(t):a,className:Gp("lucide",r),...!o&&!O1(s)&&{"aria-hidden":"true"},...s},[...i.map(([u,c])=>(0,kc.createElement)(u,c)),...Array.isArray(o)?o:[o]]));var tt=(e,t)=>{let a=(0,Xp.forwardRef)(({className:n,...r},o)=>(0,Xp.createElement)(N1,{ref:o,iconNode:t,className:Gp(`lucide-${D1(ev(e))}`,`lucide-${e}`,n),...r}));return a.displayName=ev(e),a};var g4=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],Tc=tt("arrow-down",g4);var y4=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],pr=tt("arrow-up",y4);var w4=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Lc=tt("check",w4);var v4=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],zo=tt("chevron-down",v4);var x4=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],Ec=tt("chevron-right",x4);var b4=[["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"}]],Ac=tt("clipboard-copy",b4);var S4=[["path",{d:"M12 6v6l4 2",key:"mmk7yg"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],Gr=tt("clock",S4);var I4=[["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"}]],Mc=tt("file-text",I4);var C4=[["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"}]],vl=tt("file",C4);var k4=[["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"}]],Rc=tt("globe",k4);var T4=[["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"}]],Dc=tt("image",T4);var L4=[["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"}]],_c=tt("loader",L4);var E4=[["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"}]],xl=tt("paperclip",E4);var A4=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],Pc=tt("square",A4);var M4=[["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"}]],_i=tt("wrench",M4);var R4=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],wn=tt("x",R4);var D4=[["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"}]],Oc=tt("zap",D4);var rt=j(Ee(),1),qB=j(gg(),1);var bl=j(Ee(),1),Nc=j(me(),1);function O4(e){return 1-(1-e)**3}function N4({start:e=0,end:t=100,duration:a=1e3,delay:n=0,ease:r=O4,onUpdate:o,onEnd:i}){let s=performance.now()+n;function l(){let u=performance.now()-s,c=Math.min(u/a,1);o(e+(t-e)*r(c)),c<1?requestAnimationFrame(l):i&&i()}setTimeout(()=>requestAnimationFrame(l),n)}var U4=["80% 55%","69% 34%","8% 6%","41% 38%","86% 85%","82% 18%","51% 4%"],B4=[0,1,2,0,1,2,1];function z4(e){let t=[];for(let a=0;a<7;a++){let n=e[Math.min(B4[a],e.length-1)];t.push(`radial-gradient(at ${U4[a]}, ${n} 0px, transparent 50%)`)}return t.push(`linear-gradient(${e[0]} 0 100%)`),t}var F4=({children:e,className:t="",style:a,edgeSensitivity:n=30,backgroundColor:r="#120F17",borderRadius:o=28,coneSpread:i=25,animated:s=!1,colors:l=["#c084fc","#f472b6","#38bdf8"]})=>{let[u,c]=(0,bl.useState)(110),[d,p]=(0,bl.useState)(0),[m,h]=(0,bl.useState)(!1);(0,bl.useEffect)(()=>{if(!s)return;let E=110;h(!0),c(E),N4({ease:T=>T,duration:2e3,onUpdate:T=>{let R=T/100;c(E+360*R);let O=Math.min(R/.1,1),U=R>.85?(1-R)/.15:1;p(Math.min(O,U))},onEnd:()=>h(!1)})},[s]);let v=n+20,I=m?Math.max(0,(d*100-v)/(100-v)):0,w=z4(l).map(E=>`${E} border-box`),S=`conic-gradient(from ${`${u.toFixed(3)}deg`} at center, black ${i}%, transparent ${i+15}%, transparent ${100-i-15}%, black ${100-i}%)`;return(0,Nc.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,Nc.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",...w].join(", "),opacity:I,maskImage:S,WebkitMaskImage:S,transition:m?"opacity 0.25s ease-out":"opacity 0.75s ease-in-out"}}),(0,Nc.jsx)("div",{className:"ww:flex ww:flex-col ww:relative ww:overflow-auto ww:z-[1]",children:e})]})},Yp=F4;tv();nv();var q4=q1({prefix:"ww"});function V(...e){return q4(Zp(e))}var Uc=j(me(),1);function Sl({suggestions:e,isLoading:t,onSelect:a,align:n="start",className:r,...o}){return e.length===0&&!t?null:(0,Uc.jsx)("div",{className:V("ww:px-4 ww:py-2",r),...o,children:(0,Uc.jsx)("div",{className:V("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,Uc.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,s)=>(0,Uc.jsx)("button",{type:"button",onClick:()=>a(i),className:V("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:`${s*50}ms`},children:i},i))})})}var gm=j(Ee(),1);var gL="vercel.ai.error",H4=Symbol.for(gL),H1,j1,Je=class yL extends(j1=Error,H1=H4,j1){constructor({name:t,message:a,cause:n}){super(a),this[H1]=!0,this.name=t,this.cause=n}static isInstance(t){return yL.hasMarker(t,gL)}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}},wL="AI_APICallError",vL=`vercel.ai.error.${wL}`,j4=Symbol.for(vL),V1,$1,GQ=class extends($1=Je,V1=j4,$1){constructor({message:e,url:t,requestBodyValues:a,statusCode:n,responseHeaders:r,responseBody:o,cause:i,isRetryable:s=n!=null&&(n===408||n===409||n===429||n>=500),data:l}){super({name:wL,message:e,cause:i}),this[V1]=!0,this.url=t,this.requestBodyValues=a,this.statusCode=n,this.responseHeaders=r,this.responseBody=o,this.isRetryable=s,this.data=l}static isInstance(e){return Je.hasMarker(e,vL)}},xL="AI_EmptyResponseBodyError",bL=`vercel.ai.error.${xL}`,V4=Symbol.for(bL),W1,G1,XQ=class extends(G1=Je,W1=V4,G1){constructor({message:e="Empty response body"}={}){super({name:xL,message:e}),this[W1]=!0}static isInstance(e){return Je.hasMarker(e,bL)}};function SL(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var IL="AI_InvalidArgumentError",CL=`vercel.ai.error.${IL}`,$4=Symbol.for(CL),X1,K1,kL=class extends(K1=Je,X1=$4,K1){constructor({message:e,cause:t,argument:a}){super({name:IL,message:e,cause:t}),this[X1]=!0,this.argument=a}static isInstance(e){return Je.hasMarker(e,CL)}},TL="AI_InvalidPromptError",LL=`vercel.ai.error.${TL}`,W4=Symbol.for(LL),Y1,Z1,KQ=class extends(Z1=Je,Y1=W4,Z1){constructor({prompt:e,message:t,cause:a}){super({name:TL,message:`Invalid prompt: ${t}`,cause:a}),this[Y1]=!0,this.prompt=e}static isInstance(e){return Je.hasMarker(e,LL)}},EL="AI_InvalidResponseDataError",AL=`vercel.ai.error.${EL}`,G4=Symbol.for(AL),J1,Q1,YQ=class extends(Q1=Je,J1=G4,Q1){constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:EL,message:t}),this[J1]=!0,this.data=e}static isInstance(e){return Je.hasMarker(e,AL)}},ML="AI_JSONParseError",RL=`vercel.ai.error.${ML}`,X4=Symbol.for(RL),eL,tL,ov=class extends(tL=Je,eL=X4,tL){constructor({text:e,cause:t}){super({name:ML,message:`JSON parsing failed: Text: ${e}.
|
|
122
122
|
Error message: ${SL(t)}`,cause:t}),this[eL]=!0,this.text=e}static isInstance(e){return Je.hasMarker(e,RL)}},DL="AI_LoadAPIKeyError",_L=`vercel.ai.error.${DL}`,K4=Symbol.for(_L),aL,nL,ZQ=class extends(nL=Je,aL=K4,nL){constructor({message:e}){super({name:DL,message:e}),this[aL]=!0}static isInstance(e){return Je.hasMarker(e,_L)}},PL="AI_LoadSettingError",OL=`vercel.ai.error.${PL}`,Y4=Symbol.for(OL),rL,oL,JQ=class extends(oL=Je,rL=Y4,oL){constructor({message:e}){super({name:PL,message:e}),this[rL]=!0}static isInstance(e){return Je.hasMarker(e,OL)}},NL="AI_NoContentGeneratedError",UL=`vercel.ai.error.${NL}`,Z4=Symbol.for(UL),iL,sL,QQ=class extends(sL=Je,iL=Z4,sL){constructor({message:e="No content generated."}={}){super({name:NL,message:e}),this[iL]=!0}static isInstance(e){return Je.hasMarker(e,UL)}},BL="AI_NoSuchModelError",zL=`vercel.ai.error.${BL}`,J4=Symbol.for(zL),lL,uL,eee=class extends(uL=Je,lL=J4,uL){constructor({errorName:e=BL,modelId:t,modelType:a,message:n=`No such ${a}: ${t}`}){super({name:e,message:n}),this[lL]=!0,this.modelId=t,this.modelType=a}static isInstance(e){return Je.hasMarker(e,zL)}},FL="AI_TooManyEmbeddingValuesForCallError",qL=`vercel.ai.error.${FL}`,Q4=Symbol.for(qL),cL,dL,tee=class extends(dL=Je,cL=Q4,dL){constructor(e){super({name:FL,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[cL]=!0,this.provider=e.provider,this.modelId=e.modelId,this.maxEmbeddingsPerCall=e.maxEmbeddingsPerCall,this.values=e.values}static isInstance(e){return Je.hasMarker(e,qL)}},HL="AI_TypeValidationError",jL=`vercel.ai.error.${HL}`,e5=Symbol.for(jL),fL,pL,Kn=class rv extends(pL=Je,fL=e5,pL){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:HL,message:`${r}: Value: ${JSON.stringify(t)}.
|
|
123
123
|
Error message: ${SL(a)}`,cause:a}),this[fL]=!0,this.value=t,this.context=n}static isInstance(t){return Je.hasMarker(t,jL)}static wrap({value:t,cause:a,context:n}){var r,o,i;return rv.isInstance(a)&&a.value===t&&((r=a.context)==null?void 0:r.field)===n?.field&&((o=a.context)==null?void 0:o.entityName)===n?.entityName&&((i=a.context)==null?void 0:i.entityId)===n?.entityId?a:new rv({value:t,cause:a,context:n})}},VL="AI_UnsupportedFunctionalityError",$L=`vercel.ai.error.${VL}`,t5=Symbol.for($L),mL,hL,aee=class extends(hL=Je,mL=t5,hL){constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:VL,message:t}),this[mL]=!0,this.functionality=e}static isInstance(e){return Je.hasMarker(e,$L)}};var Jp=()=>sv,sv=new Proxy(Jp,{get(e,t){return t==="parse"||t==="parseAsync"?a=>a:t==="safeParse"||t==="safeParseAsync"?a=>({success:!0,data:a}):t==="_def"?{}:t==="jsonSchema"?{}:Jp},apply(){return sv}}),iv=class extends Error{constructor(){super(...arguments);K(this,"issues",[])}},f=new Proxy(Jp,{get(e,t){return t==="ZodError"?iv:t==="NEVER"?Symbol("NEVER"):Jp},apply(){return sv}});var Me={};var Qp=class extends Error{constructor(t,a){super(t),this.name="ParseError",this.type=a.type,this.field=a.field,this.value=a.value,this.line=a.line}};function lv(e){}function WL(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:t=lv,onError:a=lv,onRetry:n=lv,onComment:r}=e,o="",i=!0,s,l="",u="";function c(v){let I=i?v.replace(/^\xEF\xBB\xBF/,""):v,[y,w]=a5(`${o}${I}`);for(let g of y)d(g);o=w,i=!1}function d(v){if(v===""){m();return}if(v.startsWith(":")){r&&r(v.slice(v.startsWith(": ")?2:1));return}let I=v.indexOf(":");if(I!==-1){let y=v.slice(0,I),w=v[I+1]===" "?2:1,g=v.slice(I+w);p(y,g,v);return}p(v,"",v)}function p(v,I,y){switch(v){case"event":u=I;break;case"data":l=`${l}${I}
|
|
124
124
|
`;break;case"id":s=I.includes("\0")?void 0:I;break;case"retry":/^\d+$/.test(I)?n(parseInt(I,10)):a(new Qp(`Invalid \`retry\` value: "${I}"`,{type:"invalid-retry",value:I,line:y}));break;default:a(new Qp(`Unknown field "${v.length>20?`${v.slice(0,20)}\u2026`:v}"`,{type:"unknown-field",field:v,value:I,line:y}));break}}function m(){l.length>0&&t({id:s,event:u||void 0,data:l.endsWith(`
|
|
@@ -139,7 +139,7 @@ Known schemas:
|
|
|
139
139
|
- ${Object.keys(n).join(`
|
|
140
140
|
- `)}`,Error(ae)}let oe=`${s}/$ref`,Ie=Nt(e,le,a,n,r,o,i,oe,l);if(Ie.valid||W.push({instanceLocation:i,keyword:"$ref",keywordLocation:oe,error:"A subschema had errors."},...Ie.errors),a==="4"||a==="7")return{valid:W.length===0,errors:W}}if(Array.isArray(h)){let le=h.length,oe=!1;for(let Ie=0;Ie<le;Ie++)if(c===h[Ie]||h[Ie]==="integer"&&c==="number"&&e%1==0&&e===e){oe=!0;break}oe||W.push({instanceLocation:i,keyword:"type",keywordLocation:`${s}/type`,error:`Instance type "${c}" is invalid. Expected "${h.join('", "')}".`})}else h==="integer"?(c!=="number"||e%1||e!==e)&&W.push({instanceLocation:i,keyword:"type",keywordLocation:`${s}/type`,error:`Instance type "${c}" is invalid. Expected "${h}".`}):h!==void 0&&c!==h&&W.push({instanceLocation:i,keyword:"type",keywordLocation:`${s}/type`,error:`Instance type "${c}" is invalid. Expected "${h}".`});if(v!==void 0&&(c==="object"||c==="array"?Kc(e,v)||W.push({instanceLocation:i,keyword:"const",keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(v)}.`}):e!==v&&W.push({instanceLocation:i,keyword:"const",keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(v)}.`})),I!==void 0&&(c==="object"||c==="array"?I.some(le=>Kc(e,le))||W.push({instanceLocation:i,keyword:"enum",keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(I)}.`}):I.some(le=>e===le)||W.push({instanceLocation:i,keyword:"enum",keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(I)}.`})),w!==void 0){let le=`${s}/not`;Nt(e,w,a,n,r,o,i,le).valid&&W.push({instanceLocation:i,keyword:"not",keywordLocation:le,error:'Instance matched "not" schema.'})}let ct=[];if(g!==void 0){let le=`${s}/anyOf`,oe=W.length,Ie=!1;for(let ae=0;ae<g.length;ae++){let k=g[ae],D=Object.create(l),F=Nt(e,k,a,n,r,m===!0?o:null,i,`${le}/${ae}`,D);W.push(...F.errors),Ie||(Ie=F.valid),F.valid&&ct.push(D)}Ie?W.length=oe:W.splice(oe,0,{instanceLocation:i,keyword:"anyOf",keywordLocation:le,error:"Instance does not match any subschemas."})}if(S!==void 0){let le=`${s}/allOf`,oe=W.length,Ie=!0;for(let ae=0;ae<S.length;ae++){let k=S[ae],D=Object.create(l),F=Nt(e,k,a,n,r,m===!0?o:null,i,`${le}/${ae}`,D);W.push(...F.errors),Ie&&(Ie=F.valid),F.valid&&ct.push(D)}Ie?W.length=oe:W.splice(oe,0,{instanceLocation:i,keyword:"allOf",keywordLocation:le,error:"Instance does not match every subschema."})}if(E!==void 0){let le=`${s}/oneOf`,oe=W.length,Ie=E.filter((ae,k)=>{let D=Object.create(l),F=Nt(e,ae,a,n,r,m===!0?o:null,i,`${le}/${k}`,D);return W.push(...F.errors),F.valid&&ct.push(D),F.valid}).length;Ie===1?W.length=oe:W.splice(oe,0,{instanceLocation:i,keyword:"oneOf",keywordLocation:le,error:`Instance does not match exactly one subschema (${Ie} matches).`})}if((c==="object"||c==="array")&&Object.assign(l,...ct),T!==void 0){let le=`${s}/if`;if(Nt(e,T,a,n,r,o,i,le,l).valid){if(R!==void 0){let oe=Nt(e,R,a,n,r,o,i,`${s}/then`,l);oe.valid||W.push({instanceLocation:i,keyword:"if",keywordLocation:le,error:'Instance does not match "then" schema.'},...oe.errors)}}else if(O!==void 0){let oe=Nt(e,O,a,n,r,o,i,`${s}/else`,l);oe.valid||W.push({instanceLocation:i,keyword:"if",keywordLocation:le,error:'Instance does not match "else" schema.'},...oe.errors)}}if(c==="object"){if(y!==void 0)for(let ae of y)ae in e||W.push({instanceLocation:i,keyword:"required",keywordLocation:`${s}/required`,error:`Instance does not have required property "${ae}".`});let le=Object.keys(e);if(Z!==void 0&&le.length<Z&&W.push({instanceLocation:i,keyword:"minProperties",keywordLocation:`${s}/minProperties`,error:`Instance does not have at least ${Z} properties.`}),X!==void 0&&le.length>X&&W.push({instanceLocation:i,keyword:"maxProperties",keywordLocation:`${s}/maxProperties`,error:`Instance does not have at least ${X} properties.`}),B!==void 0){let ae=`${s}/propertyNames`;for(let k in e){let D=`${i}/${Jn(k)}`,F=Nt(k,B,a,n,r,o,D,ae);F.valid||W.push({instanceLocation:i,keyword:"propertyNames",keywordLocation:ae,error:`Property name "${k}" does not match schema.`},...F.errors)}}if(P!==void 0){let ae=`${s}/dependantRequired`;for(let k in P)if(k in e){let D=P[k];for(let F of D)F in e||W.push({instanceLocation:i,keyword:"dependentRequired",keywordLocation:ae,error:`Instance has "${k}" but does not have "${F}".`})}}if(J!==void 0)for(let ae in J){let k=`${s}/dependentSchemas`;if(ae in e){let D=Nt(e,J[ae],a,n,r,o,i,`${k}/${Jn(ae)}`,l);D.valid||W.push({instanceLocation:i,keyword:"dependentSchemas",keywordLocation:k,error:`Instance has "${ae}" but does not match dependant schema.`},...D.errors)}}if(ge!==void 0){let ae=`${s}/dependencies`;for(let k in ge)if(k in e){let D=ge[k];if(Array.isArray(D))for(let F of D)F in e||W.push({instanceLocation:i,keyword:"dependencies",keywordLocation:ae,error:`Instance has "${k}" but does not have "${F}".`});else{let F=Nt(e,D,a,n,r,o,i,`${ae}/${Jn(k)}`);F.valid||W.push({instanceLocation:i,keyword:"dependencies",keywordLocation:ae,error:`Instance has "${k}" but does not match dependant schema.`},...F.errors)}}}let oe=Object.create(null),Ie=!1;if(A!==void 0){let ae=`${s}/properties`;for(let k in A){if(!(k in e))continue;let D=`${i}/${Jn(k)}`,F=Nt(e[k],A[k],a,n,r,o,D,`${ae}/${Jn(k)}`);if(F.valid)l[k]=oe[k]=!0;else if(Ie=r,W.push({instanceLocation:i,keyword:"properties",keywordLocation:ae,error:`Property "${k}" does not match schema.`},...F.errors),Ie)break}}if(!Ie&&Q!==void 0){let ae=`${s}/patternProperties`;for(let k in Q){let D=new RegExp(k,"u"),F=Q[k];for(let fe in e){if(!D.test(fe))continue;let Ve=`${i}/${Jn(fe)}`,Ft=Nt(e[fe],F,a,n,r,o,Ve,`${ae}/${Jn(k)}`);Ft.valid?l[fe]=oe[fe]=!0:(Ie=r,W.push({instanceLocation:i,keyword:"patternProperties",keywordLocation:ae,error:`Property "${fe}" matches pattern "${k}" but does not match associated schema.`},...Ft.errors))}}}if(!Ie&&$!==void 0){let ae=`${s}/additionalProperties`;for(let k in e){if(oe[k])continue;let D=`${i}/${Jn(k)}`,F=Nt(e[k],$,a,n,r,o,D,ae);F.valid?l[k]=!0:(Ie=r,W.push({instanceLocation:i,keyword:"additionalProperties",keywordLocation:ae,error:`Property "${k}" does not match additional properties schema.`},...F.errors))}}else if(!Ie&&H!==void 0){let ae=`${s}/unevaluatedProperties`;for(let k in e)if(!l[k]){let D=`${i}/${Jn(k)}`,F=Nt(e[k],H,a,n,r,o,D,ae);F.valid?l[k]=!0:W.push({instanceLocation:i,keyword:"unevaluatedProperties",keywordLocation:ae,error:`Property "${k}" does not match unevaluated properties schema.`},...F.errors)}}}else if(c==="array"){be!==void 0&&e.length>be&&W.push({instanceLocation:i,keyword:"maxItems",keywordLocation:`${s}/maxItems`,error:`Array has too many items (${e.length} > ${be}).`}),We!==void 0&&e.length<We&&W.push({instanceLocation:i,keyword:"minItems",keywordLocation:`${s}/minItems`,error:`Array has too few items (${e.length} < ${We}).`});let le=e.length,oe=0,Ie=!1;if(C!==void 0){let ae=`${s}/prefixItems`,k=Math.min(C.length,le);for(;oe<k;oe++){let D=Nt(e[oe],C[oe],a,n,r,o,`${i}/${oe}`,`${ae}/${oe}`);if(l[oe]=!0,!D.valid&&(Ie=r,W.push({instanceLocation:i,keyword:"prefixItems",keywordLocation:ae,error:"Items did not match schema."},...D.errors),Ie))break}}if(ze!==void 0){let ae=`${s}/items`;if(Array.isArray(ze)){let k=Math.min(ze.length,le);for(;oe<k;oe++){let D=Nt(e[oe],ze[oe],a,n,r,o,`${i}/${oe}`,`${ae}/${oe}`);if(l[oe]=!0,!D.valid&&(Ie=r,W.push({instanceLocation:i,keyword:"items",keywordLocation:ae,error:"Items did not match schema."},...D.errors),Ie))break}}else for(;oe<le;oe++){let k=Nt(e[oe],ze,a,n,r,o,`${i}/${oe}`,ae);if(l[oe]=!0,!k.valid&&(Ie=r,W.push({instanceLocation:i,keyword:"items",keywordLocation:ae,error:"Items did not match schema."},...k.errors),Ie))break}if(!Ie&&ot!==void 0){let k=`${s}/additionalItems`;for(;oe<le;oe++){let D=Nt(e[oe],ot,a,n,r,o,`${i}/${oe}`,k);l[oe]=!0,D.valid||(Ie=r,W.push({instanceLocation:i,keyword:"additionalItems",keywordLocation:k,error:"Items did not match additional items schema."},...D.errors))}}}if(te!==void 0)if(le===0&&re===void 0)W.push({instanceLocation:i,keyword:"contains",keywordLocation:`${s}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(re!==void 0&&le<re)W.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${s}/minContains`,error:`Array has less items (${le}) than minContains (${re}).`});else{let ae=`${s}/contains`,k=W.length,D=0;for(let F=0;F<le;F++){let fe=Nt(e[F],te,a,n,r,o,`${i}/${F}`,ae);fe.valid?(l[F]=!0,D++):W.push(...fe.errors)}D>=(re||0)&&(W.length=k),re===void 0&&ke===void 0&&D===0?W.splice(k,0,{instanceLocation:i,keyword:"contains",keywordLocation:ae,error:"Array does not contain item matching schema."}):re!==void 0&&D<re?W.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${s}/minContains`,error:`Array must contain at least ${re} items matching schema. Only ${D} items were found.`}):ke!==void 0&&D>ke&&W.push({instanceLocation:i,keyword:"maxContains",keywordLocation:`${s}/maxContains`,error:`Array may contain at most ${ke} items matching schema. ${D} items were found.`})}if(!Ie&&x!==void 0){let ae=`${s}/unevaluatedItems`;for(;oe<le;oe++){if(l[oe])continue;let k=Nt(e[oe],x,a,n,r,o,`${i}/${oe}`,ae);l[oe]=!0,k.valid||W.push({instanceLocation:i,keyword:"unevaluatedItems",keywordLocation:ae,error:"Items did not match unevaluated items schema."},...k.errors)}}if(Oe)for(let ae=0;ae<le;ae++){let k=e[ae],D=typeof k=="object"&&!!k;for(let F=0;F<le;F++){if(ae===F)continue;let fe=e[F];(k===fe||D&&typeof fe=="object"&&fe&&Kc(k,fe))&&(W.push({instanceLocation:i,keyword:"uniqueItems",keywordLocation:`${s}/uniqueItems`,error:`Duplicate items at indexes ${ae} and ${F}.`}),ae=2**53-1,F=2**53-1)}}}else if(c==="number"){if(a==="4"?(we!==void 0&&(Le===!0&&e<=we||e<we)&&W.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${s}/minimum`,error:`${e} is less than ${Le?"or equal to ":""} ${we}.`}),ce!==void 0&&(ie===!0&&e>=ce||e>ce)&&W.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${s}/maximum`,error:`${e} is greater than ${ie?"or equal to ":""} ${ce}.`})):(we!==void 0&&e<we&&W.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${s}/minimum`,error:`${e} is less than ${we}.`}),ce!==void 0&&e>ce&&W.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${s}/maximum`,error:`${e} is greater than ${ce}.`}),Le!==void 0&&e<=Le&&W.push({instanceLocation:i,keyword:"exclusiveMinimum",keywordLocation:`${s}/exclusiveMinimum`,error:`${e} is less than ${Le}.`}),ie!==void 0&&e>=ie&&W.push({instanceLocation:i,keyword:"exclusiveMaximum",keywordLocation:`${s}/exclusiveMaximum`,error:`${e} is greater than or equal to ${ie}.`})),xe!==void 0){let le=e%xe;Math.abs(0-le)>=11920929e-14&&Math.abs(xe-le)>=11920929e-14&&W.push({instanceLocation:i,keyword:"multipleOf",keywordLocation:`${s}/multipleOf`,error:`${e} is not a multiple of ${xe}.`})}}else if(c==="string"){let le=Ne===void 0&&_e===void 0?0:Z9(e);Ne!==void 0&&le<Ne&&W.push({instanceLocation:i,keyword:"minLength",keywordLocation:`${s}/minLength`,error:`String is too short (${le} < ${Ne}).`}),_e!==void 0&&le>_e&&W.push({instanceLocation:i,keyword:"maxLength",keywordLocation:`${s}/maxLength`,error:`String is too long (${le} > ${_e}).`}),Fe!==void 0&&!new RegExp(Fe,"u").test(e)&&W.push({instanceLocation:i,keyword:"pattern",keywordLocation:`${s}/pattern`,error:"String does not match pattern."}),U!==void 0&&dA[U]&&!dA[U](e)&&W.push({instanceLocation:i,keyword:"format",keywordLocation:`${s}/format`,error:`String does not match format "${U}".`})}return{valid:W.length===0,errors:W}}var mA=class{constructor(e,t="2019-09",a=!0){K(this,"schema");K(this,"draft");K(this,"shortCircuit");K(this,"lookup");this.schema=e,this.draft=t,this.shortCircuit=a,this.lookup=qi(e)}validate(e){return Nt(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),qi(e,this.lookup)}};function yA(e){return ej(e,"output")}function J9(e,t){let a=()=>structuredClone(e),n={"~standard":{version:1,vendor:"eve",validate:nj(e,t),jsonSchema:{input:a,output:a}}};return Q9.add(n),n}var Q9=new WeakSet,Vne=J9({});function ej(e,t){return e==null?e:tj(e,t)}function tj(e,t){let a=aj(e),n=a?.jsonSchema,r=typeof n=="object"&&n?n[t]:void 0,o=typeof a?.vendor=="string"?a.vendor:"unknown";if(a!==void 0&&typeof r!="function"&&o==="zod"){if(t==="input"){let l=Oi(e),{$schema:u,...c}=qc(l.jsonSchema);return c}throw Error("Zod 3 cannot emit an output JSON Schema. Upgrade to Zod 4 or provide a plain JSON Schema object.")}if(a!==void 0&&typeof r!="function")throw Error(`Standard Schema vendor "${o}" does not support JSON Schema conversion. Provide a Standard Schema implementation with JSON Schema conversion or a plain JSON Schema object.`);let{$schema:i,...s}=qc(a===void 0?e:r({target:"draft-07"}));return s}function aj(e){if(typeof e!="object"||!e||!("~standard"in e))return;let t=e["~standard"];return typeof t=="object"&&t?t:void 0}function nj(e,t){let a,n=!1,r=(o,i)=>(n||(n=!0,console.warn(`[eve] Tool schema cannot validate values locally; passing them through unvalidated: ${i}`)),{value:o});return o=>{if(a===void 0){let u=sj(e);if(typeof u=="string")return a=null,r(o,u);a=u}if(a===null)return{value:o};let i;try{i=a.validate(o)}catch(u){return o===void 0?{issues:[{message:"Expected a JSON value."}]}:r(o,jc(u))}if(!i.valid)return{issues:mj(i.errors)};let s=zv(e,e,o),l=t?.(s);return l===void 0?{value:s}:{issues:[{message:l}]}}}function zv(e,t,a){let n=a;for(let r of wA(e,t)){let{items:o,properties:i}=r;if(gr(n)&&gr(i))n=rj(e,i,n);else if(Array.isArray(n)&&gr(o)){let s=n,l=s.map(u=>zv(e,o,u));l.some((u,c)=>u!==s[c])&&(n=l)}}return n}function rj(e,t,a){let n=a;for(let[r,o]of Object.entries(t)){let i=Object.hasOwn(a,r)?a[r]:void 0,s=i===void 0?oj(e,o):zv(e,o,i);s!==i&&(n===a&&(n={...a}),n[r]=s)}return n}function oj(e,t){for(let a of wA(e,t))if("default"in a)return structuredClone(a.default)}function*wA(e,t){let a=new Set,n=t;for(;gr(n)&&!a.has(n);)a.add(n),yield n,n=ij(e,n.$ref)}function ij(e,t){if(typeof t!="string"||t!=="#"&&!t.startsWith("#/"))return;let a=e;for(let n of Bv(t)){if(typeof a!="object"||!a||!Object.hasOwn(a,n))return;a=a[n]}return a}function sj(e){try{let t=structuredClone(e);return Yc(t)??new mA(t,"2020-12",!1)}catch(t){return jc(t)}}var lj=new Set(["array","boolean","integer","null","number","object","string"]),uj=[["exclusiveMinimum","minimum"],["exclusiveMaximum","maximum"]],cj=["additionalItems","additionalProperties","contains","else","if","not","propertyNames","then","unevaluatedItems","unevaluatedProperties"],dj=["allOf","anyOf","oneOf","prefixItems"],fj=["$defs","definitions","dependencies","dependentSchemas","patternProperties","properties"];function Yc(e){if(typeof e=="boolean")return;if(typeof e!="object"||!e||Array.isArray(e))return"a subschema is neither an object nor a boolean";let t=e;delete t.format;for(let[s,l]of uj)typeof t[s]=="boolean"&&(t[s]&&typeof t[l]=="number"?(t[s]=t[l],delete t[l]):delete t[s]);let{enum:a,pattern:n,required:r,type:o}=t;if(o!==void 0&&!(Array.isArray(o)?o.every(hA):hA(o)))return`unsupported type ${JSON.stringify(o)}`;if(a!==void 0&&!Array.isArray(a))return"`enum` is not an array";if(r!==void 0&&!(Array.isArray(r)&&r.every(s=>typeof s=="string")))return"`required` is not an array of strings";if(n!==void 0&&!gA(n))return`invalid pattern ${JSON.stringify(n)}`;for(let s of cj)if(s in t){let l=Yc(t[s]);if(l!==void 0)return l}let i=t.items;for(let s of Array.isArray(i)?i:i===void 0?[]:[i]){let l=Yc(s);if(l!==void 0)return l}for(let s of dj){let l=t[s];if(l!==void 0){if(!Array.isArray(l))return`\`${s}\` is not an array`;for(let u of l){let c=Yc(u);if(c!==void 0)return c}}}for(let s of fj){let l=t[s];if(l!==void 0){if(typeof l!="object"||!l||Array.isArray(l))return`\`${s}\` is not an object`;for(let[u,c]of Object.entries(l)){if(s==="patternProperties"&&!gA(u))return`invalid pattern ${JSON.stringify(u)}`;if(s==="dependencies"&&Array.isArray(c))continue;let d=Yc(c);if(d!==void 0)return d}}}}function hA(e){return typeof e=="string"&&lj.has(e)}function gA(e){if(typeof e!="string")return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}var pj=/\/(?:additional|unevaluated)Properties$/;function mj(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n],o=e[n+1];if(pj.test(r.keywordLocation)&&o?.keyword==="false"){let i=Bv(o.instanceLocation).at(-1);t.push({keyword:"false",location:o.instanceLocation,message:`Unrecognized key: ${JSON.stringify(i)}`,object:r.instanceLocation}),n++}else t.push({keyword:r.keyword,location:r.instanceLocation,message:r.error})}let a=t.filter(n=>n.object===void 0||!t.some(r=>r.object===void 0&&(r.location===n.location||r.location.startsWith(`${n.location}/`))));return a.filter((n,r)=>{let o=a[r+1];return o===void 0?!0:o.location.startsWith(`${n.location}/`)?!1:n.keyword!=="$ref"||o.location!==n.location}).map(({location:n,message:r,object:o})=>{let i=Bv(o??n);return i.length===0?{message:r}:{message:r,path:i}})}function Bv(e){return e.split("/").slice(1).map(t=>{let a=t;try{a=decodeURIComponent(t)}catch{}return a.replaceAll("~1","/").replaceAll("~0","~")})}var vA=Symbol("followClientSession"),La,Ut,oa,qv,Hv,xA,jv,Vv,cm,Hi,Zc=(Hi=class{constructor(t,a){ue(this,oa);ue(this,La);ue(this,Ut);q(this,La,t),q(this,Ut,a)}static async create(t,a){var i;let n=await $v(t,Ta,a,!0),{sessionId:r}=await Fv(n),o=new Hi(t,{sessionId:r,streamIndex:0});return{response:Y(i=o,oa,Hv).call(i,n,a,0),session:o}}static async prewarm(t,a={}){let{sessionId:n}=await Fv(await gj(t,a));return new Hi(t,{sessionId:n,streamIndex:0})}get state(){return b(this,Ut)}async snapshot(t){t?.signal?.throwIfAborted();let a=[];for await(let n of Y(this,oa,cm).call(this,{follow:!1,signal:t?.signal,startIndex:0}))a.push(n);return t?.signal?.throwIfAborted(),{events:a,session:{sessionId:b(this,Ut).sessionId,streamIndex:a.length}}}async send(t,a={}){return await Y(this,oa,qv).call(this,{...a,message:t},!0)}async respond(t,a={}){if(t.length===0)throw Error("ClientSession.respond() requires at least one input response.");return await Y(this,oa,qv).call(this,{...a,inputResponses:t},!1)}async cancel(t){return await sA({context:b(this,La),options:t,sessionId:b(this,Ut).sessionId})}async clear(){return await lA({context:b(this,La),sessionId:b(this,Ut).sessionId})}async compact(){return await uA({context:b(this,La),sessionId:b(this,Ut).sessionId})}async reset(t){return await cA({context:b(this,La),options:t,sessionId:b(this,Ut).sessionId})}stream(t){if(t?.follow===!1&&(t.startIndex??b(this,Ut).streamIndex)<0)throw Error("stream({ follow: false }) requires a nonnegative startIndex; a tail-relative cursor cannot be bounded.");return Y(this,oa,jv).call(this,t)}streamSubagent(t,a){if(t.data.sessionId!==b(this,Ut).sessionId)throw Error(`streamSubagent() requires a subagent.called event from session ${b(this,Ut).sessionId}, but it came from session ${t.data.sessionId}.`);if(typeof t.data.childStreamPath!="string")throw Error(`streamSubagent() requires a subagent.called event with childStreamPath, but call ${t.data.callId} has none. The event was recorded by an older eve version.`);let n=a?.startIndex??0;if(a?.follow===!1&&n<0)throw Error("streamSubagent({ follow: false }) requires a nonnegative startIndex; a tail-relative cursor cannot be bounded.");return Uv({follow:a?.follow,host:b(this,La).host,path:t.data.childStreamPath,redirect:b(this,La).redirect,resolveHeaders:()=>b(this,La).resolveHeaders(),signal:a?.signal,startIndex:n,streamReconnectPolicy:a?.streamReconnectPolicy})}[vA](t){return Y(this,oa,jv).call(this,{...t,keepAlive:!0})}},La=new WeakMap,Ut=new WeakMap,oa=new WeakSet,qv=async function(t,a){let n=b(this,Ut).streamIndex,r=ME(b(this,Ut).sessionId),o=a?await hj(b(this,La),r,t):await $v(b(this,La),r,t,!1),{sessionId:i,deliveryId:s}=await Fv(o,b(this,Ut).sessionId);if(i!==b(this,Ut).sessionId)throw Error("Message route returned a different session id.");if(t.message!==void 0&&s===void 0)throw Error("Message route did not return a delivery id. Update the server before sending with this client.");return Y(this,oa,Hv).call(this,o,t,n,t.message===void 0?void 0:s)},Hv=function(t,a,n,r){return t.body?.cancel().catch(()=>{}),new _v({cancelTurn:async o=>await this.cancel({turnId:o}),createStream:o=>Y(this,oa,xA).call(this,n,a,r,o),deliveryId:r,sessionId:b(this,Ut).sessionId})},xA=async function*(t,a,n,r){let o=0,i=n===void 0,s=!1,l=new Set;try{for await(let u of r??Y(this,oa,cm).call(this,{headers:a.headers,keepAlive:!0,signal:a.signal,startIndex:t,streamReconnectPolicy:a.streamReconnectPolicy})){if(o+=1,n!==void 0){let c=u.meta?.deliveryIds?.includes(n)===!0,d=u.type==="session.failed"||u.type==="session.completed";if(!c&&d&&(!i||u.type==="session.completed"))throw Error("The session ended before the accepted message reached its turn boundary.");if(!i&&!c||!d&&u.meta?.deliveryIds!==void 0&&!c)continue;i=!0}if(Bi(l,u),s=xn(u)&&(u.type!=="session.waiting"||l.size===0),yield u,s)break}if(n!==void 0&&!s&&!a.signal?.aborted)throw Error("The response stream ended before the accepted message reached its turn boundary.")}finally{Y(this,oa,Vv).call(this,t+o)}},jv=async function*(t){let a=t?.startIndex??b(this,Ut).streamIndex,n=0;for await(let r of Y(this,oa,cm).call(this,{follow:t?.follow,headers:t?.headers,keepAlive:t?.keepAlive,onCaughtUp:t?.onCaughtUp,resolveHeaders:t?.resolveHeaders,resolveReconnectPolicy:t?.resolveReconnectPolicy,signal:t?.signal,startIndex:a,streamReconnectPolicy:t?.streamReconnectPolicy}))n+=1,a>=0&&Y(this,oa,Vv).call(this,a+n),yield r},Vv=function(t){q(this,Ut,{sessionId:b(this,Ut).sessionId,streamIndex:Math.max(b(this,Ut).streamIndex,t)})},cm=function(t){return Uv({onCaughtUp:t.onCaughtUp,follow:t.follow,host:b(this,La).host,keepAlive:t.keepAlive,resolveHeaders:()=>b(this,La).resolveHeaders(t.resolveHeaders?.()??t.headers),path:kv(b(this,Ut).sessionId),redirect:b(this,La).redirect,signal:t.signal,startIndex:t.startIndex,streamReconnectPolicy:t.streamReconnectPolicy,resolveReconnectPolicy:t.resolveReconnectPolicy})},Hi);function bA(e,t){return e[vA](t)}async function hj(e,t,a){let n=Date.now()+2e4,r=250;for(;;){try{return await $v(e,t,a,!1)}catch(o){if(!yj(o))throw o;let i=n-Date.now();if(i<=0)throw o;await Xc(Math.min(r,i),a.signal)}a.signal?.throwIfAborted(),r=Math.min(r*2,2e3)}}async function gj(e,t){let a=await e.resolveHeaders(t.headers),n=await fetch(yr(e.host,Ta),{headers:a,method:"POST",redirect:e.redirect,signal:t.signal??null});if(!n.ok){let r=await n.text();throw new Za(n.status,r,n.headers)}return n}function yj(e){return e instanceof Za&&e.status===409&&e.code==="session_not_ready"}async function $v(e,t,a,n){let r=wj(a,n);if(r===null)throw Error(n?"Creating a session requires a non-empty message.":"A session turn requires a non-empty message or inputResponses.");let o=await e.resolveHeaders(a.headers);o.set("content-type","application/json");let i=await fetch(yr(e.host,t),{body:JSON.stringify(r),headers:o,method:"POST",redirect:e.redirect,signal:a.signal??null});if(!i.ok){let s=await i.text();throw new Za(i.status,s,i.headers)}return i}async function Fv(e,t){let a=await e.json(),n=(typeof a.sessionId=="string"?a.sessionId:void 0)??e.headers.get(UE)?.trim()??t;if(!n)throw Error("Message route did not return a session id.");return{sessionId:n,deliveryId:typeof a.deliveryId=="string"&&a.deliveryId.length>0?a.deliveryId:void 0}}function wj(e,t){let a={};e.message!==void 0&&(a.message=e.message),e.inputResponses!==void 0&&e.inputResponses.length>0&&(a.inputResponses=e.inputResponses),!t&&e.message!==void 0&&e.turnPolicy!==void 0&&(a.turnPolicy=e.turnPolicy),e.message!==void 0&&e.taskDeliveryPolicy!==void 0&&(a.taskDeliveryPolicy=e.taskDeliveryPolicy),e.clientContext!==void 0&&(a.clientContext=e.clientContext);let n=yA(e.outputSchema);return n!==void 0&&(a.outputSchema=n),t&&a.message===void 0||a.message===void 0&&a.inputResponses===void 0?null:a}var ji,SA,Wv=(SA=class{constructor(e){ue(this,ji);q(this,ji,e)}async create(e={}){return"message"in e?await Zc.create(b(this,ji),e):{session:await Zc.prewarm(b(this,ji),e)}}attach(e,t){if(e.length===0)throw Error("sessionId must be a non-empty string.");return new Zc(b(this,ji),{sessionId:e,streamIndex:t?.streamIndex??0})}},ji=new WeakMap,SA);function IA(e,t){let a=new TextEncoder().encode(`${e}:${t}`),n=Array.from(a,r=>String.fromCodePoint(r)).join("");return btoa(n)}var CA=f.object({ok:f.literal(!0),status:f.literal("ready"),workflowId:f.string().min(1)}).strict();var dm=f.discriminatedUnion("kind",[f.object({kind:f.literal("application")}).strict(),f.object({feature:f.string(),kind:f.literal("framework")}).strict(),f.object({kind:f.literal("extension"),namespace:f.string(),packageName:f.string()}).strict()]),LA=f.discriminatedUnion("kind",[f.object({externalDependencies:f.array(f.string()),extensionScope:f.object({namespace:f.string(),sourceRoot:f.string()}).strict().optional(),kind:f.literal("filesystem"),sourcePath:f.string()}).strict(),f.object({dependencies:f.record(f.string(),f.string()).optional(),kind:f.literal("programmatic"),moduleId:f.string(),parameters:f.record(f.string(),f.unknown()).optional(),registryId:f.string(),revision:f.string(),semanticRevision:f.string().optional()}).strict()]),EA=f.object({backing:LA,logicalPath:f.string(),owner:dm}).strict(),Yr=f.object({binding:EA.optional(),exportName:f.string().optional(),logicalPath:f.string(),owner:dm,sourceId:f.string(),sourceKind:f.enum(["markdown","module","skill-package"])}).strict(),Vi=Yr.extend({name:f.string()}).strict(),Jc=Yr.extend({eventNames:f.array(f.string()),slug:f.string()}).strict(),vj=f.discriminatedUnion("kind",[f.object({kind:f.literal("gateway"),target:f.string(),byok:f.string().optional()}).strict(),f.object({kind:f.literal("external"),provider:f.string()}).strict()]),xj=f.union([f.object({kind:f.literal("external"),provider:f.string()}).strict(),f.object({kind:f.literal("chatgpt"),state:f.enum(["checking","ready","signed-out","reauth-required","unavailable"]),accountLabel:f.string().optional()}).strict(),f.object({kind:f.literal("gateway"),connected:f.literal(!0),credential:f.enum(["api-key","oidc","oauth"]),team:f.optional(f.string())}).strict(),f.object({kind:f.literal("gateway"),connected:f.literal(!1)}).strict()]),kA={contextWindowTokens:f.number().optional(),providerOptions:f.unknown().optional(),reasoning:f.enum(["provider-default","none","minimal","low","medium","high","xhigh"]).optional().catch(void 0),source:Yr.optional()},bj=f.union([f.object({...kA,endpoint:xj.optional(),id:f.string(),routing:vj}).strict(),f.object({...kA,endpoint:f.never().optional(),id:f.never().optional(),routing:f.object({kind:f.literal("dynamic"),resolver:Jc}).strict()}).strict()]),Sj=Vi.extend({description:f.string(),hasAuth:f.boolean(),hasExecute:f.boolean(),hasModelOutputProjection:f.boolean(),hasOutputSchema:f.boolean(),inputSchema:f.unknown(),outputSchema:f.unknown().optional(),requiresApproval:f.boolean()}).strict(),Ij=Vi.extend({description:f.string(),license:f.string().optional(),markdown:f.string(),metadata:f.record(f.string(),f.string()).optional()}).strict(),Cj=Vi.extend({content:f.string(),role:f.enum(["system","user"])}).strict(),kj=Vi.extend({cron:f.string(),hasRun:f.boolean(),markdown:f.string().optional()}).strict(),AA=f.enum(["GET","HEAD","POST","PUT","PATCH","DELETE","OPTIONS","WEBSOCKET"]),Tj=Vi.extend({adapterKind:f.string().optional(),method:AA,urlPath:f.string()}).strict(),Lj=f.object({backing:f.union([LA,f.object({kind:f.literal("resource"),sourcePath:f.string()}).strict()]),form:f.enum(["derived","direct"]),layer:f.enum(["framework-default","extension-package","extension-override","application"]),logicalPath:f.string(),owner:dm,sourceId:f.string()}).strict(),Ej=f.object({method:AA,source:Lj,urlPath:f.string(),winnerSourceId:f.string()}).strict(),Aj=Yr.extend({connectionName:f.string(),description:f.string(),hasApproval:f.boolean(),hasAuthorization:f.boolean(),hasHeaders:f.boolean(),protocol:f.string(),toolFilter:f.unknown().optional(),url:f.string()}).strict(),Mj=Yr.extend({eventNames:f.array(f.string()),slug:f.string()}).strict(),Rj=Yr.extend({description:f.string().optional(),slot:f.string(),visibility:f.enum(["scope","session"])}).strict(),Dj=Yr.extend({provider:f.string().optional(),environmentExportName:f.string().optional(),revisionHash:f.string()}).strict(),_j=Vi.extend({configResolver:Jc.optional(),description:f.string().optional(),entryPath:f.string(),nodeId:f.string(),parentNodeId:f.string(),rootPath:f.string(),summary:f.object({channels:f.number(),connections:f.number(),hooks:f.number(),instructions:f.number(),memories:f.number(),schedules:f.number(),skills:f.number(),tools:f.number()}).strict()}).strict(),Pj=Vi.extend({description:f.string(),nodeId:f.string(),parentNodeId:f.string(),url:f.string().optional()}).strict(),Oj=f.object({action:f.enum(["subagent-call","task-cancel","workflow-tool-call"]).optional(),audience:f.array(f.enum(["root-session","delegated-task-child"])),kind:f.enum(["dispatch","provider-tool"]),sourceId:f.string()}).strict(),TA=f.object({kind:f.enum(["disabled","shadowed"]),logicalPath:f.string(),owner:dm,sourceId:f.string(),winnerSourceId:f.string().optional()}).strict(),MA=f.object({agent:f.object({agentRoot:f.string(),appRoot:f.string(),config:Yr.extend({binding:EA}).strict(),description:f.string().optional(),model:bj,name:f.string(),nodeId:f.string(),outputSchema:f.unknown().optional()}).strict(),capabilities:f.object({devRoutes:f.boolean()}).strict(),channels:f.object({routes:f.array(Tj),shadowed:f.array(Ej)}).strict(),composition:f.object({disabled:f.array(TA),shadowed:f.array(TA)}).strict(),connections:f.array(Aj),diagnostics:f.object({discoveryErrors:f.number(),discoveryWarnings:f.number()}).strict(),hooks:f.array(Mj),instructions:f.object({dynamic:f.array(Jc),static:f.array(Cj)}).strict(),instrumentation:Yr.optional(),kernelEffects:f.array(Oj),kind:f.literal("eve-agent-info"),memories:f.array(Rj),mode:f.enum(["development","production"]),remoteAgents:f.object({entries:f.array(Pj),total:f.number()}).strict(),sandbox:Dj,schedules:f.array(kj),skills:f.object({dynamic:f.array(Jc),static:f.array(Ij)}).strict(),subagents:f.object({local:f.array(_j),total:f.number()}).strict(),tools:f.object({dynamic:f.array(Jc),static:f.array(Sj)}).strict(),version:f.literal(5),workspace:f.object({resourceRoot:f.unknown(),rootEntries:f.array(f.string())}).strict()}).strict().superRefine((e,t)=>{let a=(o,i,s)=>{let l=new Set;o.forEach((u,c)=>{let d=i(u);l.has(d)&&t.addIssue({code:"custom",message:`Duplicate public identity "${d}".`,path:[...s,c]}),l.add(d)})},n=(o,i,s)=>{(!Number.isSafeInteger(o)||o<0||o!==i.length)&&t.addIssue({code:"custom",message:`Expected total ${i.length}, received ${o}.`,path:[...s]})};a(e.tools.static,o=>o.name,["tools","static"]),a(e.tools.dynamic,o=>o.slug,["tools","dynamic"]),a(e.skills.static,o=>o.name,["skills","static"]),a(e.skills.dynamic,o=>o.slug,["skills","dynamic"]),a(e.instructions.static,o=>o.name,["instructions","static"]),a(e.instructions.dynamic,o=>o.slug,["instructions","dynamic"]),a(e.schedules,o=>o.name,["schedules"]),a(e.connections,o=>o.connectionName,["connections"]),a(e.hooks,o=>o.slug,["hooks"]),a(e.memories,o=>o.slot,["memories"]),a(e.channels.routes,o=>`${o.method} ${Nj(o.urlPath)}`,["channels","routes"]),a(e.subagents.local,o=>o.nodeId,["subagents","local"]),a(e.remoteAgents.entries,o=>o.nodeId,["remoteAgents","entries"]),n(e.subagents.total,e.subagents.local,["subagents","total"]),n(e.remoteAgents.total,e.remoteAgents.entries,["remoteAgents","total"]);let r=[[e.agent.config,["agent","config"]],...e.agent.model.source===void 0?[]:[[e.agent.model.source,["agent","model","source"]]],...e.agent.model.routing.kind==="dynamic"?[[e.agent.model.routing.resolver,["agent","model","routing","resolver"]]]:[],...e.channels.routes.map((o,i)=>[o,["channels","routes",i]]),...e.connections.map((o,i)=>[o,["connections",i]]),...e.hooks.map((o,i)=>[o,["hooks",i]]),...e.instructions.dynamic.map((o,i)=>[o,["instructions","dynamic",i]]),...e.instructions.static.map((o,i)=>[o,["instructions","static",i]]),...e.memories.map((o,i)=>[o,["memories",i]]),...e.instrumentation===void 0?[]:[[e.instrumentation,["instrumentation"]]],...e.remoteAgents.entries.map((o,i)=>[o,["remoteAgents","entries",i]]),...e.schedules.map((o,i)=>[o,["schedules",i]]),...e.skills.dynamic.map((o,i)=>[o,["skills","dynamic",i]]),...e.skills.static.map((o,i)=>[o,["skills","static",i]]),...e.subagents.local.flatMap((o,i)=>o.configResolver===void 0?[]:[[o.configResolver,["subagents","local",i,"configResolver"]]]),...e.tools.dynamic.map((o,i)=>[o,["tools","dynamic",i]]),...e.tools.static.map((o,i)=>[o,["tools","static",i]]),[e.sandbox,["sandbox"]]];for(let[o,i]of r){if(o.sourceKind==="module"&&o.binding===void 0){t.addIssue({code:"custom",message:"Module source is missing its compiled binding.",path:[...i,"binding"]});continue}if(o.sourceKind!=="module"&&o.binding!==void 0){t.addIssue({code:"custom",message:`${o.sourceKind} source cannot carry a module binding.`,path:[...i,"binding"]});continue}o.binding!==void 0&&(o.binding.logicalPath!==o.logicalPath&&t.addIssue({code:"custom",message:"Source and binding logical paths do not match.",path:[...i,"binding","logicalPath"]}),JSON.stringify(o.binding.owner)!==JSON.stringify(o.owner)&&t.addIssue({code:"custom",message:"Source and binding owners do not match.",path:[...i,"binding","owner"]}))}});function Nj(e){return e.replace(/^\/+|\/+$/g,"").split("/").map(t=>t.startsWith(":")||/^\[[^\]]+\]$/.test(t)?":":t).join("/")}var RA="x-vercel-trusted-oidc-idp-token";var Qc,ed,$i,Wi,jo,fm,PA,_A,Xv=(_A=class{constructor(e){ue(this,jo);ue(this,Qc);ue(this,ed);ue(this,$i);ue(this,Wi);K(this,"sessions");q(this,$i,e.host),q(this,Qc,e.auth),q(this,ed,e.headers),q(this,Wi,e.redirect),this.sessions=new Wv({host:b(this,$i),redirect:b(this,Wi),resolveHeaders:t=>Y(this,jo,fm).call(this,t)})}async health(){let e=yr(b(this,$i),EE),t=await Y(this,jo,fm).call(this),a=await fetch(e,DA({headers:t},b(this,Wi)));if(!a.ok){let o=await a.text();throw new Za(a.status,o,a.headers)}let n;try{n=await a.json()}catch{throw new sm}let r=CA.safeParse(n);if(!r.success)throw new sm(r.error.issues.slice(0,5).map(o=>{let i=o.path.join(".");return i.length===0?o.message:`${i}: ${o.message}`}));return r.data}async info(e={}){let t=await this.fetch(AE,e);if(!t.ok){let r=await t.text();throw new Za(t.status,r,t.headers)}let a;try{a=await t.json()}catch{throw new im}let n=MA.safeParse(a);if(!n.success)throw new im(n.error.issues.slice(0,5).map(r=>{let o=r.path.join(".");return o.length===0?r.message:`${o}: ${r.message}`}));return n.data}async fetch(e,t={}){let a=yr(b(this,$i),e),n=await Y(this,jo,fm).call(this,Bj(t.headers));return await fetch(a,DA({...t,headers:n},b(this,Wi)))}},Qc=new WeakMap,ed=new WeakMap,$i=new WeakMap,Wi=new WeakMap,jo=new WeakSet,fm=async function(e){let t=new Headers,[a,n]=await Promise.all([Uj(b(this,ed)),Y(this,jo,PA).call(this)]);for(let[r,o]of Object.entries(a))t.set(r,o);for(let[r,o]of Object.entries(n))t.set(r,o);if(e)for(let[r,o]of Object.entries(e))t.set(r,o);return t},PA=async function(){let e=b(this,Qc);if(!e)return{};if("vercelOidc"in e){let t=(await Gv(e.vercelOidc.token)).trim();return t.length===0?{}:{authorization:`Bearer ${t}`,[RA]:t}}if("bearer"in e){let t=(await Gv(e.bearer)).trim();return t.length===0?{}:{authorization:`Bearer ${t}`}}if("basic"in e){let t=await Gv(e.basic.password);return{authorization:`Basic ${IA(e.basic.username,t)}`}}return{}},_A);async function Gv(e){return typeof e=="function"?e():e}async function Uj(e){return e===void 0?{}:typeof e=="function"?await e():e}function Bj(e){return e===void 0?{}:Object.fromEntries(new Headers(e).entries())}function DA(e,t){return t===void 0?e:{...e,redirect:t}}function Kv(){let e=new Set;return{admit(t){let a=t.meta?.id;return a===void 0||!e.has(a)&&(e.add(a),!0)},get size(){return e.size}}}var Gi,Xi,Zr,Ki,td,ad,nd,El,pm,OA,UA=(OA=class{constructor(e,t){ue(this,El);ue(this,Gi,new AbortController);ue(this,Xi,new Set);ue(this,Zr,Promise.withResolvers());K(this,"caughtUp",b(this,Zr).promise);ue(this,Ki,!1);ue(this,td);ue(this,ad);ue(this,nd);this.setOptions(t),this.caughtUp.catch(()=>{}),t.catchUp||b(this,Zr).resolve(),(async()=>{try{for await(let a of bA(e,{signal:b(this,Gi).signal,resolveHeaders:()=>b(this,ad),resolveReconnectPolicy:()=>b(this,nd),startIndex:t.startIndex,onCaughtUp:t.catchUp?()=>b(this,Zr).resolve():void 0})){if(b(this,Gi).signal.aborted)return;t.onEvent(a);for(let n of b(this,Xi))n.push(a);if(a.type==="session.completed"||a.type==="session.failed")break}b(this,Zr).resolve(),Y(this,El,pm).call(this)}catch(a){b(this,Zr).reject(a),Y(this,El,pm).call(this,a),b(this,Gi).signal.aborted||t.onError(a)}})()}subscribe(e){let t=new zj(()=>b(this,Xi).delete(t),e);return b(this,Ki)?t.end(b(this,td)):b(this,Xi).add(t),t}get ended(){return b(this,Ki)}setOptions(e){"headers"in e&&q(this,ad,e.headers),"streamReconnectPolicy"in e&&q(this,nd,e.streamReconnectPolicy)}close(){let e=new DOMException("Session stream was detached.","AbortError");b(this,Gi).abort(e),b(this,Zr).reject(e),Y(this,El,pm).call(this,e)}},Gi=new WeakMap,Xi=new WeakMap,Zr=new WeakMap,Ki=new WeakMap,td=new WeakMap,ad=new WeakMap,nd=new WeakMap,El=new WeakSet,pm=function(e){if(!b(this,Ki)){q(this,Ki,!0),q(this,td,e);for(let t of b(this,Xi))t.end(e)}},OA),Vo,Yi,Zi,Al,rd,NA,zj=(NA=class{constructor(e,t){ue(this,Vo,[]);ue(this,Yi,Promise.withResolvers());ue(this,Zi,!1);ue(this,Al);ue(this,rd);let a=()=>this.end(t?.reason);t?.addEventListener("abort",a,{once:!0}),q(this,rd,()=>{t?.removeEventListener("abort",a),e()}),t?.aborted&&a()}push(e){b(this,Zi)||(b(this,Vo).push(e),b(this,Yi).resolve())}end(e){b(this,Zi)||(q(this,Zi,!0),q(this,Al,e),b(this,Yi).resolve())}[Symbol.dispose](){this.end(),q(this,Vo,[]),b(this,rd).call(this)}discard(){q(this,Vo,[])}async*[Symbol.asyncIterator](){for(;;){for(;b(this,Vo).length>0;)yield b(this,Vo).shift();if(b(this,Zi)){if(b(this,Al)!==void 0)throw b(this,Al);return}q(this,Yi,Promise.withResolvers()),await b(this,Yi).promise}}},Vo=new WeakMap,Yi=new WeakMap,Zi=new WeakMap,Al=new WeakMap,rd=new WeakMap,NA);var $o,Ja,vr,Ml,mm,BA,zA=(BA=class{constructor(e,t){ue(this,Ml);ue(this,$o);ue(this,Ja);ue(this,vr);q(this,$o,e),q(this,Ja,t),q(this,vr,Y(this,Ml,mm).call(this))}get data(){return b(this,vr)}reset(){q(this,Ja,[]),q(this,vr,b(this,$o).initial())}append(e){q(this,Ja,[...b(this,Ja),e]),q(this,vr,b(this,$o).reduce(b(this,vr),e))}remove(e){q(this,Ja,b(this,Ja).filter(t=>!e(t))),q(this,vr,Y(this,Ml,mm).call(this))}replace(e,t){let a=b(this,Ja).findIndex(e);q(this,Ja,a===-1?[...b(this,Ja),t]:b(this,Ja).map((n,r)=>r===a?t:n)),q(this,vr,Y(this,Ml,mm).call(this))}},$o=new WeakMap,Ja=new WeakMap,vr=new WeakMap,Ml=new WeakSet,mm=function(){let e=b(this,$o).initial();for(let t of b(this,Ja))e=b(this,$o).reduce(e,t);return e},BA);function qA(e){let t=e.at(-1);return t!==void 0&&xn(t)&&(t.type!=="session.waiting"||Fj(e).size===0)}function Fj(e){let t=new Set;for(let a of e)Bi(t,a);return t}function Yv(e){if(e.message!==void 0==(e.inputResponses!==void 0))throw Error("A turn requires exactly one of message or inputResponses.")}var FA=0;function HA(){let e=globalThis.crypto?.randomUUID;return e===void 0?(FA+=1,`submission_${FA.toString()}`):e.call(globalThis.crypto)}function od(e,t){return e?AbortSignal.any([e,t]):t}function jA(e){if(typeof e=="string")return e;let t=[];for(let a of e)a.type==="text"?t.push(a.text):a.type==="file"&&t.push(a.filename?`[file: ${a.filename}]`:"[file]");return t.join(`
|
|
141
141
|
`)}function Zv(e){return e instanceof Error&&e.name==="AbortError"}function VA(e){if(e.type!=="session.failed")return;let t=Error(e.data.message);return t.name=e.data.code,t}function Jv(e){let t=Promise.withResolvers(),a=Promise.withResolvers(),n={abortController:new AbortController,acceptedFollowUps:0,cancel:()=>e(n),completion:a.promise,followUpDispatches:new Set,receivedFollowUps:0,receivedFollowUpEvents:new Map,followUpSubmissionIds:new Set,resolveCompletion:a.resolve,response:t.promise,resolveResponse:t.resolve};return n}async function Qv(e,t,a){for(;e.followUpDispatches.size>0;)await Promise.allSettled(e.followUpDispatches);if(!(e.receivedFollowUps>=e.acceptedFollowUps))for await(let n of t){if(!a())return;if(e.receivedFollowUps+=e.receivedFollowUpEvents.get(n)??0,e.receivedFollowUpEvents.delete(n),xn(n)){for(;e.followUpDispatches.size>0;)await Promise.allSettled(e.followUpDispatches);if(e.receivedFollowUps>=e.acceptedFollowUps)return}}}async function id(e,t){if(t===void 0)return await e;let a=Promise.withResolvers(),n=()=>a.reject(t.reason);t.addEventListener("abort",n,{once:!0}),t.aborted&&n();try{return await Promise.race([a.promise,e])}finally{t.removeEventListener("abort",n)}}var sd,Qn,Sa,Wo,ex,tx,$A,WA=($A=class{constructor(e,t){ue(this,Wo);ue(this,sd);ue(this,Qn);ue(this,Sa,[]);q(this,Qn,e),q(this,sd,t)}reset(){q(this,Sa,[])}submit(e,t){if(e.message===void 0)return;let a={createdAt:Date.now(),eventStartIndex:t,id:HA(),message:jA(e.message),requiresDeliveryId:!0};return q(this,Sa,[...b(this,Sa),a]),b(this,sd)&&b(this,Qn).append({data:{createdAt:a.createdAt,message:a.message,submissionId:a.id},type:"client.message.submitted"}),a.id}apply(e){if(e.type!=="message.received"){b(this,Qn).append(e);return}if(e.data.kind==="execution.background_task"){b(this,Qn).append(e);return}let t=Y(this,Wo,ex).call(this,e);if(t.length===0){b(this,Qn).append(e);return}return Y(this,Wo,tx).call(this,t,e,!1)}correlate(e,t,a){if(e===void 0)return;q(this,Sa,b(this,Sa).map(r=>r.id===e?{...r,deliveryId:t,requiresDeliveryId:t!==void 0}:r));let n=b(this,Sa).find(r=>r.id===e);if(n!==void 0)for(let r of a.slice(n.eventStartIndex)){if(r.type!=="message.received"||r.data.kind==="execution.background_task")continue;let o=Y(this,Wo,ex).call(this,r);if(o.some(i=>i.id===e))return Y(this,Wo,tx).call(this,o,r,!0)}}fail(e,t){let a=t===void 0?b(this,Sa)[0]:b(this,Sa).find(n=>n.id===t);a!==void 0&&(q(this,Sa,b(this,Sa).filter(n=>n.id!==a.id)),b(this,Qn).replace(n=>n.type==="client.message.submitted"&&n.data.submissionId===a.id,{data:{createdAt:a.createdAt,error:{message:e.message},message:a.message,submissionId:a.id},type:"client.message.failed"}))}failAll(e){for(let t of b(this,Sa))this.fail(e,t.id)}},sd=new WeakMap,Qn=new WeakMap,Sa=new WeakMap,Wo=new WeakSet,ex=function(e){return b(this,Sa).filter(t=>t.deliveryId===void 0?!t.requiresDeliveryId:e.meta.deliveryIds?.includes(t.deliveryId)===!0)},tx=function(e,t,a){let n=e.map(o=>o.id),r=new Set(n);return q(this,Sa,b(this,Sa).filter(o=>!r.has(o.id))),a||b(this,Qn).replace(o=>o.type==="client.message.submitted"&&o.data.submissionId===n[0],t),b(this,Qn).remove(o=>o.type==="client.message.submitted"&&r.has(o.data.submissionId)),{alreadyProjected:a,event:t,ids:n}},$A);var qj=Symbol("detachEveAgentStore"),Hj=Symbol("attachEveAgentStore"),Go,Dl,_l,Qa,Xo,Ji,ld,Ko,Pl,Ol,_t,ha,It,Aa,en,Nn,er,Qi,xr,xt,Yo,mt,se,ax,XA,KA,YA,Rl,nx,rx,Ia,ZA,JA,hm,ox,ix,Ea,GA,sx=(GA=class{constructor(e){ue(this,se);ue(this,Go);ue(this,Dl);ue(this,_l,!1);ue(this,Qa);ue(this,Xo,new Set);ue(this,Ji);ue(this,ld);ue(this,Ko);ue(this,Pl,new Set);ue(this,Ol,Kv());ue(this,_t);ue(this,ha,{});ue(this,It);ue(this,Aa);ue(this,en);ue(this,Nn,0);ue(this,er);ue(this,Qi);ue(this,xr);ue(this,xt);ue(this,Yo);ue(this,mt,"ready");q(this,Dl,e.prewarm??!1),q(this,Ji,e.session!==void 0),q(this,Go,b(this,Ji)?void 0:new Xv({auth:e.auth,headers:e.headers,host:e.host??""}));let t=[];for(let a of e.initialEvents??[])b(this,Ol).admit(a)&&t.push(a),Bi(b(this,Xo),a);q(this,Aa,t),q(this,Ko,new zA(e.reducer,b(this,Aa))),q(this,ld,e.optimistic??!0),q(this,en,new WA(b(this,Ko),b(this,ld))),q(this,xt,e.session??(e.initialSession===void 0?void 0:b(this,Go)?.sessions.attach(e.initialSession.sessionId,{streamIndex:e.initialSession.streamIndex}))),q(this,Yo,Y(this,se,ix).call(this))}get snapshot(){return b(this,Yo)}setCallbacks(e){q(this,ha,e)}subscribe(e){return b(this,Pl).add(e),()=>{b(this,Pl).delete(e)}}prewarm(){if(b(this,er)!==void 0)return b(this,er);if(b(this,xt)!==void 0||b(this,Ji))return Promise.resolve();if(b(this,_t)!==void 0)return b(this,_t).response.then(o=>{if(o===void 0)throw b(this,It)??new DOMException("Session creation was aborted.","AbortError")});let e=b(this,Go);if(e===void 0)return Promise.reject(Error("This eve agent store does not own a session client."));let t=b(this,Nn),a=new AbortController;q(this,Qi,a);let n=(async()=>{try{let o=await e.sessions.create({signal:a.signal});if(t!==b(this,Nn))return;q(this,xt,o.session),q(this,It,void 0),b(this,mt)==="error"&&q(this,mt,"ready"),b(this,ha).onSessionChange?.(o.session.state),Y(this,se,Ea).call(this),Y(this,se,Rl).call(this)}catch(o){throw t===b(this,Nn)&&b(this,_t)===void 0&&b(this,It)===void 0&&(q(this,It,Ui(o)),q(this,mt,"error"),b(this,ha).onError?.(b(this,It)),Y(this,se,Ea).call(this)),o}})();q(this,er,n);let r=()=>{b(this,er)===n&&(q(this,er,void 0),q(this,Qi,void 0))};return n.then(r,r),n}async send(e){return await Y(this,se,ax).call(this,e,b(this,ha).prepareSend)}resume(){if(b(this,xr)!==void 0)return b(this,xr);let e=Y(this,se,XA).call(this);q(this,xr,e);let t=()=>{b(this,xr)===e&&q(this,xr,void 0)};return e.then(t,t),e}cancel(){let e=b(this,_t);return e===void 0?b(this,mt)==="streaming"&&b(this,xt)!==void 0?b(this,xt).cancel():Promise.resolve({status:"no_active_turn"}):e.cancel()}[Hj](){q(this,_l,!0),b(this,Dl)&&b(this,xt)===void 0&&this.prewarm().catch(()=>{})}[qj](){q(this,_l,!1),b(this,Qa)?.close(),q(this,Qa,void 0),b(this,_t)?.abortController.abort(),Y(this,se,nx).call(this),q(this,xr,void 0)}reset(){b(this,Qa)?.close(),q(this,Qa,void 0),b(this,Xo).clear();let e=b(this,_t);q(this,_t,void 0),e?.resolveResponse(void 0),e?.resolveCompletion(),e?.abortController.abort(),Y(this,se,nx).call(this),q(this,xr,void 0),b(this,Ji)||q(this,xt,void 0),q(this,Aa,[]),q(this,Ol,Kv()),b(this,en).reset(),b(this,Ko).reset(),q(this,It,void 0),q(this,mt,"ready"),b(this,ha).onSessionChange?.(b(this,xt)?.state),Y(this,se,Ea).call(this),b(this,Dl)&&b(this,_l)&&this.prewarm().catch(()=>{})}},Go=new WeakMap,Dl=new WeakMap,_l=new WeakMap,Qa=new WeakMap,Xo=new WeakMap,Ji=new WeakMap,ld=new WeakMap,Ko=new WeakMap,Pl=new WeakMap,Ol=new WeakMap,_t=new WeakMap,ha=new WeakMap,It=new WeakMap,Aa=new WeakMap,en=new WeakMap,Nn=new WeakMap,er=new WeakMap,Qi=new WeakMap,xr=new WeakMap,xt=new WeakMap,Yo=new WeakMap,mt=new WeakMap,se=new WeakSet,ax=async function(e,t){if(b(this,_t)!==void 0){if(b(this,mt)==="resuming")throw Error("eve session is resuming.");return await Y(this,se,KA).call(this,b(this,_t),e,t)}let a=Jv(r=>r.acceptedFollowUps>0&&b(this,xt)!==void 0?b(this,xt).cancel():r.response.then(o=>o===void 0?{status:"no_active_turn"}:o.cancel()));q(this,_t,a),q(this,It,void 0),q(this,mt,"submitted"),Y(this,se,Ea).call(this);let n;try{let r=await(t===void 0?e:id(Promise.resolve(t(e)),od(e.signal,a.abortController.signal)));if(Yv(r),!Y(this,se,Ia).call(this,a))return;let o=b(this,en).submit(r,b(this,Aa).length);Y(this,se,ZA).call(this,r),Y(this,se,Ea).call(this);let i={...r,signal:od(r.signal,a.abortController.signal)},s=await Y(this,se,YA).call(this,i),l=s.response;if(n=s.reader,!Y(this,se,Ia).call(this,a))return;a.resolveResponse(l),Y(this,se,hm).call(this,b(this,en).correlate(o,Pv(l),b(this,Aa)))&&Y(this,se,Ea).call(this);for await(let u of XE(l,n)){if(!Y(this,se,Ia).call(this,a))return;a.receivedFollowUps+=a.receivedFollowUpEvents.get(u)??0,a.receivedFollowUpEvents.delete(u)}if(!Y(this,se,Ia).call(this,a)||(await Qv(a,n,()=>Y(this,se,Ia).call(this,a)),!Y(this,se,Ia).call(this,a)))return;q(this,mt,b(this,It)===void 0?"ready":"error")}catch(r){if(!Y(this,se,Ia).call(this,a))return;if(Zv(r))q(this,mt,"ready"),b(this,en).fail(Ui(r));else{let o=b(this,It)!==void 0;b(this,It)??q(this,It,Ui(r)),q(this,mt,"error"),b(this,en).fail(b(this,It)),o||b(this,ha).onError?.(b(this,It))}}finally{n?.[Symbol.dispose](),Y(this,se,rx).call(this,a)}},XA=async function(){if(b(this,mt)==="resuming"||b(this,mt)==="streaming"||b(this,mt)==="submitted")throw Error("eve session is already processing a turn.");if(b(this,xt)===void 0)throw Error("An eve session is required before resuming.");let e=b(this,xt),t=Jv(()=>e.cancel());q(this,_t,t),t.resolveResponse(void 0),q(this,It,void 0),q(this,mt,"resuming"),Y(this,se,Ea).call(this);let a;try{let n=Y(this,se,Rl).call(this,{catchUp:!0,startIndex:b(this,Aa).length===e.state.streamIndex?e.state.streamIndex:0});if(a=n.subscribe(t.abortController.signal),await n.caughtUp,!Y(this,se,Ia).call(this,t))return;a.discard();let r=b(this,Aa).at(-1);if(r!==void 0&&Y(this,se,ox).call(this,r),r!==void 0&&b(this,It)===void 0&&!qA(b(this,Aa))){q(this,mt,"streaming"),Y(this,se,Ea).call(this);for await(let o of a){if(!Y(this,se,Ia).call(this,t))return;if(t.receivedFollowUps+=t.receivedFollowUpEvents.get(o)??0,t.receivedFollowUpEvents.delete(o),xn(o)&&b(this,Xo).size===0)break}}await Qv(t,a,()=>Y(this,se,Ia).call(this,t)),Y(this,se,Ia).call(this,t)&&q(this,mt,b(this,It)===void 0?"ready":"error")}catch(n){if(!Y(this,se,Ia).call(this,t))return;Zv(n)?q(this,mt,"ready"):(q(this,It,Ui(n)),q(this,mt,"error"),b(this,ha).onError?.(b(this,It)))}finally{a?.[Symbol.dispose](),Y(this,se,rx).call(this,t)}},KA=async function(e,t,a){if(t.message===void 0||t.turnPolicy!=="steer")throw Error('eve session is already processing a turn. Send a message with turnPolicy: "steer" to guide it at the next boundary.');let n=b(this,Nn),r=od(t.signal,e.abortController.signal),o=await id(Promise.resolve(a?.(t)),r)??t;if(n!==b(this,Nn))return;if(Yv(o),o.message===void 0||o.turnPolicy!=="steer")throw Error('An in-flight follow-up requires a message with turnPolicy: "steer".');if(!Y(this,se,Ia).call(this,e))return await Y(this,se,ax).call(this,o);let i=b(this,en).submit(o,b(this,Aa).length);i!==void 0&&e.followUpSubmissionIds.add(i),Y(this,se,Ea).call(this),Y(this,se,Rl).call(this,{headers:o.headers,streamReconnectPolicy:o.streamReconnectPolicy});let s;s=(async()=>{try{let l=od(o.signal,e.abortController.signal);if(await id(e.response,l),!Y(this,se,Ia).call(this,e)||b(this,xt)===void 0)throw Error("The active eve turn ended before the follow-up could be sent.");let{message:u,...c}=o,d=await b(this,xt).send(u,{...c,signal:l});e.acceptedFollowUps+=1,Y(this,se,hm).call(this,b(this,en).correlate(i,Pv(d),b(this,Aa)))&&Y(this,se,Ea).call(this)}catch(l){throw Y(this,se,Ia).call(this,e)&&(b(this,en).fail(Ui(l),i),Y(this,se,Ea).call(this)),l}finally{e.followUpDispatches.delete(s)}})(),e.followUpDispatches.add(s),await s,await e.completion},YA=async function(e){let t={headers:e.headers,streamReconnectPolicy:e.streamReconnectPolicy};if(b(this,er)!==void 0&&(await id(b(this,er).catch(n=>{if(b(this,xt)!==void 0)throw n}),e.signal),e.signal?.throwIfAborted()),b(this,xt)===void 0){if(b(this,Go)===void 0)throw Error("An external eve session is required before sending.");if(e.message===void 0)throw Error("Cannot answer an input request before the session starts.");let n=await b(this,Go).sessions.create({...e,message:e.message});return e.signal?.throwIfAborted(),q(this,xt,n.session),b(this,ha).onSessionChange?.(n.session.state),Y(this,se,Ea).call(this),{response:n.response,reader:Y(this,se,Rl).call(this,t).subscribe(e.signal)}}let a=Y(this,se,Rl).call(this,t).subscribe(e.signal);try{if(e.inputResponses===void 0){let{message:o,...i}=e;return{response:await b(this,xt).send(o,i),reader:a}}let{inputResponses:n,...r}=e;return{response:await b(this,xt).respond(n,r),reader:a}}catch(n){throw a[Symbol.dispose](),n}},Rl=function(e={}){if(b(this,Qa)!==void 0&&!b(this,Qa).ended)return b(this,Qa).setOptions(e),b(this,Qa);if(b(this,xt)===void 0)throw Error("A session is required before opening its stream.");let t=b(this,xt),a=b(this,Nn);return q(this,Qa,new UA(t,{...e,onEvent:n=>{a===b(this,Nn)&&Y(this,se,JA).call(this,n)},onError:n=>{a===b(this,Nn)&&(q(this,Qa,void 0),b(this,_t)===void 0&&(q(this,It,Ui(n)),q(this,mt,"error"),b(this,ha).onError?.(b(this,It)),Y(this,se,Ea).call(this)))}})),b(this,Qa)},nx=function(){q(this,Nn,b(this,Nn)+1),b(this,Qi)?.abort(),q(this,Qi,void 0),q(this,er,void 0)},rx=function(e){if(Y(this,se,Ia).call(this,e)){e.resolveResponse(void 0),q(this,_t,void 0);try{b(this,ha).onSessionChange?.(b(this,xt)?.state),Y(this,se,Ea).call(this),b(this,ha).onFinish?.(b(this,Yo))}finally{e.resolveCompletion()}}},Ia=function(e){return b(this,_t)===e},ZA=function(e){e.inputResponses!==void 0&&e.inputResponses.length!==0&&b(this,Ko).append({data:{createdAt:Date.now(),responses:e.inputResponses},type:"client.input.responded"})},JA=function(e){if(!b(this,Ol).admit(e))return;let t=b(this,mt)==="streaming";Bi(b(this,Xo),e),q(this,Aa,[...b(this,Aa),e]),Y(this,se,hm).call(this,b(this,en).apply(e)),b(this,ha).onEvent?.(e),Y(this,se,ox).call(this,e);let a=xn(e)&&b(this,Xo).size===0;b(this,mt)!=="resuming"&&b(this,It)===void 0&&("data"in e&&"turnId"in e.data&&q(this,mt,"streaming"),b(this,_t)===void 0&&a&&q(this,mt,"ready")),b(this,ha).onSessionChange?.(b(this,xt)?.state),b(this,mt)!=="resuming"&&Y(this,se,Ea).call(this),b(this,_t)===void 0&&t&&a&&b(this,ha).onFinish?.(b(this,Yo))},hm=function(e){if(e===void 0)return!1;let t=0;for(let a of e.ids)b(this,_t)?.followUpSubmissionIds.delete(a)&&(t+=1);if(t>0&&b(this,_t)!==void 0)if(e.alreadyProjected)b(this,_t).receivedFollowUps+=t;else{let a=b(this,_t).receivedFollowUpEvents.get(e.event)??0;b(this,_t).receivedFollowUpEvents.set(e.event,a+t)}return!0},ox=function(e){let t=VA(e);t!==void 0&&(q(this,mt,"error"),b(this,en).failAll(t),b(this,It)===void 0&&(q(this,It,t),b(this,ha).onError?.(t)))},ix=function(){return{data:b(this,Ko).data,error:b(this,It),events:b(this,Aa),session:b(this,xt)?.state,status:b(this,mt)}},Ea=function(){q(this,Yo,Y(this,se,ix).call(this));for(let e of b(this,Pl))e()},GA);function jj(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}}function Vj(e){let t=new AbortController;for(let a of e){if(a.aborted)return t.abort(a.reason),t.signal;a.addEventListener("abort",()=>t.abort(a.reason),{once:!0,signal:t.signal})}return t.signal}function QA(){"withResolvers"in Promise||Object.defineProperty(Promise,"withResolvers",{value:jj,configurable:!0,writable:!0}),"any"in AbortSignal||Object.defineProperty(AbortSignal,"any",{value:Vj,configurable:!0,writable:!0})}var $j=3e4;function Wj(){let e=crypto.getRandomValues(new Uint8Array(32));return btoa(String.fromCharCode(...e)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function ux(e){let t=e.channelId??"";return e.threadId===void 0?t:`${t}:${e.threadId}`}function lx(e){return`waniwani:eve-conversation:${e}`}function cx(e){try{let t=JSON.parse(localStorage.getItem(lx(e))??"null");return typeof t=="object"&&t!==null&&"conversationId"in t&&typeof t.conversationId=="string"&&"ownerSecret"in t&&typeof t.ownerSecret=="string"?{conversationId:t.conversationId,ownerSecret:t.ownerSecret}:null}catch{return null}}function Ul(e,t){try{t?localStorage.setItem(lx(e),JSON.stringify(t)):localStorage.removeItem(lx(e))}catch{}}function eM(e){return JSON.stringify(e).replace(/[\u007f-\uffff]/g,t=>`\\u${t.charCodeAt(0).toString(16).padStart(4,"0")}`)}function Gj(e){return{...e.documents?.length?{"x-waniwani-documents":eM(e.documents)}:{},...e.extra&&Object.keys(e.extra).length>0?{"x-waniwani-extra":eM(e.extra)}:{}}}var Xj={initial:()=>{},reduce:()=>{}},Nl=class e{constructor(t,a,n){this.open=t;this.secret=a;K(this,"grant");K(this,"refreshing",null);K(this,"store");K(this,"forward");K(this,"caughtUp");K(this,"used",!1);this.grant=n,QA(),this.store=new sx({host:n.eveHost,auth:{bearer:()=>this.bearer()},initialSession:{sessionId:n.sessionId,streamIndex:0},optimistic:!1,reducer:Xj}),this.store.setCallbacks({onEvent:r=>this.forward?.(r)}),this.caughtUp=this.store.resume().catch(()=>{})}static async create(t){let a=Wj(),n=await t.open({operation:"create",requestId:crypto.randomUUID(),ownerSecret:a,channelId:t.channelId,visitorId:t.visitorId});return n?await new e(t.open,a,n).reachable():null}static async resume(t){let a=await t.open({operation:"resume",...t.saved});return a?await new e(t.open,t.saved.ownerSecret,a).reachable():null}async reachable(){return await this.caughtUp,this.store.snapshot.error===void 0?this:(this.close(),null)}get sessionId(){return this.grant.sessionId}get saved(){return{conversationId:this.grant.conversationId,ownerSecret:this.secret}}get followups(){return this.grant.followups}async history(){await this.caughtUp;let{events:t}=this.store.snapshot;return this.used||(this.used=t.some(a=>a.type==="message.received")),t}async bearer(){return this.grant.expiresAt-$j>Date.now()?this.grant.accessToken:(this.refreshing??(this.refreshing=this.open({operation:"refresh",conversationId:this.grant.conversationId,ownerSecret:this.secret}).then(t=>{if(!t)throw new Error("The conversation left the direct runtime");return this.grant=t,t.accessToken}).finally(()=>{this.refreshing=null})),await this.refreshing)}turn(t,a,n){this.used=!0;let r=()=>{this.store.cancel()};return n?.addEventListener("abort",r,{once:!0}),new ReadableStream({start:async i=>{let s=!1;this.forward=u=>{s||(s=u.type==="turn.failed"||u.type==="session.failed"),i.enqueue(u)},await this.caughtUp;let l=await this.store.send({message:t,signal:n,headers:Gj(a)}).then(()=>this.store.snapshot.error,u=>u instanceof Error?u:new Error(String(u)));this.forward=void 0,n?.removeEventListener("abort",r),l&&!s&&!n?.aborted&&i.enqueue({type:"session.failed",data:{code:"transport_failed",message:l.message,sessionId:this.sessionId}}),i.close()}}).pipeThrough(om())}close(){this.forward=void 0,this.store.reset()}};function Bl(e,t){let a=e[t];return typeof a=="string"&&a?a:void 0}function Kj(e){let t=e.visitor;return typeof t=="object"&&t!==null&&"id"in t&&typeof t.id=="string"?t.id:void 0}function Yj(e){return e.filter(t=>t.role==="user").map(t=>t.parts.flatMap(a=>a.type==="text"?[a.text]:[]).join(`
|
|
142
|
-
`))}function tM(e){return fetch(new URL(e.path,new URL(e.sessionApi,location.href)),{method:"POST",headers:{...e.headers(),"content-type":"application/json"},body:JSON.stringify(e.body),cache:"no-store",signal:e.signal})}function Zj(e){return async t=>{let a=await tM({...e,path:"followups",body:t,signal:AbortSignal.timeout(8e3)}),n=a.ok?await a.json():null,r=typeof n=="object"&&n!==null&&"data"in n?n.data:null,o=typeof r=="object"&&r!==null&&"suggestions"in r?r.suggestions:null;return Array.isArray(o)?o.filter(i=>typeof i=="string"):[]}}function Jj(e){let t="",a=!1,n=new Set;return new TransformStream({async transform(r,o){if(r.type==="text-delta"&&(t+=r.delta),r.type==="tool-input-available"&&n.add(r.toolName),r.type==="error"&&(a=!0),r.type==="finish"&&!a&&!e.signal?.aborted&&t.trim()){let i=await e.suggest(t,[...n]).catch(()=>[]);i.length>0&&o.enqueue({type:"data-suggestions",data:{suggestions:i}})}o.enqueue(r)}})}function Qj(e){return async t=>{let a=await tM({...e,path:e.sessionApi,body:t});if(!a.ok)throw new Error(`Opening the chat failed (${a.status})`);let n=await a.json(),r=typeof n=="object"&&n!==null&&"data"in n?n.data:null;if(typeof r!="object"||r===null||!("transport"in r))throw new Error("The session route answered no transport");if(r.transport!=="eve-native")return null;let o={...r},i=o.session,s=typeof i=="object"&&i!==null&&"sessionId"in i?i.sessionId:void 0,l=Bl(o,"conversationId"),u=Bl(o,"eveHost"),c=Bl(o,"accessToken"),d=Date.parse(Bl(o,"expiresAt")??"");if(!l||!u||!c||typeof s!="string"||Number.isNaN(d))throw new Error("The session route answered an incomplete session");return{conversationId:l,eveHost:u,sessionId:s,accessToken:c,expiresAt:d,followups:o.followups===!0}}}function eV(e){let t=e.extra;return typeof t=="object"&&t!==null&&!Array.isArray(t)?Object.fromEntries(Object.entries(t)):void 0}var dx=class{constructor(t){this.options=t;K(this,"pending");K(this,"threadOnFallback",!1);K(this,"generation",0)}get channelId(){return Bl(this.options.body(),"channelId")}key(){return ux({channelId:this.channelId,threadId:this.options.threadId()})}keepsSession(){return this.options.open!==void 0}prepare(){this.open(this.options.hasMessages())}open(t){this.options.open&&(this.pending??(this.pending=this.start(this.options.open,t)))}async restore(){let{open:t}=this.options;if(!t||this.options.threadHistory())return[];let a=this.key(),n=cx(a);if(!n)return[];let r=this.generation,o=Nl.resume({open:t,saved:n}).catch(()=>null).then(s=>this.kept(s,r));this.pending=o;let i=await o;return i?await kE(await i.history()):(Ul(a,null),this.pending===o&&(this.pending=void 0),[])}reset(){Ul(this.key(),null),this.dispose()}forget(t){Ul(ux({channelId:this.channelId,threadId:t}),null)}dispose(){this.generation+=1,this.threadOnFallback=!1,this.pending?.then(t=>t?.close()).catch(()=>{}),this.pending=void 0}async start(t,a){let n=this.generation,r=this.key(),o=cx(r);if(o){let u=await Nl.resume({open:t,saved:o}).catch(()=>null);return!u&&n===this.generation&&Ul(r,null),this.kept(u,n)}if(a)return null;let i=this.options.body(),s=await Nl.create({open:t,channelId:Bl(i,"channelId"),visitorId:Kj(i)}),l=this.kept(s,n);return n===this.generation&&Ul(r,l?.saved??null),l}kept(t,a){return t&&a!==this.generation?(t.close(),null):t}async sendMessages(t){let a=t.messages.filter(m=>m.role==="user").length<=1;a&&(this.threadOnFallback=!1);let r=[...t.messages].reverse().find(m=>m.role==="user")?.parts.some(m=>m.type==="file")??!1;if(this.threadOnFallback||r||!this.options.open)return this.threadOnFallback=!0,await this.options.fallback.sendMessages(t);this.open(!a);let o=await this.pending?.catch(()=>null);if(o?.used&&a&&(this.reset(),this.open(!1),o=await this.pending?.catch(()=>null)),!o)return this.threadOnFallback=!0,await this.options.fallback.sendMessages(t);this.options.onSession(o.sessionId);let{documents:i}=this.options.takeTurnInput(),s=Yj(t.messages),l=s.at(-1)??"",u=l.trim()?l:i?.map(m=>m.filename).join(", ")??l,c=o.turn(u,{documents:i,extra:eV(this.options.body())},t.abortSignal),{suggest:d}=this.options;if(!o.followups||!d)return c;let{saved:p}=o;return c.pipeThrough(Jj({suggest:(m,h)=>d({...p,answerText:m.slice(-8e3),recentUserMessages:s.slice(-3).map(v=>v.slice(-2e3)),toolNames:h.slice(0,20)}),signal:t.abortSignal}))}async reconnectToStream(t){return await this.pending?.catch(()=>null)?null:await this.options.fallback.reconnectToStream(t)}};function aM(e){let t=typeof e=="string"?()=>e:e;return a=>{let n=r=>{let o=t();return o?r(o):void 0};return new dx({...a,get open(){return n(r=>Qj({sessionApi:r,headers:a.headers}))},get suggest(){return n(r=>Zj({sessionApi:r,headers:a.headers}))}})}}function zl(e){let t=(0,gm.useRef)(e);t.current=e;let[a]=(0,gm.useState)(()=>aM(()=>t.current));return a}var nM=j(Ee(),1),rM="(max-width: 639px)";function tV(e){let t=window.matchMedia(rM);return t.addEventListener("change",e),()=>t.removeEventListener("change",e)}function aV(){return window.matchMedia(rM).matches}function nV(){return!1}function oM(){return(0,nM.useSyncExternalStore)(tV,aV,nV)}var ym=j(Ee(),1);function fx(e,t){return e.find(a=>a.text===t)?.id??null}async function iM(e){let{api:t,token:a,name:n,source:r,sessionId:o,properties:i}=e;if(typeof window>"u"||!t||!a)return;let s=Cc(t);if(s)try{let l=new Date().toISOString(),u=JSON.stringify({sentAt:l,source:{sdk:"@waniwani/sdk",version:"0.1.0"},events:[{id:crypto.randomUUID(),type:"mcp.event",name:n,source:r,timestamp:l,correlation:{visitorId:ma(),sessionId:o},properties:{...i,url:window.location.href},metadata:{}}]});await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:u,keepalive:!0})}catch{}}async function sM(e){let{api:t,token:a,channelId:n,mode:r,source:o,sessionId:i,promptId:s,origin:l,text:u,index:c}=e;await iM({api:t,token:a,name:"suggestion.clicked",source:o,sessionId:i,properties:{promptId:s,origin:l,text:u,index:c,channelId:n,mode:r}})}function lM(e,t){return t.map(a=>({id:fx(e,a),text:a}))}async function uM(e){let{api:t,token:a,channelId:n,mode:r,source:o,sessionId:i,prompts:s,origin:l}=e;s.length!==0&&await iM({api:t,token:a,name:"suggestion.shown",source:o,sessionId:i,properties:{prompts:s,count:s.length,origin:l,channelId:n,mode:r}})}function Fl(e){let{widgetEvents:t,api:a,token:n,channelId:r,source:o,mode:i,pagePrompts:s}=e,l=(0,ym.useRef)(e.getSessionId);l.current=e.getSessionId,(0,ym.useEffect)(()=>{if(!(!a||!n))return t.subscribe(u=>{if(u.name==="suggestion.clicked"){let{text:c,origin:d,index:p}=u.properties;sM({api:a,token:n,channelId:r,mode:i,source:o,sessionId:l.current(),promptId:fx(s??[],c),origin:d,text:c,index:p});return}if(u.name==="suggestions.shown"){let{texts:c,origin:d}=u.properties;uM({api:a,token:n,channelId:r,mode:i,source:o,sessionId:l.current(),prompts:lM(s??[],c),origin:d})}})},[t,a,n,r,o,i,s])}var ql=j(Ee(),1),rV=80,oV=50,iV=15e3,cM=500;function Hl(e,t=!0){let[a,n]=(0,ql.useState)(""),r=(0,ql.useRef)(void 0);return(0,ql.useEffect)(()=>{if(!t){n("");return}let o=0,i=!1,s=!1,l=()=>{s||(i?(o--,n(e.slice(0,o)),o<=0?(i=!1,r.current=setTimeout(l,cM)):r.current=setTimeout(l,oV)):(o++,n(e.slice(0,o)),o>=e.length?(i=!0,r.current=setTimeout(l,iV)):r.current=setTimeout(l,rV)))};return r.current=setTimeout(l,cM),()=>{s=!0,clearTimeout(r.current)}},[e,t]),a}var tr=j(Ee(),1);var dM=["en","fr","es"];function jl(e){return dM.includes(e)}function px(e){if(e&&jl(e))return e;if(e){let a=e.split("-")[0]?.toLowerCase();if(a&&jl(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(jl(n))return n;let r=n.split("-")[0];if(r&&jl(r))return r}return"en"}var wm={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 fM={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 pM={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 mx={en:wm,fr:pM,es:fM};var hM=j(me(),1),mM=(0,tr.createContext)(null);function sV(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 es({children:e,locale:t,messages:a}){let n=!!(t&&lV(t)),r=n?t:"en",[o,i]=(0,tr.useState)(r),[s,l]=(0,tr.useState)(n);(0,tr.useEffect)(()=>{i(px(t)),l(!0)},[t]);let u=(0,tr.useMemo)(()=>{let c=mx[o]??mx["en"];return{locale:o,t:sV(c,a),ready:s}},[o,a,s]);return(0,hM.jsx)(mM.Provider,{value:u,children:e})}function lV(e){return e==="en"||e==="fr"||e==="es"}function Ue(){let e=(0,tr.useContext)(mM);return e||{locale:"en",t:wm,ready:!0}}function hx(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 Qe=j(Ee(),1);var ud=(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 Be=j(Ee(),1);var ts=new Map;function gM(e,t){if(ts.has(e)){URL.revokeObjectURL(t);return}for(ts.set(e,t);ts.size>20;){let a=ts.keys().next();if(a.done)return;let n=ts.get(a.value);ts.delete(a.value),n&&URL.revokeObjectURL(n)}}function yM(e){return ts.get(e)}var wM=j(me(),1),br=({className:e,variant:t="default",size:a="default",type:n="button",...r})=>(0,wM.jsx)("button",{type:n,className:V("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 vM=j(Ee(),1);var Bt=j(me(),1),xM=({files:e,className:t,...a})=>e.length===0?null:(0,Bt.jsx)("div",{className:V("ww:flex ww:flex-wrap ww:gap-1.5",t),...a,children:e.map((n,r)=>(0,Bt.jsx)(uV,{file:n},r))});function uV({file:e}){let{t}=Ue();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)(vl,{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 bM(e,t){return e.startsWith("image/")?t.attachments.kindImage:e==="application/pdf"?t.attachments.kindPdf:t.attachments.kindFile}function cV({mediaType:e}){return e.startsWith("image/")?(0,Bt.jsx)(Dc,{className:"ww:size-5 ww:text-muted-foreground"}):e==="application/pdf"?(0,Bt.jsx)(Mc,{className:"ww:size-5 ww:text-muted-foreground"}):(0,Bt.jsx)(vl,{className:"ww:size-5 ww:text-muted-foreground"})}function gx({filename:e,mediaType:t,previewUrl:a,subtitle:n,tone:r="default",children:o,className:i}){let{t:s}=Ue(),l=bM(t,s);return(0,Bt.jsxs)("li",{"aria-label":`${e}, ${l}`,className:V("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)(cV,{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:V("ww:truncate ww:text-xs",r==="error"?"ww:text-destructive":"ww:text-muted-foreground"),children:n??l})]}),o]})}function SM(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 IM=({documents:e,className:t,...a})=>e.length===0?null:(0,Bt.jsx)("ul",{className:V("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)(dV,{document:n},`${n.documentId}-${r}`))});function dV({document:e}){let{t}=Ue(),[a,n]=(0,vM.useState)(!1),r=e.mediaType.startsWith("image/")?yM(e.documentId):void 0;return r&&!a?(0,Bt.jsx)("li",{children:(0,Bt.jsx)("img",{alt:`${e.filename}, ${bM(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)(gx,{filename:e.filename,mediaType:e.mediaType})}var Et=j(me(),1),fV=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}},pV=(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)},kM=(0,Be.createContext)(null),vm=()=>{let e=(0,Be.useContext)(kM);if(!e)throw new Error("usePromptInputAttachments must be used within a PromptInput");return e},TM=({className:e,accept:t,multiple:a,globalDrop:n,maxFiles:r,maxFileSize:o,maxPdfPages:i,attachmentsEnabled:s=!0,upload:l,onDiscard:u,onError:c,onSubmit:d,children:p,...m})=>{let{t:h,locale:v}=Ue(),I=(0,Be.useRef)(null),y=(0,Be.useRef)(null),[w,g]=(0,Be.useState)([]),S=(0,Be.useRef)(w),E=(0,Be.useRef)(new Map),T=(0,Be.useRef)(l),R=(0,Be.useRef)(c),O=(0,Be.useRef)(u);(0,Be.useEffect)(()=>{T.current=l,R.current=c,O.current=u},[l,c,u]);let U=(0,Be.useCallback)(x=>{S.current=x,g(x)},[]),A=(0,Be.useCallback)(()=>{I.current?.click()},[]),Q=(0,Be.useCallback)((x,te)=>{U(S.current.map(re=>re.id===x?{...re,...te}:re))},[U]),$=(0,Be.useCallback)((x,te)=>{let re=T.current;if(!re)return;let ke=new AbortController,We=re(te,ke.signal,be=>{Q(x,{progress:be})}).then(be=>(Q(x,{status:"ready",progress:1,documentId:be.documentId,error:void 0}),be)).catch(be=>{if(ke.signal.aborted)return null;let Oe=be instanceof Error?be.message:h.promptInput.uploadFailed;return Q(x,{status:"failed",error:Oe}),R.current?.({code:"upload_failed",message:Oe}),null});E.current.set(x,{file:te,controller:ke,done:We})},[Q,h]),H=(0,Be.useCallback)(x=>{let te=[...x];if(!s||te.length===0)return;let re=(ce,Le)=>R.current?.({code:ce,message:Le}),ke=[];for(let ce of te){if(!pV(ce,t)){re("accept",h.promptInput.errorAccept.replace("{name}",ce.name));continue}if(o&&ce.size>o){re("max_file_size",h.promptInput.errorTooLarge.replace("{name}",ce.name).replace("{limit}",LM(o,v)));continue}ke.push(ce)}if(ke.length===0)return;let We=typeof r=="number"?Math.max(0,r-S.current.length):void 0,be=typeof We=="number"?ke.slice(0,We):ke;if(be.length<ke.length&&re("max_files",h.promptInput.errorTooMany.replace("{limit}",String(r))),be.length===0)return;let Oe=!!T.current,we=be.map(ce=>({file:ce,item:{filename:ce.name,id:ud(),mediaType:ce.type,type:"file",url:URL.createObjectURL(ce),status:Oe?"uploading":"ready",progress:0}}));U([...S.current,...we.map(ce=>ce.item)]);for(let ce of we)$(ce.item.id,ce.file)},[r,o,t,s,$,U,h,v]),Z=(0,Be.useCallback)(x=>{let te=E.current.get(x);te&&(Q(x,{status:"uploading",progress:0,error:void 0}),$(x,te.file))},[Q,$]),X=(0,Be.useCallback)((x,te)=>{E.current.get(x.id)?.controller.abort(),E.current.delete(x.id),x.url&&(!te&&!!x.documentId&&!!x.mediaType?.startsWith("image/")&&x.documentId?gM(x.documentId,x.url):URL.revokeObjectURL(x.url)),te&&x.documentId&&O.current?.({documentId:x.documentId,filename:x.filename??"",mediaType:x.mediaType??""})},[]),B=(0,Be.useCallback)(x=>{let te=S.current.find(re=>re.id===x);te&&X(te,!0),U(S.current.filter(re=>re.id!==x))},[X,U]),P=(0,Be.useCallback)(()=>{for(let x of S.current)X(x,!0);U([])},[X,U]),J=(0,Be.useRef)(s);(0,Be.useEffect)(()=>{let x=J.current;J.current=s,x&&!s&&P()},[s,P]);let ge=(0,Be.useCallback)(()=>{for(let x of S.current)X(x,!1);U([])},[X,U]);(0,Be.useEffect)(()=>()=>{for(let x of S.current)E.current.get(x.id)?.controller.abort(),x.url&&URL.revokeObjectURL(x.url)},[]);let C=(0,Be.useCallback)(x=>{x.currentTarget.files&&H(x.currentTarget.files),x.currentTarget.value=""},[H]);(0,Be.useEffect)(()=>{if(!n)return;let x=re=>{re.dataTransfer?.types?.includes("Files")&&re.preventDefault()},te=re=>{re.dataTransfer?.types?.includes("Files")&&re.preventDefault(),re.dataTransfer?.files&&re.dataTransfer.files.length>0&&H(re.dataTransfer.files)};return document.addEventListener("dragover",x),document.addEventListener("drop",te),()=>{document.removeEventListener("dragover",x),document.removeEventListener("drop",te)}},[H,n]);let ze=(0,Be.useCallback)(async x=>{x.preventDefault();let te=x.currentTarget,re=new FormData(te).get("message")||"",ke=new Map;for(;ke.size<E.current.size;)await Promise.all([...E.current.entries()].filter(([we])=>!ke.has(we)).map(async([we,ce])=>{ke.set(we,await ce.done)}));for(let we of ke.keys())E.current.has(we)||ke.delete(we);if([...ke.values()].some(we=>we===null)){R.current?.({code:"upload_failed",message:h.promptInput.uploadFailed});return}let We=[...ke.values()].filter(we=>we!==null),be=T.current?[]:S.current,Oe=await Promise.all(be.map(async({id:we,status:ce,progress:Le,error:ie,...xe})=>{if(xe.url?.startsWith("blob:")){let Ne=await fV(xe.url);return{...xe,url:Ne??xe.url}}return xe}));try{let we=d({documents:We,files:Oe,text:re},x);we instanceof Promise&&await we,te.reset(),ge()}catch{}},[d,ge,h]),ot=(0,Be.useMemo)(()=>({add:H,clear:P,files:w,openFileDialog:A,remove:B,retry:Z,maxFileSize:o,maxPdfPages:i}),[w,H,B,Z,P,A,o,i]);return(0,Et.jsxs)(kM.Provider,{value:ot,children:[(0,Et.jsx)("input",{accept:t,"aria-label":h.promptInput.uploadFiles,className:"ww:hidden",multiple:a,onChange:C,ref:I,title:h.promptInput.uploadFiles,type:"file"}),(0,Et.jsx)("form",{className:V("ww:relative ww:flex ww:w-full ww:flex-col ww:rounded-lg ww:border ww:border-border ww:bg-background",e),onSubmit:ze,ref:y,...m,children:p})]})},CM=1024*1024;function LM(e,t){let a=e>=CM;return new Intl.NumberFormat(t,{style:"unit",unit:a?"megabyte":"kilobyte",maximumFractionDigits:0}).format(a?e/CM:Math.max(1,e/1024))}var EM=({onChange:e,onKeyDown:t,className:a,placeholder:n,...r})=>{let{t:o}=Ue(),i=vm(),[s,l]=(0,Be.useState)(!1),u=n??o.promptInput.placeholder,c=(0,Be.useCallback)(p=>{if(t?.(p),!p.defaultPrevented){if(p.key==="Enter"){if(s||p.nativeEvent.isComposing||p.shiftKey)return;p.preventDefault();let{form:m}=p.currentTarget;if(m?.querySelector('[data-submit-blocked="true"]')||m?.querySelector('button[type="submit"]')?.disabled)return;m?.requestSubmit()}if(p.key==="Backspace"&&p.currentTarget.value===""&&i.files.length>0){p.preventDefault();let m=i.files.at(-1);m&&i.remove(m.id)}}},[t,s,i]),d=(0,Be.useCallback)(p=>{let m=p.clipboardData?.items;if(!m)return;let h=[];for(let v of m)if(v.kind==="file"){let I=v.getAsFile();I&&h.push(I)}h.length>0&&(p.preventDefault(),i.add(h))},[i]);return(0,Et.jsx)("textarea",{className:V("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:()=>l(!1),onCompositionStart:()=>l(!0),onKeyDown:c,onPaste:d,placeholder:u,onChange:e,...r})},AM=({className:e,status:t,onStop:a,onClick:n,children:r,disabled:o,...i})=>{let{t:s}=Ue(),l=t==="submitted"||t==="streaming",u=l&&a!==void 0,c=(0,Et.jsx)(pr,{className:"ww:size-4"});t==="submitted"?c=(0,Et.jsx)(_c,{className:"ww:size-4 ww:animate-spin"}):t==="streaming"&&(c=(0,Et.jsx)(Pc,{className:"ww:size-4"}));let d=(0,Be.useCallback)(p=>{if(l&&a){p.preventDefault(),a();return}n?.(p)},[l,a,n]);return(0,Et.jsx)(br,{"aria-label":l?s.promptInput.stop:s.promptInput.submit,className:V("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})},MM=({className:e,children:t,...a})=>{let{t:n,locale:r}=Ue(),o=vm();if(o.files.length>0)return(0,Et.jsxs)(br,{className:V("ww:group ww:relative",e),onClick:()=>o.clear(),size:"icon-sm",type:"button",variant:"ghost","aria-label":n.promptInput.removeAttachments,...a,children:[(0,Et.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,Et.jsx)(wn,{className:"ww:absolute ww:size-4 ww:opacity-0 ww:transition-opacity ww:group-hover:opacity-100"})]});let s=o.maxFileSize?(o.maxPdfPages?n.promptInput.uploadFilesUpToWithPages.replace("{pages}",String(o.maxPdfPages)):n.promptInput.uploadFilesUpTo).replace("{limit}",LM(o.maxFileSize,r)):n.promptInput.uploadFiles;return(0,Et.jsx)(br,{"aria-label":s,className:V(e),title:s,onClick:()=>o.openFileDialog(),size:"icon-sm",type:"button",variant:"ghost",...a,children:t??(0,Et.jsx)(xl,{className:"ww:size-4"})})},RM=({className:e,...t})=>{let a=vm();return a.files.length===0?null:(0,Et.jsx)("ul",{className:V("ww:flex ww:list-none ww:flex-wrap ww:gap-2 ww:p-0",e),...t,children:a.files.map(n=>(0,Et.jsx)(mV,{file:n},n.id))})};function mV({file:e}){let{t}=Ue(),a=vm(),n=e.status==="failed",r=e.status==="uploading";return(0,Et.jsxs)(gx,{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,Et.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,Et.jsx)("button",{"aria-label":t.promptInput.removeAttachment,className:V("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,Et.jsx)(wn,{className:"ww:size-3.5"})}),r?(0,Et.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 DM=({enabled:e=!0})=>{let{t}=Ue(),[a,n]=(0,Be.useState)(!1);return(0,Be.useEffect)(()=>{if(!e)return;let r=0,o=u=>!!u.dataTransfer?.types?.includes("Files"),i=u=>{o(u)&&(r+=1,n(!0))},s=u=>{o(u)&&(r=Math.max(0,r-1),r===0&&n(!1))},l=()=>{r=0,n(!1)};return document.addEventListener("dragenter",i),document.addEventListener("dragleave",s),document.addEventListener("drop",l),()=>{document.removeEventListener("dragenter",i),document.removeEventListener("dragleave",s),document.removeEventListener("drop",l)}},[e]),e&&a?(0,Et.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,Et.jsxs)("span",{className:"ww:flex ww:items-center ww:gap-2 ww:text-sm ww:font-medium",children:[(0,Et.jsx)(xl,{className:"ww:size-4"}),t.promptInput.dropToAttach]})}):null};var PM=j(me(),1);function _M({text:e}){let{t}=Ue();return e===!1?null:(0,PM.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 xm=j(Ee(),1);var as=j(me(),1),OM=({className:e,...t})=>(0,as.jsx)("div",{className:V("ww:flex ww:flex-col ww:gap-1 ww:px-3 ww:py-2",e),...t}),NM=({className:e,...t})=>(0,as.jsx)("li",{className:V("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}),UM=({className:e,...t})=>(0,as.jsx)("span",{className:V("ww:inline-block ww:size-2 ww:shrink-0 ww:rounded-full ww:border ww:border-muted-foreground/50",e),...t}),BM=({className:e,...t})=>(0,as.jsx)("span",{className:V("ww:line-clamp-1 ww:grow ww:break-words ww:text-muted-foreground",e),...t}),zM=({className:e,...t})=>(0,as.jsx)("div",{className:V("ww:flex ww:shrink-0 ww:gap-1 ww:opacity-0 ww:transition-opacity ww:group-hover:opacity-100",e),...t}),FM=({className:e,...t})=>(0,as.jsx)(br,{className:V("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 Un=j(me(),1),qM=(0,xm.memo)(({message:e,onRemove:t})=>{let{t:a}=Ue(),n=(0,xm.useCallback)(()=>t(e.id),[t,e.id]);return(0,Un.jsxs)(NM,{children:[(0,Un.jsx)(UM,{}),(0,Un.jsx)(BM,{children:e.text||a.chatQueue.attachmentFallback}),(0,Un.jsx)(zM,{children:(0,Un.jsx)(FM,{"aria-label":a.chatQueue.removeFromQueue,onClick:n,children:(0,Un.jsx)(wn,{className:"ww:size-3"})})})]})});qM.displayName="ChatQueueItem";function HM({queuedMessages:e,onRemove:t,className:a}){let{t:n}=Ue();return e.length===0?null:(0,Un.jsxs)(OM,{className:V("ww:border-t ww:border-border",a),children:[(0,Un.jsx)("div",{className:"ww:text-[11px] ww:font-medium ww:text-muted-foreground ww:px-2",children:n.chatQueue.queued(e.length)}),(0,Un.jsx)("ul",{children:e.map(r=>(0,Un.jsx)(qM,{message:r,onRemove:t},r.id))})]})}var nn=j(Ee(),1);var zt=j(Ee(),1);Ch();var xU=j(Ee(),1);var bU=j(me(),1),PK=({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,bU.jsx)(e,{"data-waniwani-shimmer":"",className:V("ww:inline-block",t),style:i,...o,children:r})},or=(0,xU.memo)(PK);or.displayName="Shimmer";var Da=j(me(),1),SU=(0,zt.createContext)(null);function IU(){let e=(0,zt.useContext)(SU);if(!e)throw new Error("Reasoning components must be used within <Reasoning>");return e}var OK=1e3,NK=1e3,Ud=(0,zt.memo)(({className:e,isStreaming:t=!1,open:a,defaultOpen:n,onOpenChange:r,duration:o,children:i,...s})=>{let l=n??t,u=n===!1,c=a!==void 0,[d,p]=(0,zt.useState)(l),m=c?a:d,h=(0,zt.useCallback)(R=>{c||p(R),r?.(R)},[c,r]),[v,I]=(0,zt.useState)(void 0),y=o??v,w=(0,zt.useRef)(t),[g,S]=(0,zt.useState)(!1),E=(0,zt.useRef)(null);(0,zt.useEffect)(()=>{t?(w.current=!0,E.current===null&&(E.current=Date.now())):E.current!==null&&(I(Math.ceil((Date.now()-E.current)/NK)),E.current=null)},[t]),(0,zt.useEffect)(()=>{t&&!m&&!u&&h(!0)},[t,m,u,h]),(0,zt.useEffect)(()=>{if(w.current&&!t&&m&&!g){let R=setTimeout(()=>{h(!1),S(!0)},OK);return()=>clearTimeout(R)}},[t,m,g,h]);let T=(0,zt.useMemo)(()=>({isStreaming:t,isOpen:m,setIsOpen:h,duration:y}),[t,m,h,y]);return(0,Da.jsx)(SU.Provider,{value:T,children:(0,Da.jsx)("div",{className:V("ww:mb-4 ww:flex ww:flex-col ww:gap-2",e),"data-state":m?"open":"closed",style:{animation:"ww-fade-in 0.2s ease-out"},...s,children:i})})});Ud.displayName="Reasoning";var Bd=(0,zt.memo)(({className:e,children:t,getThinkingMessage:a,hideIcon:n=!1,onClick:r,...o})=>{let{t:i}=Ue(),{isStreaming:s,isOpen:l,duration:u,setIsOpen:c}=IU(),p=a??((m,h)=>m||h===0?(0,Da.jsx)(or,{duration:1.6,children:i.reasoning.thinking}):h===void 0?(0,Da.jsx)("span",{children:i.reasoning.thoughtBrief}):(0,Da.jsx)("span",{children:i.reasoning.thoughtForSeconds(h)}));return(0,Da.jsx)("button",{type:"button","aria-expanded":l,onClick:m=>{c(!l),r?.(m)},className:V("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,Da.jsxs)(Da.Fragment,{children:[!n&&(0,Da.jsx)(Gr,{className:"ww:size-4 ww:shrink-0"}),p(s,u)]})})});Bd.displayName="ReasoningTrigger";var zd=(0,zt.memo)(({className:e,children:t,...a})=>{let{isOpen:n}=IU();return(0,Da.jsx)("div",{className:V("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,Da.jsx)("div",{className:"ww:min-h-0 ww:overflow-hidden",children:(0,Da.jsx)("div",{className:V("ww:text-sm ww:text-muted-foreground",e),...a,children:(0,Da.jsx)(au,{children:t})})})})});zd.displayName="ReasoningContent";var Ye=j(me(),1),UK=500,CU=(0,nn.createContext)(null);function kU(){let e=(0,nn.useContext)(CU);if(!e)throw new Error("ChainOfThought components must be used within <ChainOfThought>");return e}function TU({className:e,isWorking:t=!1,activeStep:a,open:n,defaultOpen:r=!1,onOpenChange:o,children:i,...s}){let l=n!==void 0,[u,c]=(0,nn.useState)(r),d=l?n:u,p=(0,nn.useCallback)(I=>{l||c(I),o?.(I)},[l,o]),[m,h]=(0,nn.useState)(!t);(0,nn.useEffect)(()=>{if(t){h(!1);return}let I=setTimeout(()=>h(!0),UK);return()=>clearTimeout(I)},[t]);let v=(0,nn.useMemo)(()=>({open:d,setOpen:p,isWorking:t,settled:m,activeStep:a}),[d,p,t,m,a]);return(0,Ye.jsx)(CU.Provider,{value:v,children:(0,Ye.jsx)("div",{className:V("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"},...s,children:i})})}function LU({className:e,label:t,workingLabel:a,children:n,...r}){let{open:o,setOpen:i,isWorking:s,settled:l,activeStep:u}=kU();if(!l){let c=u?.icon,d=u?.label??a??t??"";return(0,Ye.jsx)("div",{className:V("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,Ye.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,Ye.jsx)(c,{className:V("ww:size-4 ww:shrink-0",s&&"ww:animate-pulse")}),(0,Ye.jsx)("span",{className:"ww:truncate",children:s?(0,Ye.jsx)(or,{duration:2.6,children:d}):d})]},d)})}return(0,Ye.jsxs)("button",{type:"button",onClick:()=>i(!o),"aria-expanded":o,className:V("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,Ye.jsx)("span",{className:"ww:truncate",children:n??t}),(0,Ye.jsx)(zo,{className:V("ww:size-4 ww:shrink-0 ww:transition-transform ww:duration-200",o&&"ww:rotate-180")})]})}function EU({className:e,children:t,...a}){let{open:n}=kU();return(0,Ye.jsx)("div",{className:V("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,Ye.jsx)("div",{className:"ww:min-h-0 ww:overflow-hidden",children:(0,Ye.jsx)("div",{className:V("ww:flex ww:flex-col",e),...a,children:t})})})}function AU({icon:e,isLast:t,running:a,error:n}){return(0,Ye.jsxs)("div",{className:"ww:flex ww:flex-col ww:items-center ww:self-stretch",children:[(0,Ye.jsx)("span",{className:"ww:flex ww:h-5 ww:items-center",children:(0,Ye.jsx)(e,{className:V("ww:size-4 ww:shrink-0",n?"ww:text-destructive":a?"ww:animate-pulse ww:text-foreground":"ww:text-muted-foreground")})}),!t&&(0,Ye.jsx)("span",{className:"ww:w-px ww:flex-1 ww:bg-border"})]})}function VS({className:e,icon:t,title:a,state:n,isLast:r=!1,children:o,...i}){let s=n==="input-available"||n==="input-streaming",l=n==="output-error",u=o!=null,[c,d]=(0,nn.useState)(!1),p=a??"",m=s?(0,Ye.jsx)(or,{duration:1.6,children:p}):(0,Ye.jsx)("span",{className:"ww:truncate",children:p});return(0,Ye.jsxs)("div",{className:V("ww:flex ww:gap-2",e),...i,children:[(0,Ye.jsx)(AU,{icon:t,isLast:r,running:s,error:l}),(0,Ye.jsxs)("div",{className:V("ww:min-w-0 ww:flex-1",!r&&"ww:pb-3"),children:[u?(0,Ye.jsxs)("button",{type:"button",onClick:()=>d(h=>!h),"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:[m,(0,Ye.jsx)(zo,{className:V("ww:size-3.5 ww:shrink-0 ww:transition-transform ww:duration-200",c&&"ww:rotate-180")})]}):(0,Ye.jsx)("div",{className:"ww:flex ww:items-center ww:text-sm ww:text-muted-foreground",children:m}),u&&(0,Ye.jsx)("div",{className:V("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,Ye.jsx)("div",{className:"ww:min-h-0 ww:overflow-hidden",children:(0,Ye.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 MU({isStreaming:e=!1,isLast:t=!1,children:a}){return(0,Ye.jsxs)("div",{className:"ww:flex ww:gap-2",children:[(0,Ye.jsx)(AU,{icon:Gr,isLast:t,running:e}),(0,Ye.jsx)("div",{className:V("ww:min-w-0 ww:flex-1",!t&&"ww:pb-3"),children:(0,Ye.jsxs)(Ud,{isStreaming:e,className:"ww:mb-0",children:[(0,Ye.jsx)(Bd,{hideIcon:!0}),(0,Ye.jsx)(zd,{children:a})]})})]})}var $S={name:"cjk-noop",type:"cjk",remarkPluginsBefore:[],remarkPluginsAfter:[],remarkPlugins:[]};var RU={name:"shiki-noop",type:"code-highlighter",supportsLanguage:()=>!1,getSupportedLanguages:()=>[],getThemes:()=>["github-light","github-dark"],highlight:()=>null};var PU=j(Ee(),1);var oo=j(Ee(),1),BK=5,DU=400;function _U(e,t,a={}){let{msPerChar:n=BK}=a,[r,o]=(0,oo.useState)(t?"":e),i=(0,oo.useRef)(e),s=(0,oo.useRef)(t?0:e.length),l=(0,oo.useRef)(0),u=(0,oo.useRef)(null);return(e.length<s.current||!e.startsWith(r.slice(0,s.current)))&&(s.current=t?0:e.length),i.current=e,(0,oo.useEffect)(()=>{if(!t){u.current!==null&&(cancelAnimationFrame(u.current),u.current=null),s.current=e.length,o(e);return}if(i.current.length-s.current>DU&&(s.current=i.current.length-DU),u.current!==null)return;let d=p=>{let m=i.current;if(s.current>=m.length){u.current=null;return}l.current===0&&(l.current=p);let h=p-l.current;if(h>=n){let v=Math.min(Math.floor(h/n),m.length-s.current);s.current+=v,o(m.slice(0,s.current)),l.current=p}u.current=requestAnimationFrame(d)};return u.current=requestAnimationFrame(d),()=>{u.current!==null&&(cancelAnimationFrame(u.current),u.current=null)}},[e,t,n]),r}var Fd=j(me(),1),WS=({className:e,from:t,children:a,...n})=>(0,Fd.jsx)("div",{className:V("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,Fd.jsx)("div",{className:V("ww:flex ww:min-w-0 ww:flex-col ww:gap-2","ww:w-full"),children:a})}),GS=({children:e,className:t,...a})=>(0,Fd.jsx)("div",{className:V("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}),zK={cjk:$S,code:RU},FK={cjk:$S},qK={enabled:!1};function HK({className:e,linkSafety:t,isStreaming:a,children:n,...r}){let i=_U(typeof n=="string"?n:"",!!a),s=typeof n=="string"?i:n;return(0,Fd.jsx)(au,{className:V("ww:size-full ww:[&>*:first-child]:mt-0 ww:[&>*:last-child]:mb-0",e),linkSafety:t??qK,plugins:a?FK:zK,...r,children:s})}var Ah=(0,PU.memo)(HK,(e,t)=>e.children===t.children&&e.isStreaming===t.isStreaming);Ah.displayName="MessageResponse";var ua=j(Ee(),1);function XS(e){if(!(typeof e!="object"||e===null))return e}function OU(e){return XS(e?.ui)}function KS(e){if(!e)return;let t=OU(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 qd(e){return OU(e)?.autoHeight===!0}function YS(e){return XS(XS(e)?._meta)}var qe=j(me(),1);function jK(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,s]of n){if(o<=8)break;let l=i.length>4?`${i.slice(0,4)}\u2026`:i,u;typeof s=="string"?u=s.length>2?`'${s.slice(0,1)}\u2026`:`'${s}'`:Array.isArray(s)?u=`Array(${s.length})`:typeof s=="object"&&s!==null?u="{\u2026}":u=String(s);let c=`${l}\u2009${u}`;r.push(c),o-=c.length+3}return`{${r.join(", ")}}`}function VK({text:e,className:t}){let{t:a}=Ue(),[n,r]=(0,ua.useState)(!1),o=(0,ua.useRef)(null);(0,ua.useEffect)(()=>()=>{o.current&&clearTimeout(o.current)},[]);let i=(0,ua.useCallback)(async s=>{s.stopPropagation();try{await navigator.clipboard.writeText(e),r(!0),o.current&&clearTimeout(o.current),o.current=setTimeout(()=>r(!1),2e3)}catch{}},[e]);return(0,qe.jsx)(br,{variant:"ghost",size:"sm",onClick:i,className:V("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,qe.jsxs)(qe.Fragment,{children:[(0,qe.jsx)(Lc,{className:"ww:size-3.5"}),(0,qe.jsx)("span",{children:a.tool.copied})]}):(0,qe.jsxs)(qe.Fragment,{children:[(0,qe.jsx)(Ac,{className:"ww:size-3.5"}),(0,qe.jsx)("span",{children:a.tool.copy})]})})}function NU({data:e,label:t,className:a,...n}){let[r,o]=(0,ua.useState)(!1),i=(0,ua.useMemo)(()=>JSON.stringify(e,null,2),[e]),s=jK(e);return(0,qe.jsxs)("div",{className:V("ww:rounded-lg ww:bg-tool-card",a),...n,children:[(0,qe.jsxs)("div",{className:"ww:flex ww:items-center ww:justify-between ww:px-3 ww:pt-2.5 ww:pb-1.5",children:[(0,qe.jsx)("span",{className:"ww:text-xs ww:font-medium ww:text-muted-foreground",children:t}),(0,qe.jsx)(VK,{text:i})]}),(0,qe.jsxs)("button",{type:"button",onClick:()=>o(l=>!l),className:"ww:flex ww:w-full ww:items-start ww:gap-2 ww:px-3 ww:pb-3 ww:text-left",children:[(0,qe.jsx)(Ec,{className:V("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,qe.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,qe.jsx)("code",{children:i})}):(0,qe.jsx)("span",{className:"ww:truncate ww:text-xs ww:font-mono ww:text-foreground/80",children:s})]})]})}var ZS=(0,ua.createContext)({open:!1,toggle:()=>{}});function UU({className:e,defaultOpen:t=!1,children:a,...n}){let[r,o]=(0,ua.useState)(t);return(0,qe.jsx)(ZS.Provider,{value:{open:r,toggle:()=>o(i=>!i)},children:(0,qe.jsx)("div",{className:V("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 BU({className:e,title:t,state:a,...n}){let{open:r,toggle:o}=(0,ua.useContext)(ZS),i=a==="input-available"||a==="input-streaming",s=t??"";return(0,qe.jsxs)("button",{type:"button",onClick:o,className:V("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,qe.jsx)(_i,{className:"ww:size-4 ww:shrink-0"}),(0,qe.jsx)("span",{className:"ww:truncate",children:i?(0,qe.jsx)(or,{duration:1.6,children:s}):s}),(0,qe.jsx)(zo,{className:V("ww:size-4 ww:shrink-0 ww:transition-transform ww:duration-200",r&&"ww:rotate-180")})]})}function zU({className:e,title:t,state:a,...n}){let r=a==="input-available"||a==="input-streaming",o=t??"";return(0,qe.jsx)("div",{className:V("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,qe.jsx)("span",{className:"ww:truncate",children:r?(0,qe.jsx)(or,{duration:1.6,children:o}):o})})}function FU({className:e,children:t,...a}){let{open:n}=(0,ua.useContext)(ZS);return(0,qe.jsx)("div",{className:V("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,qe.jsx)("div",{className:"ww:min-h-0 ww:overflow-hidden",children:(0,qe.jsx)("div",{className:V("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 $K(e,t){if(t||typeof e!="object"||e===null||Array.isArray(e))return e;let{_meta:a,telemetry:n,...r}=e;return r}function JS({className:e,input:t,debug:a,...n}){let{t:r}=Ue(),o=(0,ua.useMemo)(()=>$K(t,a),[t,a]);return(0,qe.jsx)(NU,{data:o,label:r.tool.request,className:e,...n})}function Hd(e,t,a){if(e){let n=KS(a?.[e]?._meta);if(n)return n}return KS(YS(t))}function qU(e,t,a){return e&&qd(a?.[e]?._meta)?!0:qd(YS(t))}function QS({className:e,output:t,errorText:a,debug:n,...r}){let{t:o}=Ue(),i=(0,ua.useMemo)(()=>{if(!n&&typeof t=="object"&&t!==null&&!Array.isArray(t)){let{_meta:s,...l}=t;return l}return t},[t,n]);return t||a?a?(0,qe.jsxs)("div",{className:V("ww:space-y-2",e),...r,children:[(0,qe.jsx)("h4",{className:"ww:text-xs ww:font-medium ww:uppercase ww:tracking-wide ww:text-muted-foreground",children:o.tool.error}),(0,qe.jsx)("div",{className:"ww:rounded-lg ww:bg-destructive/10 ww:p-3 ww:text-xs ww:text-destructive",children:a})]}):(0,qe.jsx)(NU,{data:i,label:o.tool.response,className:e,...r}):null}var jd=j(me(),1);function HU(e){return e.type==="text"||e.type==="reasoning"||e.type==="file"||"toolCallId"in e}function jU(e){return e.parts.some(HU)}function VU(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=>!(!HU(o)||a?.ignoreToolParts&&"toolCallId"in o||a?.ignoreReasoningParts&&o.type==="reasoning"))}function $U({className:e,...t}){let{t:a}=Ue();return(0,jd.jsxs)("div",{"aria-live":"polite",className:V("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,jd.jsx)(Oc,{className:"ww:size-4 ww:shrink-0"}),(0,jd.jsx)(or,{duration:1.6,children:a.workingIndicator.default})]})}var ut=j(Ee(),1);function nu(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 WU(e,t){return!nu(e)&&!nu(t)?null:nu(e)?nu(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 io=j(Ee(),1);var GU=(0,io.createContext)(()=>{});function XU(){return(0,io.useContext)(GU)}var KU=GU.Provider;function WK(e){let t=window.requestIdleCallback;typeof t=="function"?t(e):setTimeout(e,500)}function ru(e){let t=(0,io.useRef)(e);t.current=e;let a=(0,io.useRef)(!1);(0,io.useEffect)(()=>{if(!e.painted||a.current)return;a.current=!0;let n=requestAnimationFrame(()=>{let r=t.current;Di(r.paintMark),WK(()=>L1(r))});return()=>cancelAnimationFrame(n)},[e.painted])}var YU=j(me(),1),GK="/api/mcp/resource",XK=500,KK=0,YK=16,ZK="2026-01-26",JK=300,QK=3e3,eY=3,tY=2e3;function aY(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}function nY(e,t,a){return Hd(e,t,a)?!1:t._meta?.["waniwani/autoInjectResultText"]!==!1}function Mh({resourceUri:e,toolInput:t,toolResult:a,resourceEndpoint:n=GK,chatSessionId:r,isDark:o=!1,className:i,autoHeight:s=!1,onOpenLink:l,onFollowUp:u,onCallTool:c,onDisplayModeChange:d,isFullscreen:p=!1,toolDefinitions:m}){let h=(0,ut.useRef)(null),v=(0,ut.useRef)(t),I=(0,ut.useRef)(a),y=(0,ut.useRef)({width:0,height:0}),w=(0,ut.useRef)(null),g=(0,ut.useRef)(!1),S=(0,ut.useRef)(0),E=(0,ut.useRef)("inline"),[T,R]=(0,ut.useState)(KK),[O,U]=(0,ut.useState)(void 0),A=(0,ut.useRef)(l),Q=(0,ut.useRef)(u),$=(0,ut.useRef)(c),H=(0,ut.useRef)(d),Z=(0,ut.useRef)(r),X=(0,ut.useRef)(m);v.current=t,I.current=a,A.current=l,Q.current=u,$.current=c,H.current=d,Z.current=r,X.current=m;let B=(0,ut.useCallback)(x=>s?Math.max(x+YK,0):Math.min(Math.max(x,50),XK),[s]),P=(0,ut.useMemo)(()=>{let x=n.includes("?")?"&":"?";return`${n}${x}uri=${encodeURIComponent(e)}`},[n,e]),J=XU(),ge=(0,ut.useRef)(null),C=(0,ut.useRef)(void 0);(0,ut.useEffect)(()=>{let x=A1(e,J);return ge.current=x,()=>{clearTimeout(C.current),x.has("initialized")||x.report("timeout",S.current),ge.current=null}},[e,J]);let ze=(0,ut.useRef)(o);ze.current=o;let ot=(0,ut.useRef)(p);return(0,ut.useEffect)(()=>{ot.current=p,y.current.height=-1,w.current&&(w.current.cancel(),w.current=null)},[p]),(0,ut.useEffect)(()=>{if(!g.current)return;let x=h.current;x?.contentWindow&&x.contentWindow.postMessage({jsonrpc:"2.0",method:"ui/notifications/host-context-changed",params:{theme:o?"dark":"light"}},"*")},[o]),(0,ut.useEffect)(()=>{let x=h.current;if(!x)return;let te=!1,re=!1,ke=null,We=null,be=setTimeout(()=>{if(te||re||S.current>=eY)return;S.current+=1;let ce=new URL(x.src);ce.searchParams.set("_retry",String(S.current)),x.src=ce.toString()},QK),Oe=ce=>{x.contentWindow?.postMessage(ce,"*")},we=ce=>{if(te||ce.source!==x.contentWindow)return;let Le=ce.data;if(!Le||typeof Le!="object"||Le.jsonrpc!=="2.0")return;let ie=Le.method,xe=Le.id;if(ie==="ui/initialize"&&xe!=null){re=!0,ge.current?.mark("initialize"),clearTimeout(be),Oe({jsonrpc:"2.0",id:xe,result:{protocolVersion:Le.params?.protocolVersion??ZK,hostInfo:{name:"Waniwani Chat",version:"1.0.0"},hostCapabilities:{openLinks:{},message:{text:{}},tools:{},updateModelContext:{text:{},structuredContent:{}}},hostContext:{theme:ze.current?"dark":"light",displayMode:E.current}}});return}if(ie==="ui/notifications/initialized"){g.current=!0,ge.current?.mark("initialized"),C.current=setTimeout(()=>ge.current?.report("ok",S.current),tY);let Ne=v.current,_e=I.current,Fe=_e._meta&&typeof _e._meta=="object"?_e._meta:null,Ae=aY(Z.current),de=Fe&&typeof Fe.waniwani=="object"&&Fe.waniwani!==null?Fe.waniwani:null,W=de||Ae?{...de??{},...Ae?{sessionId:Ae}:{}}:void 0,ct=Fe||W?{...Fe??{},...W?{waniwani:W}:{}}:void 0;Oe({jsonrpc:"2.0",method:"ui/notifications/tool-input",params:{arguments:Ne}});let le=_e.content??[{type:"text",text:JSON.stringify(_e)}];Oe({jsonrpc:"2.0",method:"ui/notifications/tool-result",params:{content:le,structuredContent:_e.structuredContent,_meta:ct,meta:ct}});return}if(ie==="ui/notifications/size-changed"){clearTimeout(C.current),ge.current?.mark("firstSize"),ge.current?.report("ok",S.current);let Ne=Le.params,_e=typeof Ne?.height=="number"?Ne.height:void 0,Fe=typeof Ne?.width=="number"?Ne.width:void 0,Ae=y.current,de=_e!==void 0&&_e!==Ae.height,W=Fe!==void 0&&Fe!==Ae.width;if(!de&&!W)return;if(de&&_e!==void 0){if(Ae.height=_e,ot.current)return;let ct=B(_e),le=x.getBoundingClientRect().height;if(w.current&&(w.current.cancel(),w.current=null),R(ct),x.animate&&Math.abs(le-ct)>2){let oe=x.animate([{height:`${le}px`},{height:`${ct}px`}],{duration:JK,easing:"ease-out",fill:"forwards"});w.current=oe,oe.onfinish=()=>{w.current===oe&&(oe.cancel(),w.current=null)}}}W&&s&&Fe!==void 0&&(Ae.width=Fe,U(Fe));return}if(ie==="ui/open-link"&&xe!=null){let Ne=Le.params?.url;typeof Ne=="string"&&(A.current?A.current(Ne):window.open(Ne,"_blank","noopener,noreferrer")),Oe({jsonrpc:"2.0",id:xe,result:{}});return}if(ie==="ui/message"&&xe!=null){if(Q.current&&Le.params){let Ne=Le.params,_e=ke;if(ke=null,We){clearTimeout(We.timer);let Fe=We.text;We=null;let Ae=(Ne.content??[]).map(de=>de.text??"").join("").trim();Ne={...Ne,content:[{type:"text",text:`${Ae}
|
|
142
|
+
`))}function tM(e){return fetch(new URL(e.path,new URL(e.sessionApi,location.href)),{method:"POST",headers:{...e.headers(),"content-type":"application/json"},body:JSON.stringify(e.body),cache:"no-store",signal:e.signal})}function Zj(e){return async t=>{let a=await tM({...e,path:"followups",body:t,signal:AbortSignal.timeout(8e3)}),n=a.ok?await a.json():null,r=typeof n=="object"&&n!==null&&"data"in n?n.data:null,o=typeof r=="object"&&r!==null&&"suggestions"in r?r.suggestions:null;return Array.isArray(o)?o.filter(i=>typeof i=="string"):[]}}function Jj(e){let t="",a=!1,n=new Set;return new TransformStream({async transform(r,o){if(r.type==="text-delta"&&(t+=r.delta),r.type==="tool-input-available"&&n.add(r.toolName),r.type==="error"&&(a=!0),r.type==="finish"&&!a&&!e.signal?.aborted&&t.trim()){let i=await e.suggest(t,[...n]).catch(()=>[]);i.length>0&&o.enqueue({type:"data-suggestions",data:{suggestions:i}})}o.enqueue(r)}})}function Qj(e){return async t=>{let a=await tM({...e,path:e.sessionApi,body:t});if(!a.ok)throw new Error(`Opening the chat failed (${a.status})`);let n=await a.json(),r=typeof n=="object"&&n!==null&&"data"in n?n.data:null;if(typeof r!="object"||r===null||!("transport"in r))throw new Error("The session route answered no transport");if(r.transport!=="eve-native")return null;let o={...r},i=o.session,s=typeof i=="object"&&i!==null&&"sessionId"in i?i.sessionId:void 0,l=Bl(o,"conversationId"),u=Bl(o,"eveHost"),c=Bl(o,"accessToken"),d=Date.parse(Bl(o,"expiresAt")??"");if(!l||!u||!c||typeof s!="string"||Number.isNaN(d))throw new Error("The session route answered an incomplete session");return{conversationId:l,eveHost:u,sessionId:s,accessToken:c,expiresAt:d,followups:o.followups===!0}}}function eV(e){let t=e.extra;return typeof t=="object"&&t!==null&&!Array.isArray(t)?Object.fromEntries(Object.entries(t)):void 0}var dx=class{constructor(t){this.options=t;K(this,"pending");K(this,"threadOnFallback",!1);K(this,"generation",0)}get channelId(){return Bl(this.options.body(),"channelId")}key(){return ux({channelId:this.channelId,threadId:this.options.threadId()})}keepsSession(){return this.options.open!==void 0}prepare(){this.open(this.options.hasMessages())}open(t){this.options.open&&(this.pending??(this.pending=this.start(this.options.open,t)))}async restore(){let{open:t}=this.options;if(!t||this.options.threadHistory())return[];let a=this.key(),n=cx(a);if(!n)return[];let r=this.generation,o=Nl.resume({open:t,saved:n}).catch(()=>null).then(s=>this.kept(s,r));this.pending=o;let i=await o;return i?await kE(await i.history()):(Ul(a,null),this.pending===o&&(this.pending=void 0),[])}reset(){Ul(this.key(),null),this.dispose()}forget(t){Ul(ux({channelId:this.channelId,threadId:t}),null)}dispose(){this.generation+=1,this.threadOnFallback=!1,this.pending?.then(t=>t?.close()).catch(()=>{}),this.pending=void 0}async start(t,a){let n=this.generation,r=this.key(),o=cx(r);if(o){let u=await Nl.resume({open:t,saved:o}).catch(()=>null);return!u&&n===this.generation&&Ul(r,null),this.kept(u,n)}if(a)return null;let i=this.options.body(),s=await Nl.create({open:t,channelId:Bl(i,"channelId"),visitorId:Kj(i)}),l=this.kept(s,n);return n===this.generation&&Ul(r,l?.saved??null),l}kept(t,a){return t&&a!==this.generation?(t.close(),null):t}async sendMessages(t){let a=t.messages.filter(m=>m.role==="user").length<=1;a&&(this.threadOnFallback=!1);let r=[...t.messages].reverse().find(m=>m.role==="user")?.parts.some(m=>m.type==="file")??!1;if(this.threadOnFallback||r||!this.options.open)return this.threadOnFallback=!0,await this.options.fallback.sendMessages(t);this.open(!a);let o=await this.pending?.catch(()=>null);if(o?.used&&a&&(this.reset(),this.open(!1),o=await this.pending?.catch(()=>null)),!o)return this.threadOnFallback=!0,await this.options.fallback.sendMessages(t);this.options.onSession(o.sessionId);let{documents:i}=this.options.takeTurnInput(),s=Yj(t.messages),l=s.at(-1)??"",u=l.trim()?l:i?.map(m=>m.filename).join(", ")??l,c=o.turn(u,{documents:i,extra:eV(this.options.body())},t.abortSignal),{suggest:d}=this.options;if(!o.followups||!d)return c;let{saved:p}=o;return c.pipeThrough(Jj({suggest:(m,h)=>d({...p,answerText:m.slice(-8e3),recentUserMessages:s.slice(-3).map(v=>v.slice(-2e3)),toolNames:h.slice(0,20)}),signal:t.abortSignal}))}async reconnectToStream(t){return await this.pending?.catch(()=>null)?null:await this.options.fallback.reconnectToStream(t)}};function aM(e){let t=typeof e=="string"?()=>e:e;return a=>{let n=r=>{let o=t();return o?r(o):void 0};return new dx({...a,get open(){return n(r=>Qj({sessionApi:r,headers:a.headers}))},get suggest(){return n(r=>Zj({sessionApi:r,headers:a.headers}))}})}}function zl(e){let t=(0,gm.useRef)(e);t.current=e;let[a]=(0,gm.useState)(()=>aM(()=>t.current));return a}var nM=j(Ee(),1),rM="(max-width: 639px)";function tV(e){let t=window.matchMedia(rM);return t.addEventListener("change",e),()=>t.removeEventListener("change",e)}function aV(){return window.matchMedia(rM).matches}function nV(){return!1}function oM(){return(0,nM.useSyncExternalStore)(tV,aV,nV)}var ym=j(Ee(),1);function fx(e,t){return e.find(a=>a.text===t)?.id??null}async function iM(e){let{api:t,token:a,name:n,source:r,sessionId:o,properties:i}=e;if(typeof window>"u"||!t||!a)return;let s=Cc(t);if(s)try{let l=new Date().toISOString(),u=JSON.stringify({sentAt:l,source:{sdk:"@waniwani/sdk",version:"0.1.0"},events:[{id:crypto.randomUUID(),type:"mcp.event",name:n,source:r,timestamp:l,correlation:{visitorId:ma(),sessionId:o},properties:{...i,url:window.location.href},metadata:{}}]});await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:u,keepalive:!0})}catch{}}async function sM(e){let{api:t,token:a,channelId:n,mode:r,source:o,sessionId:i,promptId:s,origin:l,text:u,index:c}=e;await iM({api:t,token:a,name:"suggestion.clicked",source:o,sessionId:i,properties:{promptId:s,origin:l,text:u,index:c,channelId:n,mode:r}})}function lM(e,t){return t.map(a=>({id:fx(e,a),text:a}))}async function uM(e){let{api:t,token:a,channelId:n,mode:r,source:o,sessionId:i,prompts:s,origin:l}=e;s.length!==0&&await iM({api:t,token:a,name:"suggestion.shown",source:o,sessionId:i,properties:{prompts:s,count:s.length,origin:l,channelId:n,mode:r}})}function Fl(e){let{widgetEvents:t,api:a,token:n,channelId:r,source:o,mode:i,pagePrompts:s}=e,l=(0,ym.useRef)(e.getSessionId);l.current=e.getSessionId,(0,ym.useEffect)(()=>{if(!(!a||!n))return t.subscribe(u=>{if(u.name==="suggestion.clicked"){let{text:c,origin:d,index:p}=u.properties;sM({api:a,token:n,channelId:r,mode:i,source:o,sessionId:l.current(),promptId:fx(s??[],c),origin:d,text:c,index:p});return}if(u.name==="suggestions.shown"){let{texts:c,origin:d}=u.properties;uM({api:a,token:n,channelId:r,mode:i,source:o,sessionId:l.current(),prompts:lM(s??[],c),origin:d})}})},[t,a,n,r,o,i,s])}var ql=j(Ee(),1),rV=80,oV=50,iV=15e3,cM=500;function Hl(e,t=!0){let[a,n]=(0,ql.useState)(""),r=(0,ql.useRef)(void 0);return(0,ql.useEffect)(()=>{if(!t){n("");return}let o=0,i=!1,s=!1,l=()=>{s||(i?(o--,n(e.slice(0,o)),o<=0?(i=!1,r.current=setTimeout(l,cM)):r.current=setTimeout(l,oV)):(o++,n(e.slice(0,o)),o>=e.length?(i=!0,r.current=setTimeout(l,iV)):r.current=setTimeout(l,rV)))};return r.current=setTimeout(l,cM),()=>{s=!0,clearTimeout(r.current)}},[e,t]),a}var tr=j(Ee(),1);var dM=["en","fr","es"];function jl(e){return dM.includes(e)}function px(e){if(e&&jl(e))return e;if(e){let a=e.split("-")[0]?.toLowerCase();if(a&&jl(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(jl(n))return n;let r=n.split("-")[0];if(r&&jl(r))return r}return"en"}var wm={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 fM={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 pM={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 mx={en:wm,fr:pM,es:fM};var hM=j(me(),1),mM=(0,tr.createContext)(null);function sV(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 es({children:e,locale:t,messages:a}){let n=!!(t&&lV(t)),r=n?t:"en",[o,i]=(0,tr.useState)(r),[s,l]=(0,tr.useState)(n);(0,tr.useEffect)(()=>{i(px(t)),l(!0)},[t]);let u=(0,tr.useMemo)(()=>{let c=mx[o]??mx["en"];return{locale:o,t:sV(c,a),ready:s}},[o,a,s]);return(0,hM.jsx)(mM.Provider,{value:u,children:e})}function lV(e){return e==="en"||e==="fr"||e==="es"}function Ue(){let e=(0,tr.useContext)(mM);return e||{locale:"en",t:wm,ready:!0}}function hx(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 Qe=j(Ee(),1);var ud=(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 Be=j(Ee(),1);var ts=new Map;function gM(e,t){if(ts.has(e)){URL.revokeObjectURL(t);return}for(ts.set(e,t);ts.size>20;){let a=ts.keys().next();if(a.done)return;let n=ts.get(a.value);ts.delete(a.value),n&&URL.revokeObjectURL(n)}}function yM(e){return ts.get(e)}var wM=j(me(),1),br=({className:e,variant:t="default",size:a="default",type:n="button",...r})=>(0,wM.jsx)("button",{type:n,className:V("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 vM=j(Ee(),1);var Bt=j(me(),1),xM=({files:e,className:t,...a})=>e.length===0?null:(0,Bt.jsx)("div",{className:V("ww:flex ww:flex-wrap ww:gap-1.5",t),...a,children:e.map((n,r)=>(0,Bt.jsx)(uV,{file:n},r))});function uV({file:e}){let{t}=Ue();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)(vl,{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 bM(e,t){return e.startsWith("image/")?t.attachments.kindImage:e==="application/pdf"?t.attachments.kindPdf:t.attachments.kindFile}function cV({mediaType:e}){return e.startsWith("image/")?(0,Bt.jsx)(Dc,{className:"ww:size-5 ww:text-muted-foreground"}):e==="application/pdf"?(0,Bt.jsx)(Mc,{className:"ww:size-5 ww:text-muted-foreground"}):(0,Bt.jsx)(vl,{className:"ww:size-5 ww:text-muted-foreground"})}function gx({filename:e,mediaType:t,previewUrl:a,subtitle:n,tone:r="default",children:o,className:i}){let{t:s}=Ue(),l=bM(t,s);return(0,Bt.jsxs)("li",{"aria-label":`${e}, ${l}`,className:V("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)(cV,{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:V("ww:truncate ww:text-xs",r==="error"?"ww:text-destructive":"ww:text-muted-foreground"),children:n??l})]}),o]})}function SM(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 IM=({documents:e,className:t,...a})=>e.length===0?null:(0,Bt.jsx)("ul",{className:V("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)(dV,{document:n},`${n.documentId}-${r}`))});function dV({document:e}){let{t}=Ue(),[a,n]=(0,vM.useState)(!1),r=e.mediaType.startsWith("image/")?yM(e.documentId):void 0;return r&&!a?(0,Bt.jsx)("li",{children:(0,Bt.jsx)("img",{alt:`${e.filename}, ${bM(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)(gx,{filename:e.filename,mediaType:e.mediaType})}var Et=j(me(),1),fV=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}},pV=(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)},kM=(0,Be.createContext)(null),vm=()=>{let e=(0,Be.useContext)(kM);if(!e)throw new Error("usePromptInputAttachments must be used within a PromptInput");return e},TM=({className:e,accept:t,multiple:a,globalDrop:n,maxFiles:r,maxFileSize:o,maxPdfPages:i,attachmentsEnabled:s=!0,upload:l,onDiscard:u,onError:c,onSubmit:d,children:p,...m})=>{let{t:h,locale:v}=Ue(),I=(0,Be.useRef)(null),y=(0,Be.useRef)(null),[w,g]=(0,Be.useState)([]),S=(0,Be.useRef)(w),E=(0,Be.useRef)(new Map),T=(0,Be.useRef)(l),R=(0,Be.useRef)(c),O=(0,Be.useRef)(u);(0,Be.useEffect)(()=>{T.current=l,R.current=c,O.current=u},[l,c,u]);let U=(0,Be.useCallback)(x=>{S.current=x,g(x)},[]),A=(0,Be.useCallback)(()=>{I.current?.click()},[]),Q=(0,Be.useCallback)((x,te)=>{U(S.current.map(re=>re.id===x?{...re,...te}:re))},[U]),$=(0,Be.useCallback)((x,te)=>{let re=T.current;if(!re)return;let ke=new AbortController,We=re(te,ke.signal,be=>{Q(x,{progress:be})}).then(be=>(Q(x,{status:"ready",progress:1,documentId:be.documentId,error:void 0}),be)).catch(be=>{if(ke.signal.aborted)return null;let Oe=be instanceof Error?be.message:h.promptInput.uploadFailed;return Q(x,{status:"failed",error:Oe}),R.current?.({code:"upload_failed",message:Oe}),null});E.current.set(x,{file:te,controller:ke,done:We})},[Q,h]),H=(0,Be.useCallback)(x=>{let te=[...x];if(!s||te.length===0)return;let re=(ce,Le)=>R.current?.({code:ce,message:Le}),ke=[];for(let ce of te){if(!pV(ce,t)){re("accept",h.promptInput.errorAccept.replace("{name}",ce.name));continue}if(o&&ce.size>o){re("max_file_size",h.promptInput.errorTooLarge.replace("{name}",ce.name).replace("{limit}",LM(o,v)));continue}ke.push(ce)}if(ke.length===0)return;let We=typeof r=="number"?Math.max(0,r-S.current.length):void 0,be=typeof We=="number"?ke.slice(0,We):ke;if(be.length<ke.length&&re("max_files",h.promptInput.errorTooMany.replace("{limit}",String(r))),be.length===0)return;let Oe=!!T.current,we=be.map(ce=>({file:ce,item:{filename:ce.name,id:ud(),mediaType:ce.type,type:"file",url:URL.createObjectURL(ce),status:Oe?"uploading":"ready",progress:0}}));U([...S.current,...we.map(ce=>ce.item)]);for(let ce of we)$(ce.item.id,ce.file)},[r,o,t,s,$,U,h,v]),Z=(0,Be.useCallback)(x=>{let te=E.current.get(x);te&&(Q(x,{status:"uploading",progress:0,error:void 0}),$(x,te.file))},[Q,$]),X=(0,Be.useCallback)((x,te)=>{E.current.get(x.id)?.controller.abort(),E.current.delete(x.id),x.url&&(!te&&!!x.documentId&&!!x.mediaType?.startsWith("image/")&&x.documentId?gM(x.documentId,x.url):URL.revokeObjectURL(x.url)),te&&x.documentId&&O.current?.({documentId:x.documentId,filename:x.filename??"",mediaType:x.mediaType??""})},[]),B=(0,Be.useCallback)(x=>{let te=S.current.find(re=>re.id===x);te&&X(te,!0),U(S.current.filter(re=>re.id!==x))},[X,U]),P=(0,Be.useCallback)(()=>{for(let x of S.current)X(x,!0);U([])},[X,U]),J=(0,Be.useRef)(s);(0,Be.useEffect)(()=>{let x=J.current;J.current=s,x&&!s&&P()},[s,P]);let ge=(0,Be.useCallback)(()=>{for(let x of S.current)X(x,!1);U([])},[X,U]);(0,Be.useEffect)(()=>()=>{for(let x of S.current)E.current.get(x.id)?.controller.abort(),x.url&&URL.revokeObjectURL(x.url)},[]);let C=(0,Be.useCallback)(x=>{x.currentTarget.files&&H(x.currentTarget.files),x.currentTarget.value=""},[H]);(0,Be.useEffect)(()=>{if(!n)return;let x=re=>{re.dataTransfer?.types?.includes("Files")&&re.preventDefault()},te=re=>{re.dataTransfer?.types?.includes("Files")&&re.preventDefault(),re.dataTransfer?.files&&re.dataTransfer.files.length>0&&H(re.dataTransfer.files)};return document.addEventListener("dragover",x),document.addEventListener("drop",te),()=>{document.removeEventListener("dragover",x),document.removeEventListener("drop",te)}},[H,n]);let ze=(0,Be.useCallback)(async x=>{x.preventDefault();let te=x.currentTarget,re=new FormData(te).get("message")||"",ke=new Map;for(;ke.size<E.current.size;)await Promise.all([...E.current.entries()].filter(([we])=>!ke.has(we)).map(async([we,ce])=>{ke.set(we,await ce.done)}));for(let we of ke.keys())E.current.has(we)||ke.delete(we);if([...ke.values()].some(we=>we===null)){R.current?.({code:"upload_failed",message:h.promptInput.uploadFailed});return}let We=[...ke.values()].filter(we=>we!==null),be=T.current?[]:S.current,Oe=await Promise.all(be.map(async({id:we,status:ce,progress:Le,error:ie,...xe})=>{if(xe.url?.startsWith("blob:")){let Ne=await fV(xe.url);return{...xe,url:Ne??xe.url}}return xe}));try{let we=d({documents:We,files:Oe,text:re},x);we instanceof Promise&&await we,te.reset(),ge()}catch{}},[d,ge,h]),ot=(0,Be.useMemo)(()=>({add:H,clear:P,files:w,openFileDialog:A,remove:B,retry:Z,maxFileSize:o,maxPdfPages:i}),[w,H,B,Z,P,A,o,i]);return(0,Et.jsxs)(kM.Provider,{value:ot,children:[(0,Et.jsx)("input",{accept:t,"aria-label":h.promptInput.uploadFiles,className:"ww:hidden",multiple:a,onChange:C,ref:I,title:h.promptInput.uploadFiles,type:"file"}),(0,Et.jsx)("form",{className:V("ww:relative ww:flex ww:w-full ww:flex-col ww:rounded-lg ww:border ww:border-border ww:bg-background",e),onSubmit:ze,ref:y,...m,children:p})]})},CM=1024*1024;function LM(e,t){let a=e>=CM;return new Intl.NumberFormat(t,{style:"unit",unit:a?"megabyte":"kilobyte",maximumFractionDigits:0}).format(a?e/CM:Math.max(1,e/1024))}var EM=({onChange:e,onKeyDown:t,className:a,placeholder:n,...r})=>{let{t:o}=Ue(),i=vm(),[s,l]=(0,Be.useState)(!1),u=n??o.promptInput.placeholder,c=(0,Be.useCallback)(p=>{if(t?.(p),!p.defaultPrevented){if(p.key==="Enter"){if(s||p.nativeEvent.isComposing||p.shiftKey)return;p.preventDefault();let{form:m}=p.currentTarget;if(m?.querySelector('[data-submit-blocked="true"]')||m?.querySelector('button[type="submit"]')?.disabled)return;m?.requestSubmit()}if(p.key==="Backspace"&&p.currentTarget.value===""&&i.files.length>0){p.preventDefault();let m=i.files.at(-1);m&&i.remove(m.id)}}},[t,s,i]),d=(0,Be.useCallback)(p=>{let m=p.clipboardData?.items;if(!m)return;let h=[];for(let v of m)if(v.kind==="file"){let I=v.getAsFile();I&&h.push(I)}h.length>0&&(p.preventDefault(),i.add(h))},[i]);return(0,Et.jsx)("textarea",{className:V("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:()=>l(!1),onCompositionStart:()=>l(!0),onKeyDown:c,onPaste:d,placeholder:u,onChange:e,...r})},AM=({className:e,status:t,onStop:a,onClick:n,children:r,disabled:o,...i})=>{let{t:s}=Ue(),l=t==="submitted"||t==="streaming",u=l&&a!==void 0,c=(0,Et.jsx)(pr,{className:"ww:size-4"});t==="submitted"?c=(0,Et.jsx)(_c,{className:"ww:size-4 ww:animate-spin"}):t==="streaming"&&(c=(0,Et.jsx)(Pc,{className:"ww:size-4"}));let d=(0,Be.useCallback)(p=>{if(l&&a){p.preventDefault(),a();return}n?.(p)},[l,a,n]);return(0,Et.jsx)(br,{"aria-label":l?s.promptInput.stop:s.promptInput.submit,className:V("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})},MM=({className:e,children:t,...a})=>{let{t:n,locale:r}=Ue(),o=vm();if(o.files.length>0)return(0,Et.jsxs)(br,{className:V("ww:group ww:relative",e),onClick:()=>o.clear(),size:"icon-sm",type:"button",variant:"ghost","aria-label":n.promptInput.removeAttachments,...a,children:[(0,Et.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,Et.jsx)(wn,{className:"ww:absolute ww:size-4 ww:opacity-0 ww:transition-opacity ww:group-hover:opacity-100"})]});let s=o.maxFileSize?(o.maxPdfPages?n.promptInput.uploadFilesUpToWithPages.replace("{pages}",String(o.maxPdfPages)):n.promptInput.uploadFilesUpTo).replace("{limit}",LM(o.maxFileSize,r)):n.promptInput.uploadFiles;return(0,Et.jsx)(br,{"aria-label":s,className:V(e),title:s,onClick:()=>o.openFileDialog(),size:"icon-sm",type:"button",variant:"ghost",...a,children:t??(0,Et.jsx)(xl,{className:"ww:size-4"})})},RM=({className:e,...t})=>{let a=vm();return a.files.length===0?null:(0,Et.jsx)("ul",{className:V("ww:flex ww:list-none ww:flex-wrap ww:gap-2 ww:p-0",e),...t,children:a.files.map(n=>(0,Et.jsx)(mV,{file:n},n.id))})};function mV({file:e}){let{t}=Ue(),a=vm(),n=e.status==="failed",r=e.status==="uploading";return(0,Et.jsxs)(gx,{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,Et.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,Et.jsx)("button",{"aria-label":t.promptInput.removeAttachment,className:V("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,Et.jsx)(wn,{className:"ww:size-3.5"})}),r?(0,Et.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 DM=({enabled:e=!0})=>{let{t}=Ue(),[a,n]=(0,Be.useState)(!1);return(0,Be.useEffect)(()=>{if(!e)return;let r=0,o=u=>!!u.dataTransfer?.types?.includes("Files"),i=u=>{o(u)&&(r+=1,n(!0))},s=u=>{o(u)&&(r=Math.max(0,r-1),r===0&&n(!1))},l=()=>{r=0,n(!1)};return document.addEventListener("dragenter",i),document.addEventListener("dragleave",s),document.addEventListener("drop",l),()=>{document.removeEventListener("dragenter",i),document.removeEventListener("dragleave",s),document.removeEventListener("drop",l)}},[e]),e&&a?(0,Et.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,Et.jsxs)("span",{className:"ww:flex ww:items-center ww:gap-2 ww:text-sm ww:font-medium",children:[(0,Et.jsx)(xl,{className:"ww:size-4"}),t.promptInput.dropToAttach]})}):null};var PM=j(me(),1);function _M({text:e}){let{t}=Ue();return e===!1?null:(0,PM.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 xm=j(Ee(),1);var as=j(me(),1),OM=({className:e,...t})=>(0,as.jsx)("div",{className:V("ww:flex ww:flex-col ww:gap-1 ww:px-3 ww:py-2",e),...t}),NM=({className:e,...t})=>(0,as.jsx)("li",{className:V("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}),UM=({className:e,...t})=>(0,as.jsx)("span",{className:V("ww:inline-block ww:size-2 ww:shrink-0 ww:rounded-full ww:border ww:border-muted-foreground/50",e),...t}),BM=({className:e,...t})=>(0,as.jsx)("span",{className:V("ww:line-clamp-1 ww:grow ww:break-words ww:text-muted-foreground",e),...t}),zM=({className:e,...t})=>(0,as.jsx)("div",{className:V("ww:flex ww:shrink-0 ww:gap-1 ww:opacity-0 ww:transition-opacity ww:group-hover:opacity-100",e),...t}),FM=({className:e,...t})=>(0,as.jsx)(br,{className:V("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 Un=j(me(),1),qM=(0,xm.memo)(({message:e,onRemove:t})=>{let{t:a}=Ue(),n=(0,xm.useCallback)(()=>t(e.id),[t,e.id]);return(0,Un.jsxs)(NM,{children:[(0,Un.jsx)(UM,{}),(0,Un.jsx)(BM,{children:e.text||a.chatQueue.attachmentFallback}),(0,Un.jsx)(zM,{children:(0,Un.jsx)(FM,{"aria-label":a.chatQueue.removeFromQueue,onClick:n,children:(0,Un.jsx)(wn,{className:"ww:size-3"})})})]})});qM.displayName="ChatQueueItem";function HM({queuedMessages:e,onRemove:t,className:a}){let{t:n}=Ue();return e.length===0?null:(0,Un.jsxs)(OM,{className:V("ww:border-t ww:border-border",a),children:[(0,Un.jsx)("div",{className:"ww:text-[11px] ww:font-medium ww:text-muted-foreground ww:px-2",children:n.chatQueue.queued(e.length)}),(0,Un.jsx)("ul",{children:e.map(r=>(0,Un.jsx)(qM,{message:r,onRemove:t},r.id))})]})}var nn=j(Ee(),1);var zt=j(Ee(),1);Ch();var xU=j(Ee(),1);var bU=j(me(),1),PK=({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,bU.jsx)(e,{"data-waniwani-shimmer":"",className:V("ww:inline-block",t),style:i,...o,children:r})},or=(0,xU.memo)(PK);or.displayName="Shimmer";var Da=j(me(),1),SU=(0,zt.createContext)(null);function IU(){let e=(0,zt.useContext)(SU);if(!e)throw new Error("Reasoning components must be used within <Reasoning>");return e}var OK=1e3,NK=1e3,Ud=(0,zt.memo)(({className:e,isStreaming:t=!1,open:a,defaultOpen:n,onOpenChange:r,duration:o,children:i,...s})=>{let l=n??t,u=n===!1,c=a!==void 0,[d,p]=(0,zt.useState)(l),m=c?a:d,h=(0,zt.useCallback)(R=>{c||p(R),r?.(R)},[c,r]),[v,I]=(0,zt.useState)(void 0),y=o??v,w=(0,zt.useRef)(t),[g,S]=(0,zt.useState)(!1),E=(0,zt.useRef)(null);(0,zt.useEffect)(()=>{t?(w.current=!0,E.current===null&&(E.current=Date.now())):E.current!==null&&(I(Math.ceil((Date.now()-E.current)/NK)),E.current=null)},[t]),(0,zt.useEffect)(()=>{t&&!m&&!u&&h(!0)},[t,m,u,h]),(0,zt.useEffect)(()=>{if(w.current&&!t&&m&&!g){let R=setTimeout(()=>{h(!1),S(!0)},OK);return()=>clearTimeout(R)}},[t,m,g,h]);let T=(0,zt.useMemo)(()=>({isStreaming:t,isOpen:m,setIsOpen:h,duration:y}),[t,m,h,y]);return(0,Da.jsx)(SU.Provider,{value:T,children:(0,Da.jsx)("div",{className:V("ww:mb-4 ww:flex ww:flex-col ww:gap-2",e),"data-state":m?"open":"closed",style:{animation:"ww-fade-in 0.2s ease-out"},...s,children:i})})});Ud.displayName="Reasoning";var Bd=(0,zt.memo)(({className:e,children:t,getThinkingMessage:a,hideIcon:n=!1,onClick:r,...o})=>{let{t:i}=Ue(),{isStreaming:s,isOpen:l,duration:u,setIsOpen:c}=IU(),p=a??((m,h)=>m||h===0?(0,Da.jsx)(or,{duration:1.6,children:i.reasoning.thinking}):h===void 0?(0,Da.jsx)("span",{children:i.reasoning.thoughtBrief}):(0,Da.jsx)("span",{children:i.reasoning.thoughtForSeconds(h)}));return(0,Da.jsx)("button",{type:"button","aria-expanded":l,onClick:m=>{c(!l),r?.(m)},className:V("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,Da.jsxs)(Da.Fragment,{children:[!n&&(0,Da.jsx)(Gr,{className:"ww:size-4 ww:shrink-0"}),p(s,u)]})})});Bd.displayName="ReasoningTrigger";var zd=(0,zt.memo)(({className:e,children:t,...a})=>{let{isOpen:n}=IU();return(0,Da.jsx)("div",{className:V("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,Da.jsx)("div",{className:"ww:min-h-0 ww:overflow-hidden",children:(0,Da.jsx)("div",{className:V("ww:text-sm ww:text-muted-foreground",e),...a,children:(0,Da.jsx)(au,{children:t})})})})});zd.displayName="ReasoningContent";var Ye=j(me(),1),UK=500,CU=(0,nn.createContext)(null);function kU(){let e=(0,nn.useContext)(CU);if(!e)throw new Error("ChainOfThought components must be used within <ChainOfThought>");return e}function TU({className:e,isWorking:t=!1,activeStep:a,open:n,defaultOpen:r=!1,onOpenChange:o,children:i,...s}){let l=n!==void 0,[u,c]=(0,nn.useState)(r),d=l?n:u,p=(0,nn.useCallback)(I=>{l||c(I),o?.(I)},[l,o]),[m,h]=(0,nn.useState)(!t);(0,nn.useEffect)(()=>{if(t){h(!1);return}let I=setTimeout(()=>h(!0),UK);return()=>clearTimeout(I)},[t]);let v=(0,nn.useMemo)(()=>({open:d,setOpen:p,isWorking:t,settled:m,activeStep:a}),[d,p,t,m,a]);return(0,Ye.jsx)(CU.Provider,{value:v,children:(0,Ye.jsx)("div",{className:V("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"},...s,children:i})})}function LU({className:e,label:t,workingLabel:a,children:n,...r}){let{open:o,setOpen:i,isWorking:s,settled:l,activeStep:u}=kU();if(!l){let c=u?.icon,d=u?.label??a??t??"";return(0,Ye.jsx)("div",{className:V("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,Ye.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,Ye.jsx)(c,{className:V("ww:size-4 ww:shrink-0",s&&"ww:animate-pulse")}),(0,Ye.jsx)("span",{className:"ww:truncate",children:s?(0,Ye.jsx)(or,{duration:2.6,children:d}):d})]},d)})}return(0,Ye.jsxs)("button",{type:"button",onClick:()=>i(!o),"aria-expanded":o,className:V("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,Ye.jsx)("span",{className:"ww:truncate",children:n??t}),(0,Ye.jsx)(zo,{className:V("ww:size-4 ww:shrink-0 ww:transition-transform ww:duration-200",o&&"ww:rotate-180")})]})}function EU({className:e,children:t,...a}){let{open:n}=kU();return(0,Ye.jsx)("div",{className:V("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,Ye.jsx)("div",{className:"ww:min-h-0 ww:overflow-hidden",children:(0,Ye.jsx)("div",{className:V("ww:flex ww:flex-col",e),...a,children:t})})})}function AU({icon:e,isLast:t,running:a,error:n}){return(0,Ye.jsxs)("div",{className:"ww:flex ww:flex-col ww:items-center ww:self-stretch",children:[(0,Ye.jsx)("span",{className:"ww:flex ww:h-5 ww:items-center",children:(0,Ye.jsx)(e,{className:V("ww:size-4 ww:shrink-0",n?"ww:text-destructive":a?"ww:animate-pulse ww:text-foreground":"ww:text-muted-foreground")})}),!t&&(0,Ye.jsx)("span",{className:"ww:w-px ww:flex-1 ww:bg-border"})]})}function VS({className:e,icon:t,title:a,state:n,isLast:r=!1,children:o,...i}){let s=n==="input-available"||n==="input-streaming",l=n==="output-error",u=o!=null,[c,d]=(0,nn.useState)(!1),p=a??"",m=s?(0,Ye.jsx)(or,{duration:1.6,children:p}):(0,Ye.jsx)("span",{className:"ww:truncate",children:p});return(0,Ye.jsxs)("div",{className:V("ww:flex ww:gap-2",e),...i,children:[(0,Ye.jsx)(AU,{icon:t,isLast:r,running:s,error:l}),(0,Ye.jsxs)("div",{className:V("ww:min-w-0 ww:flex-1",!r&&"ww:pb-3"),children:[u?(0,Ye.jsxs)("button",{type:"button",onClick:()=>d(h=>!h),"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:[m,(0,Ye.jsx)(zo,{className:V("ww:size-3.5 ww:shrink-0 ww:transition-transform ww:duration-200",c&&"ww:rotate-180")})]}):(0,Ye.jsx)("div",{className:"ww:flex ww:items-center ww:text-sm ww:text-muted-foreground",children:m}),u&&(0,Ye.jsx)("div",{className:V("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,Ye.jsx)("div",{className:"ww:min-h-0 ww:overflow-hidden",children:(0,Ye.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 MU({isStreaming:e=!1,isLast:t=!1,children:a}){return(0,Ye.jsxs)("div",{className:"ww:flex ww:gap-2",children:[(0,Ye.jsx)(AU,{icon:Gr,isLast:t,running:e}),(0,Ye.jsx)("div",{className:V("ww:min-w-0 ww:flex-1",!t&&"ww:pb-3"),children:(0,Ye.jsxs)(Ud,{isStreaming:e,className:"ww:mb-0",children:[(0,Ye.jsx)(Bd,{hideIcon:!0}),(0,Ye.jsx)(zd,{children:a})]})})]})}var $S={name:"cjk-noop",type:"cjk",remarkPluginsBefore:[],remarkPluginsAfter:[],remarkPlugins:[]};var RU={name:"shiki-noop",type:"code-highlighter",supportsLanguage:()=>!1,getSupportedLanguages:()=>[],getThemes:()=>["github-light","github-dark"],highlight:()=>null};var PU=j(Ee(),1);var oo=j(Ee(),1),BK=5,DU=400;function _U(e,t,a={}){let{msPerChar:n=BK}=a,[r,o]=(0,oo.useState)(t?"":e),i=(0,oo.useRef)(e),s=(0,oo.useRef)(t?0:e.length),l=(0,oo.useRef)(0),u=(0,oo.useRef)(null);return(e.length<s.current||!e.startsWith(r.slice(0,s.current)))&&(s.current=t?0:e.length),i.current=e,(0,oo.useEffect)(()=>{if(!t){u.current!==null&&(cancelAnimationFrame(u.current),u.current=null),s.current=e.length,o(e);return}if(i.current.length-s.current>DU&&(s.current=i.current.length-DU),u.current!==null)return;let d=p=>{let m=i.current;if(s.current>=m.length){u.current=null;return}l.current===0&&(l.current=p);let h=p-l.current;if(h>=n){let v=Math.min(Math.floor(h/n),m.length-s.current);s.current+=v,o(m.slice(0,s.current)),l.current=p}u.current=requestAnimationFrame(d)};return u.current=requestAnimationFrame(d),()=>{u.current!==null&&(cancelAnimationFrame(u.current),u.current=null)}},[e,t,n]),r}var Fd=j(me(),1),WS=({className:e,from:t,children:a,...n})=>(0,Fd.jsx)("div",{className:V("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,Fd.jsx)("div",{className:V("ww:flex ww:min-w-0 ww:flex-col ww:gap-2","ww:w-full"),children:a})}),GS=({children:e,className:t,...a})=>(0,Fd.jsx)("div",{className:V("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}),zK={cjk:$S,code:RU},FK={cjk:$S},qK={enabled:!1};function HK({className:e,linkSafety:t,isStreaming:a,children:n,...r}){let i=_U(typeof n=="string"?n:"",!!a),s=typeof n=="string"?i:n;return(0,Fd.jsx)(au,{className:V("ww:size-full ww:[&>*:first-child]:mt-0 ww:[&>*:last-child]:mb-0",e),linkSafety:t??qK,plugins:a?FK:zK,...r,children:s})}var Ah=(0,PU.memo)(HK,(e,t)=>e.children===t.children&&e.isStreaming===t.isStreaming);Ah.displayName="MessageResponse";var ua=j(Ee(),1);function XS(e){if(!(typeof e!="object"||e===null))return e}function OU(e){return XS(e?.ui)}function KS(e){if(!e)return;let t=OU(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 qd(e){return OU(e)?.autoHeight===!0}function YS(e){return XS(XS(e)?._meta)}var qe=j(me(),1);function jK(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,s]of n){if(o<=8)break;let l=i.length>4?`${i.slice(0,4)}\u2026`:i,u;typeof s=="string"?u=s.length>2?`'${s.slice(0,1)}\u2026`:`'${s}'`:Array.isArray(s)?u=`Array(${s.length})`:typeof s=="object"&&s!==null?u="{\u2026}":u=String(s);let c=`${l}\u2009${u}`;r.push(c),o-=c.length+3}return`{${r.join(", ")}}`}function VK({text:e,className:t}){let{t:a}=Ue(),[n,r]=(0,ua.useState)(!1),o=(0,ua.useRef)(null);(0,ua.useEffect)(()=>()=>{o.current&&clearTimeout(o.current)},[]);let i=(0,ua.useCallback)(async s=>{s.stopPropagation();try{await navigator.clipboard.writeText(e),r(!0),o.current&&clearTimeout(o.current),o.current=setTimeout(()=>r(!1),2e3)}catch{}},[e]);return(0,qe.jsx)(br,{variant:"ghost",size:"sm",onClick:i,className:V("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,qe.jsxs)(qe.Fragment,{children:[(0,qe.jsx)(Lc,{className:"ww:size-3.5"}),(0,qe.jsx)("span",{children:a.tool.copied})]}):(0,qe.jsxs)(qe.Fragment,{children:[(0,qe.jsx)(Ac,{className:"ww:size-3.5"}),(0,qe.jsx)("span",{children:a.tool.copy})]})})}function NU({data:e,label:t,className:a,...n}){let[r,o]=(0,ua.useState)(!1),i=(0,ua.useMemo)(()=>JSON.stringify(e,null,2),[e]),s=jK(e);return(0,qe.jsxs)("div",{className:V("ww:rounded-lg ww:bg-tool-card",a),...n,children:[(0,qe.jsxs)("div",{className:"ww:flex ww:items-center ww:justify-between ww:px-3 ww:pt-2.5 ww:pb-1.5",children:[(0,qe.jsx)("span",{className:"ww:text-xs ww:font-medium ww:text-muted-foreground",children:t}),(0,qe.jsx)(VK,{text:i})]}),(0,qe.jsxs)("button",{type:"button",onClick:()=>o(l=>!l),className:"ww:flex ww:w-full ww:items-start ww:gap-2 ww:px-3 ww:pb-3 ww:text-left",children:[(0,qe.jsx)(Ec,{className:V("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,qe.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,qe.jsx)("code",{children:i})}):(0,qe.jsx)("span",{className:"ww:truncate ww:text-xs ww:font-mono ww:text-foreground/80",children:s})]})]})}var ZS=(0,ua.createContext)({open:!1,toggle:()=>{}});function UU({className:e,defaultOpen:t=!1,children:a,...n}){let[r,o]=(0,ua.useState)(t);return(0,qe.jsx)(ZS.Provider,{value:{open:r,toggle:()=>o(i=>!i)},children:(0,qe.jsx)("div",{className:V("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 BU({className:e,title:t,state:a,...n}){let{open:r,toggle:o}=(0,ua.useContext)(ZS),i=a==="input-available"||a==="input-streaming",s=t??"";return(0,qe.jsxs)("button",{type:"button",onClick:o,className:V("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,qe.jsx)(_i,{className:"ww:size-4 ww:shrink-0"}),(0,qe.jsx)("span",{className:"ww:truncate",children:i?(0,qe.jsx)(or,{duration:1.6,children:s}):s}),(0,qe.jsx)(zo,{className:V("ww:size-4 ww:shrink-0 ww:transition-transform ww:duration-200",r&&"ww:rotate-180")})]})}function zU({className:e,title:t,state:a,...n}){let r=a==="input-available"||a==="input-streaming",o=t??"";return(0,qe.jsx)("div",{className:V("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,qe.jsx)("span",{className:"ww:truncate",children:r?(0,qe.jsx)(or,{duration:1.6,children:o}):o})})}function FU({className:e,children:t,...a}){let{open:n}=(0,ua.useContext)(ZS);return(0,qe.jsx)("div",{className:V("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,qe.jsx)("div",{className:"ww:min-h-0 ww:overflow-hidden",children:(0,qe.jsx)("div",{className:V("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 $K(e,t){if(t||typeof e!="object"||e===null||Array.isArray(e))return e;let{_meta:a,...n}=e;return n}function JS({className:e,input:t,debug:a,...n}){let{t:r}=Ue(),o=(0,ua.useMemo)(()=>$K(t,a),[t,a]);return(0,qe.jsx)(NU,{data:o,label:r.tool.request,className:e,...n})}function Hd(e,t,a){if(e){let n=KS(a?.[e]?._meta);if(n)return n}return KS(YS(t))}function qU(e,t,a){return e&&qd(a?.[e]?._meta)?!0:qd(YS(t))}function QS({className:e,output:t,errorText:a,debug:n,...r}){let{t:o}=Ue(),i=(0,ua.useMemo)(()=>{if(!n&&typeof t=="object"&&t!==null&&!Array.isArray(t)){let{_meta:s,...l}=t;return l}return t},[t,n]);return t||a?a?(0,qe.jsxs)("div",{className:V("ww:space-y-2",e),...r,children:[(0,qe.jsx)("h4",{className:"ww:text-xs ww:font-medium ww:uppercase ww:tracking-wide ww:text-muted-foreground",children:o.tool.error}),(0,qe.jsx)("div",{className:"ww:rounded-lg ww:bg-destructive/10 ww:p-3 ww:text-xs ww:text-destructive",children:a})]}):(0,qe.jsx)(NU,{data:i,label:o.tool.response,className:e,...r}):null}var jd=j(me(),1);function HU(e){return e.type==="text"||e.type==="reasoning"||e.type==="file"||"toolCallId"in e}function jU(e){return e.parts.some(HU)}function VU(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=>!(!HU(o)||a?.ignoreToolParts&&"toolCallId"in o||a?.ignoreReasoningParts&&o.type==="reasoning"))}function $U({className:e,...t}){let{t:a}=Ue();return(0,jd.jsxs)("div",{"aria-live":"polite",className:V("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,jd.jsx)(Oc,{className:"ww:size-4 ww:shrink-0"}),(0,jd.jsx)(or,{duration:1.6,children:a.workingIndicator.default})]})}var ut=j(Ee(),1);function nu(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 WU(e,t){return!nu(e)&&!nu(t)?null:nu(e)?nu(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 io=j(Ee(),1);var GU=(0,io.createContext)(()=>{});function XU(){return(0,io.useContext)(GU)}var KU=GU.Provider;function WK(e){let t=window.requestIdleCallback;typeof t=="function"?t(e):setTimeout(e,500)}function ru(e){let t=(0,io.useRef)(e);t.current=e;let a=(0,io.useRef)(!1);(0,io.useEffect)(()=>{if(!e.painted||a.current)return;a.current=!0;let n=requestAnimationFrame(()=>{let r=t.current;Di(r.paintMark),WK(()=>L1(r))});return()=>cancelAnimationFrame(n)},[e.painted])}var YU=j(me(),1),GK="/api/mcp/resource",XK=500,KK=0,YK=16,ZK="2026-01-26",JK=300,QK=3e3,eY=3,tY=2e3;function aY(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}function nY(e,t,a){return Hd(e,t,a)?!1:t._meta?.["waniwani/autoInjectResultText"]!==!1}function Mh({resourceUri:e,toolInput:t,toolResult:a,resourceEndpoint:n=GK,chatSessionId:r,isDark:o=!1,className:i,autoHeight:s=!1,onOpenLink:l,onFollowUp:u,onCallTool:c,onDisplayModeChange:d,isFullscreen:p=!1,toolDefinitions:m}){let h=(0,ut.useRef)(null),v=(0,ut.useRef)(t),I=(0,ut.useRef)(a),y=(0,ut.useRef)({width:0,height:0}),w=(0,ut.useRef)(null),g=(0,ut.useRef)(!1),S=(0,ut.useRef)(0),E=(0,ut.useRef)("inline"),[T,R]=(0,ut.useState)(KK),[O,U]=(0,ut.useState)(void 0),A=(0,ut.useRef)(l),Q=(0,ut.useRef)(u),$=(0,ut.useRef)(c),H=(0,ut.useRef)(d),Z=(0,ut.useRef)(r),X=(0,ut.useRef)(m);v.current=t,I.current=a,A.current=l,Q.current=u,$.current=c,H.current=d,Z.current=r,X.current=m;let B=(0,ut.useCallback)(x=>s?Math.max(x+YK,0):Math.min(Math.max(x,50),XK),[s]),P=(0,ut.useMemo)(()=>{let x=n.includes("?")?"&":"?";return`${n}${x}uri=${encodeURIComponent(e)}`},[n,e]),J=XU(),ge=(0,ut.useRef)(null),C=(0,ut.useRef)(void 0);(0,ut.useEffect)(()=>{let x=A1(e,J);return ge.current=x,()=>{clearTimeout(C.current),x.has("initialized")||x.report("timeout",S.current),ge.current=null}},[e,J]);let ze=(0,ut.useRef)(o);ze.current=o;let ot=(0,ut.useRef)(p);return(0,ut.useEffect)(()=>{ot.current=p,y.current.height=-1,w.current&&(w.current.cancel(),w.current=null)},[p]),(0,ut.useEffect)(()=>{if(!g.current)return;let x=h.current;x?.contentWindow&&x.contentWindow.postMessage({jsonrpc:"2.0",method:"ui/notifications/host-context-changed",params:{theme:o?"dark":"light"}},"*")},[o]),(0,ut.useEffect)(()=>{let x=h.current;if(!x)return;let te=!1,re=!1,ke=null,We=null,be=setTimeout(()=>{if(te||re||S.current>=eY)return;S.current+=1;let ce=new URL(x.src);ce.searchParams.set("_retry",String(S.current)),x.src=ce.toString()},QK),Oe=ce=>{x.contentWindow?.postMessage(ce,"*")},we=ce=>{if(te||ce.source!==x.contentWindow)return;let Le=ce.data;if(!Le||typeof Le!="object"||Le.jsonrpc!=="2.0")return;let ie=Le.method,xe=Le.id;if(ie==="ui/initialize"&&xe!=null){re=!0,ge.current?.mark("initialize"),clearTimeout(be),Oe({jsonrpc:"2.0",id:xe,result:{protocolVersion:Le.params?.protocolVersion??ZK,hostInfo:{name:"Waniwani Chat",version:"1.0.0"},hostCapabilities:{openLinks:{},message:{text:{}},tools:{},updateModelContext:{text:{},structuredContent:{}}},hostContext:{theme:ze.current?"dark":"light",displayMode:E.current}}});return}if(ie==="ui/notifications/initialized"){g.current=!0,ge.current?.mark("initialized"),C.current=setTimeout(()=>ge.current?.report("ok",S.current),tY);let Ne=v.current,_e=I.current,Fe=_e._meta&&typeof _e._meta=="object"?_e._meta:null,Ae=aY(Z.current),de=Fe&&typeof Fe.waniwani=="object"&&Fe.waniwani!==null?Fe.waniwani:null,W=de||Ae?{...de??{},...Ae?{sessionId:Ae}:{}}:void 0,ct=Fe||W?{...Fe??{},...W?{waniwani:W}:{}}:void 0;Oe({jsonrpc:"2.0",method:"ui/notifications/tool-input",params:{arguments:Ne}});let le=_e.content??[{type:"text",text:JSON.stringify(_e)}];Oe({jsonrpc:"2.0",method:"ui/notifications/tool-result",params:{content:le,structuredContent:_e.structuredContent,_meta:ct,meta:ct}});return}if(ie==="ui/notifications/size-changed"){clearTimeout(C.current),ge.current?.mark("firstSize"),ge.current?.report("ok",S.current);let Ne=Le.params,_e=typeof Ne?.height=="number"?Ne.height:void 0,Fe=typeof Ne?.width=="number"?Ne.width:void 0,Ae=y.current,de=_e!==void 0&&_e!==Ae.height,W=Fe!==void 0&&Fe!==Ae.width;if(!de&&!W)return;if(de&&_e!==void 0){if(Ae.height=_e,ot.current)return;let ct=B(_e),le=x.getBoundingClientRect().height;if(w.current&&(w.current.cancel(),w.current=null),R(ct),x.animate&&Math.abs(le-ct)>2){let oe=x.animate([{height:`${le}px`},{height:`${ct}px`}],{duration:JK,easing:"ease-out",fill:"forwards"});w.current=oe,oe.onfinish=()=>{w.current===oe&&(oe.cancel(),w.current=null)}}}W&&s&&Fe!==void 0&&(Ae.width=Fe,U(Fe));return}if(ie==="ui/open-link"&&xe!=null){let Ne=Le.params?.url;typeof Ne=="string"&&(A.current?A.current(Ne):window.open(Ne,"_blank","noopener,noreferrer")),Oe({jsonrpc:"2.0",id:xe,result:{}});return}if(ie==="ui/message"&&xe!=null){if(Q.current&&Le.params){let Ne=Le.params,_e=ke;if(ke=null,We){clearTimeout(We.timer);let Fe=We.text;We=null;let Ae=(Ne.content??[]).map(de=>de.text??"").join("").trim();Ne={...Ne,content:[{type:"text",text:`${Ae}
|
|
143
143
|
|
|
144
144
|
${Fe}`}]}}Q.current({...Ne,..._e?{modelContext:_e}:{}})}Oe({jsonrpc:"2.0",id:xe,result:{}});return}if(ie==="ui/update-model-context"&&xe!=null){ke=WU(ke,Le.params),Oe({jsonrpc:"2.0",id:xe,result:{}});return}if(ie==="tools/call"&&xe!=null){let Ne=$.current;if(!Ne){Oe({jsonrpc:"2.0",id:xe,error:{code:-32601,message:"tools/call not supported"}});return}let _e=Le.params?.name;Ne({name:_e,arguments:Le.params?.arguments??{}}).then(Fe=>{Oe({jsonrpc:"2.0",id:xe,result:Fe});let Ae=Fe.content?.map(de=>de.text??"").join("").trim();Ae&&nY(_e,Fe,X.current)&&(We&&clearTimeout(We.timer),We={text:Ae,timer:setTimeout(()=>{if(te)return;let de=ke;ke=null,We=null,Q.current?.({role:"user",content:[{type:"text",text:Ae}],...de?{modelContext:de}:{}})},500)})}).catch(Fe=>{let Ae=Fe instanceof Error?Fe.message:"Tool call failed";Oe({jsonrpc:"2.0",id:xe,error:{code:-32e3,message:Ae}})});return}if(ie==="ui/request-display-mode"&&xe!=null){let Ne=Le.params?.mode,_e=Ne==="fullscreen"||Ne==="inline"||Ne==="pip"?Ne:"inline";E.current=_e,Oe({jsonrpc:"2.0",id:xe,result:{mode:_e}}),Oe({jsonrpc:"2.0",method:"ui/notifications/host-context-changed",params:{displayMode:_e}}),H.current?.(_e);return}if(ie==="ui/resource-teardown"&&xe!=null){Oe({jsonrpc:"2.0",id:xe,result:{}});return}ie==="ping"&&xe!=null&&Oe({jsonrpc:"2.0",id:xe,result:{}})};return window.addEventListener("message",we),()=>{te=!0,clearTimeout(be),We&&clearTimeout(We.timer),window.removeEventListener("message",we)}},[s,B]),(0,YU.jsx)("iframe",{ref:h,src:P,onLoad:()=>ge.current?.mark("iframeLoad"),sandbox:"allow-scripts allow-forms allow-same-origin allow-popups allow-popups-to-escape-sandbox",className:V(!p&&"ww:rounded-md ww:border ww:border-border",i),style:{height:p?"100%":T,minWidth:p||!O?void 0:`min(${O}px, 100%)`,width:"100%",border:"none",colorScheme:o?"dark":"auto"},title:"MCP App"})}var si=j(me(),1);function ZU({icon:e,title:t,description:a,suggestions:n,onSuggestionSelect:r}){return(0,si.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,si.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,si.jsx)("h2",{className:"ww:text-lg ww:font-semibold ww:text-foreground",children:t}),a&&(0,si.jsx)("p",{className:"ww:mt-1 ww:text-sm ww:text-muted-foreground ww:max-w-sm",children:a}),n&&n.length>0&&(0,si.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,si.jsx)("button",{type:"button",onClick:()=>r?.(o),className:V("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 JU=j(Ee(),1);var ou=j(me(),1);function rY({onRetry:e}){let{t}=Ue();return(0,ou.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,ou.jsx)("span",{children:t.widgetErrorBoundary.failedToLoad}),(0,ou.jsx)("button",{type:"button",onClick:e,className:"ww:text-xs ww:font-medium ww:text-primary ww:hover:underline",children:t.widgetErrorBoundary.retry})]})}var Rh=class extends JU.Component{constructor(){super(...arguments);K(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,ou.jsx)(rY,{onRetry:()=>this.setState({hasError:!1})}):this.props.children}};var He=j(me(),1);function eI(e){return e?e.replace(/[-_]/g," ").replace(/^\w/,t=>t.toUpperCase()):"Tool"}function QU(e){return e&&/search|find|lookup|query|web|browse|google/i.test(e)?Rc:_i}function eB({messages:e,status:t,welcomeMessage:a,welcome:n,onSuggestionSelect:r,resourceEndpoint:o,chatSessionId:i,isDark:s,onFollowUp:l,onCallTool:u,onWidgetDisplayModeChange:c,fullscreenToolCallId:d,debug:p,showToolCalls:m=!0,toolDefinitions:h,messageClassNames:v}){let{t:I}=Ue(),y=e[e.length-1],w=e.length>0,g=d!=null,S=!g&&VU(e,t,{ignoreToolParts:m===!1,ignoreReasoningParts:m===!1});return(0,He.jsxs)(He.Fragment,{children:[!g&&(!w&&n?(0,He.jsx)(ZU,{...n,onSuggestionSelect:r}):a&&(0,He.jsx)(WS,{from:"assistant",children:(0,He.jsx)(GS,{children:(0,He.jsx)(Ah,{children:a})})})),e.map(E=>{let T=E.parts.filter(B=>B.type==="text"),R=E.parts.filter(B=>B.type==="reasoning"),O=E.parts.filter(B=>B.type==="file"),U=SM(E.metadata),A=E.parts.filter(B=>"toolCallId"in B),Q=E.parts.filter(B=>B.type==="reasoning"||"toolCallId"in B),$=E===y&&E.role==="assistant",H=T.length>0,Z=g?A.some(B=>B.toolCallId===d):!1,X=m!==!1&&!Z&&Q.length>=2;return g&&!Z?(0,He.jsx)("div",{style:{display:"none"}},E.id):E.role==="assistant"&&!jU(E)?(0,He.jsx)("div",{style:{display:"none"}},E.id):m===!1&&E.role==="assistant"&&!H&&O.length===0&&A.every(B=>{let P="output"in B?B.output:void 0;return P===void 0||!o||!Hd(B.toolName,P,h)})?(0,He.jsx)("div",{style:{display:"none"}},E.id):(0,He.jsxs)(WS,{from:E.role,className:v?.message,children:[m!==!1&&!Z&&!X&&R.map((B,P)=>(0,He.jsxs)(Ud,{isStreaming:B.state==="streaming",children:[(0,He.jsx)(Bd,{}),(0,He.jsx)(zd,{children:B.text})]},`reasoning-${E.id}-${P}`)),X&&(()=>{let B=Q[Q.length-1],P=B.type==="reasoning"?{icon:Gr,label:I.reasoning.thinking}:{icon:QU(B.toolName),label:B.title??eI(B.toolName)};return(0,He.jsxs)(TU,{isWorking:$&&(t==="streaming"||t==="submitted"),activeStep:P,children:[(0,He.jsx)(LU,{workingLabel:I.chainOfThought.working,label:I.chainOfThought.done}),(0,He.jsx)(EU,{children:Q.map((J,ge)=>{let C=ge===Q.length-1;if(J.type==="reasoning")return(0,He.jsx)(MU,{isStreaming:J.state==="streaming",isLast:C,children:J.text},`reasoning-${E.id}-${ge}`);let ze=J.title??eI(J.toolName),ot=QU(J.toolName);if(m==="titles-only")return(0,He.jsx)(VS,{icon:ot,title:ze,state:J.state,isLast:C},J.toolCallId);let x="output"in J?J.output:void 0;return(0,He.jsxs)(VS,{icon:ot,title:ze,state:J.state,isLast:C,children:[(0,He.jsx)(JS,{input:J.input,debug:p}),x!==void 0&&(0,He.jsx)(QS,{output:x,errorText:"errorText"in J?J.errorText:void 0,debug:p})]},J.toolCallId)})})]})})(),m!==!1&&!Z&&!X&&A.length===1&&(()=>{let B=A[0],P=B.title??eI(B.toolName);if(m==="titles-only")return(0,He.jsx)(zU,{title:P,state:B.state});let J="output"in B?B.output:void 0;return(0,He.jsxs)(UU,{children:[(0,He.jsx)(BU,{title:P,state:B.state}),(0,He.jsxs)(FU,{children:[(0,He.jsx)(JS,{input:B.input,debug:p}),J!==void 0&&(0,He.jsx)(QS,{output:J,errorText:"errorText"in B?B.errorText:void 0,debug:p})]})]})})(),A.map(B=>{let P="output"in B?B.output:void 0,J=Hd(B.toolName,P,h),ge=qU(B.toolName,P,h),C=B.toolCallId===d;return J&&o&&P!==void 0?(0,He.jsx)("div",{style:C?{position:"absolute",inset:0,zIndex:10,display:"flex",flexDirection:"column",overflow:"hidden",background:"var(--ww-color-background)"}:void 0,children:J&&o&&P!==void 0&&(0,He.jsx)(Rh,{children:(0,He.jsx)(Mh,{isFullscreen:C,resourceUri:J,toolInput:B.input??{},toolResult:{content:P.content,structuredContent:P.structuredContent,_meta:P._meta},resourceEndpoint:o,chatSessionId:i,isDark:s,autoHeight:ge,toolDefinitions:h,onFollowUp:l,onCallTool:u,onDisplayModeChange:c?ze=>c(ze,{toolCallId:B.toolCallId,resourceUri:J,toolInput:B.input??{},toolResult:{content:P.content,structuredContent:P.structuredContent,_meta:P._meta},autoHeight:ge}):void 0})})},B.toolCallId):null}),!Z&&U.length>0&&(0,He.jsx)(IM,{documents:U}),!Z&&(0,He.jsx)("div",{children:(0,He.jsxs)(GS,{className:V(E.role==="user"?v?.userBubble:v?.assistantBubble),children:[O.length>0&&(0,He.jsx)(xM,{files:O}),H?T.map((B,P)=>{let J=$&&t==="streaming"&&P===T.length-1;return(0,He.jsx)(Ah,{isStreaming:J,children:B.type==="text"?B.text:""},`${E.id}-${P}`)}):null]})})]},E.id)}),S&&(0,He.jsx)($U,{})]})}var li=j(me(),1);function oY({label:e}){return(0,li.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,li.jsx)("title",{children:e}),(0,li.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,li.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function Dh({onClick:e}){let{t}=Ue();return(0,li.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,li.jsx)(oY,{label:t.threadMenu.newChat})})}var Vd=j(me(),1),iY="https://app.waniwani.ai/assets/waniwani-logo.svg",sY="https://waniwani.ai";function tB(){let{t:e}=Ue();return(0,Vd.jsxs)("a",{href:sY,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,Vd.jsx)("span",{children:e.poweredBy.label}),(0,Vd.jsx)("img",{src:iY,alt:"Waniwani",width:72,height:10,"data-waniwani-logo":"",className:"ww:h-2.5 ww:w-auto"})]})}var iu=j(Ee(),1);var bt=j(me(),1),aB=20;function lY({label:e}){return(0,bt.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,bt.jsx)("title",{children:e}),(0,bt.jsx)("path",{d:"M3 12a9 9 0 1 0 3-6.7"}),(0,bt.jsx)("polyline",{points:"3 4 3 9 8 9"}),(0,bt.jsx)("line",{x1:"12",y1:"7",x2:"12",y2:"12"}),(0,bt.jsx)("line",{x1:"12",y1:"12",x2:"15",y2:"14"})]})}function uY({label:e}){return(0,bt.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,bt.jsx)("title",{children:e}),(0,bt.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,bt.jsx)("path",{d:"M19 6l-2 14a2 2 0 0 1-2 2H9a2 2 0 0 1-2-2L5 6"}),(0,bt.jsx)("path",{d:"M10 11v6"}),(0,bt.jsx)("path",{d:"M14 11v6"})]})}function nB({threads:e,activeThreadId:t,onNewThread:a,onSelectThread:n,onDeleteThread:r}){let{locale:o,t:i}=Ue(),[s,l]=(0,iu.useState)(!1),u=(0,iu.useRef)(null);(0,iu.useEffect)(()=>{if(!s)return;let p=m=>{let h=u.current;h&&(m.composedPath().includes(h)||l(!1))};return document.addEventListener("mousedown",p),()=>document.removeEventListener("mousedown",p)},[s]);let c=e.slice(0,aB),d=Math.max(0,e.length-aB);return(0,bt.jsxs)("div",{ref:u,className:"ww:relative ww:flex ww:items-center ww:gap-1",children:[(0,bt.jsx)(Dh,{onClick:a}),(0,bt.jsx)("button",{type:"button",onClick:()=>l(p=>!p),title:i.threadMenu.threadHistory,"aria-label":i.threadMenu.threadHistory,"aria-expanded":s,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,bt.jsx)(lY,{label:i.threadMenu.threadHistory})}),s&&(0,bt.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,bt.jsx)("div",{className:"ww:px-3 ww:py-3 ww:text-xs ww:text-muted-foreground",children:i.threadMenu.noPreviousChats}),c.map(p=>{let m=p.threadId===t,h=Date.parse(p.updatedAt);return(0,bt.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 ${m?"ww:bg-foreground/5":""}`,children:[(0,bt.jsxs)("button",{type:"button",onClick:()=>{n(p.threadId),l(!1)},className:"ww:flex-1 ww:min-w-0 ww:text-left ww:cursor-pointer",children:[(0,bt.jsx)("div",{className:"ww:truncate ww:text-foreground ww:font-medium",children:p.title}),(0,bt.jsx)("div",{className:"ww:text-[10px] ww:text-muted-foreground",children:Number.isNaN(h)?"":hx(h,o)})]}),(0,bt.jsx)("button",{type:"button",onClick:v=>{v.stopPropagation(),r(p.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,bt.jsx)(uY,{label:i.threadMenu.deleteThread})})]},p.threadId)}),d>0&&(0,bt.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 _h=j(Ee(),1);function su(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 s of[...t])try{s(i)}catch(l){console.warn("[Waniwani] onEvent subscriber threw:",l)}}}}function rB(){return{subscribe(){return()=>{}},emit(){}}}var oB=(0,_h.createContext)(rB());function Ph(){return(0,_h.useContext)(oB)}var lu=oB.Provider;var Oh=j(Ee(),1);function iB(e){let t=(0,Oh.useRef)(e);return t.current=e,(0,Oh.useCallback)(async a=>{let{api:n,headers:r,onCallTool:o,sessionId:i}=t.current;if(o)return o(a);let s=Na(n??"/api/waniwani","/tool"),l=typeof i=="string"&&i.trim().length>0?i.trim():void 0,u=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",...l?{"X-Session-Id":l}:{},...r},body:JSON.stringify(a)});if(!u.ok)throw new Error(`Tool call failed: ${u.status} ${u.statusText}`);return u.json()},[])}var qn=j(Ee(),1);var dB=j(lB(),1);var Xd=j(Ee(),1);var Bh=j(Ee(),1);var cB=(e,t,a)=>{if(!t.has(e))throw TypeError("Cannot "+a)},At=(e,t,a)=>(cB(e,t,"read from private field"),a?a.call(e):t.get(e)),kr=(e,t,a)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,a)},ui=(e,t,a,n)=>(cB(e,t,"write to private field"),n?n.call(e,a):t.set(e,a),a);function dY(e,t){return t!=null?(0,dB.default)(e,t):e}var Fn,Nh,Uh,$d,Wd,Gd,uu,tI,aI,fY=class{constructor(e=[]){kr(this,Fn,void 0),kr(this,Nh,"ready"),kr(this,Uh,void 0),kr(this,$d,new Set),kr(this,Wd,new Set),kr(this,Gd,new Set),this.pushMessage=t=>{ui(this,Fn,At(this,Fn).concat(t)),At(this,uu).call(this)},this.popMessage=()=>{ui(this,Fn,At(this,Fn).slice(0,-1)),At(this,uu).call(this)},this.replaceMessage=(t,a)=>{ui(this,Fn,[...At(this,Fn).slice(0,t),this.snapshot(a),...At(this,Fn).slice(t+1)]),At(this,uu).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,a)=>{let n=a?dY(t,a):t;return At(this,$d).add(n),()=>{At(this,$d).delete(n)}},this["~registerStatusCallback"]=t=>(At(this,Wd).add(t),()=>{At(this,Wd).delete(t)}),this["~registerErrorCallback"]=t=>(At(this,Gd).add(t),()=>{At(this,Gd).delete(t)}),kr(this,uu,()=>{At(this,$d).forEach(t=>t())}),kr(this,tI,()=>{At(this,Wd).forEach(t=>t())}),kr(this,aI,()=>{At(this,Gd).forEach(t=>t())}),ui(this,Fn,e)}get status(){return At(this,Nh)}set status(e){ui(this,Nh,e),At(this,tI).call(this)}get error(){return At(this,Uh)}set error(e){ui(this,Uh,e),At(this,aI).call(this)}get messages(){return At(this,Fn)}set messages(e){ui(this,Fn,[...e]),At(this,uu).call(this)}};Fn=new WeakMap;Nh=new WeakMap;Uh=new WeakMap;$d=new WeakMap;Wd=new WeakMap;Gd=new WeakMap;uu=new WeakMap;tI=new WeakMap;aI=new WeakMap;var cu,uB=class extends CE{constructor({messages:e,...t}){let a=new fY(e);super({...t,state:a}),kr(this,cu,void 0),this["~registerMessagesCallback"]=(n,r)=>At(this,cu)["~registerMessagesCallback"](n,r),this["~registerStatusCallback"]=n=>At(this,cu)["~registerStatusCallback"](n),this["~registerErrorCallback"]=n=>At(this,cu)["~registerErrorCallback"](n),ui(this,cu,a)}};cu=new WeakMap;function fB({experimental_throttle:e,resume:t=!1,...a}={}){let n=(0,qn.useRef)("chat"in a?{}:{onToolCall:a.onToolCall,onData:a.onData,onFinish:a.onFinish,onError:a.onError,sendAutomaticallyWhen:a.sendAutomaticallyWhen});"chat"in a||(n.current={onToolCall:a.onToolCall,onData:a.onData,onFinish:a.onFinish,onError:a.onError,sendAutomaticallyWhen:a.sendAutomaticallyWhen});let r={...a,onToolCall:p=>{var m,h;return(h=(m=n.current).onToolCall)==null?void 0:h.call(m,p)},onData:p=>{var m,h;return(h=(m=n.current).onData)==null?void 0:h.call(m,p)},onFinish:p=>{var m,h;return(h=(m=n.current).onFinish)==null?void 0:h.call(m,p)},onError:p=>{var m,h;return(h=(m=n.current).onError)==null?void 0:h.call(m,p)},sendAutomaticallyWhen:p=>{var m,h,v;return(v=(h=(m=n.current).sendAutomaticallyWhen)==null?void 0:h.call(m,p))!=null?v:!1}},o=(0,qn.useRef)("chat"in a?a.chat:new uB(r));("chat"in a&&a.chat!==o.current||"id"in a&&o.current.id!==a.id)&&(o.current="chat"in a?a.chat:new uB(r));let s=(0,qn.useCallback)(p=>o.current["~registerMessagesCallback"](p,e),[e,o.current.id]),l=(0,qn.useSyncExternalStore)(s,()=>o.current.messages,()=>o.current.messages),u=(0,qn.useSyncExternalStore)(o.current["~registerStatusCallback"],()=>o.current.status,()=>o.current.status),c=(0,qn.useSyncExternalStore)(o.current["~registerErrorCallback"],()=>o.current.error,()=>o.current.error),d=(0,qn.useCallback)(p=>{typeof p=="function"&&(p=p(o.current.messages)),o.current.messages=p},[o]);return(0,qn.useEffect)(()=>{t&&o.current.resumeStream()},[t,o]),{id:o.current.id,messages:l,setMessages:d,sendMessage:o.current.sendMessage,regenerate:o.current.regenerate,clearError:o.current.clearError,stop:o.current.stop,error:c,resumeStream:o.current.resumeStream,status:u,addToolResult:o.current.addToolOutput,addToolOutput:o.current.addToolOutput,addToolApprovalResponse:o.current.addToolApprovalResponse}}var ee=j(Ee(),1);var pY="/api/mcp/modules/documents",mY=2e4,hY=3e5,Hn=class extends Error{constructor(a,n){super(n);K(this,"code");this.name="DocumentUploadError",this.code=a}};function pB(e,t){return Fp(e,`${pY}${t}`)}function gY(e){return pB(e,"/upload-url")}function mB(e,t){let a=new Headers(e);return new Headers(t).forEach((n,r)=>{a.set(r,n)}),a}function yY(e){let t=e?.data;if(typeof t?.documentId!="string"||typeof t.uploadUrl!="string"||!(t.documentId&&t.uploadUrl))return null;let a={};for(let[n,r]of Object.entries(t.headers??{}))typeof r=="string"&&(a[n]=r);return{documentId:t.documentId,uploadUrl:t.uploadUrl,headers:a}}function wY(e){return e===403?new Hn("upload_disabled","This agent does not accept document uploads."):e===413?new Hn("max_file_size","That file is too large."):e===422||e===400?new Hn("accept","That file type is not accepted."):new Hn("upload_failed",`The upload could not be started (${e}).`)}function vY(e){return new Promise((t,a)=>{let n=new XMLHttpRequest;n.open("PUT",e.url,!0);for(let[i,s]of Object.entries(e.headers))n.setRequestHeader(i,s);n.timeout=hY;let r=()=>n.abort();e.signal.addEventListener("abort",r,{once:!0});let o=()=>e.signal.removeEventListener("abort",r);n.upload.onprogress=i=>{i.lengthComputable&&i.total>0&&e.onProgress?.(i.loaded/i.total)},n.onload=()=>{if(o(),n.status>=200&&n.status<300||n.status===412){e.onProgress?.(1),t();return}a(new Hn("upload_failed",`The upload was rejected (${n.status}).`))},n.onerror=()=>{o(),a(new Hn("upload_failed","The upload could not be completed."))},n.ontimeout=()=>{o(),a(new Hn("upload_failed","The upload timed out."))},n.onabort=()=>{o(),a(e.signal.reason instanceof Error?e.signal.reason:new Error("aborted"))},n.send(e.file)})}async function zh(e){let t=pB(e.api,`/${e.documentId}`);if(t)try{await fetch(t,{method:"DELETE",headers:mB(e.headers,e.uploadHeaders)})}catch{}}async function hB(e){e.signal.throwIfAborted();let t=gY(e.api);if(!t)throw new Hn("upload_disabled","This agent does not accept document uploads.");let a=new AbortController,n=setTimeout(()=>a.abort(),mY),r=()=>a.abort(e.signal.reason);e.signal.addEventListener("abort",r,{once:!0});let o;try{let s=mB(e.headers,e.uploadHeaders);s.set("Content-Type","application/json"),o=await fetch(t,{method:"POST",headers:s,signal:a.signal,body:JSON.stringify({filename:e.file.name,contentType:e.file.type,byteSize:e.file.size,...e.sessionId?{sessionId:e.sessionId}:{}})})}catch(s){throw e.signal.aborted?s:new Hn("upload_failed","The upload could not be started.")}finally{clearTimeout(n),e.signal.removeEventListener("abort",r)}if(!o.ok)throw wY(o.status);let i=yY(await o.json().catch(()=>null));if(e.signal.throwIfAborted(),!i)throw new Hn("upload_failed","The upload could not be started.");return await vY({url:i.uploadUrl,headers:i.headers,file:e.file,signal:e.signal,onProgress:e.onProgress}),{documentId:i.documentId,filename:e.file.name,mediaType:e.file.type}}function xY(e){let t=e?.cause,a=t?.issues??t?.errors;if(!Array.isArray(a))return null;let n=a.find(r=>r.code==="invalid_union");if(!n?.errors)return null;for(let r of n.errors){if(!Array.isArray(r)||r.some(s=>(s.code==="invalid_value"||s.code==="invalid_literal")&&s.path?.[0]==="type"))continue;let i=r.filter(s=>s.code==="unrecognized_keys").flatMap(s=>s.keys??[]);if(i.length>0)return i}return null}var Fh=class extends bv{processResponseStream(t){let a="",n=xv(),r=n.validate?.bind(n);return t.pipeThrough(new TextDecoderStream).pipeThrough(new TransformStream({async transform(o,i){a+=o;let s=a.split(`
|
|
145
145
|
`);a=s.pop()??"";for(let l of s){let u=l.trim();if(!u.startsWith("data:"))continue;let c=u.slice(5).trim();if(c!=="[DONE]")try{let d=JSON.parse(c);if(!r){i.enqueue(d);continue}let p=await r(d);if(p.success){i.enqueue(p.value);continue}let m=xY(p.error);if(m?.length){let h={...d};for(let I of m)delete h[I];let v=await r(h);v.success&&i.enqueue(v.value)}}catch{}}}}))}};var gB=50,yB=1e3;function qh(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.threadId=="string"&&typeof t.memoryUserId=="string"&&typeof t.title=="string"&&Array.isArray(t.messages)&&typeof t.createdAt=="string"&&typeof t.updatedAt=="string"}async function Hh(e){if(typeof indexedDB>"u")return null;let t=null;try{return t=await Xw(),await e(t)}catch{return null}finally{try{t?.close()}catch{}}}function nI(e){return new Promise((t,a)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>a(e.error)})}async function rI(e){return await Hh(async a=>{let o=a.transaction(yn,"readonly").objectStore(yn).index(qp),s=(await nI(o.getAll(e))??[]).filter(qh);return s.sort((l,u)=>l.updatedAt<u.updatedAt?1:-1),s})??[]}async function jh(e){return await Hh(async a=>{let r=a.transaction(yn,"readonly").objectStore(yn),o=await nI(r.get(e));return qh(o)?o:null})??null}async function oI(e){if(!qh(e))return;let t=e.messages.length>yB?{...e,messages:e.messages.slice(e.messages.length-yB)}:e;await Hh(async a=>{await new Promise((l,u)=>{let c=a.transaction(yn,"readwrite");c.oncomplete=()=>l(),c.onerror=()=>u(c.error),c.onabort=()=>u(c.error),c.objectStore(yn).put(t)});let n=a.transaction(yn,"readwrite"),r=n.objectStore(yn),o=r.index(qp),s=(await nI(o.getAll(t.memoryUserId))??[]).filter(qh);if(s.length>gB){s.sort((u,c)=>u.updatedAt<c.updatedAt?-1:1);let l=s.slice(0,s.length-gB);for(let u of l)r.delete(u.threadId)}return await new Promise((l,u)=>{n.oncomplete=()=>l(),n.onerror=()=>u(n.error),n.onabort=()=>u(n.error)}),null})}async function wB(e){await Hh(async t=>(await new Promise((a,n)=>{let r=t.transaction(yn,"readwrite");r.oncomplete=()=>a(),r.onerror=()=>n(r.error),r.onabort=()=>n(r.error),r.objectStore(yn).delete(e)}),null))}async function iI(e){return(await rI(e))[0]?.threadId??null}function vB(e){let t=e.trim();if(!t)return`Conversation on ${new Date().toISOString().slice(0,10)}`;let a=t.split(/\r?\n/,1)[0]??t;return a.length<=60?a:`${a.slice(0,60).trimEnd()}\u2026`}var bY="x-session-id",SY=250,IY=200;function xB(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():ud()}function Vh(){return new Date().toISOString()}function bB(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}async function CY(e,t){let a=Na(e,"/tools"),n=await fetch(a,{method:"GET",headers:t?{...t}:void 0});if(!n.ok)throw new Error(`[Waniwani] Failed to fetch /tools: ${n.status} ${n.statusText}`);let r=await n.json();if(!r||!Array.isArray(r.tools))return{};let o={};for(let i of r.tools)i&&typeof i.name=="string"&&(o[i.name]=i);return o}function SB(e){let{api:t="/api/waniwani",headers:a,uploadHeaders:n,body:r,onMessageSent:o,onResponseReceived:i,enableThreadHistory:s=!1,activeThreadId:l,onThreadChange:u}=e,c=e.visitorId;(0,ee.useEffect)(()=>Sc(c),[c]);let d=Ph(),p=(0,ee.useRef)(a),m=(0,ee.useRef)(n),h=(0,ee.useRef)(r),v=(0,ee.useRef)(s);(0,ee.useEffect)(()=>{v.current=s},[s]);let I=(0,ee.useRef)(void 0),y=(0,ee.useRef)(void 0),w=(0,ee.useRef)(null),[g,S]=(0,ee.useState)(void 0),E=(0,ee.useRef)(g),[T,R]=(0,ee.useState)(l),O=(0,ee.useRef)(T),[U,A]=(0,ee.useState)([]),[Q,$]=(0,ee.useState)(!s),H=(0,ee.useRef)(void 0),Z=(0,ee.useRef)(void 0),X=(0,ee.useRef)(void 0),B=(0,ee.useRef)(void 0),P=(0,ee.useRef)(0),J=(0,ee.useRef)(u);(0,ee.useEffect)(()=>{J.current=u},[u]);let ge=(0,ee.useCallback)(_=>{O.current=_,R(_),_&&(J.current?.(_),d.emit({name:"thread.changed",sessionId:E.current,properties:{threadId:_}}))},[d]),C=(0,ee.useCallback)(async()=>{if(!s)return;let _=w.current?.memoryUserId;if(!_)return;let he=await rI(_);A(he)},[s]),ze=(0,ee.useCallback)(()=>E.current,[]),ot=(0,ee.useCallback)(_=>{let he=bB(_);if(!he||E.current===he)return;let Se=E.current===void 0;E.current=he,S(he),Se&&d.emit({name:"session.started",properties:{sessionId:he}})},[d]),x=(0,ee.useCallback)(()=>{E.current=void 0,S(void 0)},[]);(0,ee.useEffect)(()=>{p.current=a,m.current=n},[a,n]),(0,ee.useEffect)(()=>{h.current=r},[r]),(0,ee.useEffect)(()=>{let _=!1,he=P.current;return(async()=>{try{let et=await Ic();if(_)return;w.current=et}catch{}if(!s)return;let Se=w.current?.memoryUserId;if(!Se){$(!0);return}try{let et=l??await iI(Se);if(_||he!==P.current)return;if(et){let Ot=await jh(et);if(_||he!==P.current)return;Ot&&Ot.memoryUserId===Se&&(O.current=Ot.threadId,R(Ot.threadId),H.current=Ot.createdAt,Z.current=Ot.title,Ot.sessionId&&(E.current=Ot.sessionId,S(Ot.sessionId)),ct(Ot.messages))}await C()}finally{_||$(!0)}})(),()=>{_=!0}},[]);let te=(0,ee.useRef)(null),re=(0,ee.useCallback)(_=>{let he=h.current?.[_];return typeof he=="string"?he:void 0},[]),ke=(0,ee.useCallback)(()=>({api:t,token:jp(p.current),channelId:re("channelId"),sessionId:E.current}),[t,re]),We=(0,ee.useCallback)(_=>{let he=te.current;te.current=null,he?.report(ke(),{mode:re("mode"),outcome:_})},[ke,re]),be=(0,ee.useCallback)(_=>{let he=typeof _=="object"&&_!==null&&!Array.isArray(_)?_:void 0,Se=w.current?.memoryUserId,et=w.current?.language,Ot={};return Se&&(Ot.memoryUserId=Se),et&&(Ot.locale=et),Object.keys(Ot).length>0||he?{...Ot,...he??{}}:void 0},[]),Oe=(0,ee.useCallback)(()=>{let _=O.current;return _||(_=xB(),H.current=Vh(),Z.current=void 0,ge(_)),_},[ge]),we=(0,ee.useRef)(new Fh({api:t,headers:()=>({...p.current}),body:()=>{let _={...h.current??{}},he=Object.hasOwn(_,"sessionId"),Se=bB(_.sessionId);if(Se)ot(Se),_.sessionId=Se;else if(he)x(),delete _.sessionId;else{let Qh=ze();Qh&&(_.sessionId=Qh)}nu(I.current)&&(_.modelContext=I.current),y.current?.length&&(_.documents=y.current);let et=w.current,Ot=ma();et&&(_.visitorContext={timezone:et.timezone,language:et.language,languages:et.languages,deviceType:et.deviceType,referrer:et.referrer,visitorId:Ot});let Kt=typeof _.visitor=="object"&&_.visitor!==null?_.visitor:{},g3=typeof Kt.client=="object"&&Kt.client!==null?Kt.client:{};_.visitor={...Kt,id:Ot,client:{...g3,...et&&{memoryUserId:et.memoryUserId}}};let wI=be(_.extra);return wI&&(_.extra=wI),v.current&&(Object.hasOwn(_,"threadId")?typeof _.threadId=="string"&&(O.current=_.threadId):_.threadId=Oe()),_},fetch:(async(_,he)=>{let Se=te.current;Se?.mark("requestStart");try{let et=await fetch(_,he);return I.current=void 0,ot(et.headers.get(bY)),Se?Se.instrument(et):et}finally{y.current=void 0}})})),ce=(0,ee.useRef)(e.transport?.({fallback:we.current,headers:()=>p.current,body:()=>{let _=be(h.current?.extra);return{channelId:re("channelId"),visitor:{id:ma()},..._?{extra:_}:{}}},threadHistory:()=>v.current,threadId:()=>v.current?Oe():void 0,hasMessages:()=>Ie.current.length>0,takeTurnInput:()=>{let _=y.current;return y.current=void 0,I.current=void 0,_?.length?{documents:_}:{}},onSession:ot})??we.current),Le=(0,ee.useRef)(null),ie=(0,ee.useRef)(null),xe=(0,ee.useRef)({}),[Ne,_e]=(0,ee.useState)(0),Fe=e.skipRemoteConfig===!0,Ae=(0,ee.useCallback)(async()=>{if(!Fe)try{let _=await CY(t,p.current);xe.current=_,_e(he=>he+1)}catch(_){console.warn("[Waniwani] Failed to fetch tool definitions:",_ instanceof Error?_.message:_)}},[t,Fe]);(0,ee.useEffect)(()=>{Ae()},[Ae]);let{messages:de,sendMessage:W,setMessages:ct,status:le,stop:oe}=fB({messages:e.initialMessages,transport:ce.current,onFinish({message:_,isAbort:he,isDisconnect:Se,isError:et}){te.current?.mark("streamEnd"),We(he||Se||et?"error":"ok"),i?.(),!he&&!Se&&!et&&d.emit({name:"message.received"}),Le.current&&(ie.current=_)},onError(_){We("error"),console.warn("[Waniwani] Chat error:",_.message),d.emit({name:"chat.error",properties:{message:_.message.slice(0,IY)}}),Le.current&&(Le.current.reject(_),Le.current=null)}}),Ie=(0,ee.useRef)(de);(0,ee.useEffect)(()=>{Ie.current=de},[de]);let ae=ce.current.keepsSession?.()??!1,k=(0,ee.useRef)(!1);(0,ee.useEffect)(()=>{!ae||k.current||Ie.current.length>0||(k.current=!0,ce.current.restore?.().then(_=>{_.length>0&&Ie.current.length===0&&ct(_)}).catch(()=>{}))},[ae]),(0,ee.useEffect)(()=>{let _=ce.current;return()=>_.dispose?.()},[]);let D=(0,ee.useCallback)(()=>{te.current=E1(Ie.current.filter(_=>_.role==="user").length+1)},[]),[F,fe]=(0,ee.useState)(!1),Ve=(0,ee.useCallback)(async()=>{fe(!0);try{await oe();let _=E.current;if(!_)return;await fetch(Na(t,"/cancel"),{method:"POST",headers:{"Content-Type":"application/json",...p.current},body:JSON.stringify({sessionId:_})})}catch{}finally{fe(!1)}},[t,oe]),Ft=(0,ee.useRef)(s);(0,ee.useEffect)(()=>{if(!s||Ft.current||(Ft.current=!0,Ie.current.length>0))return;let _=!1,he=P.current;return $(!1),(async()=>{try{let Se=w.current;if(!Se)try{Se=await Ic(),w.current=Se}catch{}let et=Se?.memoryUserId;if(!et||_||he!==P.current){_||$(!0);return}let Ot=l??await iI(et);if(_||he!==P.current)return;if(Ot){let Kt=await jh(Ot);if(_||he!==P.current)return;Kt&&Kt.memoryUserId===et&&(O.current=Kt.threadId,R(Kt.threadId),H.current=Kt.createdAt,Z.current=Kt.title,Kt.sessionId&&(E.current=Kt.sessionId,S(Kt.sessionId)),ct(Kt.messages))}await C()}finally{_||$(!0)}})(),()=>{_=!0}},[s]),(0,ee.useEffect)(()=>{if(le==="ready"&&Le.current&&ie.current){let _=Le.current,he=ie.current;Le.current=null,ie.current=null,_.resolve(he)}},[le]);let[In,ca]=(0,ee.useState)(""),so=typeof c!="function",lo=In.length>0;(0,ee.useEffect)(()=>{so&&lo&&ce.current.prepare?.()},[so,lo]);let[qt,Vn]=(0,ee.useState)([]),on=(0,ee.useRef)([]);on.current=qt;let xu=le==="submitted"||le==="streaming",nf=(0,ee.useCallback)(_=>{for(let he of _)for(let Se of he.documents??[])zh({documentId:Se.documentId,api:t,headers:p.current,uploadHeaders:m.current})},[t]),uo=(0,ee.useCallback)(()=>{nf(on.current),Vn([])},[nf]),i3=(0,ee.useCallback)(_=>{let he=on.current.find(Se=>Se.id===_);he&&nf([he]),Vn(Se=>Se.filter(et=>et.id!==_))},[nf]),s3=xu&&qt.length>0,l3=(0,ee.useCallback)(_=>{let he=!!_.text?.trim(),Se=!!(_.files?.length||_.documents?.length);if(he||Se){if(xu){if(qt.length>0)return;Vn(et=>[...et,{id:ud(),text:_.text||"",files:_.files??[],documents:_.documents??[],modelContext:_.modelContext}]),ca("");return}D(),I.current=_.modelContext,y.current=_.documents,W({text:_.text||"",files:_.files,..._.documents?.length&&{metadata:{documents:_.documents}}}),o?.(_.text||""),d.emit({name:"message.sent"}),ca("")}},[W,o,xu,qt.length,d,D]),u3=(0,ee.useCallback)(_=>new Promise((he,Se)=>{Le.current={resolve:he,reject:Se},D(),W({text:_}),o?.(_),d.emit({name:"message.sent"})}),[W,o,d,D]);(0,ee.useEffect)(()=>{if(le!=="ready"||F||qt.length===0)return;let[_,...he]=qt;Vn(he),D(),I.current=_.modelContext,y.current=_.documents,W({text:_.text,files:_.files.length>0?_.files:void 0,..._.documents.length>0&&{metadata:{documents:_.documents}}}),o?.(_.text),d.emit({name:"message.sent"})},[le,F,W,o,qt,d,D]);let c3=(0,ee.useCallback)(()=>{ce.current.reset?.(),ct([]),uo(),x(),ca(""),xe.current={},_e(_=>_+1),Ae()},[ct,x,Ae,uo]),rf=(0,ee.useCallback)(()=>{if(!v.current)return;let _=w.current?.memoryUserId,he=O.current,Se=Ie.current;if(!(!_||!he||Se.length===0)){if(H.current||(H.current=Vh()),!Z.current){let et=Se.find(Kt=>Kt.role==="user"),Ot=et?et.parts.map(Kt=>"text"in Kt&&typeof Kt.text=="string"?Kt.text:"").join(" "):"";Z.current=vB(Ot)}return{threadId:he,memoryUserId:_,title:Z.current,messages:Se,sessionId:E.current,createdAt:H.current,updatedAt:Vh()}}},[]),hI=(0,ee.useCallback)(async()=>{let _=rf();_&&(await oI(_),await C())},[rf,C]);(0,ee.useEffect)(()=>{if(s&&Q&&!(le==="submitted"||le==="streaming")&&de.length!==0)return X.current&&clearTimeout(X.current),X.current=setTimeout(()=>{X.current=void 0;let _=hI().finally(()=>{B.current===_&&(B.current=void 0)});B.current=_},SY),()=>{X.current&&clearTimeout(X.current)}},[s,Q,de,le,hI]);let of=(0,ee.useCallback)(()=>{let _=B.current,he=X.current,Se=he?rf():void 0;return he&&(clearTimeout(he),X.current=void 0),(async()=>{_&&await _,Se&&(await oI(Se),await C())})()},[rf,C]),d3=(0,ee.useCallback)(()=>{P.current+=1,of(),ce.current.dispose?.(),ct([]),uo(),x(),ca("");let _=xB();return H.current=Vh(),Z.current=void 0,ge(_),C(),_},[ct,x,ge,C,of,uo]),Jh=(0,ee.useCallback)(async _=>{P.current+=1;let he=P.current;if(await of(),he!==P.current)return;let Se=await jh(_);he===P.current&&Se&&(ce.current.dispose?.(),Se.sessionId?(E.current=Se.sessionId,S(Se.sessionId)):x(),ge(Se.threadId),H.current=Se.createdAt,Z.current=Se.title,ct(Se.messages),uo(),ca(""))},[ct,x,ge,of,uo]),f3=(0,ee.useCallback)(async _=>{if(O.current===_){P.current+=1,X.current&&(clearTimeout(X.current),X.current=void 0);let he=B.current;he&&await he}await wB(_),ce.current.forget?.(_),await C(),O.current===_&&(ce.current.dispose?.(),ct([]),uo(),x(),ca(""),O.current=void 0,R(void 0),H.current=void 0,Z.current=void 0)},[ct,x,C,uo]);(0,ee.useEffect)(()=>{s&&Q&&l!==void 0&&l!==O.current&&Jh(l)},[l,s,Q,Jh]);let p3=(0,ee.useCallback)(_=>{ca(_.target.value)},[]),gI=de[de.length-1],yI=de.length>0,m3=xu&&(!yI||gI.role==="user"),h3=xe.current;return{messages:de,status:le,text:In,setText:ca,handleSubmit:l3,handleTextChange:p3,isLoading:xu,showLoaderBubble:m3,lastMessage:gI,hasMessages:yI,sendMessage:W,sendMessageAndWait:u3,stop:Ve,reset:c3,queuedMessages:qt,queueFull:s3,removeQueuedMessage:i3,sessionId:g,toolDefinitions:h3,refreshToolDefinitions:Ae,threads:U,activeThreadId:T,isThreadHistoryReady:Q,startNewThread:d3,switchThread:Jh,deleteThread:f3,keepsSession:ae}}var bs=j(Ee(),1);var kY=6e3;function IB(e){let{api:t,headers:a,uploadHeaders:n,sessionId:r,documentUpload:o,allowAttachments:i}=e,[s,l]=(0,bs.useState)(null),u=(0,bs.useCallback)((p,m,h)=>hB({file:p,api:t,headers:a,uploadHeaders:n,sessionId:r,signal:m,onProgress:h}),[t,a,n,r]),c=(0,bs.useCallback)(p=>{zh({documentId:p.documentId,api:t,headers:a,uploadHeaders:n})},[t,a,n]);(0,bs.useEffect)(()=>{if(!s)return;let p=setTimeout(()=>l(null),kY);return()=>clearTimeout(p)},[s]);let d=o?.enabled??!1;return{enabled:o?o.enabled:!!i,accept:o?.accept.join(","),maxFileSize:o?.maxBytes,maxPdfPages:o?.maxPdfPages,maxFiles:o?.maxFiles,upload:d?u:void 0,onDiscard:d?c:void 0,error:s,reportError:l}}var Ha=j(Ee(),1);function du(e){return e.map(t=>({id:null,text:t}))}function Ss(e){let{flow:t,followup:a,page:n,channel:r}=e;return t!==null?{origin:"flow",suggestions:t}:a?.length?{origin:"followup",suggestions:a}:n?.length?{origin:"page",suggestions:n}:r?.length?{origin:"channel",suggestions:r}:null}function fu(e){return typeof e=="object"&&e!==null}function CB(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function TY(e){if(!fu(e)||!("toolCallId"in e)||!("output"in e))return null;let t=e.output;if(!fu(t)||!fu(t._meta))return null;let a=t._meta[Hw];return!fu(a)||!CB(a.suggestions)?null:a.suggestions}function kB(e){let t=null;for(let a of e.parts){let n=TY(a);n!==null&&(t=n)}return t}function TB(e){for(let t of e.parts){if(!fu(t)||t.type!=="data-suggestions")continue;let a=t.data;if(fu(a)&&CB(a.suggestions)&&a.suggestions.length>0)return a.suggestions}return null}function LY(e){return"page"in e||"channel"in e}function EY(e){return typeof e!="object"||e===null?{}:LY(e)?{rungs:e}:{initial:e.initial}}function LB(e){let{messages:t,status:a,suggestions:n}=e,r=n!==!1,{rungs:o,initial:i}=EY(n),s=(0,Ha.useMemo)(()=>({page:null,channel:du(i??[])}),[i]),l=o??s,u=(0,Ha.useMemo)(()=>r?Ss({flow:null,followup:null,...l}):null,[r,l]),c=(0,Ha.useMemo)(()=>u?.suggestions.map(g=>g.text)??[],[u]),[d,p]=(0,Ha.useState)(c),[m,h]=(0,Ha.useState)(u?.origin??"channel"),v=(0,Ha.useRef)(a),I=(0,Ha.useCallback)(()=>{p([])},[]),y=t.length>0;(0,Ha.useEffect)(()=>{y||(p(c),h(u?.origin??"channel"))},[c,u,y]);let w=t[t.length-1];return(0,Ha.useEffect)(()=>{w?.role==="user"&&I()},[w,I]),(0,Ha.useEffect)(()=>{let g=v.current;if(v.current=a,g!=="streaming"||a!=="ready"||!r)return;let S=[...t].reverse().find(O=>O.role==="assistant");if(!S)return;let E=kB(S),T=TB(S),R=Ss({flow:E===null?null:du(E),followup:T===null?null:du(T),page:null,channel:null});p(R?R.suggestions.map(O=>O.text):[]),h(R?.origin??"channel")},[a,r,t]),{suggestions:d,source:m,isLoading:!1,clear:I}}function EB(e,t){let a=t?.Authorization,n=typeof a=="string"&&a.startsWith("Bearer ")?a.slice(7):null;return Na(e,"/resource",n?{token:n}:void 0)}var AY={primaryColor:["--ww-primary","--ww-color-primary"],primaryForeground:["--ww-primary-fg","--ww-color-primary-foreground"],backgroundColor:["--ww-bg","--ww-color-background"],textColor:["--ww-text","--ww-color-foreground","--ww-color-accent-foreground"],mutedColor:["--ww-muted","--ww-color-muted-foreground"],borderColor:["--ww-border","--ww-color-border"],borderWidth:["--ww-border-width"],boxShadow:["--ww-shadow"],assistantBubbleColor:["--ww-assistant-bubble","--ww-color-accent"],userBubbleColor:["--ww-user-bubble"],inputBackgroundColor:["--ww-input-bg","--ww-color-input"],borderRadius:["--ww-radius"],messageBorderRadius:["--ww-msg-radius"],fontFamily:["--ww-font"],headerBackgroundColor:["--ww-header-bg"],headerTextColor:["--ww-header-text"],statusColor:["--ww-status"],toolCardColor:["--ww-tool-card","--ww-color-tool-card"],userBubbleTextColor:["--ww-user-bubble-text"],assistantBubbleTextColor:["--ww-assistant-bubble-text"],messagePaddingX:["--ww-msg-pad-x"],messagePaddingY:["--ww-msg-pad-y"],messageMaxWidth:["--ww-msg-max-width"],fontSize:["--ww-font-size"],lineHeight:["--ww-line-height"],glassTint:["--ww-glass-tint"],glassTintStrength:["--ww-glass-tint-opacity"]};function pu(e){let t={};for(let[a,n]of Object.entries(AY)){let r=e[a];if(r===void 0)continue;let o=typeof r=="number"?`${r}px`:String(r);for(let i of n)t[i]=o}return t}var nt=j(me(),1),mu=(0,Qe.forwardRef)(function(t,a){let{locale:n,messages:r}=t;return(0,nt.jsx)(es,{locale:n,messages:r,children:(0,nt.jsx)(MY,{...t,ref:a})})}),MY=(0,Qe.forwardRef)(function(t,a){let{t:n,ready:r}=Ue(),{appearance:o,className:i,classNames:s,allowAttachments:l=!1,documentUpload:u,welcomeMessage:c,welcome:d,placeholder:p=n.promptInput.placeholder,triggerEvent:m="triggerDemoRequest",api:h,mcp:v,debug:I=!1,readOnly:y=!1,title:w,headerActions:g,hideHeader:S=!1,enableThreadHistory:E=!1,showToolCalls:T=!0,initializing:R=!1,onScreen:O=!0,disclaimer:U}=t,A=o?.theme,Q=o?.variables,$=o?.assistantBubble??!1,H=Q?pu(Q):{},[Z,X]=(0,Qe.useState)(!1);(0,Qe.useEffect)(()=>{if(A!=="auto"||typeof window>"u")return;let k=window.matchMedia("(prefers-color-scheme: dark)");X(k.matches);let D=()=>X(k.matches);return k.addEventListener("change",D),()=>k.removeEventListener("change",D)},[A]);let B=A==="dark"||A==="auto"&&Z,P=SB({...t,api:h}),J=Ph(),ge=iB({...t,api:h,sessionId:P.sessionId,onCallTool:v?.onCallTool}),C=v?.resourceEndpoint??EB(h,t.headers),ze=(0,Qe.useRef)({});ze.current={api:h,token:jp(t.headers),channelId:typeof t.body?.channelId=="string"?t.body.channelId:void 0,sessionId:P.sessionId};let ot=(0,Qe.useCallback)(k=>{Vp("widget",ze.current,{widget:k.widget,outcome:k.outcome},k.metrics)},[]),x=Hl(p,!P.text),te=IB({api:h,headers:t.headers,uploadHeaders:t.uploadHeaders,sessionId:P.sessionId,documentUpload:u,allowAttachments:l}),[re,ke]=(0,Qe.useState)(null),[We,be]=(0,Qe.useState)(null),Oe=(0,Qe.useRef)(null),we=(0,Qe.useRef)(null),ce=(0,Qe.useRef)(null),Le=(0,Qe.useRef)(null),[ie,xe]=(0,Qe.useState)(!0),Ne=(0,Qe.useRef)(ie);Ne.current=ie;let _e=(0,Qe.useCallback)(()=>{let k=Oe.current;if(!k)return;let D=k.querySelector("textarea");D&&D.focus()},[]),Fe=(0,Qe.useCallback)((k="smooth")=>{let D=we.current;D&&D.scrollTo({top:D.scrollHeight,behavior:k})},[]);(0,Qe.useEffect)(()=>{let k=Le.current,D=we.current;if(!k||!D)return;let F=new IntersectionObserver(([fe])=>xe(fe.isIntersecting),{root:D,rootMargin:"0px 0px 200px 0px",threshold:0});return F.observe(k),()=>F.disconnect()},[]),(0,Qe.useEffect)(()=>{let k=we.current;if(!k)return;let D=F=>{let Ve=(F.target instanceof Element?F.target:null)?.closest("a");Ve?.href&&J.emit({name:"link.clicked",properties:{url:Ve.href}})};return k.addEventListener("click",D),()=>k.removeEventListener("click",D)},[J]),(0,Qe.useEffect)(()=>{(P.messages[P.messages.length-1]?.role==="user"||Ne.current)&&Fe("smooth")},[P.messages.length,P.messages[P.messages.length-1]]),(0,Qe.useEffect)(()=>{Fe("auto")},[Fe]),(0,Qe.useEffect)(()=>{if(typeof ResizeObserver>"u")return;let k=we.current,D=ce.current;if(!k&&!D)return;let F=k?.scrollHeight??0,fe=k?.clientHeight??0,Ve=new ResizeObserver(()=>{let Ft=we.current;if(!Ft)return;let In=Ft.scrollTop+fe>=F-5;F=Ft.scrollHeight,fe=Ft.clientHeight,In&&Fe("auto")});return k&&Ve.observe(k),D&&Ve.observe(D),()=>Ve.disconnect()},[Fe]);let Ae=LB({messages:P.messages,status:P.status,suggestions:t.suggestions}),de=(0,Qe.useRef)(null);(0,Qe.useEffect)(()=>{let k=Ae.suggestions;!O||k.length===0||de.current===k||(de.current=k,J.emit({name:"suggestions.shown",properties:{texts:k,origin:Ae.source}}))},[Ae.suggestions,Ae.source,J,O]);let W=d?.suggestions,ct=(0,Qe.useRef)(null);(0,Qe.useEffect)(()=>{!O||P.messages.length>0||!W?.length||ct.current===W||(ct.current=W,J.emit({name:"suggestions.shown",properties:{texts:W,origin:"channel"}}))},[W,P.messages.length,J,O]);let le=(0,Qe.useCallback)(k=>{let D=k.content.map(F=>F.text??"").join("").trim();D&&P.handleSubmit({text:D,files:[],modelContext:k.modelContext})},[P.handleSubmit]),oe=(0,Qe.useCallback)(k=>{let D=Ae.suggestions.indexOf(k),F=D>=0?D:d?.suggestions?.indexOf(k)??-1,fe=D>=0?Ae.source:"channel";J.emit({name:"suggestion.clicked",properties:{text:k,index:F,origin:fe}}),Ae.clear(),P.handleSubmit({text:k,files:[]})},[Ae.suggestions,Ae.source,Ae.clear,P.handleSubmit,d,J]);(0,Qe.useImperativeHandle)(a,()=>({sendMessage:k=>{P.handleSubmit({text:k,files:[]}),_e()},sendMessageAndWait:k=>P.sendMessageAndWait(k),reset:P.reset,focus:_e,get messages(){return P.messages},get sessionId(){return P.sessionId}}),[P.handleSubmit,P.sendMessageAndWait,P.reset,P.messages,P.sessionId,_e]),(0,Qe.useEffect)(()=>{if(!m)return;let k=D=>{let F=D.detail,fe=typeof F?.message=="string"?F.message:void 0;fe&&P.handleSubmit({text:fe,files:[]}),_e()};return window.addEventListener(m,k),()=>window.removeEventListener(m,k)},[m,P.handleSubmit,_e]);let Ie=!S&&!!(w||E||P.keepsSession||g),ae=R||!r;return(0,nt.jsxs)("div",{ref:Oe,style:{...H,maxHeight:"inherit",...re&&We?{height:We}:{},opacity:ae?0:1,transition:"opacity 220ms ease-out"},"data-waniwani-chat":"","data-waniwani-layout":"embed","data-assistant-bubble":$?"true":void 0,"data-color-scheme":A==="auto"?"auto":void 0,...ae?{"data-waniwani-initializing":""}:{},...B?{"data-waniwani-dark":""}:{},className:V("ww:relative ww:w-full ww:h-full ww:flex ww:flex-col ww:bg-background ww:text-foreground ww:font-[family-name:var(--ww-font)] ww:overflow-hidden",A==="dark"&&"dark",i,s?.root),children:[Ie&&(0,nt.jsxs)("div",{className:V("ww-header ww:shrink-0 ww:flex ww:items-center ww:gap-2 ww:pl-4 ww:pr-3 ww:py-3 ww:border-b ww:border-border",s?.header),style:{backgroundColor:"var(--ww-color-card-header)",color:"var(--ww-color-card-header-foreground)"},children:[w&&(0,nt.jsx)("div",{className:"ww:text-sm ww:font-semibold ww:truncate ww:flex-1 ww:min-w-0",children:w}),!w&&(0,nt.jsx)("div",{className:"ww:flex-1"}),!E&&P.keepsSession&&(0,nt.jsx)(Dh,{onClick:P.reset}),E&&(0,nt.jsx)(nB,{threads:P.threads,activeThreadId:P.activeThreadId,onNewThread:P.startNewThread,onSelectThread:k=>{P.switchThread(k)},onDeleteThread:k=>{P.deleteThread(k)}}),g]}),(0,nt.jsxs)("div",{ref:we,className:V("ww:relative ww:flex-1 ww:min-h-0",re?"ww:overflow-hidden":"ww:overflow-y-auto"),children:[(0,nt.jsxs)("div",{ref:ce,className:V("ww:mx-auto ww:w-full ww:max-w-3xl ww:px-4 ww:py-6 ww:flex ww:flex-col ww:gap-6",re&&"ww:!py-0"),children:[(0,nt.jsx)(KU,{value:ot,children:(0,nt.jsx)(eB,{messages:P.messages,status:P.status,welcomeMessage:c,welcome:d,onSuggestionSelect:oe,resourceEndpoint:C,chatSessionId:P.sessionId,isDark:B,onFollowUp:le,onCallTool:ge,fullscreenToolCallId:re,debug:I,showToolCalls:T,toolDefinitions:P.toolDefinitions,messageClassNames:{message:s?.message,userBubble:s?.userBubble,assistantBubble:s?.assistantBubble},onWidgetDisplayModeChange:(k,D)=>{if(k==="fullscreen"){let F=Oe.current?.getBoundingClientRect().height??0;be(F>0?F:null),ke(D.toolCallId)}else be(null),ke(null)}})}),(0,nt.jsx)("div",{ref:Le,"aria-hidden":!0,style:{height:1}})]}),!ie&&!re&&(0,nt.jsx)("div",{className:"ww:sticky ww:bottom-2 ww:flex ww:justify-center ww:pointer-events-none",children:(0,nt.jsx)(br,{type:"button",onClick:()=>Fe("smooth"),size:"icon",variant:"outline",className:"ww:rounded-full ww:shadow ww:pointer-events-auto","aria-label":"Scroll to latest",children:(0,nt.jsx)(Tc,{className:"ww:size-4"})})})]}),!y&&(0,nt.jsxs)("div",{className:"ww:shrink-0 ww:bg-background",style:re?{display:"none"}:void 0,children:[(0,nt.jsx)(Sl,{suggestions:Ae.suggestions,isLoading:Ae.isLoading,onSelect:oe}),(0,nt.jsx)(HM,{queuedMessages:P.queuedMessages,onRemove:P.removeQueuedMessage}),(0,nt.jsx)("div",{className:"ww:px-4 ww:pb-2 ww:pt-2",children:(0,nt.jsxs)("div",{className:"ww:mx-auto ww:w-full ww:max-w-3xl",children:[(0,nt.jsxs)(TM,{onSubmit:P.handleSubmit,attachmentsEnabled:te.enabled,globalDrop:te.enabled,multiple:te.enabled,accept:te.accept,maxFileSize:te.maxFileSize,maxPdfPages:te.maxPdfPages,maxFiles:te.maxFiles,upload:te.upload,onDiscard:te.onDiscard,onError:te.reportError,className:V("ww-input ww:rounded-2xl ww:border-border ww:bg-input",s?.input),children:[(0,nt.jsx)(DM,{enabled:te.enabled}),te.enabled&&(0,nt.jsx)(RM,{className:"ww:px-4 ww:pt-3"}),(0,nt.jsxs)("div",{className:"ww:flex ww:items-center ww:gap-1 ww:pl-4 ww:pr-3 ww:py-2.5",children:[te.enabled&&(0,nt.jsx)(MM,{}),(0,nt.jsx)(EM,{onChange:P.handleTextChange,value:P.text,placeholder:x,className:"ww:min-h-0 ww:py-1 ww:px-0"}),(0,nt.jsx)(AM,{status:P.status,disabled:P.queueFull,onStop:P.stop})]})]}),te.error&&(0,nt.jsx)("output",{className:"ww:block ww:pt-1.5 ww:text-center ww:text-destructive ww:text-xs",children:te.error.message}),(0,nt.jsxs)("div",{className:"ww:pt-2 ww:pb-1 ww:flex ww:flex-nowrap ww:justify-center ww:items-center ww:gap-1.5",children:[(0,nt.jsx)(tB,{}),(0,nt.jsx)(_M,{text:U})]})]})})]})]})});var Qd=j(Ee(),1);var AB="500px",RY="https://app.waniwani.ai/api/mcp/chat",DY={api:RY};function sI(){if(typeof document>"u")return null;if(document.currentScript instanceof HTMLScriptElement)return document.currentScript;let e=document.querySelector("script[src][data-token]");if(e instanceof HTMLScriptElement)return e;let t=document.querySelectorAll("script[src]");for(let a of t)if(a instanceof HTMLScriptElement&&/embed/i.test(a.src))return a;return null}function $h(){let e=sI();if(!e)return{};let t=J=>e.getAttribute(J)??void 0,a=J=>{let ge=e.getAttribute(J);if(ge==null)return;let C=ge.trim().toLowerCase();if(C==="true"||C==="1"||C==="")return!0;if(C==="false"||C==="0")return!1},n={},r=t("data-api");r&&(n.api=r);let o=t("data-token");o&&(n.token=o);let i=t("data-visitor-id");i&&(n.visitorId=i);let s=t("data-title");s&&(n.title=s);let l=t("data-welcome-message");l&&(n.welcomeMessage=l);let u=t("data-placeholder");u&&(n.placeholder=u);let c=t("data-mcp-server-url");c&&(n.mcpServerUrl=c);let d=t("data-webmcp");d&&(n.webmcp={enabled:d!=="false"&&d!=="off"});let p=t("data-channel-id");if(p&&(n.channelId=p),t("data-show-tool-calls")?.trim().toLowerCase()==="titles-only")n.showToolCalls="titles-only";else{let J=a("data-show-tool-calls");J!==void 0&&(n.showToolCalls=J)}let h=t("data-css");h&&(n.css=h);let v=t("data-suggestions");v&&(n.suggestions=v.split(",").map(J=>J.trim()).filter(Boolean));let I=a("data-enable-thread-history");I!==void 0&&(n.enableThreadHistory=I);let y=a("data-disable-page-view");y!==void 0&&(n.disablePageView=y);let w=a("data-hide-header");w!==void 0&&(n.hideHeader=w);let g=t("data-theme");(g==="light"||g==="dark"||g==="auto")&&(n.appearance={...n.appearance,theme:g});let S=a("data-assistant-bubble");S!==void 0&&(n.appearance={...n.appearance,assistantBubble:S});let E=t("data-locale");(E==="en"||E==="fr"||E==="es")&&(n.locale=E);let T=t("data-mode");(T==="inline"||T==="floating"||T==="composer"||T==="off")&&(n.mode=T);let R={},O=t("data-composer-variant")?.trim().toLowerCase();(O==="glow"||O==="outline")&&(R.variant=O);let U=t("data-composer-size")?.trim().toLowerCase();(U==="sm"||U==="md"||U==="lg")&&(R.size=U);let A=a("data-composer-suggestions");A!==void 0&&(R.showSuggestions=A);let Q=t("data-composer-align")?.trim().toLowerCase();(Q==="start"||Q==="center")&&(R.align=Q);let $=a("data-composer-trigger");$!==void 0&&(R.trigger=$);let H=a("data-composer-mobile-trigger");H!==void 0&&(R.mobileTrigger=H),Object.keys(R).length>0&&(n.composer=R);let Z=t("data-height");Z&&(n.height=Z);let X=t("data-launcher-text");X&&(n.launcherText=X);let B=t("data-appear-delay");if(B!==void 0){let J=Number.parseInt(B.trim(),10);Number.isFinite(J)&&J>=0&&(n.appearDelay=J)}let P=t("data-disclaimer");if(P!==void 0){let J=P.trim(),ge=J.toLowerCase();ge==="false"||ge==="0"?n.disclaimer=!1:J&&(n.disclaimer=J)}return n}function Kd(e){if(!e)return{};let t={};for(let a in e)e[a]!==void 0&&(t[a]=e[a]);return t}function Yd(e,t,a){let n=a??$h(),r=_Y(t,n,e),o={...t?.composer??{},...Kd(n.composer),...Kd(e?.composer)},i=Object.keys(o).length>0,s={token:"",...DY,...Kd(t),...Kd(n),...Kd(e),...r?{appearance:r}:{},...i?{composer:o}:{}};if(!s.token)throw new Error("[Waniwani] Missing required config: `token`. Set data-token on the script tag or pass it to Waniwani.chat.init().");return s}function _Y(e,t,a){let n=a?.appearance?.theme??t.appearance?.theme??e?.appearance?.theme,r={...e?.appearance?.variables??{},...t.appearance?.variables??{},...a?.appearance?.variables??{}},o=Object.keys(r).length>0,i=a?.appearance?.assistantBubble??t.appearance?.assistantBubble??e?.appearance?.assistantBubble;if(!n&&!o&&i===void 0)return;let s={};return n&&(s.theme=n),o&&(s.variables=r),i!==void 0&&(s.assistantBubble=i),s}var OB=j(Ee(),1);var Wh=j(Ee(),1);function PY(e){return e?.patterns??e?.rules??[]}var MB="\0\0";function OY(e){let a=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\*\\\*/g,MB).replace(/\\\*/g,"[^/]*").split(MB).join(".*");return new RegExp(`^${a}$`)}function RB(e,t){try{return OY(e).test(t)}catch{return!1}}function Zd(e,t){if(!e)return!0;let a=!1;for(let n of PY(e))if(RB(n.glob,t)){if(n.action==="hide")return!1;a=!0}return a?!0:(e.default??"show")!=="hide"}function DB(e,t){for(let a of e?.appearRules??[])if(RB(a.glob,t))return a.appearAfter;return null}var lI="waniwani:locationchange",_B=!1;function NY(){if(!(_B||typeof history>"u")){_B=!0;for(let e of["pushState","replaceState"]){let t=history[e];history[e]=function(...n){let r=t.apply(this,n);return window.dispatchEvent(new Event(lI)),r}}}}function UY(e){return NY(),window.addEventListener(lI,e),window.addEventListener("popstate",e),()=>{window.removeEventListener(lI,e),window.removeEventListener("popstate",e)}}function BY(){return window.location.pathname}function zY(){return"/"}function Jd(){return(0,Wh.useSyncExternalStore)(UY,BY,zY)}function hu(e,t){let a=Jd(),n=t&&Zd(e,a);return(0,Wh.useEffect)(()=>{Ua("visibility gate",{pathname:a,ready:t,visible:n,rules:e})},[a,t,n]),n}var FY=3,qY=["low","medium","high"];function uI(e){if(e.length===0)return;let t=Math.floor(Math.random()*e.length),[a]=e.splice(t,1);return a}function HY(e){let t=new Map,a=[];for(let o of e)if(o.tier){let i=t.get(o.tier)??[];i.push(o),t.set(o.tier,i)}else a.push(o);let n=[];for(let o of qY){let i=uI(t.get(o)??[])??uI(a);i&&n.push(i)}let r=[...t.values()].flat().concat(a);for(;n.length<Math.min(FY,e.length);){let o=uI(r);if(!o)break;n.push(o)}return n}function PB(e){let t;try{t=new URL(e,"http://localhost").pathname}catch{t="/"}let a=t.replace(/\/+$/,"");return(a===""?"/":a).toLowerCase()}function NB(e){return Array.isArray(e)?e.flatMap(t=>{let a=t;if(typeof a?.url!="string"||a.url.length===0||!Array.isArray(a.prompts))return[];let n=a.prompts.flatMap(r=>{let o=r;return typeof o?.text!="string"||o.text.length===0?[]:[{id:typeof o.id=="string"?o.id:null,text:o.text,tier:o.tier==="low"||o.tier==="medium"||o.tier==="high"?o.tier:void 0}]});return n.length>0?[{url:a.url,prompts:n}]:[]}):[]}function gu(e){let{pageSuggestions:t,suggestions:a}=e,n=Jd();return(0,OB.useMemo)(()=>{let r=PB(n),o=t?.find(s=>PB(s.url)===r),i=o?HY(o.prompts).map(({id:s,text:l})=>({id:s,text:l})):null;return Ua("configured suggestions resolve",{pathname:r,matched:!!o,count:i?.length??0}),{page:i,channel:du(a??[])}},[n,t,a])}var jY="waniwani:config:";function UB(e,t,a){return`${jY}${e}|${t}|${a??""}`}function ci(e,t,a){if(typeof window>"u")return null;try{let n=window.sessionStorage.getItem(UB(e,t,a));if(!n)return null;let r=JSON.parse(n);return r&&typeof r=="object"?r:null}catch{return null}}function VY(e,t,a,n){if(!(typeof window>"u"))try{window.sessionStorage.setItem(UB(e,t,a),JSON.stringify(n))}catch{}}var $Y=600;function WY(e){if(typeof e!="object"||e===null||typeof e.enabled!="boolean")return null;let t=Array.isArray(e.accept)?e.accept.filter(n=>typeof n=="string"):[],a=n=>typeof n=="number"&&Number.isFinite(n)&&n>0;return e.enabled?a(e.maxBytes)&&a(e.maxPdfPages)&&a(e.maxFiles)&&t.length>0?{enabled:!0,maxBytes:e.maxBytes,maxPdfPages:e.maxPdfPages,maxFiles:e.maxFiles,accept:t}:null:{enabled:!1,maxBytes:0,maxPdfPages:0,maxFiles:0,accept:t}}async function GY(e,t,a,n){Di("configStart");let r=await XY(e,t,a,n);return Di("configEnd"),a?.aborted||Jw(r.metadata),r}async function XY(e,t,a,n){try{let r=Na(e,"/config",n?{channel:n}:void 0),o=await fetch(r,{method:"GET",headers:{Authorization:`Bearer ${t}`},signal:a});if(!o.ok)return{};let i=await o.json(),s=i&&typeof i=="object"&&"data"in i&&i.data?i.data:i;return s?KY(s):{}}catch{return{}}}function KY(e){let t={};e.source!=null&&(t.source=e.source),e.channelId!=null&&(t.channelId=e.channelId),e.title!=null&&(t.title=e.title),e.welcomeMessage!=null&&(t.welcomeMessage=e.welcomeMessage),e.placeholder!=null&&(t.placeholder=e.placeholder),e.suggestions!=null&&e.suggestions.length>0&&(t.suggestions=e.suggestions);let a=NB(e.pageSuggestions);a.length>0&&(t.pageSuggestions=a),typeof e.enableThreadHistory=="boolean"&&(t.enableThreadHistory=e.enableThreadHistory),typeof e.sessionApi=="string"&&e.sessionApi&&(t.sessionApi=e.sessionApi),typeof e.webmcp?.enabled=="boolean"&&(t.webmcp={enabled:e.webmcp.enabled}),e.toolCallDisplay==="full"?t.showToolCalls=!0:e.toolCallDisplay==="titles-only"?t.showToolCalls="titles-only":e.toolCallDisplay==="hidden"&&(t.showToolCalls=!1),e.visibility&&(t.visibility=e.visibility);let n=WY(e.documentUpload);return n&&(t.documentUpload=n),e.metadata&&typeof e.metadata=="object"&&(t.metadata=e.metadata),t}function yu(e,t,a){let[n,r]=(0,Qd.useState)(e),[o,i]=(0,Qd.useState)(!1);return(0,Qd.useEffect)(()=>{let s=e.api,l=e.token,u=e.channelId;if(!s||!l){i(!0);return}let c=h=>{e.disablePageView||M1({api:s,token:l,channelId:u??h.channelId,mode:e.mode==="off"?void 0:e.mode,source:h.source})},d=ci(s,l,u);if(d)try{let h=Yd(t,d,a);r(h),$p("cache"),Jw(d.metadata),i(!0),Ua("config resolved (sessionStorage cache)",{config:h,visibility:h.visibility}),c(d)}catch{}let p=new AbortController,m=setTimeout(()=>{$p("timeout"),i(!0)},$Y);return GY(s,l,p.signal,u).then(h=>{if(!p.signal.aborted){if(Ua("remote /config response",h),Object.keys(h).length>0){VY(s,l,u,h);try{let v=Yd(t,h,a);r(v),Ua("config resolved (remote)",{config:v,visibility:v.visibility})}catch(v){console.error("[Waniwani] Failed to apply remote config:",v)}}$p("remote"),i(!0),c(h)}}).catch(h=>{console.error("[Waniwani] Remote config fetch failed:",h),i(!0)}).finally(()=>clearTimeout(m)),()=>{p.abort(),clearTimeout(m)}},[e.api,e.token,e.channelId]),{config:n,ready:o}}var Gt=j(me(),1),YY={sm:{row:"ww:gap-1 ww:pl-3 ww:pr-1 ww:py-1",field:"ww:py-1 ww:text-base ww:sm:text-sm",send:"ww:size-7",sendIcon:"ww:size-3.5",radius:12},md:{row:"ww:gap-1 ww:pl-3.5 ww:pr-1.5 ww:py-1.5 ww:sm:pl-4 ww:sm:pr-2 ww:sm:py-2",field:"ww:py-1.5 ww:text-base ww:sm:text-sm",send:"ww:size-8",sendIcon:"ww:size-4",radius:16},lg:{row:"ww:gap-2 ww:pl-5 ww:pr-2 ww:py-2.5 ww:sm:pl-6 ww:sm:pr-2.5 ww:sm:py-3",field:"ww:py-2 ww:text-base",send:"ww:size-10",sendIcon:"ww:size-5",radius:20}},BB="var(--ww-composer-bg, var(--ww-color-input))",ZY="var(--ww-composer-border-color, var(--ww-color-border))",JY="var(--ww-composer-border-width, 1px)",zB="var(--ww-composer-send-bg, var(--ww-color-foreground))",FB="var(--ww-composer-send-fg, var(--ww-color-background))",HB=(0,rt.forwardRef)(function(t,a){return(0,Gt.jsx)(es,{locale:t.config.locale,children:(0,Gt.jsx)(QY,{...t,ref:a})})}),QY=(0,rt.forwardRef)(function({config:t,programmatic:a,scriptConfig:n,panelContainer:r,onVisibilityChange:o},i){let{t:s}=Ue(),{config:l,ready:u}=yu(t,a,n),c=hu(l.visibility,u);(0,rt.useEffect)(()=>{o?.(c)},[c,o]),ru({api:l.api,token:l.token,channelId:l.channelId,mode:"composer",paintMark:"chatVisible",painted:u});let d=(0,rt.useRef)(null),p=(0,rt.useMemo)(()=>su({mode:"composer",getSessionId:()=>d.current?.sessionId}),[]),m=l.onEvent;(0,rt.useEffect)(()=>{if(m)return p.subscribe(m)},[m,p]);let h=(0,rt.useRef)(null),v=(0,rt.useRef)(null),[I,y]=(0,rt.useState)(!1),[w,g]=(0,rt.useState)(""),[S,E]=(0,rt.useState)(0),T=l.appearance?.theme,R=l.appearance?.variables,O=(0,rt.useMemo)(()=>R?pu(R):{},[R]),U=gu(l),A=(0,rt.useMemo)(()=>Ss({flow:null,followup:null,...U}),[U]),Q=(0,rt.useMemo)(()=>A?.suggestions.map(de=>de.text)??[],[A]);Fl({widgetEvents:p,api:l.api,token:l.token,channelId:l.channelId,source:l.source,mode:"composer",pagePrompts:U.page,getSessionId:()=>d.current?.sessionId});let $=(0,rt.useRef)(null);(0,rt.useEffect)(()=>{!c||!A||$.current!==A&&($.current=A,p.emit({name:"suggestions.shown",properties:{texts:Q,origin:A.origin}}))},[c,A,Q,p]);let H=l.composer??{},Z=H.variant??"glow",X=YY[H.size??"md"],B=H.showSuggestions??!0,P=H.align==="center",J=oM(),ge=(H.trigger??!1)||J&&(H.mobileTrigger??!0),C=l.launcherText??l.placeholder??s.launcher.prompt,ze=Hl(C,!ge&&w.length===0),ot="var(--ww-shadow, 0 10px 30px rgba(0, 0, 0, 0.08))";(0,rt.useEffect)(()=>{let de=h.current;if(de){if(!w){de.style.height="";return}de.style.height="auto",de.style.height=`${de.scrollHeight}px`}},[w]),(0,rt.useEffect)(()=>{S>0&&I&&d.current?.focus()},[S,I]);let x=(0,rt.useRef)(!1);(0,rt.useEffect)(()=>{u&&!x.current&&(x.current=!0,p.emit({name:"chat.ready"}))},[u,p]);let te=(0,rt.useRef)(!1);(0,rt.useEffect)(()=>{let de=c&&I;de!==te.current&&(te.current=de,p.emit({name:de?"chat.opened":"chat.closed"}))},[c,I,p]);let re=(0,rt.useCallback)(de=>{y(!0),E(ct=>ct+1);let W=de.trim();W&&d.current?.sendMessage(W)},[]);(0,rt.useImperativeHandle)(i,()=>({open:()=>y(!0),close:()=>y(!1),toggle:()=>y(de=>!de),sendMessage:de=>re(de),sendMessageAndWait:async de=>{y(!0);let W=d.current;if(W)return await W.sendMessageAndWait(de)},reset:()=>d.current?.reset(),focus:()=>{I?E(de=>de+1):(h.current??v.current)?.focus()},getMessages:()=>d.current?.messages??[],getSessionId:()=>d.current?.sessionId}),[re,I]);let ke=(0,rt.useCallback)(()=>{w.trim()&&(re(w),g(""))},[w,re]),We=(0,rt.useCallback)(()=>{(d.current?.messages.length??0)>0&&(y(!0),E(de=>de+1))},[]),be={mode:"composer"},Oe=zl(l.sessionApi);l.mcpServerUrl&&(be.mcpServerUrl=l.mcpServerUrl),l.channelId&&(be.channelId=l.channelId);let we=(0,Gt.jsx)("button",{type:"button",onClick:()=>y(!1),"aria-label":s.launcher.close,className:"ww:flex ww:size-7 ww:items-center ww:justify-center ww:rounded-md ww:text-muted-foreground ww:transition-colors hover:ww:bg-accent hover:ww:text-foreground ww:cursor-pointer",children:(0,Gt.jsx)(wn,{className:"ww:size-4"})}),ce=(0,Gt.jsxs)("div",{className:V("ww:flex ww:items-end",X.row),children:[(0,Gt.jsx)("textarea",{ref:h,rows:1,value:w,placeholder:ze,onChange:de=>g(de.target.value),onFocus:We,onKeyDown:de=>{de.key==="Enter"&&!de.shiftKey&&(de.preventDefault(),ke())},className:V("ww:min-w-0 ww:flex-1 ww:resize-none ww:bg-transparent ww:max-h-36 ww:text-foreground ww:outline-none ww:placeholder:text-muted-foreground",X.field,!w&&"ww:overflow-hidden ww:whitespace-nowrap ww:text-ellipsis ww:placeholder:overflow-hidden ww:placeholder:text-ellipsis")}),(0,Gt.jsx)("button",{type:"button",onClick:ke,disabled:!w.trim(),"aria-label":s.promptInput.submit,className:V("ww:relative ww:flex ww:shrink-0 ww:items-center ww:justify-center ww:rounded-full ww:transition-opacity hover:ww:opacity-90 disabled:ww:opacity-40",X.send),style:{background:zB,color:FB},children:(0,Gt.jsx)(pr,{className:X.sendIcon})})]}),Le=(0,Gt.jsxs)("button",{ref:v,type:"button",onClick:()=>re(""),className:V("ww:flex ww:w-full ww:items-center ww:text-left ww:cursor-pointer",X.row,P&&"ww:justify-center"),children:[(0,Gt.jsx)("span",{className:V("ww:min-w-0 ww:flex-1 ww:truncate ww:text-muted-foreground",X.field,P&&"ww:flex-none"),children:C}),(0,Gt.jsx)("span",{"aria-hidden":!0,className:V("ww:flex ww:shrink-0 ww:items-center ww:justify-center ww:rounded-full",X.send,P&&"ww:ml-3"),style:{background:zB,color:FB},children:(0,Gt.jsx)(pr,{className:X.sendIcon})})]}),ie=ge?Le:ce,xe=`var(--ww-composer-radius, ${X.radius}px)`,Ne={borderRadius:xe,background:BB,borderColor:ZY,borderWidth:JY,borderStyle:"solid",boxShadow:`var(--ww-composer-shadow, ${ot})`},_e=Z==="glow"?(0,Gt.jsx)(Yp,{animated:u,backgroundColor:BB,borderRadius:xe,edgeSensitivity:30,coneSpread:25,colors:["#c084fc","#f472b6","#38bdf8"],style:Ne,children:ie}):(0,Gt.jsx)("div",{className:V(ge&&"ww:transition-colors hover:ww:border-primary/40"),style:Ne,children:ie}),Fe=(0,Gt.jsxs)("div",{"data-waniwani-chat":"","data-color-scheme":T==="auto"?"auto":void 0,"data-waniwani-composer":"input","data-composer-variant":Z,inert:I,className:V("ww:w-full ww:font-[family-name:var(--ww-font-sans)]",T==="dark"&&"dark"),style:O,children:[_e,B&&Q.length>0&&(0,Gt.jsx)(Sl,{suggestions:Q,onSelect:de=>{p.emit({name:"suggestion.clicked",properties:{text:de,index:Q.indexOf(de),origin:A?.origin??"channel"}}),re(de)},align:P?"center":"start",className:"ww:px-0.5 ww:pt-2.5 ww:pb-0"})]}),Ae=(0,Gt.jsx)("div",{"data-waniwani-chat":"","data-color-scheme":T==="auto"?"auto":void 0,className:V("ww:contents ww:font-[family-name:var(--ww-font-sans)]",T==="dark"&&"dark"),style:O,children:(0,Gt.jsx)("div",{role:"dialog","aria-label":l.title??C,"data-waniwani-floating":"panel","data-state":c&&I?"shown":"hidden",style:{boxShadow:ot},className:V("ww:fixed ww:z-[2147483002] ww:flex ww:flex-col ww:overflow-hidden ww:bg-background","ww:inset-0 ww:w-full ww:rounded-none","ww:sm:inset-auto ww:sm:bottom-4 ww:sm:left-0 ww:sm:right-0 ww:sm:mx-auto ww:sm:h-[720px] ww:sm:max-h-[calc(100dvh-2rem)] ww:sm:w-[calc(100vw-2rem)] ww:sm:max-w-[1000px] ww:sm:rounded-2xl ww:sm:border ww:sm:border-border"),children:(0,Gt.jsx)(mu,{transport:Oe,ref:d,api:l.api??"",headers:{Authorization:`Bearer ${l.token}`},skipRemoteConfig:!0,body:be,appearance:l.appearance,title:l.title,headerActions:we,hideHeader:!1,onScreen:I,welcomeMessage:l.welcomeMessage,placeholder:l.placeholder,suggestions:U,enableThreadHistory:l.enableThreadHistory,documentUpload:l.documentUpload,showToolCalls:l.showToolCalls,locale:l.locale,initializing:!u})})});return(0,Gt.jsxs)(lu,{value:p,children:[Fe,(0,qB.createPortal)(Ae,r)]})});var cI="/*! tailwindcss v4.1.18 | MIT License | https://tailwindcss.com */\n@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-space-y-reverse:0;--tw-border-style:solid;--tw-font-weight:initial;--tw-tracking:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial;--tw-duration:initial;--tw-ease:initial}}}@layer theme{:root,:host{--ww-font-mono:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,\"Liberation Mono\",\"Courier New\",monospace;--ww-color-black:#000;--ww-spacing:.25rem;--ww-container-sm:24rem;--ww-container-md:28rem;--ww-container-3xl:48rem;--ww-text-xs:.75rem;--ww-text-xs--line-height:calc(1/.75);--ww-text-sm:.875rem;--ww-text-sm--line-height:calc(1.25/.875);--ww-text-base:1rem;--ww-text-base--line-height:calc(1.5/1);--ww-text-lg:1.125rem;--ww-text-lg--line-height:calc(1.75/1.125);--ww-font-weight-medium:500;--ww-font-weight-semibold:600;--ww-tracking-wide:.025em;--ww-tracking-wider:.05em;--ww-radius-md:.375rem;--ww-radius-lg:.5rem;--ww-radius-xl:.75rem;--ww-radius-2xl:1rem;--ww-ease-out:cubic-bezier(0,0,.2,1);--ww-animate-spin:spin 1s linear infinite;--ww-animate-pulse:pulse 2s cubic-bezier(.4,0,.6,1)infinite;--ww-blur-md:12px;--ww-blur-xl:24px;--ww-default-transition-duration:.15s;--ww-default-transition-timing-function:cubic-bezier(.4,0,.2,1);--ww-default-font-family:var(--ww-font-sans,system-ui,-apple-system,\"Segoe UI\",sans-serif);--ww-default-mono-font-family:var(--ww-font-mono)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--ww-default-font-family,ui-sans-serif,system-ui,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\",\"Segoe UI Symbol\",\"Noto Color Emoji\");font-feature-settings:var(--ww-default-font-feature-settings,normal);font-variation-settings:var(--ww-default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--ww-default-mono-font-family,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,\"Liberation Mono\",\"Courier New\",monospace);font-feature-settings:var(--ww-default-mono-font-feature-settings,normal);font-variation-settings:var(--ww-default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab, red, red)){::placeholder{color:color-mix(in oklab,currentcolor 50%,transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){appearance:button}::file-selector-button{appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@layer components;@layer utilities{.ww\\:pointer-events-auto{pointer-events:auto}.ww\\:pointer-events-none{pointer-events:none}.ww\\:absolute{position:absolute}.ww\\:fixed{position:fixed}.ww\\:relative{position:relative}.ww\\:sticky{position:sticky}.ww\\:inset-0{inset:calc(var(--ww-spacing)*0)}.ww\\:top-2{top:calc(var(--ww-spacing)*2)}.ww\\:top-full{top:100%}.ww\\:right-0{right:calc(var(--ww-spacing)*0)}.ww\\:right-2{right:calc(var(--ww-spacing)*2)}.ww\\:bottom-0{bottom:calc(var(--ww-spacing)*0)}.ww\\:bottom-2{bottom:calc(var(--ww-spacing)*2)}.ww\\:bottom-3{bottom:calc(var(--ww-spacing)*3)}.ww\\:bottom-4{bottom:calc(var(--ww-spacing)*4)}.ww\\:left-0{left:calc(var(--ww-spacing)*0)}.ww\\:left-\\[50\\%\\]{left:50%}.ww\\:isolate{isolation:isolate}.ww\\:-z-\\[1\\]{z-index:calc(1*-1)}.ww\\:z-10{z-index:10}.ww\\:z-50{z-index:50}.ww\\:z-\\[1\\]{z-index:1}.ww\\:z-\\[2147483000\\]{z-index:2147483000}.ww\\:z-\\[2147483002\\]{z-index:2147483002}.ww\\:mx-auto{margin-inline:auto}.ww\\:mt-0\\.5{margin-top:calc(var(--ww-spacing)*.5)}.ww\\:mt-1{margin-top:calc(var(--ww-spacing)*1)}.ww\\:mt-2{margin-top:calc(var(--ww-spacing)*2)}.ww\\:mt-6{margin-top:calc(var(--ww-spacing)*6)}.ww\\:mb-0{margin-bottom:calc(var(--ww-spacing)*0)}.ww\\:mb-4{margin-bottom:calc(var(--ww-spacing)*4)}.ww\\:mb-6{margin-bottom:calc(var(--ww-spacing)*6)}.ww\\:ml-3{margin-left:calc(var(--ww-spacing)*3)}.ww\\:ml-auto{margin-left:auto}.ww\\:line-clamp-1{-webkit-line-clamp:1;-webkit-box-orient:vertical;display:-webkit-box;overflow:hidden}.ww\\:block{display:block}.ww\\:contents{display:contents}.ww\\:flex{display:flex}.ww\\:grid{display:grid}.ww\\:hidden{display:none}.ww\\:inline-block{display:inline-block}.ww\\:inline-flex{display:inline-flex}.ww\\:field-sizing-content{field-sizing:content}.ww\\:size-2{width:calc(var(--ww-spacing)*2);height:calc(var(--ww-spacing)*2)}.ww\\:size-3{width:calc(var(--ww-spacing)*3);height:calc(var(--ww-spacing)*3)}.ww\\:size-3\\.5{width:calc(var(--ww-spacing)*3.5);height:calc(var(--ww-spacing)*3.5)}.ww\\:size-4{width:calc(var(--ww-spacing)*4);height:calc(var(--ww-spacing)*4)}.ww\\:size-5{width:calc(var(--ww-spacing)*5);height:calc(var(--ww-spacing)*5)}.ww\\:size-7{width:calc(var(--ww-spacing)*7);height:calc(var(--ww-spacing)*7)}.ww\\:size-8{width:calc(var(--ww-spacing)*8);height:calc(var(--ww-spacing)*8)}.ww\\:size-9{width:calc(var(--ww-spacing)*9);height:calc(var(--ww-spacing)*9)}.ww\\:size-10{width:calc(var(--ww-spacing)*10);height:calc(var(--ww-spacing)*10)}.ww\\:size-12{width:calc(var(--ww-spacing)*12);height:calc(var(--ww-spacing)*12)}.ww\\:size-auto{width:auto;height:auto}.ww\\:size-full{width:100%;height:100%}.ww\\:h-0\\.5{height:calc(var(--ww-spacing)*.5)}.ww\\:h-2\\.5{height:calc(var(--ww-spacing)*2.5)}.ww\\:h-5{height:calc(var(--ww-spacing)*5)}.ww\\:h-8{height:calc(var(--ww-spacing)*8)}.ww\\:h-9{height:calc(var(--ww-spacing)*9)}.ww\\:h-16{height:calc(var(--ww-spacing)*16)}.ww\\:h-auto{height:auto}.ww\\:h-full{height:100%}.ww\\:max-h-36{max-height:calc(var(--ww-spacing)*36)}.ww\\:max-h-48{max-height:calc(var(--ww-spacing)*48)}.ww\\:max-h-80{max-height:calc(var(--ww-spacing)*80)}.ww\\:min-h-0{min-height:calc(var(--ww-spacing)*0)}.ww\\:min-h-5{min-height:calc(var(--ww-spacing)*5)}.ww\\:min-h-full{min-height:100%}.ww\\:w-60{width:calc(var(--ww-spacing)*60)}.ww\\:w-72{width:calc(var(--ww-spacing)*72)}.ww\\:w-\\[calc\\(100vw-2rem\\)\\]{width:calc(100vw - 2rem)}.ww\\:w-auto{width:auto}.ww\\:w-fit{width:fit-content}.ww\\:w-full{width:100%}.ww\\:w-px{width:1px}.ww\\:\\[max-width\\:var\\(--ww-msg-max-width\\,80\\%\\)\\]{max-width:var(--ww-msg-max-width,80%)}.ww\\:max-w-3xl{max-width:var(--ww-container-3xl)}.ww\\:max-w-24{max-width:calc(var(--ww-spacing)*24)}.ww\\:max-w-32{max-width:calc(var(--ww-spacing)*32)}.ww\\:max-w-72{max-width:calc(var(--ww-spacing)*72)}.ww\\:max-w-\\[440px\\]{max-width:440px}.ww\\:max-w-\\[720px\\]{max-width:720px}.ww\\:max-w-full{max-width:100%}.ww\\:max-w-md{max-width:var(--ww-container-md)}.ww\\:max-w-sm{max-width:var(--ww-container-sm)}.ww\\:min-w-0{min-width:calc(var(--ww-spacing)*0)}.ww\\:flex-1{flex:1}.ww\\:flex-none{flex:none}.ww\\:shrink-0{flex-shrink:0}.ww\\:grow{flex-grow:1}.ww\\:translate-x-\\[-50\\%\\]{--tw-translate-x:-50%;translate:var(--tw-translate-x)var(--tw-translate-y)}.ww\\:rotate-90{rotate:90deg}.ww\\:rotate-180{rotate:180deg}.ww\\:animate-\\[ww-fade-in_0\\.2s_ease-out_both\\]{animation:.2s ease-out both ww-fade-in}.ww\\:animate-pulse{animation:var(--ww-animate-pulse)}.ww\\:animate-spin{animation:var(--ww-animate-spin)}.ww\\:cursor-default{cursor:default}.ww\\:cursor-pointer{cursor:pointer}.ww\\:resize-none{resize:none}.ww\\:list-none{list-style-type:none}.ww\\:grid-rows-\\[0fr\\]{grid-template-rows:0fr}.ww\\:grid-rows-\\[1fr\\]{grid-template-rows:1fr}.ww\\:flex-col{flex-direction:column}.ww\\:flex-nowrap{flex-wrap:nowrap}.ww\\:flex-wrap{flex-wrap:wrap}.ww\\:items-center{align-items:center}.ww\\:items-end{align-items:flex-end}.ww\\:items-start{align-items:flex-start}.ww\\:justify-between{justify-content:space-between}.ww\\:justify-center{justify-content:center}.ww\\:justify-end{justify-content:flex-end}.ww\\:gap-1{gap:calc(var(--ww-spacing)*1)}.ww\\:gap-1\\.5{gap:calc(var(--ww-spacing)*1.5)}.ww\\:gap-2{gap:calc(var(--ww-spacing)*2)}.ww\\:gap-2\\.5{gap:calc(var(--ww-spacing)*2.5)}.ww\\:gap-3{gap:calc(var(--ww-spacing)*3)}.ww\\:gap-6{gap:calc(var(--ww-spacing)*6)}:where(.ww\\:space-y-2>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--ww-spacing)*2)*var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--ww-spacing)*2)*calc(1 - var(--tw-space-y-reverse)))}:where(.ww\\:space-y-3>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--ww-spacing)*3)*var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--ww-spacing)*3)*calc(1 - var(--tw-space-y-reverse)))}.ww\\:self-stretch{align-self:stretch}.ww\\:truncate{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.ww\\:overflow-auto{overflow:auto}.ww\\:overflow-hidden{overflow:hidden}.ww\\:overflow-x-auto{overflow-x:auto}.ww\\:overflow-y-auto{overflow-y:auto}.ww\\:overflow-y-hidden{overflow-y:hidden}.ww\\:\\!rounded-full{border-radius:3.40282e38px!important}.ww\\:rounded{border-radius:var(--ww-radius,16px)}.ww\\:rounded-2xl{border-radius:var(--ww-radius-2xl)}.ww\\:rounded-\\[20px\\]{border-radius:20px}.ww\\:rounded-\\[inherit\\]{border-radius:inherit}.ww\\:rounded-full{border-radius:3.40282e38px}.ww\\:rounded-lg{border-radius:var(--ww-radius-lg)}.ww\\:rounded-md{border-radius:var(--ww-radius-md)}.ww\\:rounded-none{border-radius:0}.ww\\:rounded-xl{border-radius:var(--ww-radius-xl)}.ww\\:border{border-style:var(--tw-border-style);border-width:1px}.ww\\:border-0{border-style:var(--tw-border-style);border-width:0}.ww\\:border-2{border-style:var(--tw-border-style);border-width:2px}.ww\\:border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.ww\\:border-b{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.ww\\:border-dashed{--tw-border-style:dashed;border-style:dashed}.ww\\:border-none{--tw-border-style:none;border-style:none}.ww\\:border-border{border-color:var(--ww-color-border,#e5e7eb)}.ww\\:border-muted-foreground\\/50{border-color:var(--ww-color-muted-foreground,#6b7280)}@supports (color:color-mix(in lab, red, red)){.ww\\:border-muted-foreground\\/50{border-color:color-mix(in oklab,var(--ww-color-muted-foreground,#6b7280)50%,transparent)}}.ww\\:border-primary{border-color:var(--ww-color-primary,#6366f1)}.ww\\:border-transparent{border-color:#0000}.ww\\:bg-accent{background-color:var(--ww-color-accent,#f3f4f6)}.ww\\:bg-background,.ww\\:bg-background\\/20{background-color:var(--ww-color-background,#fff)}@supports (color:color-mix(in lab, red, red)){.ww\\:bg-background\\/20{background-color:color-mix(in oklab,var(--ww-color-background,#fff)20%,transparent)}}.ww\\:bg-background\\/85{background-color:var(--ww-color-background,#fff)}@supports (color:color-mix(in lab, red, red)){.ww\\:bg-background\\/85{background-color:color-mix(in oklab,var(--ww-color-background,#fff)85%,transparent)}}.ww\\:bg-black\\/45{background-color:var(--ww-color-black)}@supports (color:color-mix(in lab, red, red)){.ww\\:bg-black\\/45{background-color:color-mix(in oklab,var(--ww-color-black)45%,transparent)}}.ww\\:bg-border{background-color:var(--ww-color-border,#e5e7eb)}.ww\\:bg-foreground,.ww\\:bg-foreground\\/5{background-color:var(--ww-color-foreground,#1f2937)}@supports (color:color-mix(in lab, red, red)){.ww\\:bg-foreground\\/5{background-color:color-mix(in oklab,var(--ww-color-foreground,#1f2937)5%,transparent)}}.ww\\:bg-input{background-color:var(--ww-color-input,#f9fafb)}.ww\\:bg-muted{background-color:var(--ww-color-muted,#f1f5f9)}.ww\\:bg-muted-foreground\\/60{background-color:var(--ww-color-muted-foreground,#6b7280)}@supports (color:color-mix(in lab, red, red)){.ww\\:bg-muted-foreground\\/60{background-color:color-mix(in oklab,var(--ww-color-muted-foreground,#6b7280)60%,transparent)}}.ww\\:bg-muted\\/50{background-color:var(--ww-color-muted,#f1f5f9)}@supports (color:color-mix(in lab, red, red)){.ww\\:bg-muted\\/50{background-color:color-mix(in oklab,var(--ww-color-muted,#f1f5f9)50%,transparent)}}.ww\\:bg-primary{background-color:var(--ww-color-primary,#6366f1)}.ww\\:bg-tool-card{background-color:var(--ww-color-tool-card,#f4f4f5)}.ww\\:bg-transparent{background-color:#0000}.ww\\:object-contain{object-fit:contain}.ww\\:object-cover{object-fit:cover}.ww\\:object-center{object-position:center}.ww\\:p-0{padding:calc(var(--ww-spacing)*0)}.ww\\:p-1{padding:calc(var(--ww-spacing)*1)}.ww\\:p-1\\.5{padding:calc(var(--ww-spacing)*1.5)}.ww\\:p-2{padding:calc(var(--ww-spacing)*2)}.ww\\:p-2\\.5{padding:calc(var(--ww-spacing)*2.5)}.ww\\:p-3{padding:calc(var(--ww-spacing)*3)}.ww\\:px-0{padding-inline:calc(var(--ww-spacing)*0)}.ww\\:px-0\\.5{padding-inline:calc(var(--ww-spacing)*.5)}.ww\\:px-1\\.5{padding-inline:calc(var(--ww-spacing)*1.5)}.ww\\:px-2{padding-inline:calc(var(--ww-spacing)*2)}.ww\\:px-3{padding-inline:calc(var(--ww-spacing)*3)}.ww\\:px-3\\.5{padding-inline:calc(var(--ww-spacing)*3.5)}.ww\\:px-4{padding-inline:calc(var(--ww-spacing)*4)}.ww\\:px-6{padding-inline:calc(var(--ww-spacing)*6)}.ww\\:\\!py-0{padding-block:calc(var(--ww-spacing)*0)!important}.ww\\:py-0\\.5{padding-block:calc(var(--ww-spacing)*.5)}.ww\\:py-1{padding-block:calc(var(--ww-spacing)*1)}.ww\\:py-1\\.5{padding-block:calc(var(--ww-spacing)*1.5)}.ww\\:py-2{padding-block:calc(var(--ww-spacing)*2)}.ww\\:py-2\\.5{padding-block:calc(var(--ww-spacing)*2.5)}.ww\\:py-3{padding-block:calc(var(--ww-spacing)*3)}.ww\\:py-6{padding-block:calc(var(--ww-spacing)*6)}.ww\\:py-12{padding-block:calc(var(--ww-spacing)*12)}.ww\\:pt-1{padding-top:calc(var(--ww-spacing)*1)}.ww\\:pt-1\\.5{padding-top:calc(var(--ww-spacing)*1.5)}.ww\\:pt-2{padding-top:calc(var(--ww-spacing)*2)}.ww\\:pt-2\\.5{padding-top:calc(var(--ww-spacing)*2.5)}.ww\\:pt-3{padding-top:calc(var(--ww-spacing)*3)}.ww\\:pr-1{padding-right:calc(var(--ww-spacing)*1)}.ww\\:pr-1\\.5{padding-right:calc(var(--ww-spacing)*1.5)}.ww\\:pr-2{padding-right:calc(var(--ww-spacing)*2)}.ww\\:pr-3{padding-right:calc(var(--ww-spacing)*3)}.ww\\:pr-9{padding-right:calc(var(--ww-spacing)*9)}.ww\\:pb-0{padding-bottom:calc(var(--ww-spacing)*0)}.ww\\:pb-1{padding-bottom:calc(var(--ww-spacing)*1)}.ww\\:pb-1\\.5{padding-bottom:calc(var(--ww-spacing)*1.5)}.ww\\:pb-2{padding-bottom:calc(var(--ww-spacing)*2)}.ww\\:pb-2\\.5{padding-bottom:calc(var(--ww-spacing)*2.5)}.ww\\:pb-3{padding-bottom:calc(var(--ww-spacing)*3)}.ww\\:pl-1{padding-left:calc(var(--ww-spacing)*1)}.ww\\:pl-3{padding-left:calc(var(--ww-spacing)*3)}.ww\\:pl-3\\.5{padding-left:calc(var(--ww-spacing)*3.5)}.ww\\:pl-4{padding-left:calc(var(--ww-spacing)*4)}.ww\\:pl-5{padding-left:calc(var(--ww-spacing)*5)}.ww\\:text-center{text-align:center}.ww\\:text-left{text-align:left}.ww\\:font-\\[family-name\\:var\\(--ww-font\\)\\]{font-family:var(--ww-font)}.ww\\:font-\\[family-name\\:var\\(--ww-font-sans\\)\\]{font-family:var(--ww-font-sans)}.ww\\:font-mono{font-family:var(--ww-font-mono)}.ww\\:text-base{font-size:var(--ww-text-base);line-height:var(--tw-leading,var(--ww-text-base--line-height))}.ww\\:text-lg{font-size:var(--ww-text-lg);line-height:var(--tw-leading,var(--ww-text-lg--line-height))}.ww\\:text-sm{font-size:var(--ww-text-sm);line-height:var(--tw-leading,var(--ww-text-sm--line-height))}.ww\\:text-xs{font-size:var(--ww-text-xs);line-height:var(--tw-leading,var(--ww-text-xs--line-height))}.ww\\:\\[font-size\\:var\\(--ww-font-size\\,1rem\\)\\]{font-size:var(--ww-font-size,1rem)}.ww\\:text-\\[10px\\]{font-size:10px}.ww\\:text-\\[11px\\]{font-size:11px}.ww\\:\\[line-height\\:var\\(--ww-line-height\\,1\\.5\\)\\]{line-height:var(--ww-line-height,1.5)}.ww\\:font-medium{--tw-font-weight:var(--ww-font-weight-medium);font-weight:var(--ww-font-weight-medium)}.ww\\:font-semibold{--tw-font-weight:var(--ww-font-weight-semibold);font-weight:var(--ww-font-weight-semibold)}.ww\\:tracking-wide{--tw-tracking:var(--ww-tracking-wide);letter-spacing:var(--ww-tracking-wide)}.ww\\:tracking-wider{--tw-tracking:var(--ww-tracking-wider);letter-spacing:var(--ww-tracking-wider)}.ww\\:break-words{overflow-wrap:break-word}.ww\\:break-all{word-break:break-all}.ww\\:text-ellipsis{text-overflow:ellipsis}.ww\\:whitespace-nowrap{white-space:nowrap}.ww\\:whitespace-pre-wrap{white-space:pre-wrap}.ww\\:text-background{color:var(--ww-color-background,#fff)}.ww\\:text-foreground,.ww\\:text-foreground\\/80{color:var(--ww-color-foreground,#1f2937)}@supports (color:color-mix(in lab, red, red)){.ww\\:text-foreground\\/80{color:color-mix(in oklab,var(--ww-color-foreground,#1f2937)80%,transparent)}}.ww\\:text-muted-foreground{color:var(--ww-color-muted-foreground,#6b7280)}.ww\\:text-primary{color:var(--ww-color-primary,#6366f1)}.ww\\:text-primary-foreground{color:var(--ww-color-primary-foreground,#1f2937)}.ww\\:uppercase{text-transform:uppercase}.ww\\:italic{font-style:italic}.ww\\:underline{text-decoration-line:underline}.ww\\:underline-offset-2{text-underline-offset:2px}.ww\\:opacity-0{opacity:0}.ww\\:opacity-60{opacity:.6}.ww\\:opacity-70{opacity:.7}.ww\\:opacity-100{opacity:1}.ww\\:shadow{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a),0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.ww\\:shadow-2xl{--tw-shadow:0 25px 50px -12px var(--tw-shadow-color,#00000040);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.ww\\:shadow-lg{--tw-shadow:0 10px 15px -3px var(--tw-shadow-color,#0000001a),0 4px 6px -4px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.ww\\:ring-2{--tw-ring-shadow:var(--tw-ring-inset,)0 0 0 calc(2px + var(--tw-ring-offset-width))var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.ww\\:ring-\\[\\#0a6c74\\]{--tw-ring-color:#0a6c74}.ww\\:backdrop-blur-md{--tw-backdrop-blur:blur(var(--ww-blur-md));-webkit-backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,)}.ww\\:backdrop-blur-xl{--tw-backdrop-blur:blur(var(--ww-blur-xl));-webkit-backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,)}.ww\\:backdrop-saturate-150{--tw-backdrop-saturate:saturate(150%);-webkit-backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,)}.ww\\:transition-\\[grid-template-rows\\,opacity\\]{transition-property:grid-template-rows,opacity;transition-timing-function:var(--tw-ease,var(--ww-default-transition-timing-function));transition-duration:var(--tw-duration,var(--ww-default-transition-duration))}.ww\\:transition-\\[max-width\\]{transition-property:max-width;transition-timing-function:var(--tw-ease,var(--ww-default-transition-timing-function));transition-duration:var(--tw-duration,var(--ww-default-transition-duration))}.ww\\:transition-\\[width\\]{transition-property:width;transition-timing-function:var(--tw-ease,var(--ww-default-transition-timing-function));transition-duration:var(--tw-duration,var(--ww-default-transition-duration))}.ww\\:transition-all{transition-property:all;transition-timing-function:var(--tw-ease,var(--ww-default-transition-timing-function));transition-duration:var(--tw-duration,var(--ww-default-transition-duration))}.ww\\:transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease,var(--ww-default-transition-timing-function));transition-duration:var(--tw-duration,var(--ww-default-transition-duration))}.ww\\:transition-opacity{transition-property:opacity;transition-timing-function:var(--tw-ease,var(--ww-default-transition-timing-function));transition-duration:var(--tw-duration,var(--ww-default-transition-duration))}.ww\\:transition-transform{transition-property:transform,translate,scale,rotate;transition-timing-function:var(--tw-ease,var(--ww-default-transition-timing-function));transition-duration:var(--tw-duration,var(--ww-default-transition-duration))}.ww\\:duration-150{--tw-duration:.15s;transition-duration:.15s}.ww\\:duration-200{--tw-duration:.2s;transition-duration:.2s}.ww\\:duration-300{--tw-duration:.3s;transition-duration:.3s}.ww\\:ease-out{--tw-ease:var(--ww-ease-out);transition-timing-function:var(--ww-ease-out)}.ww\\:outline-none{--tw-outline-style:none;outline-style:none}@media (hover:hover){.ww\\:group-hover\\:opacity-0:is(:where(.ww\\:group):hover *){opacity:0}.ww\\:group-hover\\:opacity-100:is(:where(.ww\\:group):hover *){opacity:1}}.ww\\:group-\\[\\.is-assistant\\]\\:text-foreground:is(:where(.ww\\:group).is-assistant *){color:var(--ww-color-foreground,#1f2937)}.ww\\:group-\\[\\.is-user\\]\\:ml-auto:is(:where(.ww\\:group).is-user *){margin-left:auto}.ww\\:group-\\[\\.is-user\\]\\:\\[border-radius\\:var\\(--ww-msg-radius\\,8px\\)\\]:is(:where(.ww\\:group).is-user *){border-radius:var(--ww-msg-radius,8px)}.ww\\:group-\\[\\.is-user\\]\\:bg-user-bubble:is(:where(.ww\\:group).is-user *){background-color:var(--ww-color-user-bubble,#f4f4f4)}.ww\\:group-\\[\\.is-user\\]\\:\\[padding\\:var\\(--ww-msg-pad-y\\,12px\\)_var\\(--ww-msg-pad-x\\,16px\\)\\]:is(:where(.ww\\:group).is-user *){padding:var(--ww-msg-pad-y,12px)var(--ww-msg-pad-x,16px)}.ww\\:group-\\[\\.is-user\\]\\:\\[color\\:var\\(--ww-color-user-bubble-text\\)\\]:is(:where(.ww\\:group).is-user *){color:var(--ww-color-user-bubble-text)}.ww\\:placeholder\\:overflow-hidden::placeholder{overflow:hidden}.ww\\:placeholder\\:text-ellipsis::placeholder{text-overflow:ellipsis}.ww\\:placeholder\\:text-muted-foreground::placeholder{color:var(--ww-color-muted-foreground,#6b7280)}@media (hover:hover){.ww\\:hover\\:border-primary\\/30:hover{border-color:var(--ww-color-primary,#6366f1)}@supports (color:color-mix(in lab, red, red)){.ww\\:hover\\:border-primary\\/30:hover{border-color:color-mix(in oklab,var(--ww-color-primary,#6366f1)30%,transparent)}}.ww\\:hover\\:bg-accent:hover{background-color:var(--ww-color-accent,#f3f4f6)}.ww\\:hover\\:bg-border:hover{background-color:var(--ww-color-border,#e5e7eb)}.ww\\:hover\\:bg-foreground:hover{background-color:var(--ww-color-foreground,#1f2937)}.ww\\:hover\\:bg-muted:hover{background-color:var(--ww-color-muted,#f1f5f9)}.ww\\:hover\\:bg-muted-foreground\\/10:hover{background-color:var(--ww-color-muted-foreground,#6b7280)}@supports (color:color-mix(in lab, red, red)){.ww\\:hover\\:bg-muted-foreground\\/10:hover{background-color:color-mix(in oklab,var(--ww-color-muted-foreground,#6b7280)10%,transparent)}}.ww\\:hover\\:bg-primary\\/90:hover{background-color:var(--ww-color-primary,#6366f1)}@supports (color:color-mix(in lab, red, red)){.ww\\:hover\\:bg-primary\\/90:hover{background-color:color-mix(in oklab,var(--ww-color-primary,#6366f1)90%,transparent)}}.ww\\:hover\\:text-accent-foreground:hover{color:var(--ww-color-accent-foreground,#1f2937)}.ww\\:hover\\:text-foreground:hover{color:var(--ww-color-foreground,#1f2937)}.ww\\:hover\\:underline:hover{text-decoration-line:underline}}.ww\\:disabled\\:pointer-events-none:disabled{pointer-events:none}.ww\\:disabled\\:opacity-40:disabled{opacity:.4}.ww\\:disabled\\:opacity-50:disabled{opacity:.5}@media (min-width:40rem){.ww\\:sm\\:inset-auto{inset:auto}.ww\\:sm\\:right-0{right:calc(var(--ww-spacing)*0)}.ww\\:sm\\:bottom-4{bottom:calc(var(--ww-spacing)*4)}.ww\\:sm\\:left-0{left:calc(var(--ww-spacing)*0)}.ww\\:sm\\:mx-auto{margin-inline:auto}.ww\\:sm\\:h-\\[720px\\]{height:720px}.ww\\:sm\\:max-h-\\[calc\\(100dvh-2rem\\)\\]{max-height:calc(100dvh - 2rem)}.ww\\:sm\\:w-\\[calc\\(100vw-2rem\\)\\]{width:calc(100vw - 2rem)}.ww\\:sm\\:max-w-\\[1000px\\]{max-width:1000px}.ww\\:sm\\:rounded-2xl{border-radius:var(--ww-radius-2xl)}.ww\\:sm\\:border{border-style:var(--tw-border-style);border-width:1px}.ww\\:sm\\:border-border{border-color:var(--ww-color-border,#e5e7eb)}.ww\\:sm\\:py-2{padding-block:calc(var(--ww-spacing)*2)}.ww\\:sm\\:py-3{padding-block:calc(var(--ww-spacing)*3)}.ww\\:sm\\:pr-2{padding-right:calc(var(--ww-spacing)*2)}.ww\\:sm\\:pr-2\\.5{padding-right:calc(var(--ww-spacing)*2.5)}.ww\\:sm\\:pl-4{padding-left:calc(var(--ww-spacing)*4)}.ww\\:sm\\:pl-6{padding-left:calc(var(--ww-spacing)*6)}.ww\\:sm\\:text-sm{font-size:var(--ww-text-sm);line-height:var(--tw-leading,var(--ww-text-sm--line-height))}.ww\\:sm\\:text-\\[11px\\]{font-size:11px}}.ww\\:\\[\\&\\>\\*\\:first-child\\]\\:mt-0>:first-child{margin-top:calc(var(--ww-spacing)*0)}.ww\\:\\[\\&\\>\\*\\:last-child\\]\\:mb-0>:last-child{margin-bottom:calc(var(--ww-spacing)*0)}}@keyframes ww-fade-in{0%{opacity:0;transform:translateY(-4px)}to{opacity:1;transform:translateY(0)}}@keyframes ww-fade-out{0%{opacity:1;transform:translateY(0)}to{opacity:0;transform:translateY(-4px)}}@keyframes ww-pulse{0%,80%,to{opacity:.3;transform:scale(.8)}40%{opacity:1;transform:scale(1)}}@keyframes ww-shimmer{0%{background-position:200% 0}to{background-position:-200% 0}}@media (prefers-reduced-motion:reduce){[data-waniwani-chat] [data-waniwani-shimmer]{color:var(--ww-color-muted-foreground)!important;animation:none!important}}[data-waniwani-floating=dock]{transition:opacity .32s,transform .42s cubic-bezier(.22,1,.36,1),max-width .3s,visibility 0s linear .42s}[data-waniwani-floating=dock][data-appeared=true][data-state=shown]{visibility:visible;opacity:1;pointer-events:auto;transition:opacity .32s,transform .42s cubic-bezier(.22,1,.36,1),max-width .3s,visibility;transform:translateY(0)}[data-waniwani-floating=dock][data-appeared=false],[data-waniwani-floating=dock][data-state=hidden]{opacity:0;visibility:hidden;pointer-events:none;transform:translateY(1rem)}[data-waniwani-floating=panel]{transition:clip-path .44s cubic-bezier(.22,1,.36,1),opacity .26s,visibility 0s linear .44s}[data-waniwani-floating=panel][data-state=shown]{visibility:visible;opacity:1;pointer-events:auto;clip-path:inset(-40px round 18px);transition:clip-path .44s cubic-bezier(.22,1,.36,1),opacity .26s,visibility}[data-waniwani-floating=panel][data-state=hidden]{opacity:0;visibility:hidden;pointer-events:none;clip-path:inset(calc(100% - 60px) 12% 0 round 24px)}@media (max-width:639px){[data-waniwani-floating=panel][data-state=shown]{clip-path:inset(0)}[data-waniwani-floating=panel][data-state=hidden]{clip-path:inset(calc(100% - 72px) 6% 0 round 22px)}}@media (prefers-reduced-motion:reduce){[data-waniwani-floating=dock],[data-waniwani-floating=panel]{clip-path:none;transition:visibility 0s linear 10ms}[data-waniwani-floating=dock][data-appeared=true][data-state=shown],[data-waniwani-floating=panel][data-state=shown]{transition:visibility}}[data-waniwani-chat] ::-webkit-scrollbar{width:8px}[data-waniwani-chat] ::-webkit-scrollbar-track{background:0 0}[data-waniwani-chat] ::-webkit-scrollbar-thumb{background:var(--ww-color-border);border-radius:9999px}[data-waniwani-chat] ::-webkit-scrollbar-thumb:hover{background:var(--ww-color-muted-foreground)}[data-waniwani-chat] *{scrollbar-width:thin;scrollbar-color:var(--ww-color-border)transparent}[data-waniwani-chat]{--ww-color-background:var(--ww-bg,#fff);--ww-color-foreground:var(--ww-text,#1f2937);--ww-color-primary:var(--ww-primary,#6366f1);--ww-color-primary-foreground:var(--ww-primary-fg,#1f2937);--ww-color-muted-foreground:var(--ww-muted,#6b7280);--ww-color-border:var(--ww-border,#e5e7eb);--ww-color-input:var(--ww-input-bg,#f9fafb);--ww-color-accent:var(--ww-assistant-bubble,#f3f4f6);--ww-color-accent-foreground:var(--ww-text,#1f2937);--ww-color-user-bubble:var(--ww-user-bubble,#f4f4f4);--ww-color-card:var(--ww-bg,#fff);--ww-color-card-foreground:var(--ww-text,#1f2937);--ww-color-card-header:var(--ww-header-bg,#fff);--ww-color-card-header-foreground:var(--ww-header-text,#1f2937);--ww-color-status:var(--ww-status,#22c55e);--ww-color-tool-card:var(--ww-tool-card,#f4f4f5);--ww-radius:var(--ww-radius,16px);--ww-font-sans:var(--ww-font,system-ui,-apple-system,\"Segoe UI\",sans-serif);--ww-color-user-bubble-text:var(--ww-user-bubble-text,var(--ww-color-primary-foreground));--ww-color-assistant-bubble-text:var(--ww-assistant-bubble-text,var(--ww-color-foreground));--ww-glass:var(--ww-glass-tint,transparent)}@supports (color:color-mix(in lab, red, red)){[data-waniwani-chat]{--ww-glass:color-mix(in srgb,var(--ww-glass-tint,transparent)calc(var(--ww-glass-tint-opacity,0)*100%),#eceef499)}}[data-waniwani-chat]{--ww-glass-border:#0000000f;border-style:solid;border-width:var(--ww-border-width,0);border-color:var(--ww-color-border);box-shadow:var(--ww-shadow,none)}[data-waniwani-chat][data-assistant-bubble=true] .ww-message-assistant .ww-bubble{background:var(--ww-color-accent);color:var(--ww-color-assistant-bubble-text);border-radius:var(--ww-msg-radius,8px);padding:var(--ww-msg-pad-y,12px)var(--ww-msg-pad-x,16px);width:fit-content;max-width:var(--ww-msg-max-width,80%)}.dark [data-waniwani-chat],[data-waniwani-chat].dark{--ww-color-background:var(--ww-bg,#212121);--ww-color-foreground:var(--ww-text,#ececec);--ww-color-primary:var(--ww-primary,#6366f1);--ww-color-primary-foreground:var(--ww-primary-fg,#fff);--ww-color-muted-foreground:var(--ww-muted,#8e8ea0);--ww-color-border:var(--ww-border,#444);--ww-color-input:var(--ww-input-bg,#2f2f2f);--ww-color-accent:var(--ww-assistant-bubble,#2f2f2f);--ww-color-accent-foreground:var(--ww-text,#ececec);--ww-color-user-bubble:var(--ww-user-bubble,#303030);--ww-color-card:var(--ww-bg,#212121);--ww-color-card-foreground:var(--ww-text,#ececec);--ww-color-card-header:var(--ww-header-bg,#1e1e1e);--ww-color-card-header-foreground:var(--ww-header-text,#ececec);--ww-color-status:var(--ww-status,#22c55e);--ww-color-tool-card:var(--ww-tool-card,#262626);--ww-color-user-bubble-text:var(--ww-user-bubble-text,#fff);--ww-color-assistant-bubble-text:var(--ww-assistant-bubble-text,var(--ww-color-foreground));--ww-glass:var(--ww-glass-tint,transparent)}@supports (color:color-mix(in lab, red, red)){.dark [data-waniwani-chat],[data-waniwani-chat].dark{--ww-glass:color-mix(in srgb,var(--ww-glass-tint,transparent)calc(var(--ww-glass-tint-opacity,0)*100%),#282a3480)}}.dark [data-waniwani-chat],[data-waniwani-chat].dark{--ww-glass-border:#ffffff1f}@media (prefers-color-scheme:dark){[data-waniwani-chat][data-color-scheme=auto]{--ww-color-background:var(--ww-bg,#212121);--ww-color-foreground:var(--ww-text,#ececec);--ww-color-primary:var(--ww-primary,#6366f1);--ww-color-primary-foreground:var(--ww-primary-fg,#fff);--ww-color-muted-foreground:var(--ww-muted,#8e8ea0);--ww-color-border:var(--ww-border,#444);--ww-color-input:var(--ww-input-bg,#2f2f2f);--ww-color-accent:var(--ww-assistant-bubble,#2f2f2f);--ww-color-accent-foreground:var(--ww-text,#ececec);--ww-color-user-bubble:var(--ww-user-bubble,#303030);--ww-color-card:var(--ww-bg,#212121);--ww-color-card-foreground:var(--ww-text,#ececec);--ww-color-card-header:var(--ww-header-bg,#1e1e1e);--ww-color-card-header-foreground:var(--ww-header-text,#ececec);--ww-color-status:var(--ww-status,#22c55e);--ww-color-tool-card:var(--ww-tool-card,#262626);--ww-color-user-bubble-text:var(--ww-user-bubble-text,#fff);--ww-color-assistant-bubble-text:var(--ww-assistant-bubble-text,var(--ww-color-foreground));--ww-glass:var(--ww-glass-tint,transparent)}@supports (color:color-mix(in lab, red, red)){[data-waniwani-chat][data-color-scheme=auto]{--ww-glass:color-mix(in srgb,var(--ww-glass-tint,transparent)calc(var(--ww-glass-tint-opacity,0)*100%),#282a3480)}}[data-waniwani-chat][data-color-scheme=auto]{--ww-glass-border:#ffffff1f}}[data-waniwani-chat] [data-streamdown=table-wrapper]{flex-direction:column;gap:.5rem;margin-top:1rem;margin-bottom:1rem;display:flex}[data-waniwani-chat] [data-streamdown=table-wrapper]>div:first-child:has(button){justify-content:flex-end;align-items:center;gap:.25rem;display:flex}[data-waniwani-chat] [data-streamdown=table-wrapper]>div:last-child{overflow-x:auto}[data-waniwani-chat] [data-streamdown=table]{border-collapse:collapse;border:1px solid var(--ww-color-border);border-radius:.75rem;width:100%;overflow:hidden}[data-waniwani-chat] [data-streamdown=table-header]{background-color:var(--ww-color-accent)}@supports (color:color-mix(in lab, red, red)){[data-waniwani-chat] [data-streamdown=table-header]{background-color:color-mix(in srgb,var(--ww-color-accent)80%,transparent)}}[data-waniwani-chat] [data-streamdown=table-body]{background-color:var(--ww-color-accent)}@supports (color:color-mix(in lab, red, red)){[data-waniwani-chat] [data-streamdown=table-body]{background-color:color-mix(in srgb,var(--ww-color-accent)40%,transparent)}}[data-waniwani-chat] [data-streamdown=table-body]>tr+tr{border-top:1px solid var(--ww-color-border)}[data-waniwani-chat] [data-streamdown=table-row]{border-bottom:1px solid var(--ww-color-border)}[data-waniwani-chat] [data-streamdown=table-header-cell]{white-space:nowrap;text-align:left;padding:.5rem 1rem;font-size:.875rem;font-weight:600}[data-waniwani-chat] [data-streamdown=table-cell]{padding:.5rem 1rem;font-size:.875rem}[data-waniwani-chat] [data-streamdown=link]{color:var(--ww-color-primary);overflow-wrap:anywhere;cursor:pointer;font-weight:500;text-decoration:underline}[data-waniwani-chat].dark [data-streamdown=link],.dark [data-waniwani-chat] [data-streamdown=link]{color:var(--ww-color-primary)}@supports (color:color-mix(in lab, red, red)){[data-waniwani-chat].dark [data-streamdown=link],.dark [data-waniwani-chat] [data-streamdown=link]{color:color-mix(in oklab,var(--ww-color-primary)55%,white)}}@media (prefers-color-scheme:dark){[data-waniwani-chat][data-color-scheme=auto] [data-streamdown=link]{color:var(--ww-color-primary)}@supports (color:color-mix(in lab, red, red)){[data-waniwani-chat][data-color-scheme=auto] [data-streamdown=link]{color:color-mix(in oklab,var(--ww-color-primary)55%,white)}}}[data-waniwani-chat].dark [data-waniwani-logo],.dark [data-waniwani-chat] [data-waniwani-logo]{filter:invert()}@media (prefers-color-scheme:dark){[data-waniwani-chat][data-color-scheme=auto] [data-waniwani-logo]{filter:invert()}}[data-waniwani-chat] [data-streamdown=link-safety-modal]{z-index:50;background-color:var(--ww-color-background);justify-content:center;align-items:center;display:flex;position:fixed;inset:0}@supports (color:color-mix(in lab, red, red)){[data-waniwani-chat] [data-streamdown=link-safety-modal]{background-color:color-mix(in srgb,var(--ww-color-background)50%,transparent)}}[data-waniwani-chat] [data-streamdown=link-safety-modal]{-webkit-backdrop-filter:blur(4px);backdrop-filter:blur(4px)}[data-waniwani-chat] [data-streamdown=link-safety-modal]>div{border:1px solid var(--ww-color-border);background-color:var(--ww-color-background);width:100%;max-width:28rem;color:var(--ww-color-foreground);border-radius:.75rem;flex-direction:column;gap:1rem;margin:0 1rem;padding:1.5rem;display:flex;position:relative;box-shadow:0 10px 25px #0000001a}[data-waniwani-chat] [data-streamdown=link-safety-modal] button{cursor:pointer}[data-waniwani-chat] [data-streamdown=link-safety-modal]>div>button:first-child{color:var(--ww-color-muted-foreground);background:0 0;border:none;border-radius:.375rem;padding:.25rem;transition:background-color .15s,color .15s;position:absolute;top:1rem;right:1rem}[data-waniwani-chat] [data-streamdown=link-safety-modal]>div>button:first-child:hover{background-color:var(--ww-color-accent);color:var(--ww-color-foreground)}[data-waniwani-chat] [data-streamdown=link-safety-modal]>div>div:first-of-type{flex-direction:column;gap:.5rem;display:flex}[data-waniwani-chat] [data-streamdown=link-safety-modal]>div>div:first-of-type>div{align-items:center;gap:.5rem;font-size:1.125rem;font-weight:600;display:flex}[data-waniwani-chat] [data-streamdown=link-safety-modal]>div>div:first-of-type>p{color:var(--ww-color-muted-foreground);font-size:.875rem}[data-waniwani-chat] [data-streamdown=link-safety-modal]>div>div:nth-child(3){word-break:break-all;background-color:var(--ww-color-accent);border-radius:.375rem;max-height:8rem;padding:.75rem;font-family:ui-monospace,monospace;font-size:.875rem;overflow-y:auto}[data-waniwani-chat] [data-streamdown=link-safety-modal]>div>div:last-child{gap:.5rem;display:flex}[data-waniwani-chat] [data-streamdown=link-safety-modal]>div>div:last-child>button{border:none;border-radius:.375rem;flex:1;justify-content:center;align-items:center;gap:.5rem;padding:.5rem 1rem;font-size:.875rem;font-weight:500;transition:background-color .15s;display:flex}[data-waniwani-chat] [data-streamdown=link-safety-modal]>div>div:last-child>button:first-child{border:1px solid var(--ww-color-border);background-color:var(--ww-color-background);color:var(--ww-color-foreground)}[data-waniwani-chat] [data-streamdown=link-safety-modal]>div>div:last-child>button:first-child:hover{background-color:var(--ww-color-accent)}[data-waniwani-chat] [data-streamdown=link-safety-modal]>div>div:last-child>button:last-child{background-color:var(--ww-color-primary);color:#fff}[data-waniwani-chat] [data-streamdown=link-safety-modal]>div>div:last-child>button:last-child:hover{opacity:.9}[data-waniwani-chat] [data-streamdown=ordered-list]{white-space:normal;list-style-type:decimal;list-style-position:inside}[data-waniwani-chat] li [data-streamdown=ordered-list]{padding-left:1.5rem}[data-waniwani-chat] [data-streamdown=unordered-list]{white-space:normal;list-style-type:disc;list-style-position:inside}[data-waniwani-chat] li [data-streamdown=unordered-list]{padding-left:1.5rem}[data-waniwani-chat] [data-streamdown=list-item]{padding-top:.25rem;padding-bottom:.25rem}[data-waniwani-chat] [data-streamdown=list-item]>p{display:inline}[data-waniwani-chat] [data-streamdown=inline-code]{background-color:var(--ww-color-accent);border-radius:.25rem;padding:.125rem .375rem;font-family:ui-monospace,SFMono-Regular,SF Mono,Menlo,monospace;font-size:.875rem}[data-waniwani-chat] [data-streamdown=heading-1]{margin-top:1.5rem;margin-bottom:.5rem;font-size:1.875rem;font-weight:600;line-height:2.25rem}[data-waniwani-chat] [data-streamdown=heading-2]{margin-top:1.5rem;margin-bottom:.5rem;font-size:1.5rem;font-weight:600;line-height:2rem}[data-waniwani-chat] [data-streamdown=heading-3]{margin-top:1.5rem;margin-bottom:.5rem;font-size:1.25rem;font-weight:600;line-height:1.75rem}[data-waniwani-chat] [data-streamdown=heading-4]{margin-top:1.5rem;margin-bottom:.5rem;font-size:1.125rem;font-weight:600;line-height:1.75rem}[data-waniwani-chat] [data-streamdown=heading-5]{margin-top:1.5rem;margin-bottom:.5rem;font-size:1rem;font-weight:600;line-height:1.5rem}[data-waniwani-chat] [data-streamdown=heading-6]{margin-top:1.5rem;margin-bottom:.5rem;font-size:.875rem;font-weight:600;line-height:1.25rem}[data-waniwani-chat] [data-streamdown=blockquote]{border-left:4px solid var(--ww-color-muted-foreground);margin-top:1rem;margin-bottom:1rem}@supports (color:color-mix(in lab, red, red)){[data-waniwani-chat] [data-streamdown=blockquote]{border-left:4px solid color-mix(in srgb,var(--ww-color-muted-foreground)30%,transparent)}}[data-waniwani-chat] [data-streamdown=blockquote]{color:var(--ww-color-muted-foreground);padding-left:1rem;font-style:italic}[data-waniwani-chat] [data-streamdown=horizontal-rule]{border-color:var(--ww-color-border);margin-top:1.5rem;margin-bottom:1.5rem}[data-waniwani-chat] [data-streamdown=strong]{font-weight:600}[data-waniwani-chat] [data-streamdown=image-wrapper]{margin-top:1rem;margin-bottom:1rem;display:inline-block;position:relative}[data-waniwani-chat] [data-streamdown=image]{border-radius:.5rem;max-width:100%}[data-waniwani-chat] [data-streamdown=code-block]{border:1px solid var(--ww-color-border);border-radius:.75rem;width:100%;margin-top:1rem;margin-bottom:1rem;overflow:hidden}[data-waniwani-chat] [data-streamdown=code-block-header]{background-color:var(--ww-color-accent);justify-content:space-between;align-items:center;display:flex}@supports (color:color-mix(in lab, red, red)){[data-waniwani-chat] [data-streamdown=code-block-header]{background-color:color-mix(in srgb,var(--ww-color-accent)80%,transparent)}}[data-waniwani-chat] [data-streamdown=code-block-header]{color:var(--ww-color-muted-foreground);padding:.75rem;font-size:.75rem}[data-waniwani-chat] [data-streamdown=code-block-body]{padding:1rem;font-size:.875rem;overflow-x:auto}[data-waniwani-chat] [data-streamdown=code-block-copy-button],[data-waniwani-chat] [data-streamdown=code-block-download-button]{cursor:pointer;color:var(--ww-color-muted-foreground);background:0 0;border:none;padding:.25rem;transition:color .15s}[data-waniwani-chat] [data-streamdown=code-block-copy-button]:hover,[data-waniwani-chat] [data-streamdown=code-block-download-button]:hover{color:var(--ww-color-foreground)}[data-waniwani-chat] [data-streamdown=mermaid-block]{border:1px solid var(--ww-color-border);border-radius:.75rem;height:auto;margin-top:1rem;margin-bottom:1rem;padding:1rem;position:relative}[data-waniwani-chat] [data-streamdown=mermaid]{width:100%;height:100%}@property --tw-translate-x{syntax:\"*\";inherits:false;initial-value:0}@property --tw-translate-y{syntax:\"*\";inherits:false;initial-value:0}@property --tw-translate-z{syntax:\"*\";inherits:false;initial-value:0}@property --tw-space-y-reverse{syntax:\"*\";inherits:false;initial-value:0}@property --tw-border-style{syntax:\"*\";inherits:false;initial-value:solid}@property --tw-font-weight{syntax:\"*\";inherits:false}@property --tw-tracking{syntax:\"*\";inherits:false}@property --tw-shadow{syntax:\"*\";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:\"*\";inherits:false}@property --tw-shadow-alpha{syntax:\"<percentage>\";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:\"*\";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:\"*\";inherits:false}@property --tw-inset-shadow-alpha{syntax:\"<percentage>\";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:\"*\";inherits:false}@property --tw-ring-shadow{syntax:\"*\";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:\"*\";inherits:false}@property --tw-inset-ring-shadow{syntax:\"*\";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:\"*\";inherits:false}@property --tw-ring-offset-width{syntax:\"<length>\";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:\"*\";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:\"*\";inherits:false;initial-value:0 0 #0000}@property --tw-backdrop-blur{syntax:\"*\";inherits:false}@property --tw-backdrop-brightness{syntax:\"*\";inherits:false}@property --tw-backdrop-contrast{syntax:\"*\";inherits:false}@property --tw-backdrop-grayscale{syntax:\"*\";inherits:false}@property --tw-backdrop-hue-rotate{syntax:\"*\";inherits:false}@property --tw-backdrop-invert{syntax:\"*\";inherits:false}@property --tw-backdrop-opacity{syntax:\"*\";inherits:false}@property --tw-backdrop-saturate{syntax:\"*\";inherits:false}@property --tw-backdrop-sepia{syntax:\"*\";inherits:false}@property --tw-duration{syntax:\"*\";inherits:false}@property --tw-ease{syntax:\"*\";inherits:false}@keyframes spin{to{transform:rotate(360deg)}}@keyframes pulse{50%{opacity:.5}}";function eZ(e){return e.startsWith("__WANIWANI")}function Gh(e){if(!cI||eZ(cI))return;let t=document.createElement("style");t.textContent=cI,e.appendChild(t)}var je=j(Ee(),1);var Xh=j(Ee(),1),tZ=3e3,aZ=120,nZ=24;function jB(e){let[t,a]=(0,Xh.useState)(!1);return(0,Xh.useEffect)(()=>{if(!e||typeof document>"u"){a(!1);return}let n=!1,r=null,o=null,i=null,s=u=>{r=new IntersectionObserver(c=>{let d=c[0];d&&a(!d.isIntersecting&&d.boundingClientRect.bottom<=0)},{rootMargin:`0px 0px -${nZ}px 0px`,threshold:0}),r.observe(u)},l=()=>{if(n)return;let u=null;try{u=document.querySelector(e)}catch{a(!0);return}if(u){s(u);return}o=setTimeout(l,aZ)};return l(),i=setTimeout(()=>{n||r||(o&&clearTimeout(o),a(!0))},tZ),()=>{n=!0,r?.disconnect(),o&&clearTimeout(o),i&&clearTimeout(i)}},[e]),t}var Mt=j(me(),1),rZ=2e3,oZ=90,iZ=1e3,VB=(0,je.forwardRef)(function(t,a){return(0,Mt.jsx)(es,{locale:t.config.locale,children:(0,Mt.jsx)(sZ,{...t,ref:a})})}),sZ=(0,je.forwardRef)(function({config:t,programmatic:a,scriptConfig:n},r){let{t:o}=Ue(),{config:i,ready:s}=yu(t,a,n),l=hu(i.visibility,s),u=Jd(),c=l?DB(i.visibility,u):null,d=jB(c),p=(0,je.useRef)(null),m=(0,je.useMemo)(()=>su({mode:"floating",getSessionId:()=>p.current?.sessionId}),[]),h=i.onEvent;(0,je.useEffect)(()=>{if(h)return m.subscribe(h)},[h,m]);let v=(0,je.useRef)(null),I=(0,je.useRef)(null),y=(0,je.useRef)(!1),[w,g]=(0,je.useState)("input"),[S,E]=(0,je.useState)(""),[T,R]=(0,je.useState)(!1),[O,U]=(0,je.useState)(!1),[A,Q]=(0,je.useState)(0),$=i.appearance?.theme,H=i.appearance?.variables,Z=(0,je.useMemo)(()=>H?pu(H):{},[H]),X=gu(i),B=(0,je.useMemo)(()=>Ss({flow:null,followup:null,...X}),[X]),P=(0,je.useMemo)(()=>B?.suggestions.map(ie=>ie.text)??[],[B]);Fl({widgetEvents:m,api:i.api,token:i.token,channelId:i.channelId,source:i.source,mode:"floating",pagePrompts:X.page,getSessionId:()=>p.current?.sessionId});let J=(0,je.useRef)(null);(0,je.useEffect)(()=>{!O||!B||J.current!==B&&(J.current=B,m.emit({name:"suggestions.shown",properties:{texts:P,origin:B.origin}}))},[O,B,P,m]);let ge=i.launcherText??i.placeholder??o.launcher.prompt,C=Hl(ge,S.length===0),ze="var(--ww-shadow, 0 10px 30px rgba(0, 0, 0, 0.08))";(0,je.useEffect)(()=>{if(!l){R(!1);return}if(c){R(d);return}let ie=i.appearDelay??rZ,xe=setTimeout(()=>R(!0),Math.max(0,ie));return()=>clearTimeout(xe)},[l,i.appearDelay,c,d]),(0,je.useEffect)(()=>{if(!T||P.length===0)return;let ie=setTimeout(()=>{y.current||g(xe=>xe==="input"?"expanded":xe)},iZ);return()=>clearTimeout(ie)},[T,P.length]),(0,je.useEffect)(()=>{A>0&&w==="open"&&p.current?.focus()},[A,w]);let ot=(0,je.useRef)(!1);(0,je.useEffect)(()=>{s&&!ot.current&&(ot.current=!0,m.emit({name:"chat.ready"}))},[s,m]),ru({api:i.api,token:i.token,channelId:i.channelId,mode:"floating",paintMark:"launcherPainted",painted:s&&l});let x=(0,je.useRef)(!1);(0,je.useEffect)(()=>{let ie=l&&w==="open";ie!==x.current&&(x.current=ie,m.emit({name:ie?"chat.opened":"chat.closed"}))},[l,w,m]);let te=(0,je.useCallback)(()=>{g("open")},[]),re=(0,je.useCallback)(()=>{y.current=!0,g("input")},[]);(0,je.useEffect)(()=>{if(w!=="expanded"){U(!1);return}let ie=setTimeout(()=>U(!0),oZ);return()=>clearTimeout(ie)},[w]);let ke=(0,je.useCallback)(ie=>{te();let xe=ie.trim();xe&&p.current?.sendMessage(xe)},[te]);(0,je.useImperativeHandle)(r,()=>({open:()=>te(),close:()=>re(),toggle:()=>{g(ie=>ie==="open"?"input":"open")},sendMessage:ie=>ke(ie),sendMessageAndWait:async ie=>{te();let xe=p.current;if(xe)return await xe.sendMessageAndWait(ie)},reset:()=>p.current?.reset(),focus:()=>{te(),Q(ie=>ie+1)},getMessages:()=>p.current?.messages??[],getSessionId:()=>p.current?.sessionId}),[ke,te,re]);let We=(0,je.useCallback)(()=>{S.trim()&&(ke(S),E(""))},[S,ke]),be=(0,je.useCallback)(()=>{(p.current?.messages.length??0)>0?(g("open"),Q(ie=>ie+1)):(y.current=!1,g(ie=>ie==="input"?"expanded":ie))},[]),Oe={mode:"floating"},we=zl(i.sessionApi);i.mcpServerUrl&&(Oe.mcpServerUrl=i.mcpServerUrl),i.channelId&&(Oe.channelId=i.channelId);let ce=P.length>0&&w!=="input",Le=(0,Mt.jsx)("button",{type:"button",onClick:re,"aria-label":o.launcher.close,className:"ww:flex ww:size-7 ww:items-center ww:justify-center ww:rounded-md ww:text-muted-foreground ww:transition-colors hover:ww:bg-accent hover:ww:text-foreground ww:cursor-pointer",children:(0,Mt.jsx)(wn,{className:"ww:size-4"})});return(0,Mt.jsx)(lu,{value:m,children:(0,Mt.jsx)("div",{"data-waniwani-chat":"","data-color-scheme":$==="auto"?"auto":void 0,className:V("ww:contents ww:font-[family-name:var(--ww-font-sans)]",$==="dark"&&"dark"),style:Z,children:l&&(0,Mt.jsxs)(Mt.Fragment,{children:[(0,Mt.jsx)("div",{ref:I,"data-waniwani-floating":"dock","data-state":w==="open"?"hidden":"shown","data-appeared":T?"true":"false",className:V("ww:fixed ww:bottom-3 ww:sm:bottom-4 ww:left-0 ww:right-0 ww:mx-auto ww:z-[2147483002] ww:flex ww:flex-col","ww:w-[calc(100vw-2rem)] ww:transition-[max-width] ww:duration-300 ww:ease-out",ce?"ww:max-w-[720px]":"ww:max-w-[440px]"),children:(0,Mt.jsxs)("div",{className:V("ww:relative ww:flex ww:flex-col ww:rounded-[20px] ww:border ww:transition-all ww:duration-300 ww:ease-out",ce?"ww:p-2 ww:backdrop-blur-xl ww:backdrop-saturate-150":"ww:border-transparent ww:p-0"),style:ce?{boxShadow:ze,backgroundColor:"var(--ww-glass)",borderColor:"var(--ww-glass-border)"}:void 0,children:[ce&&w!=="open"&&(0,Mt.jsx)("button",{type:"button",onClick:re,"aria-label":o.launcher.close,className:"ww:absolute ww:right-2 ww:top-2 ww:z-10 ww:flex ww:size-7 ww:items-center ww:justify-center ww:rounded-md ww:text-muted-foreground ww:transition-colors hover:ww:bg-accent hover:ww:text-foreground ww:cursor-pointer",children:(0,Mt.jsx)(wn,{className:"ww:size-4"})}),P.length>0&&(0,Mt.jsx)("div",{className:V("ww:grid ww:transition-all ww:duration-300 ww:ease-out",O?"ww:grid-rows-[1fr] ww:opacity-100":"ww:pointer-events-none ww:grid-rows-[0fr] ww:opacity-0"),children:(0,Mt.jsx)("div",{className:"ww:overflow-hidden",children:(0,Mt.jsx)(Sl,{suggestions:P,onSelect:ie=>{m.emit({name:"suggestion.clicked",properties:{text:ie,index:P.indexOf(ie),origin:B?.origin??"channel"}}),ke(ie)},className:"ww:pl-1 ww:pr-9 ww:pt-1 ww:pb-2.5"})})}),(0,Mt.jsx)(Yp,{animated:T,backgroundColor:"var(--ww-color-input)",borderRadius:16,edgeSensitivity:30,coneSpread:25,colors:["#c084fc","#f472b6","#38bdf8"],className:"ww:border-border",style:{boxShadow:ze},children:(0,Mt.jsxs)("div",{className:"ww:flex ww:items-center ww:gap-1 ww:pl-3.5 ww:pr-1.5 ww:py-1.5 ww:sm:pl-4 ww:sm:pr-2 ww:sm:py-2",children:[(0,Mt.jsx)("input",{ref:v,type:"text",value:S,placeholder:C,onChange:ie=>E(ie.target.value),onFocus:be,onKeyDown:ie=>{ie.key==="Enter"&&!ie.shiftKey&&(ie.preventDefault(),We())},className:"ww:min-w-0 ww:flex-1 ww:bg-transparent ww:py-1 ww:text-base ww:sm:text-sm ww:text-foreground ww:outline-none ww:placeholder:text-muted-foreground"}),(0,Mt.jsx)("button",{type:"button",onClick:We,disabled:!S.trim(),"aria-label":o.promptInput.submit,className:"ww:relative ww:flex ww:size-8 ww:shrink-0 ww:items-center ww:justify-center ww:rounded-full ww:bg-foreground ww:text-background ww:transition-opacity hover:ww:opacity-90 disabled:ww:opacity-40",children:(0,Mt.jsx)(pr,{className:"ww:size-4"})})]})})]})}),(0,Mt.jsx)("div",{role:"dialog","aria-label":i.title??ge,"data-waniwani-floating":"panel","data-state":w==="open"?"shown":"hidden",style:{boxShadow:ze},className:V("ww:fixed ww:z-[2147483002] ww:flex ww:flex-col ww:overflow-hidden ww:bg-background","ww:inset-0 ww:w-full ww:rounded-none","ww:sm:inset-auto ww:sm:bottom-4 ww:sm:left-0 ww:sm:right-0 ww:sm:mx-auto ww:sm:h-[720px] ww:sm:max-h-[calc(100dvh-2rem)] ww:sm:w-[calc(100vw-2rem)] ww:sm:max-w-[1000px] ww:sm:rounded-2xl ww:sm:border ww:sm:border-border"),children:(0,Mt.jsx)(mu,{transport:we,ref:p,api:i.api??"",headers:{Authorization:`Bearer ${i.token}`},skipRemoteConfig:!0,body:Oe,appearance:i.appearance,title:i.title,headerActions:Le,hideHeader:!1,onScreen:w==="open",welcomeMessage:i.welcomeMessage,placeholder:i.placeholder,suggestions:X,enableThreadHistory:i.enableThreadHistory,documentUpload:i.documentUpload,showToolCalls:i.showToolCalls,locale:i.locale,initializing:!s})})]})})})});var rn=j(Ee(),1);var dI=j(me(),1),$B=(0,rn.forwardRef)(function({config:t,programmatic:a,scriptConfig:n,onReady:r,onVisibilityChange:o},i){let{config:s,ready:l}=yu(t,a,n),u=(0,rn.useRef)(null),c=(0,rn.useMemo)(()=>su({mode:"inline",getSessionId:()=>u.current?.sessionId}),[]),d=s.onEvent;(0,rn.useEffect)(()=>{if(d)return c.subscribe(d)},[d,c]);let p=(0,rn.useRef)(!1);(0,rn.useEffect)(()=>{l&&!p.current&&(p.current=!0,c.emit({name:"chat.ready"}))},[l,c]),(0,rn.useEffect)(()=>{r?.()},[]);let m=hu(s.visibility,l);(0,rn.useEffect)(()=>{o?.(m)},[m,o]),ru({api:s.api,token:s.token,channelId:s.channelId,mode:"inline",paintMark:"chatVisible",painted:l}),(0,rn.useImperativeHandle)(i,()=>({get chat(){return u.current}}),[]);let h=gu(s);Fl({widgetEvents:c,api:s.api,token:s.token,channelId:s.channelId,source:s.source,mode:"inline",pagePrompts:h.page,getSessionId:()=>u.current?.sessionId});let v={mode:"inline"},I=zl(s.sessionApi);return s.mcpServerUrl&&(v.mcpServerUrl=s.mcpServerUrl),s.channelId&&(v.channelId=s.channelId),(0,dI.jsx)(lu,{value:c,children:(0,dI.jsx)(mu,{transport:I,ref:u,api:s.api??"",headers:{Authorization:`Bearer ${s.token}`},skipRemoteConfig:!0,body:v,appearance:s.appearance,title:s.title,hideHeader:s.hideHeader,welcomeMessage:s.welcomeMessage,placeholder:s.placeholder,suggestions:h,enableThreadHistory:s.enableThreadHistory,documentUpload:s.documentUpload,showToolCalls:s.showToolCalls,locale:s.locale,initializing:!l})})});var ef=j(Ee(),1),JB=j(qw(),1);function WB(){if(typeof document>"u"&&typeof navigator>"u")return null;let e=(typeof document<"u"?document.modelContext:void 0)??(typeof navigator<"u"?navigator.modelContext:void 0);return e&&typeof e.registerTool=="function"?e:null}function fI(){return WB()!==null}function lZ(){return{url:location.href,title:document.title}}async function pI(e){let{endpoint:t,listEndpoint:a,headers:n,sessionId:r,visitorId:o,channelId:i,onWidget:s}=e,l=e.logger??console,u=WB();if(!u)return null;let c=new AbortController,d=()=>c.abort();window.addEventListener("pagehide",d);let p=!1,m=()=>{p||(p=!0,window.removeEventListener("pagehide",d),c.abort())};function h(){return{sessionId:r,visitorId:o,channelId:i,page:lZ()}}async function v(g,S){let E=await fetch(t,{method:"POST",headers:{"content-type":"application/json",...n},body:JSON.stringify(g),...S?{signal:S}:{}});if(!E.ok)throw new Error(`webmcp ${g.action} failed: ${E.status}`);return await E.json()}async function I(){if(a)try{let g=await fetch(a);if(g.ok)return await g.json();l.info(`[webmcp] list GET answered ${g.status}, using POST`)}catch(g){l.info("[webmcp] list GET failed, using POST",g)}return v({...h(),action:"list"})}let y=[];try{let g=await I();y=Array.isArray(g?.tools)?g.tools:[]}catch(g){return l.error("[webmcp] could not list site tools",g),m(),null}let w=[];return await Promise.all(y.map(async g=>{try{await u.registerTool({name:g.name,description:g.description??"",...g.inputSchema?{inputSchema:g.inputSchema}:{},...g.annotations?{annotations:g.annotations}:{},execute:async(S,E)=>{let T=await v({...h(),action:"call",name:g.name,arguments:S??{}},E?.signal);return T?.widget&&s?.(T.widget),{content:T?.content??[]}}},{signal:c.signal}),w.push(g)}catch(S){l.error(`[webmcp] could not register ${g.name}`,S)}})),l.info(`[webmcp] registered ${w.length} site tool(s)`),{get tools(){return w},callTool:({name:g,arguments:S})=>v({...h(),action:"call",name:g,arguments:S??{}}),dispose:m}}function GB(e,t,a){if(e.webmcp?.enabled===!1||t===!1)return null;let n=e.api??"";if(!e.token)return null;let r=e.mcpServerUrl?{mcpServerUrl:e.mcpServerUrl}:void 0,o=e.channelId??a;return{toolsEndpoint:Na(n,"/webmcp",r),listEndpoint:Na(n,"/webmcp/tools",{token:e.token,...o&&{channel:o},...r}),...o&&{channelId:o},headers:{Authorization:`Bearer ${e.token}`},resourceEndpoint:Na(n,"/resource",{token:e.token,...r})}}var di=j(Ee(),1);var wu=j(me(),1),XB=672,KB=32;function YB({widget:e,onCallTool:t,toolsEndpoint:a,headers:n,resourceEndpoint:r,onClose:o,isDark:i=!1}){let[s,l]=(0,di.useState)(null);(0,di.useEffect)(()=>{let m=()=>l({width:window.innerWidth,height:window.innerHeight});return m(),window.addEventListener("resize",m),()=>window.removeEventListener("resize",m)},[]);let u=e?.preview===!0;(0,di.useEffect)(()=>{if(!e||!u)return;let m=h=>{h.key==="Escape"&&o()};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[e,u,o]),(0,di.useEffect)(()=>{if(!e)return;let m=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=m}},[e]);let c=(0,di.useCallback)(async m=>{if(t)return t(m);if(!a)throw new Error("webmcp overlay needs onCallTool");let h=await fetch(a,{method:"POST",headers:{"content-type":"application/json",...n},body:JSON.stringify({action:"call",...m})});if(!h.ok)throw new Error(`webmcp tool call failed: ${h.status}`);return await h.json()},[t,a,n]);if(!e)return null;let d=s?Math.min(XB,s.width-KB):XB,p=s?s.height-KB:void 0;return(0,wu.jsxs)("div",{role:"dialog","aria-modal":"true","aria-label":"Waniwani",className:V("ww:fixed ww:inset-0 ww:z-[2147483000] ww:flex ww:items-center ww:justify-center ww:bg-black/45 ww:backdrop-blur-md",i&&"dark"),children:[u&&(0,wu.jsx)("button",{type:"button","aria-label":"Close",onClick:o,className:"ww:absolute ww:inset-0 ww:h-full ww:w-full ww:cursor-pointer ww:border-none ww:bg-transparent ww:p-0"}),(0,wu.jsx)("div",{className:"ww:relative ww:overflow-auto ww:rounded-2xl ww:bg-background ww:shadow-2xl",style:{width:d,maxHeight:p},children:(0,wu.jsx)(Mh,{resourceUri:e.viewUri,resourceEndpoint:r,toolInput:e.data,toolResult:e.result,autoHeight:qd(e.result._meta),isDark:i,onCallTool:c,onOpenLink:m=>window.open(m,"_blank","noopener")},`${r}|${e.viewUri}`)})]})}var mI=j(me(),1),ZB="waniwani:webmcp:session";function uZ(){try{let e=sessionStorage.getItem(ZB);if(e)return e;let t=crypto.randomUUID();return sessionStorage.setItem(ZB,t),t}catch{return`s-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}}function cZ(e){let t=e.token?ci(e.api??"",e.token,e.channelId):null,a=GB(e,t?.webmcp?.enabled,t?.channelId);return a||Ua("[webmcp] not publishing site tools: switched off, or no token"),a}function dZ(){try{return window.matchMedia("(prefers-color-scheme: dark)").matches}catch{return!1}}function fZ(){let e=null,t=null;return{emit(a){e?e(a):t=a},subscribe(a){return e=a,t&&(a(t),t=null),()=>{e===a&&(e=null)}}}}function pZ({resourceEndpoint:e,subscribe:t,callTool:a}){let[n,r]=ef.default.useState(null),[o,i]=ef.default.useState(dZ);return ef.default.useEffect(()=>t(r),[t]),ef.default.useEffect(()=>{let s;try{s=window.matchMedia("(prefers-color-scheme: dark)")}catch{return}let l=()=>i(s.matches);return s.addEventListener("change",l),()=>s.removeEventListener("change",l)},[]),(0,mI.jsx)(YB,{widget:n,onCallTool:a,resourceEndpoint:e,isDark:o,onClose:()=>r(null)})}function QB(e){if(!fI())return null;let t=cZ(e);if(!t)return null;let a=document.createElement("div");a.setAttribute("data-waniwani-webmcp",""),a.style.cssText="position:relative;z-index:2147483001;",document.body.appendChild(a);let n=a.attachShadow({mode:"open"});Gh(n);let r=document.createElement("div");n.appendChild(r);let o=fZ(),i=null,s=!1;pI({endpoint:t.toolsEndpoint,listEndpoint:t.listEndpoint,headers:t.headers,channelId:t.channelId,sessionId:uZ(),visitorId:ma(),onWidget:o.emit}).then(c=>{if(s){c?.dispose();return}i=c}).catch(c=>{console.error("[webmcp] could not publish site tools",c)});let l=async c=>{if(!i)throw new Error("webmcp bridge is not registered");let d=await i.callTool(c);return d.widget?.interactive&&o.emit(d.widget),d},u=JB.default.createRoot(r);return u.render((0,mI.jsx)(pZ,{resourceEndpoint:t.resourceEndpoint,subscribe:o.subscribe,callTool:l})),{getTools:()=>(i?.tools??[]).map(c=>c.name),destroy:()=>{s=!0,i?.dispose(),u.unmount(),a.remove()}}}var Pt=null,jn=null,Xt=null,Is=null,Kh=null,mZ="waniwani-chat-sizing",hZ="waniwani-chat-defaults",gZ="waniwani-chat-chrome",yZ="waniwani-chat-auto-card",wZ=`:where([data-waniwani-embed]){height:${AB}}`,vZ=":where([data-waniwani-embed]){border-radius:16px;overflow:hidden}",xZ=":where([data-waniwani-embed]){border-style:solid;border-width:var(--ww-border-width,0);border-color:var(--ww-border,transparent);box-shadow:var(--ww-shadow,none)}",bZ=":where([data-waniwani-embed][data-waniwani-auto]){width:100%;max-width:28rem;margin-inline:auto;border-radius:16px;overflow:hidden;border-style:solid;border-width:var(--ww-border-width,1px);border-color:var(--ww-border,rgba(0,0,0,0.1));box-shadow:var(--ww-shadow,0 10px 30px rgba(0,0,0,0.08))}",SZ="waniwani-chat-composer-auto",IZ=":where([data-waniwani-embed][data-waniwani-auto]){width:100%;max-width:40rem;margin-inline:auto}";function tf(e,t){if(typeof document>"u"||document.getElementById(e))return;let a=document.createElement("style");a.id=e,a.textContent=t,document.head.appendChild(a)}function a3(e,t){let a=t.appearance?.variables;!a||!(e instanceof HTMLElement)||(typeof a.borderWidth=="number"&&e.style.setProperty("--ww-border-width",`${a.borderWidth}px`),a.borderColor&&e.style.setProperty("--ww-border",a.borderColor),a.boxShadow&&e.style.setProperty("--ww-shadow",a.boxShadow))}function Yh(e,t){Gh(e);let a=document.createElement("style");if(a.textContent="[data-waniwani-chat]{border-width:0;box-shadow:none}",e.appendChild(a),t.css)try{let n=new URL(t.css,window.location.href);if(n.protocol==="https:"||n.protocol==="http:"){let r=document.createElement("link");r.rel="stylesheet",r.href=n.href,e.appendChild(r)}else console.warn("[Waniwani] Custom CSS URL must use http or https protocol.")}catch{console.warn("[Waniwani] Invalid custom CSS URL:",t.css)}}var e3="data-waniwani-embed",af="data-waniwani-auto";function n3(e){let t=document.querySelector(`[${e3}]`);if(t)return t;let a=document.createElement("div");a.setAttribute(e3,""),a.setAttribute(af,"");let n=e?!!document.head?.contains(e):!1;return e?.parentNode&&!n?e.parentNode.insertBefore(a,e):document.body.appendChild(a),a}function CZ(e){return/^\d+$/.test(e.trim())?`${e.trim()}px`:e.trim()}function kZ(e,t,a,n){let r=n3(n);tf(mZ,wZ),e.height&&r instanceof HTMLElement&&(r.style.height=CZ(e.height)),e.appearance?.theme&&tf(hZ,vZ),tf(gZ,xZ),r.hasAttribute(af)&&tf(yZ,bZ),a3(r,e),Xt=document.createElement("div"),Xt.id="waniwani-chat-embed",Xt.style.cssText="width:100%;height:100%;max-height:inherit;display:flex;flex-direction:column;flex:1 1 auto;min-height:0;",r.appendChild(Xt);let o=Xt,i=()=>{let d=getComputedStyle(r);if(!d.maxHeight.endsWith("px")){o.style.removeProperty("max-height");return}let p=Number.parseFloat(d.maxHeight);if(!Number.isFinite(p)){o.style.removeProperty("max-height");return}let m=p;d.boxSizing==="border-box"&&(m-=(Number.parseFloat(d.paddingTop)||0)+(Number.parseFloat(d.paddingBottom)||0)+(Number.parseFloat(d.borderTopWidth)||0)+(Number.parseFloat(d.borderBottomWidth)||0)),m>0?o.style.maxHeight=`${m}px`:o.style.removeProperty("max-height")};i(),Kh=new ResizeObserver(i),Kh.observe(r);let s=Xt.attachShadow({mode:"open"});Yh(s,e);let l=document.createElement("div");l.className="ww:contents",s.appendChild(l);let u=Cs.default.createRef(),c=d=>{r instanceof HTMLElement&&(r.style.display=d?"":"none")};if(e.token){let d=ci(e.api??"",e.token,e.channelId);d?.visibility&&!Zd(d.visibility,window.location.pathname)&&c(!1)}return jn=Zh.default.createRoot(l),jn.render(Cs.default.createElement($B,{ref:u,config:e,programmatic:t,scriptConfig:a,onVisibilityChange:c})),{destroy:()=>{Kh?.disconnect(),Kh=null,jn?.unmount(),jn=null,Xt?.remove(),Xt=null,r.hasAttribute(af)&&r.remove(),Pt=null},open:()=>{},close:()=>{},toggle:()=>{},sendMessage:d=>u.current?.chat?.sendMessage(d),sendMessageAndWait:async d=>{let p=u.current?.chat;if(p)return await p.sendMessageAndWait(d)},reset:()=>u.current?.chat?.reset(),focus:()=>u.current?.chat?.focus(),getMessages:()=>u.current?.chat?.messages??[],getSessionId:()=>u.current?.chat?.sessionId}}function TZ(e,t,a){Xt=document.createElement("div"),Xt.id="waniwani-chat-embed",Xt.style.cssText="position:fixed;inset:0;z-index:2147483000;pointer-events:none;",document.body.appendChild(Xt);let n=Xt.attachShadow({mode:"open"});Yh(n,e);let r=document.createElement("div");r.className="ww:contents",n.appendChild(r);let o=Cs.default.createRef();return jn=Zh.default.createRoot(r),jn.render(Cs.default.createElement(VB,{ref:o,config:e,programmatic:t,scriptConfig:a})),{destroy:()=>{jn?.unmount(),jn=null,Xt?.remove(),Xt=null,Pt=null},open:()=>o.current?.open(),close:()=>o.current?.close(),toggle:()=>o.current?.toggle(),sendMessage:i=>o.current?.sendMessage(i),sendMessageAndWait:async i=>{if(o.current)return o.current.sendMessageAndWait(i)},reset:()=>o.current?.reset(),focus:()=>o.current?.focus(),getMessages:()=>o.current?.getMessages()??[],getSessionId:()=>o.current?.getSessionId()}}function LZ(){return{destroy:()=>{Pt=null},open:()=>{},close:()=>{},toggle:()=>{},sendMessage:()=>{},sendMessageAndWait:async()=>{},reset:()=>{},focus:()=>{},getMessages:()=>[],getSessionId:()=>{}}}function EZ(e,t,a,n){let r=n3(n);r.hasAttribute(af)&&tf(SZ,IZ),a3(r,e),Xt=document.createElement("div"),Xt.id="waniwani-chat-embed",Xt.style.cssText="display:block;width:100%;",r.appendChild(Xt);let o=Xt.attachShadow({mode:"open"});Yh(o,e);let i=document.createElement("div");i.className="ww:contents",o.appendChild(i),Is=document.createElement("div"),Is.id="waniwani-chat-panel",Is.style.cssText="position:fixed;inset:0;z-index:2147483000;pointer-events:none;",document.body.appendChild(Is);let s=Is.attachShadow({mode:"open"});Yh(s,e);let l=document.createElement("div");l.className="ww:contents",s.appendChild(l);let u=Cs.default.createRef(),c=d=>{r instanceof HTMLElement&&(r.style.display=d?"":"none")};if(e.token){let d=ci(e.api??"",e.token,e.channelId);d?.visibility&&!Zd(d.visibility,window.location.pathname)&&c(!1)}return jn=Zh.default.createRoot(i),jn.render(Cs.default.createElement(HB,{ref:u,config:e,programmatic:t,scriptConfig:a,panelContainer:l,onVisibilityChange:c})),{destroy:()=>{jn?.unmount(),jn=null,Xt?.remove(),Xt=null,Is?.remove(),Is=null,r.hasAttribute(af)&&r.remove(),Pt=null},open:()=>u.current?.open(),close:()=>u.current?.close(),toggle:()=>u.current?.toggle(),sendMessage:d=>u.current?.sendMessage(d),sendMessageAndWait:async d=>{if(u.current)return u.current.sendMessageAndWait(d)},reset:()=>u.current?.reset(),focus:()=>u.current?.focus(),getMessages:()=>u.current?.getMessages()??[],getSessionId:()=>u.current?.getSessionId()}}function r3(e){if(Pt)return console.warn("[Waniwani] Chat widget is already initialized. Call destroy() first to re-initialize."),Pt;let t=sI(),a=$h(),n=Yd(e,void 0,a);Sc(n.visitorId);let r=null;try{r=QB(n)}catch(l){console.error("[Waniwani] WebMCP setup failed",l)}let o;n.mode==="off"?o=LZ():n.mode==="floating"?o=TZ(n,e,a):n.mode==="composer"?o=EZ(n,e,a,t):o=kZ(n,e,a,t);let i=n.api??"",s=n.token?R1({api:i,token:n.token,channelId:()=>n.channelId??ci(i,n.token,n.channelId)?.channelId,getSource:()=>ci(i,n.token,n.channelId)?.source??void 0,getSessionId:()=>o.getSessionId()}):Wp("no public token configured (set data-token or pass token to init())");return Pt={...o,track:s.track,identify:(l,u)=>s.identify(l,u),setVisitorId:l=>wl(l),getVisitorId:()=>ma(),destroy:()=>{s.shutdown(),r?.destroy(),o.destroy()}},Pt}function AZ(){Pt&&Pt.destroy()}var o3=Wp("chat widget is not initialized (call WaniWani.chat.init() first)"),vu=()=>Pt?Pt.track:o3.track;window.WaniWani=window.WaniWani||{};window.WaniWani.chat={init:r3,destroy:AZ,open:()=>Pt?.open(),close:()=>Pt?.close(),toggle:()=>Pt?.toggle(),sendMessage:e=>Pt?.sendMessage(e),sendMessageAndWait:async e=>{if(Pt)return Pt.sendMessageAndWait(e)},reset:()=>Pt?.reset(),focus:()=>Pt?.focus(),getMessages:()=>Pt?.getMessages()??[],getSessionId:()=>Pt?.getSessionId(),track:Object.assign(e=>vu()(e),{priceShown:e=>vu().priceShown(e),pricesCompared:e=>vu().pricesCompared(e),optionSelected:e=>vu().optionSelected(e),leadQualified:e=>vu().leadQualified(e),converted:e=>vu().converted(e)}),identify:(e,t)=>Pt?Pt.identify(e,t):o3.identify(e,t),setVisitorId:e=>wl(e),getVisitorId:()=>ma()};function t3(){if($h().token)try{r3()}catch(t){console.error("[Waniwani] Auto-initialization failed:",t)}}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",t3):t3();})();
|