@waniwani/sdk 0.1.20-beta.6 → 0.1.20-beta.8

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.
@@ -102,8 +102,12 @@ interface ChatBaseProps {
102
102
  interface ChatBarProps extends ChatBaseProps {
103
103
  /** Chat bar width in pixels. Defaults to 600. */
104
104
  width?: number;
105
+ /** Width of the expanded card in pixels. Defaults to width × 1.2. */
106
+ expandedWidth?: number;
105
107
  /** Max height of the expanded messages panel in pixels. Defaults to 400. */
106
108
  expandedHeight?: number;
109
+ /** Title shown in the header when expanded. Defaults to "Assistant". */
110
+ title?: string;
107
111
  }
108
112
  interface ChatCardProps extends ChatBaseProps {
109
113
  /** Title shown in the card header. Defaults to "Assistant". */
@@ -112,10 +116,12 @@ interface ChatCardProps extends ChatBaseProps {
112
116
  subtitle?: string;
113
117
  /** Show the status dot in the header. Defaults to true. */
114
118
  showStatus?: boolean;
115
- /** Card width in pixels. Defaults to 400. */
116
- width?: number;
117
- /** Card height in pixels. Defaults to 600. */
118
- height?: number;
119
+ /** Card width. Accepts a pixel number or any CSS value (e.g. "100%", "50vw"). Defaults to 500. */
120
+ width?: number | string;
121
+ /** Card height. Accepts a pixel number or any CSS value (e.g. "100%", "80vh"). Defaults to 600. */
122
+ height?: number | string;
123
+ /** Additional class names applied to the root element (e.g. Tailwind classes). */
124
+ className?: string;
119
125
  }
120
126
  interface ChatHandle {
121
127
  /** Programmatically send a user message into the chat */
@@ -1,3 +1,3 @@
1
1
  "use client";
2
- import{forwardRef as sn,useCallback as Ae,useEffect as Lt,useImperativeHandle as an,useRef as Ht,useState as Je}from"react";import{ArrowDownIcon as zt}from"lucide-react";import{useCallback as _t}from"react";import{StickToBottom as Ze,useStickToBottomContext as Wt}from"use-stick-to-bottom";import{clsx as Bt}from"clsx";import{extendTailwindMerge as Ut}from"tailwind-merge";var Ot=Ut({prefix:"ww"});function l(...e){return Ot(Bt(e))}import{jsx as Qt}from"react/jsx-runtime";var G=({className:e,variant:t="default",size:o="default",type:n="button",...r})=>Qt("button",{type:n,className:l("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",o==="default"&&"ww:h-9 ww:px-4 ww:py-2 ww:text-sm",o==="sm"&&"ww:h-8 ww:px-3 ww:text-xs",o==="icon"&&"ww:size-9",o==="icon-sm"&&"ww:size-7",e),...r});import{jsx as we}from"react/jsx-runtime";var ce=({className:e,...t})=>we(Ze,{className:l("ww:relative ww:flex-1 ww:overflow-y-hidden",e),initial:"smooth",resize:"smooth",role:"log",...t}),pe=({className:e,...t})=>we(Ze.Content,{className:l("ww:flex ww:flex-col ww:gap-8 ww:p-4",e),...t}),de=({className:e,...t})=>{let{isAtBottom:o,scrollToBottom:n}=Wt(),r=_t(()=>{n()},[n]);return!o&&we(G,{className:l("ww:absolute ww:bottom-4 ww:left-[50%] ww:translate-x-[-50%] ww:rounded-full",e),onClick:r,size:"icon",variant:"outline",...t,children:we(zt,{className:"ww:size-4"})})};import{ArrowUpIcon as jt,LoaderIcon as $t,PaperclipIcon as qt,SquareIcon as Vt,XIcon as Jt}from"lucide-react";import{nanoid as Kt}from"nanoid";import{createContext as Gt,useCallback as X,useContext as Xt,useEffect as Fe,useMemo as Yt,useRef as De,useState as et}from"react";import{jsx as V,jsxs as nt}from"react/jsx-runtime";var Zt=async e=>{try{let o=await(await fetch(e)).blob();return new Promise(n=>{let r=new FileReader;r.onloadend=()=>n(r.result),r.onerror=()=>n(null),r.readAsDataURL(o)})}catch{return null}},tt=Gt(null),ot=()=>{let e=Xt(tt);if(!e)throw new Error("usePromptInputAttachments must be used within a PromptInput");return e},me=({className:e,accept:t,multiple:o,globalDrop:n,maxFiles:r,maxFileSize:i,onSubmit:u,children:w,...c})=>{let f=De(null),g=De(null),[h,T]=et([]),y=De(h);Fe(()=>{y.current=h},[h]);let S=X(()=>{f.current?.click()},[]),P=X(s=>{let p=[...s];if(p.length===0)return;let C=R=>i?R.size<=i:!0,v=p.filter(C);T(R=>{let A=typeof r=="number"?Math.max(0,r-R.length):void 0,H=typeof A=="number"?v.slice(0,A):v;return[...R,...H.map(a=>({filename:a.name,id:Kt(),mediaType:a.type,type:"file",url:URL.createObjectURL(a)}))]})},[r,i]),m=X(s=>{T(p=>{let C=p.find(v=>v.id===s);return C?.url&&URL.revokeObjectURL(C.url),p.filter(v=>v.id!==s)})},[]),E=X(()=>{T(s=>{for(let p of s)p.url&&URL.revokeObjectURL(p.url);return[]})},[]);Fe(()=>()=>{for(let s of y.current)s.url&&URL.revokeObjectURL(s.url)},[]);let k=X(s=>{s.currentTarget.files&&P(s.currentTarget.files),s.currentTarget.value=""},[P]);Fe(()=>{if(!n)return;let s=C=>{C.dataTransfer?.types?.includes("Files")&&C.preventDefault()},p=C=>{C.dataTransfer?.types?.includes("Files")&&C.preventDefault(),C.dataTransfer?.files&&C.dataTransfer.files.length>0&&P(C.dataTransfer.files)};return document.addEventListener("dragover",s),document.addEventListener("drop",p),()=>{document.removeEventListener("dragover",s),document.removeEventListener("drop",p)}},[P,n]);let x=X(async s=>{s.preventDefault();let p=s.currentTarget,v=new FormData(p).get("message")||"";p.reset();let R=await Promise.all(h.map(async({id:A,...H})=>{if(H.url?.startsWith("blob:")){let a=await Zt(H.url);return{...H,url:a??H.url}}return H}));try{let A=u({files:R,text:v},s);A instanceof Promise&&await A,E()}catch{}},[h,u,E]),z=Yt(()=>({add:P,clear:E,files:h,openFileDialog:S,remove:m}),[h,P,m,E,S]);return nt(tt.Provider,{value:z,children:[V("input",{accept:t,"aria-label":"Upload files",className:"ww:hidden",multiple:o,onChange:k,ref:f,title:"Upload files",type:"file"}),V("form",{className:l("ww:flex ww:w-full ww:flex-col ww:rounded-lg ww:border ww:border-border ww:bg-background",e),onSubmit:x,ref:g,...c,children:w})]})};var fe=({onChange:e,onKeyDown:t,className:o,placeholder:n="What would you like to know?",...r})=>{let i=ot(),[u,w]=et(!1),c=X(g=>{if(t?.(g),!g.defaultPrevented){if(g.key==="Enter"){if(u||g.nativeEvent.isComposing||g.shiftKey)return;g.preventDefault();let{form:h}=g.currentTarget;if(h?.querySelector('button[type="submit"]')?.disabled)return;h?.requestSubmit()}if(g.key==="Backspace"&&g.currentTarget.value===""&&i.files.length>0){g.preventDefault();let h=i.files.at(-1);h&&i.remove(h.id)}}},[t,u,i]),f=X(g=>{let h=g.clipboardData?.items;if(!h)return;let T=[];for(let y of h)if(y.kind==="file"){let S=y.getAsFile();S&&T.push(S)}T.length>0&&(g.preventDefault(),i.add(T))},[i]);return V("textarea",{className:l("ww:field-sizing-content ww:max-h-48 ww:min-h-16 ww:w-full ww:resize-none ww:border-0 ww:bg-transparent ww:px-3 ww:py-3 ww:text-sm ww:outline-none ww:placeholder:text-muted-foreground",o),name:"message",onCompositionEnd:()=>w(!1),onCompositionStart:()=>w(!0),onKeyDown:c,onPaste:f,placeholder:n,onChange:e,...r})},ge=({className:e,status:t,onStop:o,onClick:n,children:r,...i})=>{let u=t==="submitted"||t==="streaming",w=V(jt,{className:"ww:size-4"});t==="submitted"?w=V($t,{className:"ww:size-4 ww:animate-spin"}):t==="streaming"&&(w=V(Vt,{className:"ww:size-4"}));let c=X(f=>{if(u&&o){f.preventDefault(),o();return}n?.(f)},[u,o,n]);return V(G,{"aria-label":u?"Stop":"Submit",className:l("ww:bg-foreground ww:text-background ww:hover:bg-foreground",e),onClick:c,size:"icon-sm",type:u&&o?"button":"submit",variant:"ghost",...i,children:r??w})},he=({className:e,children:t,...o})=>{let n=ot();return n.files.length>0?nt(G,{className:l("ww:group ww:relative",e),onClick:()=>n.clear(),size:"icon-sm",type:"button",variant:"ghost","aria-label":"Remove all attachments",...o,children:[V("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:n.files.length}),V(Jt,{className:"ww:absolute ww:size-4 ww:opacity-0 ww:transition-opacity ww:group-hover:opacity-100"})]}):V(G,{className:l(e),onClick:()=>n.openFileDialog(),size:"icon-sm",type:"button",variant:"ghost",...o,children:t??V(qt,{className:"ww:size-4"})})};import{XIcon as eo}from"lucide-react";import{memo as to,useCallback as oo}from"react";import{jsx as te}from"react/jsx-runtime";var rt=({className:e,...t})=>te("div",{className:l("ww:flex ww:flex-col ww:gap-1 ww:px-3 ww:py-2",e),...t}),st=({className:e,...t})=>te("li",{className:l("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}),it=({className:e,...t})=>te("span",{className:l("ww:inline-block ww:size-2 ww:shrink-0 ww:rounded-full ww:border ww:border-muted-foreground/50",e),...t}),at=({className:e,...t})=>te("span",{className:l("ww:line-clamp-1 ww:grow ww:break-words ww:text-muted-foreground",e),...t}),ut=({className:e,...t})=>te("div",{className:l("ww:flex ww:shrink-0 ww:gap-1 ww:opacity-0 ww:transition-opacity ww:group-hover:opacity-100",e),...t}),lt=({className:e,...t})=>te(G,{className:l("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});import{jsx as ee,jsxs as Be}from"react/jsx-runtime";var wt=to(({message:e,onRemove:t})=>{let o=oo(()=>t(e.id),[t,e.id]);return Be(st,{children:[ee(it,{}),ee(at,{children:e.text||"(attachment)"}),ee(ut,{children:ee(lt,{"aria-label":"Remove from queue",onClick:o,children:ee(eo,{className:"ww:size-3"})})})]})});wt.displayName="ChatQueueItem";function be({queuedMessages:e,onRemove:t,className:o}){return e.length===0?null:Be(rt,{className:l("ww:border-t ww:border-border",o),children:[Be("div",{className:"ww:text-[11px] ww:font-medium ww:text-muted-foreground ww:px-2",children:[e.length," queued"]}),ee("ul",{children:e.map(n=>ee(wt,{message:n,onRemove:t},n.id))})]})}import{FileIcon as no}from"lucide-react";import{jsx as se,jsxs as so}from"react/jsx-runtime";var ct=({files:e,className:t,...o})=>e.length===0?null:se("div",{className:l("ww:flex ww:flex-wrap ww:gap-1.5",t),...o,children:e.map((n,r)=>se(ro,{file:n},r))});function ro({file:e}){return e.mediaType?.startsWith("image/")&&e.url?se("img",{src:e.url,alt:e.filename??"attachment",className:"ww:h-16 ww:max-w-32 ww:rounded ww:object-cover"}):so("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:[se(no,{className:"ww:size-3 ww:shrink-0"}),se("span",{className:"ww:max-w-24 ww:truncate",children:e.filename??"file"})]})}import{jsx as pt}from"react/jsx-runtime";var Ue=({className:e,size:t=5,...o})=>pt("div",{className:l("ww:flex ww:items-center ww:gap-1",e),...o,children:[0,1,2].map(n=>pt("div",{className:"ww:rounded-full ww:bg-muted-foreground/60",style:{width:t,height:t,animation:"ww-pulse 1.4s ease-in-out infinite",animationDelay:`${n*.2}s`}},n))});import{cjk as io}from"@streamdown/cjk";import{code as ao}from"@streamdown/code";import{memo as uo}from"react";import{Streamdown as lo}from"streamdown";import{jsx as Oe}from"react/jsx-runtime";var xe=({className:e,from:t,...o})=>Oe("div",{className:l("ww:group ww:flex ww:w-full ww:max-w-[95%] ww:flex-col ww:gap-2",t==="user"?"is-user ww:ml-auto ww:justify-end":"is-assistant",e),...o}),ye=({children:e,className:t,...o})=>Oe("div",{className:l("ww:flex ww:w-fit ww:min-w-0 ww:max-w-full ww:flex-col ww:gap-2 ww:overflow-hidden ww:text-base","ww:group-[.is-user]:ml-auto ww:group-[.is-user]:rounded-lg ww:group-[.is-user]:bg-user-bubble ww:group-[.is-user]:px-4 ww:group-[.is-user]:py-3 ww:group-[.is-user]:text-primary-foreground","ww:group-[.is-assistant]:text-foreground",t),...o,children:e}),wo={cjk:io,code:ao},Ce=uo(({className:e,...t})=>Oe(lo,{className:l("ww:size-full ww:[&>*:first-child]:mt-0 ww:[&>*:last-child]:mb-0",e),plugins:wo,...t}),(e,t)=>e.children===t.children);Ce.displayName="MessageResponse";import{jsx as co}from"react/jsx-runtime";function dt({className:e,text:t,...o}){return t?co("pre",{className:l("ww:mb-2 ww:overflow-x-auto ww:whitespace-pre-wrap ww:break-words ww:text-xs ww:font-mono ww:text-muted-foreground",e),...o,children:t}):null}import{BracesIcon as po,CheckIcon as mo,ChevronDownIcon as fo,ChevronRightIcon as go,ClipboardCopyIcon as ho,ServerIcon as ir}from"lucide-react";import{createContext as bo,useCallback as xo,useContext as ft,useEffect as yo,useMemo as Co,useRef as vo,useState as Qe}from"react";import{Fragment as mt,jsx as M,jsxs as Z}from"react/jsx-runtime";function To(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 o=JSON.stringify(e);if(o.length<=t)return o;let n=Object.entries(e),r=[],i=t-2;for(let[u,w]of n){if(i<=8)break;let c=u.length>4?`${u.slice(0,4)}\u2026`:u,f;typeof w=="string"?f=w.length>2?`'${w.slice(0,1)}\u2026`:`'${w}'`:Array.isArray(w)?f=`Array(${w.length})`:typeof w=="object"&&w!==null?f="{\u2026}":f=String(w);let g=`${c}\u2009${f}`;r.push(g),i-=g.length+3}return`{${r.join(", ")}}`}function Po({text:e,className:t}){let[o,n]=Qe(!1),r=vo(null);yo(()=>()=>{r.current&&clearTimeout(r.current)},[]);let i=xo(async u=>{u.stopPropagation();try{await navigator.clipboard.writeText(e),n(!0),r.current&&clearTimeout(r.current),r.current=setTimeout(()=>n(!1),2e3)}catch{}},[e]);return M(G,{variant:"ghost",size:"sm",onClick:i,className:l("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:o?Z(mt,{children:[M(mo,{className:"ww:size-3.5"}),M("span",{children:"Copied"})]}):Z(mt,{children:[M(ho,{className:"ww:size-3.5"}),M("span",{children:"Copy"})]})})}function gt({data:e,label:t,className:o,...n}){let[r,i]=Qe(!1),u=Co(()=>JSON.stringify(e,null,2),[e]),w=To(e);return Z("div",{className:l("ww:rounded-lg ww:bg-tool-card",o),...n,children:[Z("div",{className:"ww:flex ww:items-center ww:justify-between ww:px-3 ww:pt-2.5 ww:pb-1.5",children:[M("span",{className:"ww:text-xs ww:font-medium ww:text-muted-foreground",children:t}),M(Po,{text:u})]}),Z("button",{type:"button",onClick:()=>i(c=>!c),className:"ww:flex ww:w-full ww:items-start ww:gap-2 ww:px-3 ww:pb-3 ww:text-left",children:[M(go,{className:l("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?M("pre",{className:"ww:overflow-x-auto ww:text-xs ww:font-mono ww:text-foreground ww:whitespace-pre-wrap ww:break-all",children:M("code",{children:u})}):M("span",{className:"ww:truncate ww:text-xs ww:font-mono ww:text-foreground/80",children:w})]})]})}var ze=bo({open:!1,toggle:()=>{}});function ht({className:e,defaultOpen:t=!1,children:o,...n}){let[r,i]=Qe(t);return M(ze.Provider,{value:{open:r,toggle:()=>i(u=>!u)},children:M("div",{className:l("ww:mb-4 ww:w-full",e),"data-state":r?"open":"closed",...n,children:o})})}function bt({className:e,title:t,state:o,...n}){let{open:r,toggle:i}=ft(ze),u=o==="input-available"||o==="input-streaming";return Z("button",{type:"button",onClick:i,className:l("ww:flex ww:w-full ww:items-center ww:justify-between ww:gap-3 ww:py-1.5",e),"aria-expanded":r,...n,children:[Z("div",{className:"ww:flex ww:min-w-0 ww:items-center ww:gap-2",children:[M(po,{className:"ww:size-4 ww:shrink-0 ww:text-muted-foreground"}),M("span",{className:"ww:truncate ww:text-sm ww:font-medium",children:t}),u&&M("span",{className:"ww:size-2 ww:shrink-0 ww:rounded-full ww:bg-primary ww:animate-pulse"})]}),M(fo,{className:l("ww:size-4 ww:shrink-0 ww:text-muted-foreground ww:transition-transform ww:duration-200",r&&"ww:rotate-180")})]})}function xt({className:e,children:t,...o}){let{open:n}=ft(ze);return M("div",{className:l("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:M("div",{className:"ww:min-h-0 ww:overflow-hidden",children:M("div",{className:l("ww:mt-2 ww:space-y-3 ww:rounded-lg ww:border ww:border-border ww:bg-background ww:p-3",e),...o,children:t})})})}function yt({className:e,input:t,...o}){return M(gt,{data:t,label:"Request",className:e,...o})}function Ct(e){if(typeof e!="object"||e===null)return;let t=e._meta;if(typeof t!="object"||t===null)return;let o=t.ui;if(!(typeof o!="object"||o===null))return o}function vt(e){let t=Ct(e)?.resourceUri;return typeof t=="string"?t:void 0}function Tt(e){return Ct(e)?.autoHeight===!0}function Pt({className:e,output:t,errorText:o,...n}){return t||o?o?Z("div",{className:l("ww:space-y-2",e),...n,children:[M("h4",{className:"ww:text-xs ww:font-medium ww:uppercase ww:tracking-wide ww:text-muted-foreground",children:"Error"}),M("div",{className:"ww:rounded-lg ww:bg-destructive/10 ww:p-3 ww:text-xs ww:text-destructive",children:o})]}):M(gt,{data:t,label:"Response",className:e,...n}):null}import{useCallback as Io,useEffect as It,useMemo as Mo,useRef as j,useState as Mt}from"react";import{jsx as Lo}from"react/jsx-runtime";var ko="/api/mcp/resource",So=500,Eo=0,Ro="2026-01-26",Ao=300,No=3e3,_e=3;function We({resourceUri:e,toolInput:t,toolResult:o,resourceEndpoint:n=ko,isDark:r=!1,className:i,autoHeight:u=!0,onOpenLink:w,onFollowUp:c,onCallTool:f,onDisplayModeChange:g}){let h=j(null),T=j(t),y=j(o),S=j({width:0,height:0}),P=j(null),m=j(!1),E=j(0),k=j("inline"),[x,z]=Mt(Eo),[s,p]=Mt(void 0),C=j(w),v=j(c),R=j(f),A=j(g);T.current=t,y.current=o,C.current=w,v.current=c,R.current=f,A.current=g;let H=Io(b=>u?Math.max(b,0):Math.min(Math.max(b,50),So),[u]),a=Mo(()=>`${n}?uri=${encodeURIComponent(e)}`,[n,e]),I=j(r);return I.current=r,It(()=>{if(!m.current)return;let b=h.current;b?.contentWindow&&b.contentWindow.postMessage({jsonrpc:"2.0",method:"ui/notifications/host-context-changed",params:{theme:r?"dark":"light"}},"*")},[r]),It(()=>{let b=h.current;if(!b)return;let _=!1,F=!1,d=(...q)=>console.log("[McpAppFrame]",...q);d("effect mounted, waiting for handshake");let D=setTimeout(()=>{if(_||F)return;if(E.current>=_e){d("handshake failed after",_e,"retries, giving up");return}E.current+=1,d("handshake timeout, reloading iframe (retry",E.current,"of",_e,")");let q=new URL(b.src);q.searchParams.set("_retry",String(E.current)),b.src=q.toString()},No),L=q=>{d("\u2192 send",q.method??`response:${q.id}`,q),b.contentWindow?.postMessage(q,"*")},re=q=>{if(_||q.source!==b.contentWindow)return;let O=q.data;if(console.log("data",O),!O||typeof O!="object"||O.jsonrpc!=="2.0")return;let K=O.method,Q=O.id;if(d("\u2190 recv",K??`response:${Q}`,O),K==="ui/initialize"&&Q!=null){F=!0,clearTimeout(D),d("handshake started"),L({jsonrpc:"2.0",id:Q,result:{protocolVersion:O.params?.protocolVersion??Ro,hostInfo:{name:"WaniWani Chat",version:"1.0.0"},hostCapabilities:{openLinks:{},message:{},tools:{}},hostContext:{theme:I.current?"dark":"light",displayMode:k.current}}});return}if(K==="ui/notifications/initialized"){d("handshake complete, sending tool data"),m.current=!0;let B=T.current,N=y.current;L({jsonrpc:"2.0",method:"ui/notifications/tool-input",params:{arguments:B}});let W=N.content??[{type:"text",text:JSON.stringify(N)}];L({jsonrpc:"2.0",method:"ui/notifications/tool-result",params:{content:W,structuredContent:N.structuredContent}});return}if(K==="ui/notifications/size-changed"){let B=O.params,N=typeof B?.height=="number"?B.height:void 0,W=typeof B?.width=="number"?B.width:void 0,Y=S.current,Ne=N!==void 0&&N!==Y.height,Le=W!==void 0&&W!==Y.width;if(d("size-changed",{newHeight:N,newWidth:W,lastHeight:Y.height,lastWidth:Y.width,heightChanged:Ne,widthChanged:Le}),!Ne&&!Le)return;if(Ne&&N!==void 0){Y.height=N;let He=H(N),Ye=b.getBoundingClientRect().height;if(P.current&&(P.current.cancel(),P.current=null),z(He),b.animate&&Math.abs(Ye-He)>2){let le=b.animate([{height:`${Ye}px`},{height:`${He}px`}],{duration:Ao,easing:"ease-out",fill:"forwards"});P.current=le,le.onfinish=()=>{P.current===le&&(le.cancel(),P.current=null)}}}Le&&u&&W!==void 0&&(Y.width=W,p(W));return}if(K==="ui/open-link"&&Q!=null){let B=O.params?.url;typeof B=="string"&&(C.current?C.current(B):window.open(B,"_blank","noopener,noreferrer")),L({jsonrpc:"2.0",id:Q,result:{}});return}if(K==="ui/message"&&Q!=null){v.current&&O.params&&v.current(O.params),L({jsonrpc:"2.0",id:Q,result:{}});return}if(K==="tools/call"&&Q!=null){d("tools/call",O.params?.name,O.params?.arguments);let B=R.current;if(!B){L({jsonrpc:"2.0",id:Q,error:{code:-32601,message:"tools/call not supported"}});return}B({name:O.params?.name,arguments:O.params?.arguments??{}}).then(N=>{L({jsonrpc:"2.0",id:Q,result:N});let W=N.content?.map(Y=>Y.text??"").join("").trim();W&&v.current&&v.current({role:"user",content:[{type:"text",text:W}]})}).catch(N=>{let W=N instanceof Error?N.message:"Tool call failed";L({jsonrpc:"2.0",id:Q,error:{code:-32e3,message:W}})});return}if(K==="ui/request-display-mode"&&Q!=null){let B=O.params?.mode,N=B==="fullscreen"||B==="inline"||B==="pip"?B:"inline";k.current=N,L({jsonrpc:"2.0",id:Q,result:{mode:N}}),L({jsonrpc:"2.0",method:"ui/notifications/host-context-changed",params:{displayMode:N}}),A.current?.(N);return}if(K==="ui/resource-teardown"&&Q!=null){L({jsonrpc:"2.0",id:Q,result:{}});return}K==="ping"&&Q!=null&&L({jsonrpc:"2.0",id:Q,result:{}})};return window.addEventListener("message",re),()=>{d("effect cleanup (disposed)"),_=!0,clearTimeout(D),window.removeEventListener("message",re)}},[u,H]),Lo("iframe",{ref:h,src:a,sandbox:"allow-scripts allow-forms allow-same-origin",className:l("ww:rounded-md ww:border ww:border-border",i),style:{height:x,minWidth:s?`min(${s}px, 100%)`:void 0,width:"100%",border:"none",colorScheme:"auto"},title:"MCP App"})}import{Component as Ho}from"react";import{jsx as kt,jsxs as Fo}from"react/jsx-runtime";var ve=class extends Ho{state={hasError:!1};static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(t){console.warn("[WaniWani] Widget failed to render:",t.message)}render(){return this.state.hasError?Fo("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:[kt("span",{children:"Widget failed to load"}),kt("button",{type:"button",onClick:()=>this.setState({hasError:!1}),className:"ww:text-xs ww:font-medium ww:text-primary ww:hover:underline",children:"Retry"})]}):this.props.children}};import{Fragment as Bo,jsx as U,jsxs as oe}from"react/jsx-runtime";function Do(e){return e.replace(/[-_]/g," ").replace(/^\w/,t=>t.toUpperCase())}function Te({messages:e,status:t,welcomeMessage:o,resourceEndpoint:n,isDark:r,onFollowUp:i,onCallTool:u,onWidgetDisplayModeChange:w,fullscreenToolCallId:c}){let f=t==="submitted"||t==="streaming",g=e[e.length-1],h=e.length>0,T=f&&(!h||g.role==="user");return oe(Bo,{children:[o&&!c&&U(xe,{from:"assistant",children:U(ye,{children:U(Ce,{children:o})})}),e.map(y=>{let S=y.parts.filter(s=>s.type==="text"),P=y.parts.filter(s=>s.type==="reasoning"),m=y.parts.filter(s=>s.type==="file"),E=y.parts.filter(s=>"toolCallId"in s),k=y===g&&y.role==="assistant",x=S.length>0,z=c&&E.some(s=>s.toolCallId===c);return c&&!z?null:oe(xe,{from:y.role,children:[P.map((s,p)=>U("div",{style:c?{display:"none"}:void 0,children:U(dt,{text:s.text})},`reasoning-${y.id}-${p}`)),E.map(s=>{let p="output"in s?s.output:void 0,C=p!==void 0?vt(p):void 0,v=p!==void 0?Tt(p):!1,R=s.toolCallId===c,A=c!=null&&!R;return oe("div",{style:A?{display:"none"}:R?{height:"100%"}:void 0,children:[U("div",{style:R?{display:"none"}:void 0,children:oe(ht,{defaultOpen:s.state==="output-available",children:[U(bt,{title:s.title??Do(s.toolName),state:s.state}),oe(xt,{children:[U(yt,{input:s.input}),p!==void 0&&U(Pt,{output:p,errorText:"errorText"in s?s.errorText:void 0})]})]})}),C&&p!==void 0&&U(ve,{children:U(We,{resourceUri:C,toolInput:s.input??{},toolResult:{content:p.content,structuredContent:p.structuredContent},resourceEndpoint:n,isDark:r,autoHeight:v,onFollowUp:i,onCallTool:u,onDisplayModeChange:w?H=>w(H,{toolCallId:s.toolCallId,resourceUri:C,toolInput:s.input??{},toolResult:{content:p.content,structuredContent:p.structuredContent},autoHeight:v}):void 0})})]},s.toolCallId)}),U("div",{style:c?{display:"none"}:void 0,children:oe(ye,{children:[m.length>0&&U(ct,{files:m}),x?S.map((s,p)=>U(Ce,{children:s.type==="text"?s.text:""},`${y.id}-${p}`)):k&&f&&U(Ue,{})]})})]},y.id)}),T&&!c&&U(xe,{from:"assistant",children:U(ye,{children:U(Ue,{})})})]})}import{jsx as je}from"react/jsx-runtime";function Pe({suggestions:e,isLoading:t,onSelect:o,className:n,...r}){return e.length===0&&!t?null:je("div",{className:l("ww:flex ww:flex-wrap ww:gap-2 ww:px-3 ww:py-2",n),...r,children:t?[0,1,2].map(i=>je("div",{className:"ww:h-7 ww:rounded-full ww:bg-accent ww:animate-pulse",style:{width:`${60+i*20}px`}},i)):e.map((i,u)=>je("button",{type:"button",onClick:()=>o(i),className:l("ww:rounded-full ww:border ww:border-border ww:bg-background ww:px-3 ww:py-1 ww:text-xs","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:`${u*50}ms`},children:i},i))})}import{useCallback as Uo,useRef as Oo}from"react";function Ie(e){let t=Oo(e);return t.current=e,Uo(async o=>{let{api:n,headers:r,onCallTool:i}=t.current;if(i)return i(o);let u=`${n??"https://app.waniwani.ai/api/chat"}/tool`,w=await fetch(u,{method:"POST",headers:{"Content-Type":"application/json",...r},body:JSON.stringify(o)});if(!w.ok)throw new Error(`Tool call failed: ${w.status} ${w.statusText}`);return w.json()},[])}import{useChat as Qo}from"@ai-sdk/react";import{DefaultChatTransport as zo}from"ai";import{nanoid as _o}from"nanoid";import{useCallback as ne,useEffect as $e,useRef as Me,useState as St}from"react";var Ve="waniwani-chat-session-id",Wo="x-session-id";function qe(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}function jo(){if(!(typeof window>"u"))try{return qe(window.sessionStorage.getItem(Ve))}catch{return}}function $o(e){if(!(typeof window>"u"))try{window.sessionStorage.setItem(Ve,e)}catch{}}function qo(){if(!(typeof window>"u"))try{window.sessionStorage.removeItem(Ve)}catch{}}function ke(e){let{api:t="https://app.waniwani.ai/api/chat",headers:o,body:n,onMessageSent:r,onResponseReceived:i}=e,u=Me(o),w=Me(n),c=Me(void 0),f=ne(()=>{if(c.current)return c.current;let a=jo();return a&&(c.current=a),a},[]),g=ne(a=>{let I=qe(a);I&&c.current!==I&&(c.current=I,$o(I))},[]),h=ne(()=>{c.current=void 0,qo()},[]);$e(()=>{u.current=o},[o]),$e(()=>{w.current=n},[n]);let T=Me(new zo({api:t,headers:()=>({...u.current}),body:()=>{let a={...w.current??{}},I=Object.hasOwn(a,"sessionId"),b=qe(a.sessionId);if(b)return g(b),a.sessionId=b,a;if(I)return h(),delete a.sessionId,a;let _=f();return _&&(a.sessionId=_),a},fetch:async(a,I)=>{let b=await fetch(a,I);return g(b.headers.get(Wo)),b}})),{messages:y,sendMessage:S,status:P}=Qo({transport:T.current,onFinish(){i?.()},onError(a){console.warn("[WaniWani] Chat error:",a.message)}}),[m,E]=St(""),[k,x]=St([]),z=P==="submitted"||P==="streaming",s=ne(a=>{x(I=>I.filter(b=>b.id!==a))},[]),p=z&&k.length>0,C=ne(a=>{let I=!!a.text?.trim(),b=!!a.files?.length;if(I||b){if(z){if(k.length>0)return;x(_=>[..._,{id:_o(),text:a.text||"",files:a.files??[]}]),E("");return}S({text:a.text||"",files:a.files}),r?.(a.text||""),E("")}},[S,r,z,k.length]);$e(()=>{if(P!=="ready"||k.length===0)return;let[a,...I]=k;x(I),S({text:a.text,files:a.files.length>0?a.files:void 0}),r?.(a.text)},[P,S,r,k]);let v=ne(a=>{E(a.target.value)},[]),R=y[y.length-1],A=y.length>0,H=z&&(!A||R.role==="user");return{messages:y,status:P,text:m,setText:E,handleSubmit:C,handleTextChange:v,isLoading:z,showLoaderBubble:H,lastMessage:R,hasMessages:A,sendMessage:S,queuedMessages:k,queueFull:p,removeQueuedMessage:s}}import{useCallback as Vo,useEffect as Et,useRef as Jo,useState as Ko}from"react";function Go(e){for(let t of e.parts){let o=t;if(o.type==="data"||o.type==="data-suggestions"){let n=o.data;if(n&&Array.isArray(n.suggestions))return n.suggestions}}return null}function Rt(e){return typeof e=="object"&&e!==null&&"initial"in e}function Se(e){let{messages:t,status:o,config:n}=e,[r,i]=Ko((Rt(n)&&n.initial?n.initial:[])??[]),u=Jo(o),w=n===!0||Rt(n)&&n.dynamic!==!1,c=Vo(()=>{i([])},[]),f=t[t.length-1];return Et(()=>{f?.role==="user"&&c()},[f,c]),Et(()=>{let g=u.current;if(u.current=o,g==="streaming"&&o==="ready"&&w){let h=[...t].reverse().find(y=>y.role==="assistant");if(!h)return;console.log("[WaniWani] Assistant parts:",h.parts);let T=Go(h);console.log("[WaniWani] Extracted suggestions:",T),T&&i(T)}},[o,w,t]),{suggestions:r,isLoading:!1,clear:c}}import{useEffect as Xo,useRef as Yo,useState as Zo}from"react";var en=50,tn=30,on=2e3,At=500;function Ee(e,t=!0){let[o,n]=Zo(""),r=Yo(void 0);return Xo(()=>{if(!t){n("");return}let i=0,u=!1,w=!1,c=()=>{w||(u?(i--,n(e.slice(0,i)),i<=0?(u=!1,r.current=setTimeout(c,At)):r.current=setTimeout(c,tn)):(i++,n(e.slice(0,i)),i>=e.length?(u=!0,r.current=setTimeout(c,on)):r.current=setTimeout(c,en)))};return r.current=setTimeout(c,At),()=>{w=!0,clearTimeout(r.current)}},[e,t]),o}var Nt={primaryColor:"#6366f1",primaryForeground:"#1f2937",backgroundColor:"#ffffff",textColor:"#1f2937",mutedColor:"#6b7280",borderColor:"#e5e7eb",assistantBubbleColor:"#f3f4f6",userBubbleColor:"#f4f4f4",inputBackgroundColor:"#f9fafb",borderRadius:16,messageBorderRadius:12,fontFamily:"system-ui, -apple-system, 'Segoe UI', sans-serif",headerBackgroundColor:"#ffffff",headerTextColor:"#1f2937",statusColor:"#22c55e",toolCardColor:"#f4f4f5"},nn={backgroundColor:"#212121",headerBackgroundColor:"#1e1e1e",headerTextColor:"#ececec",textColor:"#ececec",primaryForeground:"#ffffff",mutedColor:"#8e8ea0",borderColor:"#444444",assistantBubbleColor:"#2f2f2f",userBubbleColor:"#303030",inputBackgroundColor:"#2f2f2f",primaryColor:"#6366f1",statusColor:"#22c55e",toolCardColor:"#262626"},rn={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"],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"]};function ie(e){return{...Nt,...e}}function Re(e){let t=e.backgroundColor.replace("#",""),o=parseInt(t.substring(0,2),16),n=parseInt(t.substring(2,4),16),r=parseInt(t.substring(4,6),16);return(o*299+n*587+r*114)/1e3<128}function ae(e){let t={};for(let[o,n]of Object.entries(rn)){let r=e[o],i=typeof r=="number"?`${r}px`:String(r);for(let u of n)t[u]=i}return t}import{jsx as J,jsxs as Ke}from"react/jsx-runtime";var Ge=sn(function(t,o){let{theme:n,width:r=600,expandedHeight:i=400,allowAttachments:u=!1,welcomeMessage:w,placeholder:c="Ask me anything...",triggerEvent:f="triggerDemoRequest",resourceEndpoint:g,api:h}=t,T=g??(h?`${h}/resource`:void 0),y=ie(n),S=ae(y),P=Re(y),m=ke(t),E=Ie(t),k=Se({messages:m.messages,status:m.status,config:t.suggestions}),x=Ae(d=>{let D=d.content.map(L=>L.text??"").join("").trim();D&&m.handleSubmit({text:D,files:[]})},[m.handleSubmit]),z=Ae(d=>{k.clear(),m.handleSubmit({text:d,files:[]})},[k.clear,m.handleSubmit]),s=Ee(c,!m.text),[p,C]=Je(!1),[v,R]=Je(!1),[A,H]=Je(null),a=Ht(null),I=Ht(void 0),b=Ae(()=>{let d=a.current;if(!d)return;d.scrollIntoView({behavior:"smooth",block:"center"});let D=d.querySelector("textarea");D&&setTimeout(()=>D.focus(),300),C(!0),R(!0),clearTimeout(I.current),I.current=setTimeout(()=>R(!1),2e3)},[]);an(o,()=>({sendMessage:d=>{m.handleSubmit({text:d,files:[]}),b()},focus:b}),[m.handleSubmit,b]),Lt(()=>{if(!f)return;let d=D=>{let L=D.detail,re=typeof L?.message=="string"?L.message:void 0;re&&m.handleSubmit({text:re,files:[]}),b()};return window.addEventListener(f,d),()=>window.removeEventListener(f,d)},[f,m.handleSubmit,b]);let _=p||A!==null;Lt(()=>{if(!p)return;let d=D=>{a.current&&!a.current.contains(D.target)&&C(!1)};return document.addEventListener("mousedown",d),()=>document.removeEventListener("mousedown",d)},[p]);let F=Ae(()=>{C(!0)},[]);return Ke("div",{ref:a,style:{...S,width:r},"data-waniwani-chat":"","data-waniwani-layout":"bar",...P?{"data-waniwani-dark":""}:{},className:"ww:flex ww:flex-col ww:font-[family-name:var(--ww-font)] ww:text-foreground",children:[J("div",{className:l("ww:overflow-hidden ww:bg-background/80 ww:backdrop-blur-xl ww:transition-all ww:duration-300 ww:ease-out",_?"ww:opacity-100 ww:translate-y-0":"ww:opacity-0 ww:translate-y-2 ww:pointer-events-none ww:max-h-0"),style:{..._?{maxHeight:i}:void 0,maskImage:"linear-gradient(to bottom, transparent, black 24px, black calc(100% - 16px), transparent), linear-gradient(to right, transparent, black 16px, black calc(100% - 16px), transparent)",maskComposite:"intersect",WebkitMaskImage:"linear-gradient(to bottom, transparent, black 24px, black calc(100% - 16px), transparent), linear-gradient(to right, transparent, black 16px, black calc(100% - 16px), transparent)",WebkitMaskComposite:"source-in"},children:Ke(ce,{className:"ww:flex-1",style:{height:i},children:[J(pe,{children:J(Te,{messages:m.messages,status:m.status,welcomeMessage:w,resourceEndpoint:T,isDark:P,onFollowUp:x,onCallTool:E,fullscreenToolCallId:A,onWidgetDisplayModeChange:(d,D)=>{H(d==="fullscreen"?D.toolCallId:null)}})}),!A&&J(de,{})]})}),J(Pe,{suggestions:k.suggestions,isLoading:k.isLoading,onSelect:z}),J(be,{queuedMessages:m.queuedMessages,onRemove:m.removeQueuedMessage}),J("div",{className:"ww:shrink-0",children:J(me,{onSubmit:m.handleSubmit,globalDrop:u,multiple:u,className:l("ww:rounded-[var(--ww-radius)] ww:shadow-sm ww:transition-all ww:duration-300 ww:ease-out",v&&"ww:ring-2 ww:ring-blue-400/70 ww:ring-offset-2 ww:ring-offset-background"),children:Ke("div",{className:"ww:flex ww:items-center ww:gap-1 ww:px-3 ww:py-2",children:[u&&J(he,{}),J(fe,{onChange:m.handleTextChange,value:m.text,placeholder:s,onFocus:F,className:"ww:min-h-0 ww:py-1.5 ww:px-2"}),J(ge,{status:m.status,disabled:m.queueFull})]})})})]})});import{forwardRef as un,useCallback as Xe,useEffect as ln,useImperativeHandle as wn,useRef as Ft,useState as Dt}from"react";import{jsx as $,jsxs as ue}from"react/jsx-runtime";var cn=un(function(t,o){let{theme:n,title:r="Assistant",subtitle:i,showStatus:u=!0,width:w=500,height:c=600,allowAttachments:f=!1,welcomeMessage:g,placeholder:h="Ask me anything...",triggerEvent:T="triggerDemoRequest",resourceEndpoint:y,api:S}=t,P=y??(S?`${S}/resource`:void 0),m=ie(n),E=ae(m),k=Re(m),x=ke(t),z=Ie(t),s=Ee(h,!x.text),[p,C]=Dt(!1),[v,R]=Dt(null),A=Ft(null),H=Ft(void 0),a=Xe(()=>{let F=A.current;if(!F)return;F.scrollIntoView({behavior:"smooth",block:"center"});let d=F.querySelector("textarea");d&&setTimeout(()=>d.focus(),300),C(!0),clearTimeout(H.current),H.current=setTimeout(()=>C(!1),2e3)},[]),I=Se({messages:x.messages,status:x.status,config:t.suggestions}),b=Xe(F=>{let d=F.content.map(D=>D.text??"").join("").trim();d&&x.handleSubmit({text:d,files:[]})},[x.handleSubmit]),_=Xe(F=>{I.clear(),x.handleSubmit({text:F,files:[]})},[I.clear,x.handleSubmit]);return wn(o,()=>({sendMessage:F=>{x.handleSubmit({text:F,files:[]}),a()},focus:a}),[x.handleSubmit,a]),ln(()=>{if(!T)return;let F=d=>{let D=d.detail,L=typeof D?.message=="string"?D.message:void 0;L&&x.handleSubmit({text:L,files:[]}),a()};return window.addEventListener(T,F),()=>window.removeEventListener(T,F)},[T,x.handleSubmit,a]),ue("div",{ref:A,style:{...E,width:w,height:c},"data-waniwani-chat":"","data-waniwani-layout":"card",...k?{"data-waniwani-dark":""}:{},className:l("ww:flex ww:flex-col ww:font-[family-name:var(--ww-font)] ww:text-foreground ww:bg-background ww:rounded-[var(--ww-radius)] ww:border ww:border-border ww:shadow-md ww:overflow-hidden ww:transition-shadow ww:duration-300",p&&"ww:ring-2 ww:ring-blue-400/70 ww:ring-offset-2 ww:ring-offset-background"),children:[ue("div",{className:"ww:shrink-0 ww:flex ww:items-center ww:gap-3 ww:px-4 ww:py-2 ww:border-b ww:border-border",style:{backgroundColor:m.headerBackgroundColor,color:m.headerTextColor},children:[u&&$("span",{className:"ww:size-2.5 ww:rounded-full ww:bg-status"}),ue("div",{className:"ww:flex-1 ww:min-w-0",children:[$("div",{className:"ww:text-xs ww:font-semibold ww:truncate",children:r}),i&&$("div",{className:"ww:text-[11px] ww:text-muted-foreground ww:truncate",children:i})]})]}),ue(ce,{className:"ww:flex-1 ww:min-h-0 ww:bg-background",children:[$(pe,{children:$(Te,{messages:x.messages,status:x.status,welcomeMessage:g,resourceEndpoint:P,isDark:k,onFollowUp:b,onCallTool:z,fullscreenToolCallId:v,onWidgetDisplayModeChange:(F,d)=>{R(F==="fullscreen"?d.toolCallId:null)}})}),!v&&$(de,{})]}),!v&&$(Pe,{suggestions:I.suggestions,isLoading:I.isLoading,onSelect:_,className:"ww:border-t ww:border-border"}),!v&&$(be,{queuedMessages:x.queuedMessages,onRemove:x.removeQueuedMessage}),!v&&$("div",{className:"ww:shrink-0 ww:border-t ww:border-border ww:bg-background",children:$(me,{onSubmit:x.handleSubmit,globalDrop:f,multiple:f,className:l("ww:rounded-none ww:border-0"),children:ue("div",{className:"ww:flex ww:items-center ww:gap-1 ww:px-3 ww:py-2",children:[f&&$(he,{}),$(fe,{onChange:x.handleTextChange,value:x.text,placeholder:s,className:"ww:min-h-0 ww:py-1.5 ww:px-2"}),$(ge,{status:x.status,disabled:x.queueFull})]})})})]})});export{Ge as ChatBar,cn as ChatCard,Ge as ChatWidget,nn as DARK_THEME,Nt as DEFAULT_THEME,We as McpAppFrame,ie as mergeTheme,ae as themeToCSSProperties};
2
+ import{forwardRef as sn,useCallback as Ne,useEffect as Lt,useImperativeHandle as an,useRef as Ht,useState as Je}from"react";import{ArrowDownIcon as zt}from"lucide-react";import{useCallback as _t}from"react";import{StickToBottom as Ze,useStickToBottomContext as Wt}from"use-stick-to-bottom";import{clsx as Bt}from"clsx";import{extendTailwindMerge as Ut}from"tailwind-merge";var Ot=Ut({prefix:"ww"});function u(...e){return Ot(Bt(e))}import{jsx as Qt}from"react/jsx-runtime";var G=({className:e,variant:t="default",size:o="default",type:n="button",...r})=>Qt("button",{type:n,className:u("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",o==="default"&&"ww:h-9 ww:px-4 ww:py-2 ww:text-sm",o==="sm"&&"ww:h-8 ww:px-3 ww:text-xs",o==="icon"&&"ww:size-9 ww:rounded-full",o==="icon-sm"&&"ww:size-7 ww:rounded-full",e),...r});import{jsx as le}from"react/jsx-runtime";var we=({className:e,...t})=>le(Ze,{className:u("ww:relative ww:flex-1 ww:overflow-y-hidden",e),initial:"smooth",resize:"smooth",role:"log",...t}),ce=({className:e,...t})=>le(Ze.Content,{className:u("ww:flex ww:flex-col ww:gap-6 ww:px-4 ww:py-6 ww:mx-auto ww:w-full ww:max-w-3xl",e),...t}),de=({className:e,...t})=>{let{isAtBottom:o,scrollToBottom:n}=Wt(),r=_t(()=>{n()},[n]);return!o&&le(G,{className:u("ww:absolute ww:bottom-4 ww:left-[50%] ww:translate-x-[-50%] ww:rounded-full",e),onClick:r,size:"icon",variant:"outline",...t,children:le(zt,{className:"ww:size-4"})})};import{ArrowUpIcon as jt,LoaderIcon as $t,PaperclipIcon as qt,SquareIcon as Vt,XIcon as Jt}from"lucide-react";import{nanoid as Kt}from"nanoid";import{createContext as Xt,useCallback as Y,useContext as Gt,useEffect as Be,useMemo as Yt,useRef as Ue,useState as et}from"react";import{jsx as X,jsxs as nt}from"react/jsx-runtime";var Zt=async e=>{try{let o=await(await fetch(e)).blob();return new Promise(n=>{let r=new FileReader;r.onloadend=()=>n(r.result),r.onerror=()=>n(null),r.readAsDataURL(o)})}catch{return null}},tt=Xt(null),ot=()=>{let e=Gt(tt);if(!e)throw new Error("usePromptInputAttachments must be used within a PromptInput");return e},pe=({className:e,accept:t,multiple:o,globalDrop:n,maxFiles:r,maxFileSize:i,onSubmit:l,children:c,...w})=>{let y=Ue(null),f=Ue(null),[p,M]=et([]),g=Ue(p);Be(()=>{g.current=p},[p]);let F=Y(()=>{y.current?.click()},[]),C=Y(s=>{let d=[...s];if(d.length===0)return;let x=k=>i?k.size<=i:!0,S=d.filter(x);M(k=>{let N=typeof r=="number"?Math.max(0,r-k.length):void 0,E=typeof N=="number"?S.slice(0,N):S;return[...k,...E.map(a=>({filename:a.name,id:Kt(),mediaType:a.type,type:"file",url:URL.createObjectURL(a)}))]})},[r,i]),B=Y(s=>{M(d=>{let x=d.find(S=>S.id===s);return x?.url&&URL.revokeObjectURL(x.url),d.filter(S=>S.id!==s)})},[]),R=Y(()=>{M(s=>{for(let d of s)d.url&&URL.revokeObjectURL(d.url);return[]})},[]);Be(()=>()=>{for(let s of g.current)s.url&&URL.revokeObjectURL(s.url)},[]);let m=Y(s=>{s.currentTarget.files&&C(s.currentTarget.files),s.currentTarget.value=""},[C]);Be(()=>{if(!n)return;let s=x=>{x.dataTransfer?.types?.includes("Files")&&x.preventDefault()},d=x=>{x.dataTransfer?.types?.includes("Files")&&x.preventDefault(),x.dataTransfer?.files&&x.dataTransfer.files.length>0&&C(x.dataTransfer.files)};return document.addEventListener("dragover",s),document.addEventListener("drop",d),()=>{document.removeEventListener("dragover",s),document.removeEventListener("drop",d)}},[C,n]);let h=Y(async s=>{s.preventDefault();let d=s.currentTarget,S=new FormData(d).get("message")||"";d.reset();let k=await Promise.all(p.map(async({id:N,...E})=>{if(E.url?.startsWith("blob:")){let a=await Zt(E.url);return{...E,url:a??E.url}}return E}));try{let N=l({files:k,text:S},s);N instanceof Promise&&await N,R()}catch{}},[p,l,R]),z=Yt(()=>({add:C,clear:R,files:p,openFileDialog:F,remove:B}),[p,C,B,R,F]);return nt(tt.Provider,{value:z,children:[X("input",{accept:t,"aria-label":"Upload files",className:"ww:hidden",multiple:o,onChange:m,ref:y,title:"Upload files",type:"file"}),X("form",{className:u("ww:flex ww:w-full ww:flex-col ww:rounded-lg ww:border ww:border-border ww:bg-background",e),onSubmit:h,ref:f,...w,children:c})]})};var me=({onChange:e,onKeyDown:t,className:o,placeholder:n="What would you like to know?",...r})=>{let i=ot(),[l,c]=et(!1),w=Y(f=>{if(t?.(f),!f.defaultPrevented){if(f.key==="Enter"){if(l||f.nativeEvent.isComposing||f.shiftKey)return;f.preventDefault();let{form:p}=f.currentTarget;if(p?.querySelector('button[type="submit"]')?.disabled)return;p?.requestSubmit()}if(f.key==="Backspace"&&f.currentTarget.value===""&&i.files.length>0){f.preventDefault();let p=i.files.at(-1);p&&i.remove(p.id)}}},[t,l,i]),y=Y(f=>{let p=f.clipboardData?.items;if(!p)return;let M=[];for(let g of p)if(g.kind==="file"){let F=g.getAsFile();F&&M.push(F)}M.length>0&&(f.preventDefault(),i.add(M))},[i]);return X("textarea",{className:u("ww:field-sizing-content ww:max-h-48 ww:min-h-16 ww:w-full ww:resize-none ww:border-0 ww:bg-transparent ww:px-3 ww:py-3 ww:text-sm ww:outline-none ww:placeholder:text-muted-foreground",o),name:"message",onCompositionEnd:()=>c(!1),onCompositionStart:()=>c(!0),onKeyDown:w,onPaste:y,placeholder:n,onChange:e,...r})},fe=({className:e,status:t,onStop:o,onClick:n,children:r,...i})=>{let l=t==="submitted"||t==="streaming",c=X(jt,{className:"ww:size-4"});t==="submitted"?c=X($t,{className:"ww:size-4 ww:animate-spin"}):t==="streaming"&&(c=X(Vt,{className:"ww:size-4"}));let w=Y(y=>{if(l&&o){y.preventDefault(),o();return}n?.(y)},[l,o,n]);return X(G,{"aria-label":l?"Stop":"Submit",className:u("ww:bg-foreground ww:text-background ww:hover:bg-foreground ww:rounded-full",e),onClick:w,size:"icon-sm",type:l&&o?"button":"submit",variant:"ghost",...i,children:r??c})},ge=({className:e,children:t,...o})=>{let n=ot();return n.files.length>0?nt(G,{className:u("ww:group ww:relative",e),onClick:()=>n.clear(),size:"icon-sm",type:"button",variant:"ghost","aria-label":"Remove all attachments",...o,children:[X("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:n.files.length}),X(Jt,{className:"ww:absolute ww:size-4 ww:opacity-0 ww:transition-opacity ww:group-hover:opacity-100"})]}):X(G,{className:u(e),onClick:()=>n.openFileDialog(),size:"icon-sm",type:"button",variant:"ghost",...o,children:t??X(qt,{className:"ww:size-4"})})};import{XIcon as eo}from"lucide-react";import{memo as to,useCallback as oo}from"react";import{jsx as oe}from"react/jsx-runtime";var rt=({className:e,...t})=>oe("div",{className:u("ww:flex ww:flex-col ww:gap-1 ww:px-3 ww:py-2",e),...t}),st=({className:e,...t})=>oe("li",{className:u("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}),it=({className:e,...t})=>oe("span",{className:u("ww:inline-block ww:size-2 ww:shrink-0 ww:rounded-full ww:border ww:border-muted-foreground/50",e),...t}),at=({className:e,...t})=>oe("span",{className:u("ww:line-clamp-1 ww:grow ww:break-words ww:text-muted-foreground",e),...t}),ut=({className:e,...t})=>oe("div",{className:u("ww:flex ww:shrink-0 ww:gap-1 ww:opacity-0 ww:transition-opacity ww:group-hover:opacity-100",e),...t}),lt=({className:e,...t})=>oe(G,{className:u("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});import{jsx as te,jsxs as Oe}from"react/jsx-runtime";var wt=to(({message:e,onRemove:t})=>{let o=oo(()=>t(e.id),[t,e.id]);return Oe(st,{children:[te(it,{}),te(at,{children:e.text||"(attachment)"}),te(ut,{children:te(lt,{"aria-label":"Remove from queue",onClick:o,children:te(eo,{className:"ww:size-3"})})})]})});wt.displayName="ChatQueueItem";function he({queuedMessages:e,onRemove:t,className:o}){return e.length===0?null:Oe(rt,{className:u("ww:border-t ww:border-border",o),children:[Oe("div",{className:"ww:text-[11px] ww:font-medium ww:text-muted-foreground ww:px-2",children:[e.length," queued"]}),te("ul",{children:e.map(n=>te(wt,{message:n,onRemove:t},n.id))})]})}import{FileIcon as no}from"lucide-react";import{jsx as se,jsxs as so}from"react/jsx-runtime";var ct=({files:e,className:t,...o})=>e.length===0?null:se("div",{className:u("ww:flex ww:flex-wrap ww:gap-1.5",t),...o,children:e.map((n,r)=>se(ro,{file:n},r))});function ro({file:e}){return e.mediaType?.startsWith("image/")&&e.url?se("img",{src:e.url,alt:e.filename??"attachment",className:"ww:h-16 ww:max-w-32 ww:rounded ww:object-cover"}):so("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:[se(no,{className:"ww:size-3 ww:shrink-0"}),se("span",{className:"ww:max-w-24 ww:truncate",children:e.filename??"file"})]})}import{jsx as dt}from"react/jsx-runtime";var Qe=({className:e,size:t=5,...o})=>dt("div",{className:u("ww:flex ww:items-center ww:gap-1",e),...o,children:[0,1,2].map(n=>dt("div",{className:"ww:rounded-full ww:bg-muted-foreground/60",style:{width:t,height:t,animation:"ww-pulse 1.4s ease-in-out infinite",animationDelay:`${n*.2}s`}},n))});import{cjk as io}from"@streamdown/cjk";import{code as ao}from"@streamdown/code";import{memo as uo}from"react";import{Streamdown as lo}from"streamdown";import{jsx as xe}from"react/jsx-runtime";var be=({className:e,from:t,children:o,...n})=>xe("div",{className:u("ww:group ww:flex ww:w-full",t==="user"?"is-user ww:ml-auto ww:max-w-[80%] ww:flex-col ww:items-end":"is-assistant ww:flex-col",e),...n,children:xe("div",{className:u("ww:flex ww:min-w-0 ww:flex-col ww:gap-2","ww:w-full"),children:o})}),ye=({children:e,className:t,...o})=>xe("div",{className:u("ww:flex ww:w-fit ww:min-w-0 ww:max-w-full ww:flex-col ww:gap-2 ww:overflow-hidden ww:text-base","ww:group-[.is-user]:ml-auto ww:group-[.is-user]:rounded-lg ww:group-[.is-user]:bg-user-bubble ww:group-[.is-user]:px-4 ww:group-[.is-user]:py-3 ww:group-[.is-user]:text-primary-foreground","ww:group-[.is-assistant]:text-foreground",t),...o,children:e}),wo={cjk:io,code:ao},Ce=uo(({className:e,...t})=>xe(lo,{className:u("ww:size-full ww:[&>*:first-child]:mt-0 ww:[&>*:last-child]:mb-0",e),plugins:wo,...t}),(e,t)=>e.children===t.children);Ce.displayName="MessageResponse";import{jsx as co}from"react/jsx-runtime";function pt({className:e,text:t,...o}){return t?co("pre",{className:u("ww:mb-2 ww:overflow-x-auto ww:whitespace-pre-wrap ww:break-words ww:text-xs ww:font-mono ww:text-muted-foreground",e),...o,children:t}):null}import{BracesIcon as po,CheckIcon as mo,ChevronDownIcon as fo,ChevronRightIcon as go,ClipboardCopyIcon as ho,ServerIcon as ir}from"lucide-react";import{createContext as xo,useCallback as bo,useContext as ft,useEffect as yo,useMemo as Co,useRef as vo,useState as ze}from"react";import{Fragment as mt,jsx as I,jsxs as ee}from"react/jsx-runtime";function To(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 o=JSON.stringify(e);if(o.length<=t)return o;let n=Object.entries(e),r=[],i=t-2;for(let[l,c]of n){if(i<=8)break;let w=l.length>4?`${l.slice(0,4)}\u2026`:l,y;typeof c=="string"?y=c.length>2?`'${c.slice(0,1)}\u2026`:`'${c}'`:Array.isArray(c)?y=`Array(${c.length})`:typeof c=="object"&&c!==null?y="{\u2026}":y=String(c);let f=`${w}\u2009${y}`;r.push(f),i-=f.length+3}return`{${r.join(", ")}}`}function Po({text:e,className:t}){let[o,n]=ze(!1),r=vo(null);yo(()=>()=>{r.current&&clearTimeout(r.current)},[]);let i=bo(async l=>{l.stopPropagation();try{await navigator.clipboard.writeText(e),n(!0),r.current&&clearTimeout(r.current),r.current=setTimeout(()=>n(!1),2e3)}catch{}},[e]);return I(G,{variant:"ghost",size:"sm",onClick:i,className:u("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:o?ee(mt,{children:[I(mo,{className:"ww:size-3.5"}),I("span",{children:"Copied"})]}):ee(mt,{children:[I(ho,{className:"ww:size-3.5"}),I("span",{children:"Copy"})]})})}function gt({data:e,label:t,className:o,...n}){let[r,i]=ze(!1),l=Co(()=>JSON.stringify(e,null,2),[e]),c=To(e);return ee("div",{className:u("ww:rounded-lg ww:bg-tool-card",o),...n,children:[ee("div",{className:"ww:flex ww:items-center ww:justify-between ww:px-3 ww:pt-2.5 ww:pb-1.5",children:[I("span",{className:"ww:text-xs ww:font-medium ww:text-muted-foreground",children:t}),I(Po,{text:l})]}),ee("button",{type:"button",onClick:()=>i(w=>!w),className:"ww:flex ww:w-full ww:items-start ww:gap-2 ww:px-3 ww:pb-3 ww:text-left",children:[I(go,{className:u("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?I("pre",{className:"ww:overflow-x-auto ww:text-xs ww:font-mono ww:text-foreground ww:whitespace-pre-wrap ww:break-all",children:I("code",{children:l})}):I("span",{className:"ww:truncate ww:text-xs ww:font-mono ww:text-foreground/80",children:c})]})]})}var _e=xo({open:!1,toggle:()=>{}});function ht({className:e,defaultOpen:t=!1,children:o,...n}){let[r,i]=ze(t);return I(_e.Provider,{value:{open:r,toggle:()=>i(l=>!l)},children:I("div",{className:u("ww:mb-4 ww:w-full",e),"data-state":r?"open":"closed",...n,children:o})})}function xt({className:e,title:t,state:o,...n}){let{open:r,toggle:i}=ft(_e),l=o==="input-available"||o==="input-streaming";return ee("button",{type:"button",onClick:i,className:u("ww:flex ww:w-full ww:items-center ww:justify-between ww:gap-3 ww:py-1.5",e),"aria-expanded":r,...n,children:[ee("div",{className:"ww:flex ww:min-w-0 ww:items-center ww:gap-2",children:[I(po,{className:"ww:size-4 ww:shrink-0 ww:text-muted-foreground"}),I("span",{className:"ww:truncate ww:text-sm ww:font-medium",children:t}),l&&I("span",{className:"ww:size-2 ww:shrink-0 ww:rounded-full ww:bg-primary ww:animate-pulse"})]}),I(fo,{className:u("ww:size-4 ww:shrink-0 ww:text-muted-foreground ww:transition-transform ww:duration-200",r&&"ww:rotate-180")})]})}function bt({className:e,children:t,...o}){let{open:n}=ft(_e);return I("div",{className:u("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:I("div",{className:"ww:min-h-0 ww:overflow-hidden",children:I("div",{className:u("ww:mt-2 ww:space-y-3 ww:rounded-lg ww:border ww:border-border ww:bg-background ww:p-3",e),...o,children:t})})})}function yt({className:e,input:t,...o}){return I(gt,{data:t,label:"Request",className:e,...o})}function Ct(e){if(typeof e!="object"||e===null)return;let t=e._meta;if(typeof t!="object"||t===null)return;let o=t.ui;if(!(typeof o!="object"||o===null))return o}function vt(e){let t=Ct(e)?.resourceUri;return typeof t=="string"?t:void 0}function Tt(e){return Ct(e)?.autoHeight===!0}function Pt({className:e,output:t,errorText:o,...n}){return t||o?o?ee("div",{className:u("ww:space-y-2",e),...n,children:[I("h4",{className:"ww:text-xs ww:font-medium ww:uppercase ww:tracking-wide ww:text-muted-foreground",children:"Error"}),I("div",{className:"ww:rounded-lg ww:bg-destructive/10 ww:p-3 ww:text-xs ww:text-destructive",children:o})]}):I(gt,{data:t,label:"Response",className:e,...n}):null}import{useCallback as Io,useEffect as It,useMemo as Mo,useRef as V,useState as Mt}from"react";import{jsx as Lo}from"react/jsx-runtime";var So="/api/mcp/resource",ko=500,Ro=0,Eo="2026-01-26",Ao=300,No=3e3,We=3;function je({resourceUri:e,toolInput:t,toolResult:o,resourceEndpoint:n=So,isDark:r=!1,className:i,autoHeight:l=!1,onOpenLink:c,onFollowUp:w,onCallTool:y,onDisplayModeChange:f}){let p=V(null),M=V(t),g=V(o),F=V({width:0,height:0}),C=V(null),B=V(!1),R=V(0),m=V("inline"),[h,z]=Mt(Ro),[s,d]=Mt(void 0),x=V(c),S=V(w),k=V(y),N=V(f);M.current=t,g.current=o,x.current=c,S.current=w,k.current=y,N.current=f;let E=Io(b=>l?Math.max(b,0):Math.min(Math.max(b,50),ko),[l]),a=Mo(()=>`${n}?uri=${encodeURIComponent(e)}`,[n,e]),T=V(r);return T.current=r,It(()=>{if(!B.current)return;let b=p.current;b?.contentWindow&&b.contentWindow.postMessage({jsonrpc:"2.0",method:"ui/notifications/host-context-changed",params:{theme:r?"dark":"light"}},"*")},[r]),It(()=>{let b=p.current;if(!b)return;let v=!1,_=!1,L=(...P)=>console.log("[McpAppFrame]",...P);L("effect mounted, waiting for handshake");let W=setTimeout(()=>{if(v||_)return;if(R.current>=We){L("handshake failed after",We,"retries, giving up");return}R.current+=1,L("handshake timeout, reloading iframe (retry",R.current,"of",We,")");let P=new URL(b.src);P.searchParams.set("_retry",String(R.current)),b.src=P.toString()},No),j=P=>{L("\u2192 send",P.method??`response:${P.id}`,P),b.contentWindow?.postMessage(P,"*")},D=P=>{if(v||P.source!==b.contentWindow)return;let A=P.data;if(console.log("data",A),!A||typeof A!="object"||A.jsonrpc!=="2.0")return;let $=A.method,Q=A.id;if(L("\u2190 recv",$??`response:${Q}`,A),$==="ui/initialize"&&Q!=null){_=!0,clearTimeout(W),L("handshake started"),j({jsonrpc:"2.0",id:Q,result:{protocolVersion:A.params?.protocolVersion??Eo,hostInfo:{name:"WaniWani Chat",version:"1.0.0"},hostCapabilities:{openLinks:{},message:{},tools:{}},hostContext:{theme:T.current?"dark":"light",displayMode:m.current}}});return}if($==="ui/notifications/initialized"){L("handshake complete, sending tool data"),B.current=!0;let U=M.current,H=g.current;j({jsonrpc:"2.0",method:"ui/notifications/tool-input",params:{arguments:U}});let q=H.content??[{type:"text",text:JSON.stringify(H)}];j({jsonrpc:"2.0",method:"ui/notifications/tool-result",params:{content:q,structuredContent:H.structuredContent}});return}if($==="ui/notifications/size-changed"){let U=A.params,H=typeof U?.height=="number"?U.height:void 0,q=typeof U?.width=="number"?U.width:void 0,Z=F.current,He=H!==void 0&&H!==Z.height,Fe=q!==void 0&&q!==Z.width;if(L("size-changed",{newHeight:H,newWidth:q,lastHeight:Z.height,lastWidth:Z.width,heightChanged:He,widthChanged:Fe}),!He&&!Fe)return;if(He&&H!==void 0){Z.height=H;let De=E(H),Ye=b.getBoundingClientRect().height;if(C.current&&(C.current.cancel(),C.current=null),z(De),b.animate&&Math.abs(Ye-De)>2){let ue=b.animate([{height:`${Ye}px`},{height:`${De}px`}],{duration:Ao,easing:"ease-out",fill:"forwards"});C.current=ue,ue.onfinish=()=>{C.current===ue&&(ue.cancel(),C.current=null)}}}Fe&&l&&q!==void 0&&(Z.width=q,d(q));return}if($==="ui/open-link"&&Q!=null){let U=A.params?.url;typeof U=="string"&&(x.current?x.current(U):window.open(U,"_blank","noopener,noreferrer")),j({jsonrpc:"2.0",id:Q,result:{}});return}if($==="ui/message"&&Q!=null){S.current&&A.params&&S.current(A.params),j({jsonrpc:"2.0",id:Q,result:{}});return}if($==="tools/call"&&Q!=null){L("tools/call",A.params?.name,A.params?.arguments);let U=k.current;if(!U){j({jsonrpc:"2.0",id:Q,error:{code:-32601,message:"tools/call not supported"}});return}U({name:A.params?.name,arguments:A.params?.arguments??{}}).then(H=>{j({jsonrpc:"2.0",id:Q,result:H});let q=H.content?.map(Z=>Z.text??"").join("").trim();q&&S.current&&S.current({role:"user",content:[{type:"text",text:q}]})}).catch(H=>{let q=H instanceof Error?H.message:"Tool call failed";j({jsonrpc:"2.0",id:Q,error:{code:-32e3,message:q}})});return}if($==="ui/request-display-mode"&&Q!=null){let U=A.params?.mode,H=U==="fullscreen"||U==="inline"||U==="pip"?U:"inline";m.current=H,j({jsonrpc:"2.0",id:Q,result:{mode:H}}),j({jsonrpc:"2.0",method:"ui/notifications/host-context-changed",params:{displayMode:H}}),N.current?.(H);return}if($==="ui/resource-teardown"&&Q!=null){j({jsonrpc:"2.0",id:Q,result:{}});return}$==="ping"&&Q!=null&&j({jsonrpc:"2.0",id:Q,result:{}})};return window.addEventListener("message",D),()=>{L("effect cleanup (disposed)"),v=!0,clearTimeout(W),window.removeEventListener("message",D)}},[l,E]),Lo("iframe",{ref:p,src:a,sandbox:"allow-scripts allow-forms allow-same-origin",className:u("ww:rounded-md ww:border ww:border-border",i),style:{height:h,minWidth:s?`min(${s}px, 100%)`:void 0,width:"100%",border:"none",colorScheme:"auto"},title:"MCP App"})}import{Component as Ho}from"react";import{jsx as St,jsxs as Fo}from"react/jsx-runtime";var ve=class extends Ho{state={hasError:!1};static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(t){console.warn("[WaniWani] Widget failed to render:",t.message)}render(){return this.state.hasError?Fo("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:[St("span",{children:"Widget failed to load"}),St("button",{type:"button",onClick:()=>this.setState({hasError:!1}),className:"ww:text-xs ww:font-medium ww:text-primary ww:hover:underline",children:"Retry"})]}):this.props.children}};import{Fragment as Bo,jsx as O,jsxs as ne}from"react/jsx-runtime";function Do(e){return e.replace(/[-_]/g," ").replace(/^\w/,t=>t.toUpperCase())}function Te({messages:e,status:t,welcomeMessage:o,resourceEndpoint:n,isDark:r,onFollowUp:i,onCallTool:l,onWidgetDisplayModeChange:c,fullscreenToolCallId:w}){let y=t==="submitted"||t==="streaming",f=e[e.length-1],p=e.length>0,M=y&&(!p||f.role==="user");return ne(Bo,{children:[o&&!w&&O(be,{from:"assistant",children:O(ye,{children:O(Ce,{children:o})})}),e.map(g=>{let F=g.parts.filter(s=>s.type==="text"),C=g.parts.filter(s=>s.type==="reasoning"),B=g.parts.filter(s=>s.type==="file"),R=g.parts.filter(s=>"toolCallId"in s),m=g===f&&g.role==="assistant",h=F.length>0,z=w&&R.some(s=>s.toolCallId===w);return w&&!z?null:ne(be,{from:g.role,children:[C.map((s,d)=>O("div",{style:w?{display:"none"}:void 0,children:O(pt,{text:s.text})},`reasoning-${g.id}-${d}`)),R.map(s=>{let d="output"in s?s.output:void 0,x=d!==void 0?vt(d):void 0,S=d!==void 0?Tt(d):!1,k=s.toolCallId===w,N=w!=null&&!k;return ne("div",{style:N?{display:"none"}:k?{height:"100%"}:void 0,children:[O("div",{style:k?{display:"none"}:void 0,children:ne(ht,{defaultOpen:s.state==="output-available",children:[O(xt,{title:s.title??Do(s.toolName),state:s.state}),ne(bt,{children:[O(yt,{input:s.input}),d!==void 0&&O(Pt,{output:d,errorText:"errorText"in s?s.errorText:void 0})]})]})}),x&&d!==void 0&&O(ve,{children:O(je,{resourceUri:x,toolInput:s.input??{},toolResult:{content:d.content,structuredContent:d.structuredContent},resourceEndpoint:n,isDark:r,autoHeight:S,onFollowUp:i,onCallTool:l,onDisplayModeChange:c?E=>c(E,{toolCallId:s.toolCallId,resourceUri:x,toolInput:s.input??{},toolResult:{content:d.content,structuredContent:d.structuredContent},autoHeight:S}):void 0})})]},s.toolCallId)}),O("div",{style:w?{display:"none"}:void 0,children:ne(ye,{children:[B.length>0&&O(ct,{files:B}),h?F.map((s,d)=>O(Ce,{children:s.type==="text"?s.text:""},`${g.id}-${d}`)):m&&y&&O(Qe,{})]})})]},g.id)}),M&&!w&&O(be,{from:"assistant",children:O(ye,{children:O(Qe,{})})})]})}import{jsx as Pe}from"react/jsx-runtime";function Ie({suggestions:e,isLoading:t,onSelect:o,className:n,...r}){return e.length===0&&!t?null:Pe("div",{className:u("ww:px-4 ww:py-2",n),...r,children:Pe("div",{className:"ww:mx-auto ww:w-full ww:max-w-3xl ww:flex ww:flex-wrap ww:gap-2",children:t?[0,1,2].map(i=>Pe("div",{className:"ww:h-7 ww:rounded-full ww:bg-accent ww:animate-pulse",style:{width:`${60+i*20}px`}},i)):e.map((i,l)=>Pe("button",{type:"button",onClick:()=>o(i),className:u("ww:rounded-full ww:border ww:border-border ww:bg-background ww:px-3 ww:py-1 ww:text-xs","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:`${l*50}ms`},children:i},i))})})}import{useCallback as Uo,useRef as Oo}from"react";function Me(e){let t=Oo(e);return t.current=e,Uo(async o=>{let{api:n,headers:r,onCallTool:i}=t.current;if(i)return i(o);let l=`${n??"https://app.waniwani.ai/api/chat"}/tool`,c=await fetch(l,{method:"POST",headers:{"Content-Type":"application/json",...r},body:JSON.stringify(o)});if(!c.ok)throw new Error(`Tool call failed: ${c.status} ${c.statusText}`);return c.json()},[])}import{useChat as Qo}from"@ai-sdk/react";import{DefaultChatTransport as zo}from"ai";import{nanoid as _o}from"nanoid";import{useCallback as re,useEffect as $e,useRef as Se,useState as kt}from"react";var Ve="waniwani-chat-session-id",Wo="x-session-id";function qe(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}function jo(){if(!(typeof window>"u"))try{return qe(window.sessionStorage.getItem(Ve))}catch{return}}function $o(e){if(!(typeof window>"u"))try{window.sessionStorage.setItem(Ve,e)}catch{}}function qo(){if(!(typeof window>"u"))try{window.sessionStorage.removeItem(Ve)}catch{}}function ke(e){let{api:t="https://app.waniwani.ai/api/chat",headers:o,body:n,onMessageSent:r,onResponseReceived:i}=e,l=Se(o),c=Se(n),w=Se(void 0),y=re(()=>{if(w.current)return w.current;let a=jo();return a&&(w.current=a),a},[]),f=re(a=>{let T=qe(a);T&&w.current!==T&&(w.current=T,$o(T))},[]),p=re(()=>{w.current=void 0,qo()},[]);$e(()=>{l.current=o},[o]),$e(()=>{c.current=n},[n]);let M=Se(new zo({api:t,headers:()=>({...l.current}),body:()=>{let a={...c.current??{}},T=Object.hasOwn(a,"sessionId"),b=qe(a.sessionId);if(b)return f(b),a.sessionId=b,a;if(T)return p(),delete a.sessionId,a;let v=y();return v&&(a.sessionId=v),a},fetch:async(a,T)=>{let b=await fetch(a,T);return f(b.headers.get(Wo)),b}})),{messages:g,sendMessage:F,status:C}=Qo({transport:M.current,onFinish(){i?.()},onError(a){console.warn("[WaniWani] Chat error:",a.message)}}),[B,R]=kt(""),[m,h]=kt([]),z=C==="submitted"||C==="streaming",s=re(a=>{h(T=>T.filter(b=>b.id!==a))},[]),d=z&&m.length>0,x=re(a=>{let T=!!a.text?.trim(),b=!!a.files?.length;if(T||b){if(z){if(m.length>0)return;h(v=>[...v,{id:_o(),text:a.text||"",files:a.files??[]}]),R("");return}F({text:a.text||"",files:a.files}),r?.(a.text||""),R("")}},[F,r,z,m.length]);$e(()=>{if(C!=="ready"||m.length===0)return;let[a,...T]=m;h(T),F({text:a.text,files:a.files.length>0?a.files:void 0}),r?.(a.text)},[C,F,r,m]);let S=re(a=>{R(a.target.value)},[]),k=g[g.length-1],N=g.length>0,E=z&&(!N||k.role==="user");return{messages:g,status:C,text:B,setText:R,handleSubmit:x,handleTextChange:S,isLoading:z,showLoaderBubble:E,lastMessage:k,hasMessages:N,sendMessage:F,queuedMessages:m,queueFull:d,removeQueuedMessage:s}}import{useCallback as Vo,useEffect as Rt,useRef as Jo,useState as Ko}from"react";function Xo(e){for(let t of e.parts){let o=t;if(o.type==="data"||o.type==="data-suggestions"){let n=o.data;if(n&&Array.isArray(n.suggestions))return n.suggestions}}return null}function Et(e){return typeof e=="object"&&e!==null&&"initial"in e}function Re(e){let{messages:t,status:o,config:n}=e,[r,i]=Ko((Et(n)&&n.initial?n.initial:[])??[]),l=Jo(o),c=n===!0||Et(n)&&n.dynamic!==!1,w=Vo(()=>{i([])},[]),y=t[t.length-1];return Rt(()=>{y?.role==="user"&&w()},[y,w]),Rt(()=>{let f=l.current;if(l.current=o,f==="streaming"&&o==="ready"&&c){let p=[...t].reverse().find(g=>g.role==="assistant");if(!p)return;console.log("[WaniWani] Assistant parts:",p.parts);let M=Xo(p);console.log("[WaniWani] Extracted suggestions:",M),M&&i(M)}},[o,c,t]),{suggestions:r,isLoading:!1,clear:w}}import{useEffect as Go,useRef as Yo,useState as Zo}from"react";var en=50,tn=30,on=2e3,At=500;function Ee(e,t=!0){let[o,n]=Zo(""),r=Yo(void 0);return Go(()=>{if(!t){n("");return}let i=0,l=!1,c=!1,w=()=>{c||(l?(i--,n(e.slice(0,i)),i<=0?(l=!1,r.current=setTimeout(w,At)):r.current=setTimeout(w,tn)):(i++,n(e.slice(0,i)),i>=e.length?(l=!0,r.current=setTimeout(w,on)):r.current=setTimeout(w,en)))};return r.current=setTimeout(w,At),()=>{c=!0,clearTimeout(r.current)}},[e,t]),o}var Nt={primaryColor:"#6366f1",primaryForeground:"#1f2937",backgroundColor:"#ffffff",textColor:"#1f2937",mutedColor:"#6b7280",borderColor:"#e5e7eb",assistantBubbleColor:"#f3f4f6",userBubbleColor:"#f4f4f4",inputBackgroundColor:"#f9fafb",borderRadius:16,messageBorderRadius:12,fontFamily:"system-ui, -apple-system, 'Segoe UI', sans-serif",headerBackgroundColor:"#ffffff",headerTextColor:"#1f2937",statusColor:"#22c55e",toolCardColor:"#f4f4f5"},nn={backgroundColor:"#212121",headerBackgroundColor:"#1e1e1e",headerTextColor:"#ececec",textColor:"#ececec",primaryForeground:"#ffffff",mutedColor:"#8e8ea0",borderColor:"#444444",assistantBubbleColor:"#2f2f2f",userBubbleColor:"#303030",inputBackgroundColor:"#2f2f2f",primaryColor:"#6366f1",statusColor:"#22c55e",toolCardColor:"#262626"},rn={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"],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"]};function ie(e){return{...Nt,...e}}function Ae(e){let t=e.backgroundColor.replace("#",""),o=parseInt(t.substring(0,2),16),n=parseInt(t.substring(2,4),16),r=parseInt(t.substring(4,6),16);return(o*299+n*587+r*114)/1e3<128}function ae(e){let t={};for(let[o,n]of Object.entries(rn)){let r=e[o],i=typeof r=="number"?`${r}px`:String(r);for(let l of n)t[l]=i}return t}import{jsx as K,jsxs as Le}from"react/jsx-runtime";var Ke=sn(function(t,o){let{theme:n,title:r="Assistant",width:i=600,expandedWidth:l,expandedHeight:c=400,allowAttachments:w=!1,welcomeMessage:y,placeholder:f="Ask me anything...",triggerEvent:p="triggerDemoRequest",resourceEndpoint:M,api:g}=t,F=l??Math.round((typeof i=="number"?i:600)*1.2),C=M??(g?`${g}/resource`:void 0),B=ie(n),R=ae(B),m=Ae(B),h=ke(t),z=Me(t),s=Re({messages:h.messages,status:h.status,config:t.suggestions}),d=Ne(D=>{let P=D.content.map(A=>A.text??"").join("").trim();P&&h.handleSubmit({text:P,files:[]})},[h.handleSubmit]),x=Ne(D=>{s.clear(),h.handleSubmit({text:D,files:[]})},[s.clear,h.handleSubmit]),S=Ee(f,!h.text),[k,N]=Je(!1),[E,a]=Je(!1),[T,b]=Je(null),v=Ht(null),_=Ht(void 0),L=Ne(()=>{let D=v.current;if(!D)return;D.scrollIntoView({behavior:"smooth",block:"center"});let P=D.querySelector("textarea");P&&setTimeout(()=>P.focus(),300),N(!0),a(!0),clearTimeout(_.current),_.current=setTimeout(()=>a(!1),2e3)},[]);an(o,()=>({sendMessage:D=>{h.handleSubmit({text:D,files:[]}),L()},focus:L}),[h.handleSubmit,L]),Lt(()=>{if(!p)return;let D=P=>{let A=P.detail,$=typeof A?.message=="string"?A.message:void 0;$&&h.handleSubmit({text:$,files:[]}),L()};return window.addEventListener(p,D),()=>window.removeEventListener(p,D)},[p,h.handleSubmit,L]);let W=k||T!==null;Lt(()=>{if(!k)return;let D=P=>{v.current&&!v.current.contains(P.target)&&N(!1)};return document.addEventListener("mousedown",D),()=>document.removeEventListener("mousedown",D)},[k]);let j=Ne(()=>{N(!0)},[]);return Le("div",{ref:v,style:{...R,width:W?F:i,transition:"width 0.4s cubic-bezier(0.16, 1, 0.3, 1)"},"data-waniwani-chat":"","data-waniwani-layout":"bar",...m?{"data-waniwani-dark":""}:{},className:"ww:flex ww:flex-col ww:font-[family-name:var(--ww-font)] ww:text-foreground",children:[Le("div",{style:{overflow:"hidden",backgroundColor:B.backgroundColor,borderRadius:"var(--ww-radius) var(--ww-radius) 0 0",maxHeight:W?c+200:0,opacity:W?1:0,transform:W?"scaleX(1)":"scaleX(0.88)",transformOrigin:"center bottom",transition:"max-height 0.4s cubic-bezier(0.16, 1, 0.3, 1), opacity 0.25s ease-out, transform 0.4s cubic-bezier(0.16, 1, 0.3, 1)"},children:[K("div",{className:"ww:shrink-0 ww:flex ww:items-center ww:px-6 ww:py-3",style:{backgroundColor:B.headerBackgroundColor,color:B.headerTextColor},children:K("div",{className:"ww:text-sm ww:font-semibold ww:truncate",children:r})}),Le(we,{className:"ww:flex-1",style:{height:c},children:[K(ce,{children:K(Te,{messages:h.messages,status:h.status,welcomeMessage:y,resourceEndpoint:C,isDark:m,onFollowUp:d,onCallTool:z,fullscreenToolCallId:T,onWidgetDisplayModeChange:(D,P)=>{b(D==="fullscreen"?P.toolCallId:null)}})}),!T&&K(de,{})]}),!T&&K(Ie,{suggestions:s.suggestions,isLoading:s.isLoading,onSelect:x}),!T&&K(he,{queuedMessages:h.queuedMessages,onRemove:h.removeQueuedMessage})]}),K("div",{style:{backgroundColor:W?B.backgroundColor:"transparent",borderRadius:W?"0 0 var(--ww-radius) var(--ww-radius)":void 0,boxShadow:W?"0 8px 24px rgba(0,0,0,0.1)":"none",transition:"background-color 0.2s ease, border-radius 0.3s ease, box-shadow 0.35s ease, padding 0.3s ease",padding:W?"8px 16px 16px":"0"},children:K(pe,{onSubmit:h.handleSubmit,globalDrop:w,multiple:w,className:u("ww:rounded-2xl ww:border-border ww:bg-input ww:transition-all ww:duration-300",!W&&"ww:shadow-sm",E&&"ww:ring-2 ww:ring-blue-400/70 ww:ring-offset-2 ww:ring-offset-background"),children:Le("div",{className:"ww:flex ww:items-center ww:gap-1 ww:pl-4 ww:pr-3 ww:py-2.5",children:[w&&K(ge,{}),K(me,{onChange:h.handleTextChange,value:h.text,placeholder:S,onFocus:j,className:"ww:min-h-0 ww:py-1 ww:px-0"}),K(fe,{status:h.status,disabled:h.queueFull})]})})})]})});import{forwardRef as un,useCallback as Xe,useEffect as ln,useImperativeHandle as wn,useRef as Ft,useState as Dt}from"react";import{jsx as J,jsxs as Ge}from"react/jsx-runtime";var cn=un(function(t,o){let{theme:n,title:r="Assistant",width:i,height:l,className:c,allowAttachments:w=!1,welcomeMessage:y,placeholder:f="Ask me anything...",triggerEvent:p="triggerDemoRequest",resourceEndpoint:M,api:g}=t,F=M??(g?`${g}/resource`:void 0),C=ie(n),B=ae(C),R=Ae(C),m=ke(t),h=Me(t),z=Ee(f,!m.text),[s,d]=Dt(!1),[x,S]=Dt(null),k=Ft(null),N=Ft(void 0),E=Xe(()=>{let v=k.current;if(!v)return;v.scrollIntoView({behavior:"smooth",block:"center"});let _=v.querySelector("textarea");_&&setTimeout(()=>_.focus(),300),d(!0),clearTimeout(N.current),N.current=setTimeout(()=>d(!1),2e3)},[]),a=Re({messages:m.messages,status:m.status,config:t.suggestions}),T=Xe(v=>{let _=v.content.map(L=>L.text??"").join("").trim();_&&m.handleSubmit({text:_,files:[]})},[m.handleSubmit]),b=Xe(v=>{a.clear(),m.handleSubmit({text:v,files:[]})},[a.clear,m.handleSubmit]);return wn(o,()=>({sendMessage:v=>{m.handleSubmit({text:v,files:[]}),E()},focus:E}),[m.handleSubmit,E]),ln(()=>{if(!p)return;let v=_=>{let L=_.detail,W=typeof L?.message=="string"?L.message:void 0;W&&m.handleSubmit({text:W,files:[]}),E()};return window.addEventListener(p,v),()=>window.removeEventListener(p,v)},[p,m.handleSubmit,E]),Ge("div",{ref:k,style:{...B,width:i,height:l},"data-waniwani-chat":"","data-waniwani-layout":"card",...R?{"data-waniwani-dark":""}:{},className:u("ww:flex ww:flex-col ww:font-[family-name:var(--ww-font)] ww:text-foreground ww:bg-background ww:rounded-[var(--ww-radius)] ww:overflow-hidden",s&&"ww:ring-2 ww:ring-blue-400/70 ww:ring-offset-2 ww:ring-offset-background",c),children:[J("div",{className:"ww:shrink-0 ww:flex ww:items-center ww:px-6 ww:py-3",style:{backgroundColor:C.headerBackgroundColor,color:C.headerTextColor},children:J("div",{className:"ww:text-sm ww:font-semibold ww:truncate",children:r})}),Ge(we,{className:"ww:flex-1 ww:min-h-0 ww:bg-background",children:[J(ce,{children:J(Te,{messages:m.messages,status:m.status,welcomeMessage:y,resourceEndpoint:F,isDark:R,onFollowUp:T,onCallTool:h,fullscreenToolCallId:x,onWidgetDisplayModeChange:(v,_)=>{S(v==="fullscreen"?_.toolCallId:null)}})}),!x&&J(de,{})]}),!x&&J(Ie,{suggestions:a.suggestions,isLoading:a.isLoading,onSelect:b}),!x&&J(he,{queuedMessages:m.queuedMessages,onRemove:m.removeQueuedMessage}),!x&&J("div",{className:"ww:shrink-0 ww:px-4 ww:pb-8 ww:pt-2 ww:bg-background",children:J("div",{className:"ww:mx-auto ww:w-full ww:max-w-3xl",children:J(pe,{onSubmit:m.handleSubmit,globalDrop:w,multiple:w,className:"ww:rounded-2xl ww:border-border ww:bg-input",children:Ge("div",{className:"ww:flex ww:items-center ww:gap-1 ww:pl-4 ww:pr-3 ww:py-2.5",children:[w&&J(ge,{}),J(me,{onChange:m.handleTextChange,value:m.text,placeholder:z,className:"ww:min-h-0 ww:py-1 ww:px-0"}),J(fe,{status:m.status,disabled:m.queueFull})]})})})})]})});export{Ke as ChatBar,cn as ChatCard,Ke as ChatWidget,nn as DARK_THEME,Nt as DEFAULT_THEME,je as McpAppFrame,ie as mergeTheme,ae as themeToCSSProperties};
3
3
  //# sourceMappingURL=index.js.map