@runtypelabs/persona 4.24.0 → 4.25.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/approval-ui.d.cts +63 -0
- package/dist/approval-ui.d.ts +63 -0
- package/dist/artifacts-ui.d.cts +63 -0
- package/dist/artifacts-ui.d.ts +63 -0
- package/dist/codegen.cjs +1 -1
- package/dist/codegen.js +1 -1
- package/dist/context-mentions.d.cts +63 -0
- package/dist/context-mentions.d.ts +63 -0
- package/dist/event-stream-view.d.cts +63 -0
- package/dist/event-stream-view.d.ts +63 -0
- package/dist/forms-ui.d.cts +74 -0
- package/dist/forms-ui.d.ts +74 -0
- package/dist/index.cjs +42 -42
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +75 -1
- package/dist/index.d.ts +75 -1
- package/dist/index.global.js +27 -27
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +42 -42
- package/dist/index.js.map +1 -1
- package/dist/session-reconnect.d.cts +63 -0
- package/dist/session-reconnect.d.ts +63 -0
- package/dist/smart-dom-reader.d.cts +63 -0
- package/dist/smart-dom-reader.d.ts +63 -0
- package/dist/theme-editor-preview.cjs +49 -49
- package/dist/theme-editor-preview.d.cts +63 -0
- package/dist/theme-editor-preview.d.ts +63 -0
- package/dist/theme-editor-preview.js +27 -27
- package/dist/theme-editor.d.cts +63 -0
- package/dist/theme-editor.d.ts +63 -0
- package/dist/voice-runtime-7DA7MJH4.js +1 -0
- package/dist/voice-runtime.cjs +1 -1
- package/dist/voice-runtime.d.cts +33 -0
- package/dist/voice-runtime.d.ts +33 -0
- package/dist/voice-runtime.js +1 -1
- package/package.json +1 -1
- package/src/index-core.ts +2 -0
- package/src/session.ts +30 -1
- package/src/session.voice.test.ts +72 -1
- package/src/types.ts +71 -0
- package/src/ui.ts +59 -0
- package/src/ui.voice-prewarm.test.ts +222 -0
- package/src/voice/runtype-voice-provider.ts +238 -27
- package/src/voice/voice.test.ts +272 -2
- package/dist/voice-runtime-EFR3R5ES.js +0 -1
|
@@ -1,22 +1,22 @@
|
|
|
1
|
-
"use strict";var PP=Object.create;var pp=Object.defineProperty;var LP=Object.getOwnPropertyDescriptor;var IP=Object.getOwnPropertyNames;var RP=Object.getPrototypeOf,HP=Object.prototype.hasOwnProperty;var be=(t,e)=>()=>(t&&(e=t(t=0)),e);var $n=(t,e)=>{for(var n in e)pp(t,n,{get:e[n],enumerable:!0})},dw=(t,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of IP(e))!HP.call(t,r)&&r!==n&&pp(t,r,{get:()=>e[r],enumerable:!(o=LP(e,r))||o.enumerable});return t};var pw=(t,e,n)=>(n=t!=null?PP(RP(t)):{},dw(e||!t||!t.__esModule?pp(n,"default",{value:t,enumerable:!0}):n,t)),WP=t=>dw(pp({},"__esModule",{value:!0}),t);var Ge,zn=be(()=>{"use strict";Ge=(t,e=24,n="currentColor",o=2)=>{if(!Array.isArray(t))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(e)),r.setAttribute("height",String(e)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",n),r.setAttribute("stroke-width",String(o)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),t.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],l=s[1];if(!l)return;let c=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(l).forEach(([p,u])=>{p!=="stroke"&&c.setAttribute(p,String(u))}),r.appendChild(c)}),r}});var v,Cw,F,Gt,je=be(()=>{"use strict";v=(t,e)=>{let n=document.createElement(t);return e&&(n.className=e),n},Cw=()=>document.createDocumentFragment(),F=(t,e={},...n)=>{let o=document.createElement(t);if(e.className&&(o.className=e.className),e.text!==void 0&&(o.textContent=e.text),e.attrs)for(let[s,a]of Object.entries(e.attrs))o.setAttribute(s,a);if(e.style){let s=o.style,a=e.style;for(let l of Object.keys(a)){let c=a[l];c!=null&&(s[l]=c)}}let r=n.filter(s=>s!=null);return r.length>0&&o.append(...r),o},Gt=(...t)=>t.filter(Boolean).join(" ")});var Qt,ro=be(()=>{"use strict";Qt=t=>{let{fallbackImport:e,resetOnSetLoader:n=!1}=t,o=null,r=null,s=null;return{setLoader:u=>{o=u,n&&(r=null,s=null)},load:()=>r?Promise.resolve(r):s||(s=(o??e)().then(m=>(r=m,m)).catch(m=>{throw s=null,m}),s),provide:u=>{r=u},getSync:()=>r}}});var ww={};$n(ww,{EXTRA_LUCIDE_ICONS:()=>FP});var ae,FP,xw=be(()=>{"use strict";ae=require("lucide"),FP={user:ae.User,mail:ae.Mail,phone:ae.Phone,calendar:ae.Calendar,clock:ae.Clock,building:ae.Building,"map-pin":ae.MapPin,lock:ae.Lock,key:ae.Key,"credit-card":ae.CreditCard,hash:ae.Hash,globe:ae.Globe,link:ae.Link,"circle-check":ae.CircleCheck,"circle-x":ae.CircleX,"triangle-alert":ae.TriangleAlert,info:ae.Info,ban:ae.Ban,shield:ae.Shield,house:ae.House,"pen-line":ae.PenLine,save:ae.Save,share:ae.Share,funnel:ae.Funnel,settings:ae.Settings,"rotate-cw":ae.RotateCw,"shopping-cart":ae.ShoppingCart,"shopping-bag":ae.ShoppingBag,package:ae.Package,truck:ae.Truck,tag:ae.Tag,gift:ae.Gift,receipt:ae.Receipt,wallet:ae.Wallet,store:ae.Store,"dollar-sign":ae.DollarSign,percent:ae.Percent,play:ae.Play,pause:ae.Pause,"volume-x":ae.VolumeX,camera:ae.Camera,image:ae.Image,film:ae.Film,headphones:ae.Headphones,"message-circle":ae.MessageCircle,bell:ae.Bell,heart:ae.Heart,"eye-off":ae.EyeOff,bookmark:ae.Bookmark,"calendar-days":ae.CalendarDays,timer:ae.Timer,folder:ae.Folder,"folder-open":ae.FolderOpen,files:ae.Files,"chart-column":ae.ChartColumn,sparkles:ae.Sparkles,zap:ae.Zap,sun:ae.Sun,moon:ae.Moon,flag:ae.Flag,lightbulb:ae.Lightbulb,monitor:ae.Monitor,smartphone:ae.Smartphone}});var VP,$P,Sg,hp,yp=be(()=>{"use strict";ro();({setLoader:VP,load:$P}=Qt({fallbackImport:()=>Promise.resolve().then(()=>(xw(),ww))})),Sg=VP,hp=$P});var me,zP,UP,bp,Ca,Ag,vp,qP,Sw,jP,Mg,KP,GP,ke,Zt=be(()=>{"use strict";zn();yp();me=require("lucide"),zP={activity:me.Activity,"arrow-down":me.ArrowDown,"arrow-up":me.ArrowUp,"arrow-up-right":me.ArrowUpRight,bot:me.Bot,"chevron-down":me.ChevronDown,"chevron-up":me.ChevronUp,"chevron-right":me.ChevronRight,"chevron-left":me.ChevronLeft,check:me.Check,clipboard:me.Clipboard,"clipboard-copy":me.ClipboardCopy,"code-xml":me.CodeXml,copy:me.Copy,file:me.File,"file-code":me.FileCode,"file-spreadsheet":me.FileSpreadsheet,"file-text":me.FileText,"image-plus":me.ImagePlus,loader:me.Loader,"loader-circle":me.LoaderCircle,mic:me.Mic,paperclip:me.Paperclip,quote:me.Quote,"refresh-cw":me.RefreshCw,search:me.Search,send:me.Send,"shield-alert":me.ShieldAlert,"shield-check":me.ShieldCheck,"shield-x":me.ShieldX,square:me.Square,"thumbs-down":me.ThumbsDown,"thumbs-up":me.ThumbsUp,upload:me.Upload,"volume-2":me.Volume2,x:me.X,"at-sign":me.AtSign,"arrow-left":me.ArrowLeft,"arrow-right":me.ArrowRight,"external-link":me.ExternalLink,ellipsis:me.Ellipsis,"ellipsis-vertical":me.EllipsisVertical,menu:me.Menu,"panel-left":me.PanelLeft,plus:me.Plus,minus:me.Minus,pencil:me.Pencil,trash:me.Trash,"trash-2":me.Trash2,download:me.Download,maximize:me.Maximize,minimize:me.Minimize,"message-square":me.MessageSquare,star:me.Star,eye:me.Eye,history:me.History},UP=["user","mail","phone","calendar","clock","building","map-pin","lock","key","credit-card","hash","globe","link","circle-check","circle-x","triangle-alert","info","ban","shield","house","pen-line","save","share","funnel","settings","rotate-cw","shopping-cart","shopping-bag","package","truck","tag","gift","receipt","wallet","store","dollar-sign","percent","play","pause","volume-x","camera","image","film","headphones","message-circle","bell","heart","eye-off","bookmark","calendar-days","timer","folder","folder-open","files","chart-column","sparkles","zap","sun","moon","flag","lightbulb","monitor","smartphone"],bp=new Map(Object.entries(zP)),Ca=new Set,Ag=!1,vp=new Set,qP=t=>{let e=[...vp];t&&vp.clear();for(let n of e)try{n()}catch{}},Sw=t=>Ag?()=>{}:(vp.add(t),()=>{vp.delete(t)}),jP=()=>{let t=0;for(let e of[...Ca]){let n=bp.get(e.name);if(!n)continue;Ca.delete(e),t++;let o=Ge(n,e.size,e.color,e.strokeWidth);if(o)for(e.el.removeAttribute("data-persona-icon-pending");o.firstChild;)e.el.appendChild(o.firstChild)}return t},Mg=!1,KP=()=>{hp().then(t=>{if(!Ag){for(let[e,n]of Object.entries(t.EXTRA_LUCIDE_ICONS))bp.has(e)||bp.set(e,n);Ag=!0,jP(),qP(!0)}}).catch(t=>{Mg=!0,console.warn("[Persona] Failed to load the icons-extra chunk",t)})},GP=(t,e,n)=>{let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(t)),o.setAttribute("height",String(t)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",e),o.setAttribute("stroke-width",String(n)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),o.setAttribute("data-persona-icon-pending","true"),o},ke=(t,e=24,n="currentColor",o=2)=>{let r=bp.get(t);if(r)return Ge(r,e,n,o);if(UP.includes(t)){Mg&&(Mg=!1);let s=GP(e,n,o);if(Ca.size>=500){let a=Ca.values().next().value;a&&Ca.delete(a)}return Ca.add({el:s,name:t,size:e,color:n,strokeWidth:o}),KP(),s}return console.warn(`Lucide icon "${t}" is not in the Persona registry. Register it via registerIcons(), or add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null}});var Lw={};$n(Lw,{DOMPurify:()=>Pw.default,Marked:()=>kw.Marked});var kw,Pw,Iw=be(()=>{"use strict";kw=require("marked"),Pw=pw(require("dompurify"),1)});var pO,tL,nL,kg,kp,Rw,Hw,xa,Pg,Ro,Si=be(()=>{"use strict";ro();({setLoader:pO,load:tL,provide:nL,getSync:kg}=Qt({fallbackImport:()=>Promise.resolve().then(()=>(Iw(),Lw))})),kp=new Set,Rw=()=>{let t=[...kp];kp.clear();for(let e of t)try{e()}catch{}},Hw=()=>{let t=kg();return t?Promise.resolve(t):tL().then(e=>(Rw(),e))},xa=t=>kg()?()=>{}:(kp.add(t),()=>{kp.delete(t)}),Pg=t=>{nL(t),Rw()},Ro=kg});var oL,Lg,Pp,fO,$r,Lp=be(()=>{"use strict";Si();oL=t=>{if(!t)return;let e={},n=t;if(n.heading){let o=n.heading;e.heading=(r,s,a)=>o({type:"heading",raw:a,depth:s,text:r,tokens:[]})}if(n.code){let o=n.code;e.code=(r,s,a)=>o({type:"code",raw:"",text:r,lang:s,escaped:a})}if(n.blockquote){let o=n.blockquote;e.blockquote=r=>o({type:"blockquote",raw:"",text:r,tokens:[]})}if(n.table){let o=n.table;e.table=(r,s)=>o({type:"table",raw:"",header:[],rows:[],align:[],headerHtml:r,bodyHtml:s})}if(n.link){let o=n.link;e.link=(r,s,a)=>o({type:"link",raw:"",href:r,title:s??null,text:a,tokens:[]})}if(n.image){let o=n.image;e.image=(r,s,a)=>o({type:"image",raw:"",href:r,title:s??null,text:a})}if(n.list){let o=n.list;e.list=(r,s,a)=>o({type:"list",raw:"",ordered:s,start:a,loose:!1,items:[],itemsHtml:r})}if(n.listitem){let o=n.listitem;e.listitem=(r,s,a)=>o({type:"list_item",raw:"",task:s,checked:a,loose:!1,text:r,tokens:[]})}if(n.paragraph){let o=n.paragraph;e.paragraph=r=>o({type:"paragraph",raw:"",text:r,tokens:[]})}if(n.codespan){let o=n.codespan;e.codespan=r=>o({type:"codespan",raw:"",text:r})}if(n.strong){let o=n.strong;e.strong=r=>o({type:"strong",raw:"",text:r,tokens:[]})}if(n.em){let o=n.em;e.em=r=>o({type:"em",raw:"",text:r,tokens:[]})}if(n.del){let o=n.del;e.del=r=>o({type:"del",raw:"",text:r,tokens:[]})}if(n.html){let o=n.html;e.html=r=>o({type:"html",raw:r,text:r})}if(n.text){let o=n.text;e.text=r=>o({type:"text",raw:r,text:r})}if(n.checkbox){let o=n.checkbox;e.checkbox=r=>o({checked:r})}return n.hr&&(e.hr=n.hr),n.br&&(e.br=n.br),e},Lg=t=>{let e=null;return n=>{let o=Ro();if(!o)return $r(n);if(!e){let{Marked:r}=o,s=t?.markedOptions;e=new r({gfm:s?.gfm??!0,breaks:s?.breaks??!0,pedantic:s?.pedantic,silent:s?.silent});let a=oL(t?.renderer);a&&e.use({renderer:a})}return e.parse(n)}},Pp=t=>t?Lg({markedOptions:t.options,renderer:t.renderer}):Lg(),fO=Lg(),$r=t=>t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")});var rL,sL,iL,Ip,Ig=be(()=>{"use strict";Lp();Si();rL={ALLOWED_TAGS:["h1","h2","h3","h4","h5","h6","p","br","hr","div","span","ul","ol","li","dl","dt","dd","strong","em","b","i","u","s","del","ins","mark","small","sub","sup","abbr","kbd","var","samp","code","a","img","blockquote","pre","details","summary","table","thead","tbody","tfoot","tr","th","td","caption","colgroup","col","input","label","select","option","textarea","button"],ALLOWED_ATTR:["href","src","alt","title","target","rel","loading","width","height","colspan","rowspan","scope","class","id","type","name","value","placeholder","disabled","checked","for","aria-label","aria-hidden","aria-expanded","role","tabindex","data-tv-form","data-message-id","data-persona-component-directive","data-preserve-animation","data-persona-instance"]},sL=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,iL=()=>{let t=null;return e=>{let n=Ro();if(!n)return $r(e);if(!t){let{DOMPurify:o}=n;t=o(typeof window<"u"?window:void 0),t.addHook("uponSanitizeAttribute",(r,s)=>{if(s.attrName==="src"||s.attrName==="href"){let a=s.attrValue;a.toLowerCase().startsWith("data:")&&!sL.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return t.sanitize(e,rL)}},Ip=t=>t===!1?null:typeof t=="function"?t:iL()});function qw(t){if(t.length===0)return"0:empty";let e=t.map(n=>[n.name,n.description??"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",n.origin??"",n.annotations?JSON.stringify(n.annotations):""].join("")).sort();return`${t.length}:${dL(e.join(""))}`}function zw(t,e){let n=3735928559^e,o=1103547991^e;for(let r=0;r<t.length;r++){let s=t.charCodeAt(r);n=Math.imul(n^s,2654435761),o=Math.imul(o^s,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(o^o>>>13,3266489909),o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&o)+(n>>>0)}function dL(t){let e=zw(t,0).toString(36),n=zw(t,2654435761).toString(36);return`${e}.${n}`}var zr,Hg,Uw,Rp,$w,pL,Sa,jw,Aa=be(()=>{"use strict";zr="webmcp:",Hg=new Map,Uw=t=>{Hg.clear();for(let e of t){let n=e.title?.trim();n&&Hg.set(e.name,n)}},Rp=t=>Hg.get(pL(t)),$w=null;pL=t=>t.startsWith(zr)?t.slice(zr.length):t,Sa=t=>t.startsWith(zr),jw=()=>$w?$w():import("@mcp-b/webmcp-polyfill")});var Kw,uL,Hp,Bp,mL,Wp,fL,gL,hL,Ko,yL,bL,vL,CL,Gw=be(()=>{"use strict";Kw="webmcp:",uL=t=>t.startsWith(Kw)?t.slice(Kw.length):t,Hp={warn(t,...e){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${t}`,...e)}},Bp=class{constructor(e,n){this.config=e;this.deps=n;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;this.confirmHandler=e.onConfirm??null,this.timeoutMs=3e4}setConfirmHandler(e){this.confirmHandler=e}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let e=this.getModelContext();if(!e)return[];let n;try{n=await e.getTools()}catch(r){return Hp.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}this.deps.recordToolDisplayTitles(n);let o=typeof location<"u"?location.origin:"";return n.filter(r=>this.passesClientAllowlist(r.name)).map(r=>{let s=fL(r.annotations);return{name:r.name,description:r.description,parametersSchema:gL(r.inputSchema),origin:"webmcp",...o?{pageOrigin:o}:{},...s?{annotations:s}:{},...s?.untrustedContentHint===!0?{untrustedContentHint:!0}:{}}})}async executeToolCall(e,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return Ko("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let b=typeof document<"u"&&!!document.modelContext;return Ko(b?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let s=uL(e),a;try{a=await r.getTools()}catch(b){let C=b instanceof Error?b.message:String(b);return Ko(`Failed to read WebMCP registry: ${C}`)}this.deps.recordToolDisplayTitles(a);let l=a.find(b=>b.name===s);if(!l)return Ko(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return Ko(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return Ko("Aborted by cancel()");let c=this.deps.getToolDisplayTitle(s),p={toolName:s,args:n,description:l.description,...c?{title:c}:{},reason:"gate"};if(!await this.requestConfirm(p))return Ko("User declined the tool call.");if(o?.aborted)return Ko("Aborted by cancel()");let u=new AbortController,m=!1,g=setTimeout(()=>{m=!0,u.abort()},this.timeoutMs),h=()=>u.abort();o&&(o.aborted?u.abort():o.addEventListener("abort",h,{once:!0}));try{let b=await r.executeTool(l,vL(n),{signal:u.signal});return hL(b)}catch(b){if(m)return Ko(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return Ko("Aborted by cancel()");let C=b instanceof Error?b.message:String(b);return Ko(C)}finally{clearTimeout(g),o&&o.removeEventListener("abort",h)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(await this.deps.loadPolyfill()).initializeWebMCPPolyfill(),this.installed=!0}catch(e){Hp.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",e),this.installed=!1}}getModelContext(){if(typeof document>"u")return null;let e=document.modelContext;if(!e||typeof e!="object")return null;let n=e;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,Hp.warn("document.modelContext is present but does not expose getTools()/executeTool(): WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):e}async requestConfirm(e){let n=this.confirmHandler??yL;try{return await n(e)}catch(o){return Hp.warn(`Confirm handler threw for WebMCP tool '${e.toolName}'; declining.`,o),!1}}passesClientAllowlist(e){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(o=>mL(e,o))}},mL=(t,e)=>{if(e==="*")return!0;let n=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(t)},Wp={type:"object",properties:{}},fL=t=>{if(!t||typeof t!="object")return;let e={...typeof t.readOnlyHint=="boolean"?{readOnlyHint:t.readOnlyHint}:{},...typeof t.untrustedContentHint=="boolean"?{untrustedContentHint:t.untrustedContentHint}:{}};return Object.keys(e).length>0?e:void 0},gL=t=>{if(t===void 0||t==="")return{...Wp};if(typeof t=="object")return t!==null&&!Array.isArray(t)?t:{...Wp};try{let e=JSON.parse(t);return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{...Wp}}catch{return{...Wp}}},hL=t=>{if(t==null)return{content:[{type:"text",text:""}]};let e;try{e=JSON.parse(t)}catch{return{content:[{type:"text",text:t}]}}return e!==null&&typeof e=="object"&&Array.isArray(e.content)?e:{content:[{type:"text",text:typeof e=="string"?e:CL(e)}]}},Ko=t=>({isError:!0,content:[{type:"text",text:t}]}),yL=async t=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let e=bL(t.args),n=`Allow the AI to call ${t.toolName}`+(e?`
|
|
1
|
+
"use strict";var NP=Object.create;var pp=Object.defineProperty;var FP=Object.getOwnPropertyDescriptor;var VP=Object.getOwnPropertyNames;var $P=Object.getPrototypeOf,zP=Object.prototype.hasOwnProperty;var be=(t,e)=>()=>(t&&(e=t(t=0)),e);var $n=(t,e)=>{for(var n in e)pp(t,n,{get:e[n],enumerable:!0})},vw=(t,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of VP(e))!zP.call(t,r)&&r!==n&&pp(t,r,{get:()=>e[r],enumerable:!(o=FP(e,r))||o.enumerable});return t};var Cw=(t,e,n)=>(n=t!=null?NP($P(t)):{},vw(e||!t||!t.__esModule?pp(n,"default",{value:t,enumerable:!0}):n,t)),UP=t=>vw(pp({},"__esModule",{value:!0}),t);var Ge,zn=be(()=>{"use strict";Ge=(t,e=24,n="currentColor",o=2)=>{if(!Array.isArray(t))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(e)),r.setAttribute("height",String(e)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",n),r.setAttribute("stroke-width",String(o)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),t.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],l=s[1];if(!l)return;let c=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(l).forEach(([p,u])=>{p!=="stroke"&&c.setAttribute(p,String(u))}),r.appendChild(c)}),r}});var v,Pw,F,Gt,je=be(()=>{"use strict";v=(t,e)=>{let n=document.createElement(t);return e&&(n.className=e),n},Pw=()=>document.createDocumentFragment(),F=(t,e={},...n)=>{let o=document.createElement(t);if(e.className&&(o.className=e.className),e.text!==void 0&&(o.textContent=e.text),e.attrs)for(let[s,a]of Object.entries(e.attrs))o.setAttribute(s,a);if(e.style){let s=o.style,a=e.style;for(let l of Object.keys(a)){let c=a[l];c!=null&&(s[l]=c)}}let r=n.filter(s=>s!=null);return r.length>0&&o.append(...r),o},Gt=(...t)=>t.filter(Boolean).join(" ")});var Qt,so=be(()=>{"use strict";Qt=t=>{let{fallbackImport:e,resetOnSetLoader:n=!1}=t,o=null,r=null,s=null;return{setLoader:u=>{o=u,n&&(r=null,s=null)},load:()=>r?Promise.resolve(r):s||(s=(o??e)().then(m=>(r=m,m)).catch(m=>{throw s=null,m}),s),provide:u=>{r=u},getSync:()=>r}}});var Lw={};$n(Lw,{EXTRA_LUCIDE_ICONS:()=>QP});var ae,QP,Iw=be(()=>{"use strict";ae=require("lucide"),QP={user:ae.User,mail:ae.Mail,phone:ae.Phone,calendar:ae.Calendar,clock:ae.Clock,building:ae.Building,"map-pin":ae.MapPin,lock:ae.Lock,key:ae.Key,"credit-card":ae.CreditCard,hash:ae.Hash,globe:ae.Globe,link:ae.Link,"circle-check":ae.CircleCheck,"circle-x":ae.CircleX,"triangle-alert":ae.TriangleAlert,info:ae.Info,ban:ae.Ban,shield:ae.Shield,house:ae.House,"pen-line":ae.PenLine,save:ae.Save,share:ae.Share,funnel:ae.Funnel,settings:ae.Settings,"rotate-cw":ae.RotateCw,"shopping-cart":ae.ShoppingCart,"shopping-bag":ae.ShoppingBag,package:ae.Package,truck:ae.Truck,tag:ae.Tag,gift:ae.Gift,receipt:ae.Receipt,wallet:ae.Wallet,store:ae.Store,"dollar-sign":ae.DollarSign,percent:ae.Percent,play:ae.Play,pause:ae.Pause,"volume-x":ae.VolumeX,camera:ae.Camera,image:ae.Image,film:ae.Film,headphones:ae.Headphones,"message-circle":ae.MessageCircle,bell:ae.Bell,heart:ae.Heart,"eye-off":ae.EyeOff,bookmark:ae.Bookmark,"calendar-days":ae.CalendarDays,timer:ae.Timer,folder:ae.Folder,"folder-open":ae.FolderOpen,files:ae.Files,"chart-column":ae.ChartColumn,sparkles:ae.Sparkles,zap:ae.Zap,sun:ae.Sun,moon:ae.Moon,flag:ae.Flag,lightbulb:ae.Lightbulb,monitor:ae.Monitor,smartphone:ae.Smartphone}});var XP,JP,Mg,hp,yp=be(()=>{"use strict";so();({setLoader:XP,load:JP}=Qt({fallbackImport:()=>Promise.resolve().then(()=>(Iw(),Lw))})),Mg=XP,hp=JP});var me,ZP,eL,bp,Ca,Tg,vp,tL,Hw,nL,Eg,oL,rL,ke,Zt=be(()=>{"use strict";zn();yp();me=require("lucide"),ZP={activity:me.Activity,"arrow-down":me.ArrowDown,"arrow-up":me.ArrowUp,"arrow-up-right":me.ArrowUpRight,bot:me.Bot,"chevron-down":me.ChevronDown,"chevron-up":me.ChevronUp,"chevron-right":me.ChevronRight,"chevron-left":me.ChevronLeft,check:me.Check,clipboard:me.Clipboard,"clipboard-copy":me.ClipboardCopy,"code-xml":me.CodeXml,copy:me.Copy,file:me.File,"file-code":me.FileCode,"file-spreadsheet":me.FileSpreadsheet,"file-text":me.FileText,"image-plus":me.ImagePlus,loader:me.Loader,"loader-circle":me.LoaderCircle,mic:me.Mic,paperclip:me.Paperclip,quote:me.Quote,"refresh-cw":me.RefreshCw,search:me.Search,send:me.Send,"shield-alert":me.ShieldAlert,"shield-check":me.ShieldCheck,"shield-x":me.ShieldX,square:me.Square,"thumbs-down":me.ThumbsDown,"thumbs-up":me.ThumbsUp,upload:me.Upload,"volume-2":me.Volume2,x:me.X,"at-sign":me.AtSign,"arrow-left":me.ArrowLeft,"arrow-right":me.ArrowRight,"external-link":me.ExternalLink,ellipsis:me.Ellipsis,"ellipsis-vertical":me.EllipsisVertical,menu:me.Menu,"panel-left":me.PanelLeft,plus:me.Plus,minus:me.Minus,pencil:me.Pencil,trash:me.Trash,"trash-2":me.Trash2,download:me.Download,maximize:me.Maximize,minimize:me.Minimize,"message-square":me.MessageSquare,star:me.Star,eye:me.Eye,history:me.History},eL=["user","mail","phone","calendar","clock","building","map-pin","lock","key","credit-card","hash","globe","link","circle-check","circle-x","triangle-alert","info","ban","shield","house","pen-line","save","share","funnel","settings","rotate-cw","shopping-cart","shopping-bag","package","truck","tag","gift","receipt","wallet","store","dollar-sign","percent","play","pause","volume-x","camera","image","film","headphones","message-circle","bell","heart","eye-off","bookmark","calendar-days","timer","folder","folder-open","files","chart-column","sparkles","zap","sun","moon","flag","lightbulb","monitor","smartphone"],bp=new Map(Object.entries(ZP)),Ca=new Set,Tg=!1,vp=new Set,tL=t=>{let e=[...vp];t&&vp.clear();for(let n of e)try{n()}catch{}},Hw=t=>Tg?()=>{}:(vp.add(t),()=>{vp.delete(t)}),nL=()=>{let t=0;for(let e of[...Ca]){let n=bp.get(e.name);if(!n)continue;Ca.delete(e),t++;let o=Ge(n,e.size,e.color,e.strokeWidth);if(o)for(e.el.removeAttribute("data-persona-icon-pending");o.firstChild;)e.el.appendChild(o.firstChild)}return t},Eg=!1,oL=()=>{hp().then(t=>{if(!Tg){for(let[e,n]of Object.entries(t.EXTRA_LUCIDE_ICONS))bp.has(e)||bp.set(e,n);Tg=!0,nL(),tL(!0)}}).catch(t=>{Eg=!0,console.warn("[Persona] Failed to load the icons-extra chunk",t)})},rL=(t,e,n)=>{let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(t)),o.setAttribute("height",String(t)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",e),o.setAttribute("stroke-width",String(n)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),o.setAttribute("data-persona-icon-pending","true"),o},ke=(t,e=24,n="currentColor",o=2)=>{let r=bp.get(t);if(r)return Ge(r,e,n,o);if(eL.includes(t)){Eg&&(Eg=!1);let s=rL(e,n,o);if(Ca.size>=500){let a=Ca.values().next().value;a&&Ca.delete(a)}return Ca.add({el:s,name:t,size:e,color:n,strokeWidth:o}),oL(),s}return console.warn(`Lucide icon "${t}" is not in the Persona registry. Register it via registerIcons(), or add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null}});var Nw={};$n(Nw,{DOMPurify:()=>_w.default,Marked:()=>Ow.Marked});var Ow,_w,Fw=be(()=>{"use strict";Ow=require("marked"),_w=Cw(require("dompurify"),1)});var EO,pL,uL,Lg,kp,Vw,$w,xa,Ig,Ho,Si=be(()=>{"use strict";so();({setLoader:EO,load:pL,provide:uL,getSync:Lg}=Qt({fallbackImport:()=>Promise.resolve().then(()=>(Fw(),Nw))})),kp=new Set,Vw=()=>{let t=[...kp];kp.clear();for(let e of t)try{e()}catch{}},$w=()=>{let t=Lg();return t?Promise.resolve(t):pL().then(e=>(Vw(),e))},xa=t=>Lg()?()=>{}:(kp.add(t),()=>{kp.delete(t)}),Ig=t=>{uL(t),Vw()},Ho=Lg});var mL,Hg,Pp,LO,$r,Lp=be(()=>{"use strict";Si();mL=t=>{if(!t)return;let e={},n=t;if(n.heading){let o=n.heading;e.heading=(r,s,a)=>o({type:"heading",raw:a,depth:s,text:r,tokens:[]})}if(n.code){let o=n.code;e.code=(r,s,a)=>o({type:"code",raw:"",text:r,lang:s,escaped:a})}if(n.blockquote){let o=n.blockquote;e.blockquote=r=>o({type:"blockquote",raw:"",text:r,tokens:[]})}if(n.table){let o=n.table;e.table=(r,s)=>o({type:"table",raw:"",header:[],rows:[],align:[],headerHtml:r,bodyHtml:s})}if(n.link){let o=n.link;e.link=(r,s,a)=>o({type:"link",raw:"",href:r,title:s??null,text:a,tokens:[]})}if(n.image){let o=n.image;e.image=(r,s,a)=>o({type:"image",raw:"",href:r,title:s??null,text:a})}if(n.list){let o=n.list;e.list=(r,s,a)=>o({type:"list",raw:"",ordered:s,start:a,loose:!1,items:[],itemsHtml:r})}if(n.listitem){let o=n.listitem;e.listitem=(r,s,a)=>o({type:"list_item",raw:"",task:s,checked:a,loose:!1,text:r,tokens:[]})}if(n.paragraph){let o=n.paragraph;e.paragraph=r=>o({type:"paragraph",raw:"",text:r,tokens:[]})}if(n.codespan){let o=n.codespan;e.codespan=r=>o({type:"codespan",raw:"",text:r})}if(n.strong){let o=n.strong;e.strong=r=>o({type:"strong",raw:"",text:r,tokens:[]})}if(n.em){let o=n.em;e.em=r=>o({type:"em",raw:"",text:r,tokens:[]})}if(n.del){let o=n.del;e.del=r=>o({type:"del",raw:"",text:r,tokens:[]})}if(n.html){let o=n.html;e.html=r=>o({type:"html",raw:r,text:r})}if(n.text){let o=n.text;e.text=r=>o({type:"text",raw:r,text:r})}if(n.checkbox){let o=n.checkbox;e.checkbox=r=>o({checked:r})}return n.hr&&(e.hr=n.hr),n.br&&(e.br=n.br),e},Hg=t=>{let e=null;return n=>{let o=Ho();if(!o)return $r(n);if(!e){let{Marked:r}=o,s=t?.markedOptions;e=new r({gfm:s?.gfm??!0,breaks:s?.breaks??!0,pedantic:s?.pedantic,silent:s?.silent});let a=mL(t?.renderer);a&&e.use({renderer:a})}return e.parse(n)}},Pp=t=>t?Hg({markedOptions:t.options,renderer:t.renderer}):Hg(),LO=Hg(),$r=t=>t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")});var fL,gL,hL,Ip,Rg=be(()=>{"use strict";Lp();Si();fL={ALLOWED_TAGS:["h1","h2","h3","h4","h5","h6","p","br","hr","div","span","ul","ol","li","dl","dt","dd","strong","em","b","i","u","s","del","ins","mark","small","sub","sup","abbr","kbd","var","samp","code","a","img","blockquote","pre","details","summary","table","thead","tbody","tfoot","tr","th","td","caption","colgroup","col","input","label","select","option","textarea","button"],ALLOWED_ATTR:["href","src","alt","title","target","rel","loading","width","height","colspan","rowspan","scope","class","id","type","name","value","placeholder","disabled","checked","for","aria-label","aria-hidden","aria-expanded","role","tabindex","data-tv-form","data-message-id","data-persona-component-directive","data-preserve-animation","data-persona-instance"]},gL=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,hL=()=>{let t=null;return e=>{let n=Ho();if(!n)return $r(e);if(!t){let{DOMPurify:o}=n;t=o(typeof window<"u"?window:void 0),t.addHook("uponSanitizeAttribute",(r,s)=>{if(s.attrName==="src"||s.attrName==="href"){let a=s.attrValue;a.toLowerCase().startsWith("data:")&&!gL.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return t.sanitize(e,fL)}},Ip=t=>t===!1?null:typeof t=="function"?t:hL()});function ex(t){if(t.length===0)return"0:empty";let e=t.map(n=>[n.name,n.description??"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",n.origin??"",n.annotations?JSON.stringify(n.annotations):""].join("")).sort();return`${t.length}:${CL(e.join(""))}`}function Jw(t,e){let n=3735928559^e,o=1103547991^e;for(let r=0;r<t.length;r++){let s=t.charCodeAt(r);n=Math.imul(n^s,2654435761),o=Math.imul(o^s,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(o^o>>>13,3266489909),o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&o)+(n>>>0)}function CL(t){let e=Jw(t,0).toString(36),n=Jw(t,2654435761).toString(36);return`${e}.${n}`}var zr,Bg,Zw,Hp,Xw,wL,Sa,tx,Aa=be(()=>{"use strict";zr="webmcp:",Bg=new Map,Zw=t=>{Bg.clear();for(let e of t){let n=e.title?.trim();n&&Bg.set(e.name,n)}},Hp=t=>Bg.get(wL(t)),Xw=null;wL=t=>t.startsWith(zr)?t.slice(zr.length):t,Sa=t=>t.startsWith(zr),tx=()=>Xw?Xw():import("@mcp-b/webmcp-polyfill")});var nx,xL,Rp,Bp,SL,Wp,AL,ML,TL,Ko,EL,kL,PL,LL,ox=be(()=>{"use strict";nx="webmcp:",xL=t=>t.startsWith(nx)?t.slice(nx.length):t,Rp={warn(t,...e){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${t}`,...e)}},Bp=class{constructor(e,n){this.config=e;this.deps=n;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;this.confirmHandler=e.onConfirm??null,this.timeoutMs=3e4}setConfirmHandler(e){this.confirmHandler=e}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let e=this.getModelContext();if(!e)return[];let n;try{n=await e.getTools()}catch(r){return Rp.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}this.deps.recordToolDisplayTitles(n);let o=typeof location<"u"?location.origin:"";return n.filter(r=>this.passesClientAllowlist(r.name)).map(r=>{let s=AL(r.annotations);return{name:r.name,description:r.description,parametersSchema:ML(r.inputSchema),origin:"webmcp",...o?{pageOrigin:o}:{},...s?{annotations:s}:{},...s?.untrustedContentHint===!0?{untrustedContentHint:!0}:{}}})}async executeToolCall(e,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return Ko("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let b=typeof document<"u"&&!!document.modelContext;return Ko(b?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let s=xL(e),a;try{a=await r.getTools()}catch(b){let C=b instanceof Error?b.message:String(b);return Ko(`Failed to read WebMCP registry: ${C}`)}this.deps.recordToolDisplayTitles(a);let l=a.find(b=>b.name===s);if(!l)return Ko(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return Ko(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return Ko("Aborted by cancel()");let c=this.deps.getToolDisplayTitle(s),p={toolName:s,args:n,description:l.description,...c?{title:c}:{},reason:"gate"};if(!await this.requestConfirm(p))return Ko("User declined the tool call.");if(o?.aborted)return Ko("Aborted by cancel()");let u=new AbortController,m=!1,g=setTimeout(()=>{m=!0,u.abort()},this.timeoutMs),h=()=>u.abort();o&&(o.aborted?u.abort():o.addEventListener("abort",h,{once:!0}));try{let b=await r.executeTool(l,PL(n),{signal:u.signal});return TL(b)}catch(b){if(m)return Ko(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return Ko("Aborted by cancel()");let C=b instanceof Error?b.message:String(b);return Ko(C)}finally{clearTimeout(g),o&&o.removeEventListener("abort",h)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(await this.deps.loadPolyfill()).initializeWebMCPPolyfill(),this.installed=!0}catch(e){Rp.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",e),this.installed=!1}}getModelContext(){if(typeof document>"u")return null;let e=document.modelContext;if(!e||typeof e!="object")return null;let n=e;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,Rp.warn("document.modelContext is present but does not expose getTools()/executeTool(): WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):e}async requestConfirm(e){let n=this.confirmHandler??EL;try{return await n(e)}catch(o){return Rp.warn(`Confirm handler threw for WebMCP tool '${e.toolName}'; declining.`,o),!1}}passesClientAllowlist(e){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(o=>SL(e,o))}},SL=(t,e)=>{if(e==="*")return!0;let n=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(t)},Wp={type:"object",properties:{}},AL=t=>{if(!t||typeof t!="object")return;let e={...typeof t.readOnlyHint=="boolean"?{readOnlyHint:t.readOnlyHint}:{},...typeof t.untrustedContentHint=="boolean"?{untrustedContentHint:t.untrustedContentHint}:{}};return Object.keys(e).length>0?e:void 0},ML=t=>{if(t===void 0||t==="")return{...Wp};if(typeof t=="object")return t!==null&&!Array.isArray(t)?t:{...Wp};try{let e=JSON.parse(t);return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{...Wp}}catch{return{...Wp}}},TL=t=>{if(t==null)return{content:[{type:"text",text:""}]};let e;try{e=JSON.parse(t)}catch{return{content:[{type:"text",text:t}]}}return e!==null&&typeof e=="object"&&Array.isArray(e.content)?e:{content:[{type:"text",text:typeof e=="string"?e:LL(e)}]}},Ko=t=>({isError:!0,content:[{type:"text",text:t}]}),EL=async t=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let e=kL(t.args),n=`Allow the AI to call ${t.toolName}`+(e?`
|
|
2
2
|
|
|
3
3
|
Arguments:
|
|
4
4
|
${e}`:"")+(t.description?`
|
|
5
5
|
|
|
6
|
-
${t.description}`:"");return window.confirm(n)},
|
|
7
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),mr=t=>{if(t===null)return"null";if(t===void 0)return"";if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);try{return JSON.stringify(t,null,2)}catch{return String(t)}},
|
|
6
|
+
${t.description}`:"");return window.confirm(n)},kL=t=>{if(t==null)return"";try{let e=JSON.stringify(t,null,2);return e.length>500?e.slice(0,500)+"\u2026":e}catch{return String(t)}},PL=t=>{if(t===void 0)return"{}";try{let e=JSON.stringify(t);return e===void 0?"{}":e}catch{return"{}"}},LL=t=>{if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}}});var rx={};$n(rx,{WebMcpBridge:()=>Bp});var sx=be(()=>{"use strict";ox()});var Ia,Mx,mr,uI,Tx,mI,fI,Ex,gI,kx,Vp,Kl,$p,Ug,zp,jl,hI,Gl,Px,Lx,Ix,Hx,Ts=be(()=>{"use strict";Ia=require("partial-json"),Mx=t=>t.replace(/\\n/g,`
|
|
7
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),mr=t=>{if(t===null)return"null";if(t===void 0)return"";if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);try{return JSON.stringify(t,null,2)}catch{return String(t)}},uI=t=>{let e=t.completedAt??Date.now(),n=t.startedAt??e,r=(t.durationMs!==void 0?t.durationMs:Math.max(0,e-n))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},Tx=t=>t.status==="complete"?uI(t):t.status==="pending"?"Waiting":"",mI=15e3,fI=1200,Ex=(t,e)=>{let n=e?.durationMs??mI,o=e?.chars??fI;return typeof t.durationMs=="number"?t.durationMs<n:(t.chunks??[]).join("").length<o},gI=t=>{let n=(typeof t.duration=="number"?t.duration:typeof t.durationMs=="number"?t.durationMs:Math.max(0,(t.completedAt??Date.now())-(t.startedAt??t.completedAt??Date.now())))/1e3;return n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`},kx=t=>t.status==="complete"?gI(t):"Using tool...",Vp=t=>{let e=t/1e3;return e<.1?"<0.1s":e>=10?`${Math.round(e)}s`:`${e.toFixed(1).replace(/\.0$/,"")}s`},Kl=t=>{let e=typeof t.duration=="number"?t.duration:typeof t.durationMs=="number"?t.durationMs:Math.max(0,(t.completedAt??Date.now())-(t.startedAt??t.completedAt??Date.now()));return Vp(e)},$p=t=>{let e=t.durationMs!==void 0?t.durationMs:Math.max(0,(t.completedAt??Date.now())-(t.startedAt??t.completedAt??Date.now()));return Vp(e)},Ug=(t,e,n)=>{if(!e)return n;let o=t.name?.trim()||"tool",r=Kl(t);return e.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},zp=(t,e)=>{let n=t.replace(/\{toolName\}/g,e),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=r.exec(n))!==null;)a.index>s&&jl(o,n.slice(s,a.index),[]),a[1]!==void 0?jl(o,a[1],["bold"]):a[2]!==void 0?jl(o,a[2],["italic"]):a[3]!==void 0&&jl(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&jl(o,n.slice(s),[]),o},jl=(t,e,n)=>{let o=e.split("{duration}");for(let r=0;r<o.length;r++)o[r]&&t.push({text:o[r],styles:n}),r<o.length-1&&t.push({text:"{duration}",styles:n,isDuration:!0})},hI=()=>{let t=null,e=0,n=o=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=o.match(r);if(s&&s[1])try{return s[1].replace(/\\n/g,`
|
|
8
8
|
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,l=o.match(a);if(l&&l[1])try{return l[1].replace(/\\n/g,`
|
|
9
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>t,processChunk:async o=>{if(o.length<=e)return t!==null?{text:t,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(t=s),e=o.length,t!==null?{text:t,raw:o}:null},close:async()=>{}}},Gl=t=>{try{let e=JSON.parse(t);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},
|
|
10
|
-
`)){let o=/^ {0,3}(`+)/.exec(n);o&&o[1].length>e&&(e=o[1].length)}return e}function Jl(t,e){let n="`".repeat(Math.max(3,
|
|
9
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>t,processChunk:async o=>{if(o.length<=e)return t!==null?{text:t,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(t=s),e=o.length,t!==null?{text:t,raw:o}:null},close:async()=>{}}},Gl=t=>{try{let e=JSON.parse(t);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},Px=()=>{let t={processChunk:e=>null,getExtractedText:()=>null};return t.__isPlainTextParser=!0,t},Lx=()=>{let t=hI();return{processChunk:async e=>{let n=e.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:t.processChunk(e)},getExtractedText:t.getExtractedText.bind(t),close:t.close?.bind(t)}},Ix=()=>{let t=null,e=0;return{getExtractedText:()=>t,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=e)return t!==null||t===""?{text:t||"",raw:n}:null;try{let r=(0,Ia.parse)(n,Ia.STR|Ia.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?t=typeof r.text=="string"?Mx(r.text):"":r.type==="init"&&r.form?t="":typeof r.text=="string"&&(t=Mx(r.text)))}catch{}return e=n.length,t!==null?{text:t,raw:n}:null},close:()=>{}}},Hx=()=>{let t=null;return{processChunk:e=>{if(!e.trim().startsWith("<"))return null;let o=e.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(t=o[1],{text:t,raw:e}):null},getExtractedText:()=>t}}});function PI(t){let e=0;for(let n of t.split(`
|
|
10
|
+
`)){let o=/^ {0,3}(`+)/.exec(n);o&&o[1].length>e&&(e=o[1].length)}return e}function Jl(t,e){let n="`".repeat(Math.max(3,PI(e)+1));return`${n}${t}
|
|
11
11
|
${e}
|
|
12
|
-
${n}`}function
|
|
12
|
+
${n}`}function LI(t,e,n){return e.includes("</document_content>")?Jl(t,e):`<document index="${n+1}">
|
|
13
13
|
<source>${t}</source>
|
|
14
14
|
<document_content>
|
|
15
15
|
${e}
|
|
16
16
|
</document_content>
|
|
17
|
-
</document>`}function Ux(t,e,n="fenced"){if(typeof n=="function")try{return n(t,e)}catch(o){return console.warn("[persona] contextMentions.llmFormat threw; falling back to the fenced format for this mention",o),Jl(t.label,t.text)}return n==="document"?CI(t.label,t.text,e):Jl(t.label,t.text)}var Kg=be(()=>{"use strict"});function Gp(t){return t instanceof gr}var gr,Zl=be(()=>{"use strict";gr=class extends Error{constructor(e,n,o){super(n),this.name="HistoryProviderError",this.code=e,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}}});var Ha,Xg=be(()=>{"use strict";Ha=class{constructor(e=24e3,n={}){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.startedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.started=!1;this.userPaused=!1;this.pendingBuffers=[];this.pendingSamples=0;this.remainder=null;this.sampleRate=e;let o=Math.max(0,n.prebufferMs??0);this.waterlineSamples=Math.round(e*o/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let n=typeof window<"u"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let o=n.AudioContext||n.webkitAudioContext;this.ctx=new o({sampleRate:this.sampleRate})}let e=this.ctx;return e.state==="suspended"&&!this.userPaused&&e.resume(),e}enqueue(e){if(e.length===0)return;let n=e;if(this.remainder){let r=new Uint8Array(this.remainder.length+e.length);r.set(this.remainder),r.set(e,this.remainder.length),n=r,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let o=this.pcmToFloat32(n);o.length!==0&&(this.buffering?(this.pendingBuffers.push(o),this.pendingSamples+=o.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(o))}markStreamEnd(){this.pendingBuffers.length>0&&this.releaseBuffer(),this.streamEnded=!0,this.checkFinished()}flush(){for(let e of this.activeSources)try{e.stop(),e.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.startedCallbacks=[],this.remainder=null,this.pendingBuffers=[],this.pendingSamples=0,this.buffering=this.waterlineSamples>0,this.started=!1}isPlaying(){return this.playing}onFinished(e){this.finishedCallbacks.push(e)}onStarted(e){this.startedCallbacks.push(e)}pause(){this.userPaused=!0,this.ctx&&this.ctx.state==="running"&&this.ctx.suspend()}resume(){this.userPaused=!1,this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume()}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}releaseBuffer(){this.buffering=!1;let e=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let n of e)this.scheduleSamples(n)}scheduleSamples(e){if(e.length===0)return;let n=this.ensureContext(),o=n.createBuffer(1,e.length,this.sampleRate);o.getChannelData(0).set(e);let r=n.createBufferSource();r.buffer=o,r.connect(n.destination);let s=n.currentTime;if(this.nextStartTime===0?this.nextStartTime=s:this.nextStartTime<s&&(this.nextStartTime=s,this.waterlineSamples>0&&(this.buffering=!0)),r.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(r),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let a=this.startedCallbacks.slice();this.startedCallbacks=[];for(let l of a)l()}r.onended=()=>{let a=this.activeSources.indexOf(r);a!==-1&&this.activeSources.splice(a,1),this.pendingCount--,this.checkFinished()}}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.pendingBuffers.length===0){this.playing=!1,this.streamEnded=!1;let e=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of e)n()}}pcmToFloat32(e){let n=Math.floor(e.length/2),o=new Float32Array(n),r=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let s=0;s<n;s++){let a=r.getInt16(s*2,!0);o[s]=a/32768}return o}}});function EI(t){return t.byteLength>=44&&new DataView(t).getUint32(0,!1)===TI?new Uint8Array(t,44):new Uint8Array(t)}function kI(t){let e=t.replace(/\/+$/,"");return/^wss?:\/\//i.test(e)?e:/^https?:\/\//i.test(e)?e.replace(/^http/i,"ws"):`${typeof window<"u"&&window.location?.protocol==="https:"?"wss:":"ws:"}//${e}`}var Gx,SI,AI,MI,TI,Wa,Jg=be(()=>{"use strict";Xg();Gx=16e3,SI=24e3,AI=4096,MI=4,TI=1380533830;Wa=class{constructor(e){this.config=e;this.type="runtype";this.ws=null;this.captureContext=null;this.levelCallbacks=[];this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){if(this.callLive)return;let e=this.config?.agentId,n=this.config?.clientToken,o=this.config?.host;if(!e)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!o)throw new Error("Runtype voice requires a host (or widget apiUrl)");let r=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let s=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:Gx,channelCount:1,echoCancellation:!0}});if(r!==this.callGeneration){s.getTracks().forEach(m=>m.stop());return}this.mediaStream=s;let a=window.AudioContext||window.webkitAudioContext,l=new a({sampleRate:Gx});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let c=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new Ha(SI);if(r!==this.callGeneration){c.destroy(),s.getTracks().forEach(m=>m.stop()),l.close().catch(()=>{});return}this.playback=c,c.onFinished(()=>{r===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let p=`${kI(o)}/ws/agents/${encodeURIComponent(e)}/voice`,u=new WebSocket(p,["runtype.bearer",n]);u.binaryType="arraybuffer",this.ws=u,u.onopen=()=>{r===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(l,s,u,r))},u.onmessage=m=>this.handleMessage(m,r),u.onerror=()=>{r===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},u.onclose=m=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(r===this.callGeneration){if(m.code!==1e3){let g=m.code?` (code ${m.code})`:"";this.emitError(new Error(`Voice connection closed${g}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(s){throw this.cleanup(),this.emitError(s),this.emitStatus("error"),s}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}onLevel(e){this.levelCallbacks.push(e)}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(e,n,o,r){let s=e.createMediaStreamSource(n);this.sourceNode=s;let a=e.createScriptProcessor(AI,1,1);this.processor=a,a.onaudioprocess=l=>{if(r!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let c=l.inputBuffer.getChannelData(0),p=new Int16Array(c.length),u=0;for(let m=0;m<c.length;m++){let g=Math.max(-1,Math.min(1,c[m]));u+=g*g,p[m]=g<0?g*32768:g*32767}if(o.send(p.buffer),this.levelCallbacks.length>0){let m=Math.sqrt(u/c.length),g=Math.max(0,Math.min(1,m*MI));for(let h of this.levelCallbacks)h(g)}},s.connect(a),a.connect(e.destination)}handleMessage(e,n){if(n!==this.callGeneration)return;if(e.data instanceof ArrayBuffer){this.handleAudioFrame(e.data,n);return}let o;try{o=JSON.parse(e.data)}catch{return}switch(o.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",o.text??"",!1);break;case"transcript_final":{let r=o.role==="assistant"?"assistant":"user";this.emitStatus(r==="user"?"processing":"speaking"),this.emitTranscript(r,o.text??"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.emitError(new Error(o.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(e,n){if(n!==this.callGeneration||!this.playback)return;let o=EI(e);o.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(o))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(e=>e.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}onTranscript(e){this.transcriptCallbacks.push(e)}onMetrics(e){this.metricsCallbacks.push(e)}emitStatus(e){this.statusCallbacks.forEach(n=>n(e))}emitError(e){this.errorCallbacks.forEach(n=>n(e))}emitTranscript(e,n,o){this.transcriptCallbacks.forEach(r=>r(e,n,o))}emitMetrics(e){this.metricsCallbacks.forEach(n=>n(e))}}});var Es,Zg=be(()=>{"use strict";Es=class{constructor(e={}){this.config=e;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window<"u"?window:void 0}async connect(){this.statusCallbacks.forEach(e=>e("connected"))}async startListening(){try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let e=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!e)throw new Error("Browser speech recognition not supported");this.recognition=new e,this.recognition.lang=this.config?.language||"en-US",this.recognition.continuous=this.config?.continuous||!1,this.recognition.interimResults=!0,this.recognition.onresult=n=>{let o=Array.from(n.results).map(s=>s[0]).map(s=>s.transcript).join(""),r=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(s=>s({text:o,confidence:r?.8:.5,provider:"browser"})),r&&!this.config?.continuous&&this.stopListening()},this.recognition.onerror=n=>{this.errorCallbacks.forEach(o=>o(new Error(n.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(n=>n("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))},this.recognition.start()}catch(e){throw this.errorCallbacks.forEach(n=>n(e)),this.statusCallbacks.forEach(n=>n("error")),e}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(e=>e("idle"))}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(e=>e("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}}});function nc(t){switch(t.type){case"runtype":if(!t.runtype)throw new Error("Runtype voice provider requires configuration");return new Wa(t.runtype);case"browser":if(!Es.isSupported())throw new Error("Browser speech recognition not supported");return new Es(t.browser||{});case"custom":{let e=t.custom;if(!e)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof e=="function"?e():e;if(!n||typeof n.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw new Error(`Unknown voice provider type: ${t.type}`)}}function eh(t){if(t?.type==="custom"&&t.custom)return nc({type:"custom",custom:t.custom});if(t?.type==="runtype"&&t.runtype)return nc({type:"runtype",runtype:t.runtype});if(Es.isSupported())return nc({type:"browser",browser:t?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function Yx(t){try{return eh(t),!0}catch{return!1}}var Qx=be(()=>{"use strict";Jg();Zg()});var Xx={};$n(Xx,{BrowserVoiceProvider:()=>Es,RuntypeVoiceProvider:()=>Wa,createBestAvailableVoiceProvider:()=>eh,createVoiceProvider:()=>nc,isVoiceSupported:()=>Yx});var Jx=be(()=>{"use strict";Qx();Jg();Zg()});function II(t){return t.replace(/\/+$/,"")}async function RI(t){try{let e=await t.json();return e.detail?`${e.error??`Runtype TTS ${t.status}`}: ${e.detail}`:e.error??`Runtype TTS request failed (${t.status})`}catch{return`Runtype TTS request failed (${t.status})`}}var Qp,eS=be(()=>{"use strict";Xg();Qp=class{constructor(e){this.opts=e;this.id="runtype-tts";this.supportsPause=!0;this.player=null;this.playerPromise=null;this.generation=0}ensurePlayer(){return this.playerPromise??(this.playerPromise=Promise.resolve(this.opts.createPlaybackEngine?this.opts.createPlaybackEngine():new Ha(24e3,{prebufferMs:this.opts.prebufferMs??200})).then(e=>this.player=e))}speak(e,n){let o=++this.generation;this.run(o,e,n)}async run(e,n,o){try{let r=await this.ensurePlayer();if(e!==this.generation)return;r.flush(),r.resume(),r.onStarted(()=>{e===this.generation&&o.onStart?.()}),r.onFinished(()=>{e===this.generation&&o.onEnd?.()});let s=`${II(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,a=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.opts.clientToken}`},body:JSON.stringify({text:n.text,voice:n.voice??this.opts.voice,format:"pcm"})});if(e!==this.generation)return;if(!a.ok||!a.body)throw new Error(await RI(a));let l=a.body.getReader();for(;;){let{done:c,value:p}=await l.read();if(e!==this.generation){await l.cancel().catch(()=>{});return}if(c)break;p&&p.byteLength>0&&r.enqueue(p)}r.markStreamEnd()}catch(r){if(e!==this.generation)return;let s=r instanceof Error?r:new Error(String(r));this.opts.onError?.(s),o.onError?.(s)}}pause(){this.player?.pause()}resume(){this.player?.resume()}stop(){this.generation++,this.player?.flush()}destroy(){this.generation++,this.player?.destroy(),this.player=null,this.playerPromise=null}}});var Xp,tS=be(()=>{"use strict";Xp=class{constructor(e,n,o={}){this.primary=e;this.fallback=n;this.options=o;this.id="fallback";this.active=e}get supportsPause(){return this.active.supportsPause}speak(e,n){this.active=this.primary;let o=!1;this.primary.speak(e,{onStart:()=>{o=!0,n.onStart?.()},onEnd:()=>n.onEnd?.(),onError:r=>{if(o){n.onError?.(r);return}this.options.onFallback?.(r),this.active=this.fallback,this.fallback.speak(e,n)}})}pause(){this.active.pause()}resume(){this.active.resume()}stop(){this.active.stop()}destroy(){this.primary.destroy?.(),this.fallback.destroy?.()}}});var nS={};$n(nS,{FallbackSpeechEngine:()=>Xp,RuntypeSpeechEngine:()=>Qp});var oS=be(()=>{"use strict";eS();tS()});var sS={};$n(sS,{createReconnectController:()=>WI});function WI(t){let e=0,n=null,o=null,r=!1,s=()=>{if(o&&(clearTimeout(o),o=null),n){let b=n;n=null,b()}},a=()=>{let b=t.getStatus();b!=="resuming"&&b!=="paused"||s()},l=()=>{typeof document<"u"&&document.visibilityState==="hidden"||a()},c=()=>{a()},p=()=>{r||(typeof document<"u"&&document.addEventListener("visibilitychange",l),typeof window<"u"&&window.addEventListener("online",c),r=!0)},u=()=>{r&&(typeof document<"u"&&document.removeEventListener("visibilitychange",l),typeof window<"u"&&window.removeEventListener("online",c),r=!1)},m=b=>new Promise(C=>{n=C,o=setTimeout(()=>{o=null,n=null,C()},b)}),g=()=>{let b=t.getResumable();t.clearResumable(),t.setReconnecting(!1),e=0,u(),t.setAbortController(null);let C=!1;for(let E of t.getMessages())E.streaming&&(E.streaming=!1,C=!0);let M=t.buildErrorContent("Connection lost and the response could not be resumed.");M?t.appendMessage({id:`reconnect-failed-${b?.executionId??t.nextSequence()}`,role:"assistant",content:M,createdAt:new Date().toISOString(),streaming:!1,sequence:t.nextSequence()}):C&&t.notifyMessagesChanged(),t.setStreaming(!1),t.setStatus("idle"),t.onError(new Error("Durable session reconnect failed."))},h=async()=>{let b=t.config.reconnect?.backoffMs??HI,C=t.config.reconnect?.maxAttempts??b.length,M=t.config.reconnectStream;if(!M){t.setReconnecting(!1);return}for(;t.getResumable()&&e<C;){e+=1,t.setStatus("resuming");let E=t.getResumable(),T=E.lastEventId,H=new AbortController;t.setAbortController(H),t.emitReconnect({phase:"resuming",handle:E,attempt:e});let A=null;try{let D=await M({executionId:E.executionId,after:E.lastEventId,signal:H.signal});D&&D.ok&&D.body&&(A=D.body)}catch{A=null}if(H.signal.aborted)return;if(A){let D=t.getMessages().find(U=>U.id===E.assistantMessageId)?.content,W=typeof D=="string"?D:"";try{await t.resumeConnect(A,E.assistantMessageId,W)}catch{}if(H.signal.aborted)return;if(!t.getResumable()){t.setReconnecting(!1),e=0,u(),t.emitReconnect({phase:"resumed",handle:E});return}t.getResumable().lastEventId!==T&&(e=0)}if(t.getResumable()&&e<C&&(t.setStatus("paused"),await m(b[Math.min(e-1,b.length-1)]??1e3),H.signal.aborted))return}t.getResumable()&&g()};return{begin(){e=0,p(),h()},teardown(){o&&(clearTimeout(o),o=null),n=null,e=0,u()},wake:s}}var HI,iS=be(()=>{"use strict";HI=[1e3,2e3,4e3,8e3,8e3]});var dn,On,Ba,ks=be(()=>{"use strict";dn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},On=1e5,Ba=On+1});function xS(t){let e=t.getRootNode?.();return e&&SS(e)||e&&uu(e)?e:t.ownerDocument??document}function pu(t,e,n){let o=uu(t)?t.head:t,r=e.replace(/["\\]/g,"\\$&");if(o.querySelector(`style[data-persona-plugin-style="${r}"]`))return;let a=(uu(t)?t:t.ownerDocument??document).createElement("style");a.setAttribute("data-persona-plugin-style",e),a.textContent=n,o.appendChild(a)}function mu(t,e,n){if(uu(t)||SS(t)){pu(t,e,n);return}let o=t;if(o.isConnected){pu(xS(o),e,n);return}let r=o.ownerDocument??document;pu(r,e,n),queueMicrotask(()=>{let s=xS(o);s!==r&&pu(s,e,n)})}function eR(t){let e=t.getRootNode?.();return e instanceof ShadowRoot?e:(t.ownerDocument??document).body}function Ps(t){let{anchor:e,content:n,placement:o="bottom-start",offset:r=6,matchAnchorWidth:s=!1,horizontalOffset:a,verticalOffset:l,zIndex:c=2147483e3,onOpen:p,onDismiss:u}=t,m=t.container??eR(e),g=!1,h=null,b=()=>{if(!g)return;let E=e.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${E.width}px`),a&&(n.style.maxWidth=`${E.width}px`);let T=n.getBoundingClientRect(),H=l?.()??null,A=H!=null?E.top+H:E.top,D=o==="top-start"||o==="top-end"?A-r-T.height:E.bottom+r,U=o==="bottom-end"||o==="top-end"?E.right-T.width:E.left,B=a?.()??null;if(B!=null){let O=Math.max(E.left,E.right-T.width);U=Math.min(Math.max(E.left+B,E.left),O)}n.style.top=`${D}px`,n.style.left=`${U}px`},C=()=>{g&&(g=!1,h&&(h(),h=null),n.remove())},M=()=>{if(g)return;g=!0,c!=null&&(n.style.zIndex=String(c)),m.appendChild(n),b();let E=(e.ownerDocument??document).defaultView??window,T=e.ownerDocument??document,H=()=>{if(!e.isConnected){C(),u?.("anchor-removed");return}b()},A=W=>{let U=typeof W.composedPath=="function"?W.composedPath():[];U.includes(n)||U.includes(e)||(C(),u?.("outside"))},D=E.setTimeout(()=>{T.addEventListener("pointerdown",A,!0)},0);E.addEventListener("scroll",H,!0),E.addEventListener("resize",H),h=()=>{E.clearTimeout(D),T.removeEventListener("pointerdown",A,!0),E.removeEventListener("scroll",H,!0),E.removeEventListener("resize",H)},p?.()};return{get isOpen(){return g},open:M,close:C,toggle:()=>g?C():M(),reposition:b,destroy:C}}function AS(t){return(typeof t.composedPath=="function"?t.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var uu,SS,Oa=be(()=>{"use strict";uu=t=>t.nodeType===Node.DOCUMENT_NODE,SS=t=>t.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&t.host!==void 0});function _a(t){t.style.display=t.childElementCount>0?"flex":"none"}function vh(t){let e=t.querySelector(bh);if(e)return e;let n=F("div",{className:"persona-composer-chip-row",attrs:{"data-persona-composer-chip-row":""}});n.style.display="none";let o=t.querySelector("[data-persona-composer-quote], [data-persona-composer-pending]");return o?.parentElement===t?t.insertBefore(n,o):t.appendChild(n),n}var bh,fu=be(()=>{"use strict";je();bh="[data-persona-composer-chip-row]"});function sc(t){t&&(typeof t.requestSubmit=="function"?t.requestSubmit():t.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})))}function JS(t){let e=()=>{t.dispatchEvent(new Event("input",{bubbles:!0}))};return{element:t,getValue:()=>t.value,getLogicalText:()=>t.value,getSelection:()=>({start:t.selectionStart??0,end:t.selectionEnd??0}),setSelection:(n,o=n)=>{t.setSelectionRange(n,o)},setValueWithCaret:(n,o)=>{t.value=n,t.setSelectionRange(o,o)},setValue:n=>{t.value=n,t.setSelectionRange(n.length,n.length),e(),t.focus()},submit:()=>sc(t.form),dispatchInput:e,focus:()=>t.focus()}}var yu=be(()=>{"use strict"});function AR(t,e,n){if(n==="input-start")return e===0;let o=e>0?t[e-1]:"";return n==="line-start"?o===""||o===`
|
|
18
|
-
`:o===""||
|
|
19
|
-
`||a==="\uFFFC"||!r&&
|
|
17
|
+
</document>`}function Zx(t,e,n="fenced"){if(typeof n=="function")try{return n(t,e)}catch(o){return console.warn("[persona] contextMentions.llmFormat threw; falling back to the fenced format for this mention",o),Jl(t.label,t.text)}return n==="document"?LI(t.label,t.text,e):Jl(t.label,t.text)}var Yg=be(()=>{"use strict"});function Gp(t){return t instanceof gr}var gr,Zl=be(()=>{"use strict";gr=class extends Error{constructor(e,n,o){super(n),this.name="HistoryProviderError",this.code=e,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}}});var Ra,Zg=be(()=>{"use strict";Ra=class{constructor(e=24e3,n={}){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.startedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.started=!1;this.userPaused=!1;this.pendingBuffers=[];this.pendingSamples=0;this.remainder=null;this.sampleRate=e;let o=Math.max(0,n.prebufferMs??0);this.waterlineSamples=Math.round(e*o/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let n=typeof window<"u"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let o=n.AudioContext||n.webkitAudioContext;this.ctx=new o({sampleRate:this.sampleRate})}let e=this.ctx;return e.state==="suspended"&&!this.userPaused&&e.resume(),e}enqueue(e){if(e.length===0)return;let n=e;if(this.remainder){let r=new Uint8Array(this.remainder.length+e.length);r.set(this.remainder),r.set(e,this.remainder.length),n=r,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let o=this.pcmToFloat32(n);o.length!==0&&(this.buffering?(this.pendingBuffers.push(o),this.pendingSamples+=o.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(o))}markStreamEnd(){this.pendingBuffers.length>0&&this.releaseBuffer(),this.streamEnded=!0,this.checkFinished()}flush(){for(let e of this.activeSources)try{e.stop(),e.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.startedCallbacks=[],this.remainder=null,this.pendingBuffers=[],this.pendingSamples=0,this.buffering=this.waterlineSamples>0,this.started=!1}isPlaying(){return this.playing}onFinished(e){this.finishedCallbacks.push(e)}onStarted(e){this.startedCallbacks.push(e)}pause(){this.userPaused=!0,this.ctx&&this.ctx.state==="running"&&this.ctx.suspend()}resume(){this.userPaused=!1,this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume()}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}releaseBuffer(){this.buffering=!1;let e=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let n of e)this.scheduleSamples(n)}scheduleSamples(e){if(e.length===0)return;let n=this.ensureContext(),o=n.createBuffer(1,e.length,this.sampleRate);o.getChannelData(0).set(e);let r=n.createBufferSource();r.buffer=o,r.connect(n.destination);let s=n.currentTime;if(this.nextStartTime===0?this.nextStartTime=s:this.nextStartTime<s&&(this.nextStartTime=s,this.waterlineSamples>0&&(this.buffering=!0)),r.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(r),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let a=this.startedCallbacks.slice();this.startedCallbacks=[];for(let l of a)l()}r.onended=()=>{let a=this.activeSources.indexOf(r);a!==-1&&this.activeSources.splice(a,1),this.pendingCount--,this.checkFinished()}}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.pendingBuffers.length===0){this.playing=!1,this.streamEnded=!1;let e=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of e)n()}}pcmToFloat32(e){let n=Math.floor(e.length/2),o=new Float32Array(n),r=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let s=0;s<n;s++){let a=r.getInt16(s*2,!0);o[s]=a/32768}return o}}});function $I(t){return t.byteLength>=44&&new DataView(t).getUint32(0,!1)===DI?new Uint8Array(t,44):new Uint8Array(t)}function rS(t){let e=t.replace(/\/+$/,"");return/^wss?:\/\//i.test(e)?e:/^https?:\/\//i.test(e)?e.replace(/^http/i,"ws"):`${typeof window<"u"&&window.location?.protocol==="https:"?"wss:":"ws:"}//${e}`}function zI(t){return rS(t).replace(/^ws/i,"http")}function UI(t){return typeof t!="number"||!Number.isFinite(t)?NI:Math.min(VI,Math.max(FI,Math.round(t)))}var oS,RI,WI,BI,DI,OI,_I,NI,FI,VI,Wa,eh=be(()=>{"use strict";Zg();oS=16e3,RI=24e3,WI=4096,BI=4,DI=1380533830,OI=3e4,_I=5e3,NI=3e4,FI=3e4,VI=6e5;Wa=class{constructor(e){this.config=e;this.type="runtype";this.ws=null;this.captureContext=null;this.levelCallbacks=[];this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.lastPrewarmAt=Number.NEGATIVE_INFINITY;this.attached=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}prewarm(){if(this.callLive||this.attached)return;let e=this.config?.agentId,n=this.config?.clientToken,o=this.config?.host;if(!e||!n||!o)return;let r=Date.now();if(!(r-this.lastPrewarmAt<OI)){this.lastPrewarmAt=r;try{this.config?.prewarmMode==="attach"?this.attach(o,e,n):this.requestPrewarm(o,e,n)}catch{}}}requestPrewarm(e,n,o){if(typeof fetch!="function")return;let r=`${zI(e)}/v1/client/agents/${encodeURIComponent(n)}/voice/prewarm`;fetch(r,{method:"POST",headers:{Authorization:`Bearer ${o}`},keepalive:!0}).catch(()=>{})}attach(e,n,o){let r=new URLSearchParams({clientCapabilities:"attach"}),s=this.config?.attachIdleMs,a=UI(s);s!==void 0&&r.set("attachIdleMs",String(a));let l=new WebSocket(`${this.voiceSocketUrl(e,n)}?${r}`,["runtype.bearer","runtype.attach",o]);l.binaryType="arraybuffer";let c=()=>{},p=new Promise(m=>{c=m}),u={ws:l,state:"connecting",ready:p,settle:c,openedAt:0,idleTimer:void 0};this.attached=u,l.onopen=()=>{this.attached===u&&(u.state=l.protocol==="runtype.attach"?"attached":"live",u.openedAt=Date.now(),this.armAttachIdle(u,a),u.state==="attached"&&l.send('{"type":"ping"}'),u.settle())},l.onmessage=m=>{if(this.attached!==u||typeof m.data!="string")return;let g;try{g=JSON.parse(m.data)}catch{return}g.type==="attached"&&typeof g.idleMs=="number"&&this.armAttachIdle(u,g.idleMs-(Date.now()-u.openedAt))},l.onerror=()=>{},l.onclose=()=>{this.attached===u&&this.releaseAttached()}}armAttachIdle(e,n){clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>{this.attached===e&&this.releaseAttached()},Math.max(0,n))}releaseAttached(){let e=this.attached;if(!e)return;this.attached=null,clearTimeout(e.idleTimer);let{ws:n}=e;if(n.onopen=null,n.onmessage=null,n.onerror=null,n.onclose=null,e.settle(),n.readyState===WebSocket.CONNECTING||n.readyState===WebSocket.OPEN)try{n.close(1e3,"prewarm released")}catch{}}async takeAttachedSocket(){let e=this.attached;if(!e)return null;if(e.state==="connecting"){let n;await Promise.race([e.ready,new Promise(o=>{n=setTimeout(o,_I)})]),clearTimeout(n)}return this.attached!==e?null:e.state==="connecting"||e.ws.readyState!==WebSocket.OPEN?(this.releaseAttached(),null):(this.attached=null,clearTimeout(e.idleTimer),{ws:e.ws,live:e.state==="live"})}voiceSocketUrl(e,n){return`${rS(e)}/ws/agents/${encodeURIComponent(n)}/voice`}async startListening(){if(this.callLive)return;let e=this.config?.agentId,n=this.config?.clientToken,o=this.config?.host;if(!e)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!o)throw new Error("Runtype voice requires a host (or widget apiUrl)");let r=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let s=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:oS,channelCount:1,echoCancellation:!0}});if(r!==this.callGeneration){s.getTracks().forEach(m=>m.stop());return}this.mediaStream=s;let a=window.AudioContext||window.webkitAudioContext,l=new a({sampleRate:oS});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let c=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new Ra(RI);if(r!==this.callGeneration){c.destroy(),s.getTracks().forEach(m=>m.stop()),l.close().catch(()=>{});return}this.playback=c,c.onFinished(()=>{r===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let p=await this.takeAttachedSocket();if(r!==this.callGeneration){p?.ws.close(1e3,"client ended call");return}if(p){let{ws:m}=p;this.ws=m,this.bindCallSocket(m,r),p.live||m.send('{"type":"start"}'),this.emitStatus("listening"),this.startCapture(l,s,m,r);return}let u=new WebSocket(this.voiceSocketUrl(o,e),["runtype.bearer",n]);u.binaryType="arraybuffer",this.ws=u,u.onopen=()=>{r===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(l,s,u,r))},this.bindCallSocket(u,r)}catch(s){throw this.cleanup(),this.emitError(s),this.emitStatus("error"),s}}bindCallSocket(e,n){e.onmessage=o=>this.handleMessage(o,n),e.onerror=()=>{n===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},e.onclose=o=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(n===this.callGeneration){if(o.code!==1e3){let r=o.code?` (code ${o.code})`:"";this.emitError(new Error(`Voice connection closed${r}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}onLevel(e){this.levelCallbacks.push(e)}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(e,n,o,r){let s=e.createMediaStreamSource(n);this.sourceNode=s;let a=e.createScriptProcessor(WI,1,1);this.processor=a,a.onaudioprocess=l=>{if(r!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let c=l.inputBuffer.getChannelData(0),p=new Int16Array(c.length),u=0;for(let m=0;m<c.length;m++){let g=Math.max(-1,Math.min(1,c[m]));u+=g*g,p[m]=g<0?g*32768:g*32767}if(o.send(p.buffer),this.levelCallbacks.length>0){let m=Math.sqrt(u/c.length),g=Math.max(0,Math.min(1,m*BI));for(let h of this.levelCallbacks)h(g)}},s.connect(a),a.connect(e.destination)}handleMessage(e,n){if(n!==this.callGeneration)return;if(e.data instanceof ArrayBuffer){this.handleAudioFrame(e.data,n);return}let o;try{o=JSON.parse(e.data)}catch{return}switch(o.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",o.text??"",!1);break;case"transcript_final":{let r=o.role==="assistant"?"assistant":"user";this.emitStatus(r==="user"?"processing":"speaking"),this.emitTranscript(r,o.text??"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.emitError(new Error(o.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(e,n){if(n!==this.callGeneration||!this.playback)return;let o=$I(e);o.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(o))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.releaseAttached(),this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(e=>e.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}onTranscript(e){this.transcriptCallbacks.push(e)}onMetrics(e){this.metricsCallbacks.push(e)}emitStatus(e){this.statusCallbacks.forEach(n=>n(e))}emitError(e){this.errorCallbacks.forEach(n=>n(e))}emitTranscript(e,n,o){this.transcriptCallbacks.forEach(r=>r(e,n,o))}emitMetrics(e){this.metricsCallbacks.forEach(n=>n(e))}}});var Es,th=be(()=>{"use strict";Es=class{constructor(e={}){this.config=e;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window<"u"?window:void 0}async connect(){this.statusCallbacks.forEach(e=>e("connected"))}async startListening(){try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let e=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!e)throw new Error("Browser speech recognition not supported");this.recognition=new e,this.recognition.lang=this.config?.language||"en-US",this.recognition.continuous=this.config?.continuous||!1,this.recognition.interimResults=!0,this.recognition.onresult=n=>{let o=Array.from(n.results).map(s=>s[0]).map(s=>s.transcript).join(""),r=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(s=>s({text:o,confidence:r?.8:.5,provider:"browser"})),r&&!this.config?.continuous&&this.stopListening()},this.recognition.onerror=n=>{this.errorCallbacks.forEach(o=>o(new Error(n.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(n=>n("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))},this.recognition.start()}catch(e){throw this.errorCallbacks.forEach(n=>n(e)),this.statusCallbacks.forEach(n=>n("error")),e}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(e=>e("idle"))}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(e=>e("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}}});function nc(t){switch(t.type){case"runtype":if(!t.runtype)throw new Error("Runtype voice provider requires configuration");return new Wa(t.runtype);case"browser":if(!Es.isSupported())throw new Error("Browser speech recognition not supported");return new Es(t.browser||{});case"custom":{let e=t.custom;if(!e)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof e=="function"?e():e;if(!n||typeof n.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw new Error(`Unknown voice provider type: ${t.type}`)}}function nh(t){if(t?.type==="custom"&&t.custom)return nc({type:"custom",custom:t.custom});if(t?.type==="runtype"&&t.runtype)return nc({type:"runtype",runtype:t.runtype});if(Es.isSupported())return nc({type:"browser",browser:t?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function sS(t){try{return nh(t),!0}catch{return!1}}var iS=be(()=>{"use strict";eh();th()});var aS={};$n(aS,{BrowserVoiceProvider:()=>Es,RuntypeVoiceProvider:()=>Wa,createBestAvailableVoiceProvider:()=>nh,createVoiceProvider:()=>nc,isVoiceSupported:()=>sS});var lS=be(()=>{"use strict";iS();eh();th()});function KI(t){return t.replace(/\/+$/,"")}async function GI(t){try{let e=await t.json();return e.detail?`${e.error??`Runtype TTS ${t.status}`}: ${e.detail}`:e.error??`Runtype TTS request failed (${t.status})`}catch{return`Runtype TTS request failed (${t.status})`}}var Qp,dS=be(()=>{"use strict";Zg();Qp=class{constructor(e){this.opts=e;this.id="runtype-tts";this.supportsPause=!0;this.player=null;this.playerPromise=null;this.generation=0}ensurePlayer(){return this.playerPromise??(this.playerPromise=Promise.resolve(this.opts.createPlaybackEngine?this.opts.createPlaybackEngine():new Ra(24e3,{prebufferMs:this.opts.prebufferMs??200})).then(e=>this.player=e))}speak(e,n){let o=++this.generation;this.run(o,e,n)}async run(e,n,o){try{let r=await this.ensurePlayer();if(e!==this.generation)return;r.flush(),r.resume(),r.onStarted(()=>{e===this.generation&&o.onStart?.()}),r.onFinished(()=>{e===this.generation&&o.onEnd?.()});let s=`${KI(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,a=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.opts.clientToken}`},body:JSON.stringify({text:n.text,voice:n.voice??this.opts.voice,format:"pcm"})});if(e!==this.generation)return;if(!a.ok||!a.body)throw new Error(await GI(a));let l=a.body.getReader();for(;;){let{done:c,value:p}=await l.read();if(e!==this.generation){await l.cancel().catch(()=>{});return}if(c)break;p&&p.byteLength>0&&r.enqueue(p)}r.markStreamEnd()}catch(r){if(e!==this.generation)return;let s=r instanceof Error?r:new Error(String(r));this.opts.onError?.(s),o.onError?.(s)}}pause(){this.player?.pause()}resume(){this.player?.resume()}stop(){this.generation++,this.player?.flush()}destroy(){this.generation++,this.player?.destroy(),this.player=null,this.playerPromise=null}}});var Xp,pS=be(()=>{"use strict";Xp=class{constructor(e,n,o={}){this.primary=e;this.fallback=n;this.options=o;this.id="fallback";this.active=e}get supportsPause(){return this.active.supportsPause}speak(e,n){this.active=this.primary;let o=!1;this.primary.speak(e,{onStart:()=>{o=!0,n.onStart?.()},onEnd:()=>n.onEnd?.(),onError:r=>{if(o){n.onError?.(r);return}this.options.onFallback?.(r),this.active=this.fallback,this.fallback.speak(e,n)}})}pause(){this.active.pause()}resume(){this.active.resume()}stop(){this.active.stop()}destroy(){this.primary.destroy?.(),this.fallback.destroy?.()}}});var uS={};$n(uS,{FallbackSpeechEngine:()=>Xp,RuntypeSpeechEngine:()=>Qp});var mS=be(()=>{"use strict";dS();pS()});var gS={};$n(gS,{createReconnectController:()=>QI});function QI(t){let e=0,n=null,o=null,r=!1,s=()=>{if(o&&(clearTimeout(o),o=null),n){let b=n;n=null,b()}},a=()=>{let b=t.getStatus();b!=="resuming"&&b!=="paused"||s()},l=()=>{typeof document<"u"&&document.visibilityState==="hidden"||a()},c=()=>{a()},p=()=>{r||(typeof document<"u"&&document.addEventListener("visibilitychange",l),typeof window<"u"&&window.addEventListener("online",c),r=!0)},u=()=>{r&&(typeof document<"u"&&document.removeEventListener("visibilitychange",l),typeof window<"u"&&window.removeEventListener("online",c),r=!1)},m=b=>new Promise(C=>{n=C,o=setTimeout(()=>{o=null,n=null,C()},b)}),g=()=>{let b=t.getResumable();t.clearResumable(),t.setReconnecting(!1),e=0,u(),t.setAbortController(null);let C=!1;for(let E of t.getMessages())E.streaming&&(E.streaming=!1,C=!0);let M=t.buildErrorContent("Connection lost and the response could not be resumed.");M?t.appendMessage({id:`reconnect-failed-${b?.executionId??t.nextSequence()}`,role:"assistant",content:M,createdAt:new Date().toISOString(),streaming:!1,sequence:t.nextSequence()}):C&&t.notifyMessagesChanged(),t.setStreaming(!1),t.setStatus("idle"),t.onError(new Error("Durable session reconnect failed."))},h=async()=>{let b=t.config.reconnect?.backoffMs??YI,C=t.config.reconnect?.maxAttempts??b.length,M=t.config.reconnectStream;if(!M){t.setReconnecting(!1);return}for(;t.getResumable()&&e<C;){e+=1,t.setStatus("resuming");let E=t.getResumable(),T=E.lastEventId,R=new AbortController;t.setAbortController(R),t.emitReconnect({phase:"resuming",handle:E,attempt:e});let A=null;try{let D=await M({executionId:E.executionId,after:E.lastEventId,signal:R.signal});D&&D.ok&&D.body&&(A=D.body)}catch{A=null}if(R.signal.aborted)return;if(A){let D=t.getMessages().find(U=>U.id===E.assistantMessageId)?.content,W=typeof D=="string"?D:"";try{await t.resumeConnect(A,E.assistantMessageId,W)}catch{}if(R.signal.aborted)return;if(!t.getResumable()){t.setReconnecting(!1),e=0,u(),t.emitReconnect({phase:"resumed",handle:E});return}t.getResumable().lastEventId!==T&&(e=0)}if(t.getResumable()&&e<C&&(t.setStatus("paused"),await m(b[Math.min(e-1,b.length-1)]??1e3),R.signal.aborted))return}t.getResumable()&&g()};return{begin(){e=0,p(),h()},teardown(){o&&(clearTimeout(o),o=null),n=null,e=0,u()},wake:s}}var YI,hS=be(()=>{"use strict";YI=[1e3,2e3,4e3,8e3,8e3]});var dn,On,Ba,ks=be(()=>{"use strict";dn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},On=1e5,Ba=On+1});function HS(t){let e=t.getRootNode?.();return e&&RS(e)||e&&uu(e)?e:t.ownerDocument??document}function pu(t,e,n){let o=uu(t)?t.head:t,r=e.replace(/["\\]/g,"\\$&");if(o.querySelector(`style[data-persona-plugin-style="${r}"]`))return;let a=(uu(t)?t:t.ownerDocument??document).createElement("style");a.setAttribute("data-persona-plugin-style",e),a.textContent=n,o.appendChild(a)}function mu(t,e,n){if(uu(t)||RS(t)){pu(t,e,n);return}let o=t;if(o.isConnected){pu(HS(o),e,n);return}let r=o.ownerDocument??document;pu(r,e,n),queueMicrotask(()=>{let s=HS(o);s!==r&&pu(s,e,n)})}function hH(t){let e=t.getRootNode?.();return e instanceof ShadowRoot?e:(t.ownerDocument??document).body}function Ps(t){let{anchor:e,content:n,placement:o="bottom-start",offset:r=6,matchAnchorWidth:s=!1,horizontalOffset:a,verticalOffset:l,zIndex:c=2147483e3,onOpen:p,onDismiss:u}=t,m=t.container??hH(e),g=!1,h=null,b=()=>{if(!g)return;let E=e.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${E.width}px`),a&&(n.style.maxWidth=`${E.width}px`);let T=n.getBoundingClientRect(),R=l?.()??null,A=R!=null?E.top+R:E.top,D=o==="top-start"||o==="top-end"?A-r-T.height:E.bottom+r,U=o==="bottom-end"||o==="top-end"?E.right-T.width:E.left,B=a?.()??null;if(B!=null){let O=Math.max(E.left,E.right-T.width);U=Math.min(Math.max(E.left+B,E.left),O)}n.style.top=`${D}px`,n.style.left=`${U}px`},C=()=>{g&&(g=!1,h&&(h(),h=null),n.remove())},M=()=>{if(g)return;g=!0,c!=null&&(n.style.zIndex=String(c)),m.appendChild(n),b();let E=(e.ownerDocument??document).defaultView??window,T=e.ownerDocument??document,R=()=>{if(!e.isConnected){C(),u?.("anchor-removed");return}b()},A=W=>{let U=typeof W.composedPath=="function"?W.composedPath():[];U.includes(n)||U.includes(e)||(C(),u?.("outside"))},D=E.setTimeout(()=>{T.addEventListener("pointerdown",A,!0)},0);E.addEventListener("scroll",R,!0),E.addEventListener("resize",R),h=()=>{E.clearTimeout(D),T.removeEventListener("pointerdown",A,!0),E.removeEventListener("scroll",R,!0),E.removeEventListener("resize",R)},p?.()};return{get isOpen(){return g},open:M,close:C,toggle:()=>g?C():M(),reposition:b,destroy:C}}function WS(t){return(typeof t.composedPath=="function"?t.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var uu,RS,Oa=be(()=>{"use strict";uu=t=>t.nodeType===Node.DOCUMENT_NODE,RS=t=>t.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&t.host!==void 0});function _a(t){t.style.display=t.childElementCount>0?"flex":"none"}function wh(t){let e=t.querySelector(Ch);if(e)return e;let n=F("div",{className:"persona-composer-chip-row",attrs:{"data-persona-composer-chip-row":""}});n.style.display="none";let o=t.querySelector("[data-persona-composer-quote], [data-persona-composer-pending]");return o?.parentElement===t?t.insertBefore(n,o):t.appendChild(n),n}var Ch,fu=be(()=>{"use strict";je();Ch="[data-persona-composer-chip-row]"});function sc(t){t&&(typeof t.requestSubmit=="function"?t.requestSubmit():t.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})))}function lA(t){let e=()=>{t.dispatchEvent(new Event("input",{bubbles:!0}))};return{element:t,getValue:()=>t.value,getLogicalText:()=>t.value,getSelection:()=>({start:t.selectionStart??0,end:t.selectionEnd??0}),setSelection:(n,o=n)=>{t.setSelectionRange(n,o)},setValueWithCaret:(n,o)=>{t.value=n,t.setSelectionRange(o,o)},setValue:n=>{t.value=n,t.setSelectionRange(n.length,n.length),e(),t.focus()},submit:()=>sc(t.form),dispatchInput:e,focus:()=>t.focus()}}var yu=be(()=>{"use strict"});function FH(t,e,n){if(n==="input-start")return e===0;let o=e>0?t[e-1]:"";return n==="line-start"?o===""||o===`
|
|
18
|
+
`:o===""||uA.test(o)}function VH(t,e,n="@",o="anywhere",r=!1){if(!n||e<=0||e>t.length)return null;let s=e-1;for(;s>=0;){let a=t[s];if(a===n)return FH(t,s,o)?{triggerIndex:s,query:t.slice(s+1,e)}:null;if(a===`
|
|
19
|
+
`||a==="\uFFFC"||!r&&uA.test(a))return null;s--}return null}function ic(t,e,n){for(let o of n){let r=VH(t,e,o.trigger,o.position??"anywhere",o.allowSpaces??!1);if(r)return{channel:o,match:r}}return null}function mA(t){return t?t!=="insertFromPaste"&&t!=="insertFromDrop":!0}function fA(t,e,n){return{value:t.slice(0,e.triggerIndex)+t.slice(n),caret:e.triggerIndex}}var uA,bu=be(()=>{"use strict";uA=/\s/});function vu(t){let e={trigger:t.trigger??"@",position:t.triggerPosition??"anywhere",allowSpaces:!1,sources:Array.isArray(t.sources)?t.sources:[],searchPlaceholder:t.searchPlaceholder,showButton:t.showButton!==!1,buttonIconName:t.buttonIconName,buttonTooltipText:t.buttonTooltipText},n=(t.triggers??[]).map(o=>({trigger:o.trigger,position:o.triggerPosition??"anywhere",allowSpaces:o.allowSpaces??!1,sources:Array.isArray(o.sources)?o.sources:[],searchPlaceholder:o.searchPlaceholder,showButton:o.showButton===!0,buttonIconName:o.buttonIconName,buttonTooltipText:o.buttonTooltipText}));return[e,...n]}var Ah=be(()=>{"use strict"});var hA,Mh,Cu,wu=be(()=>{"use strict";hA=null,Mh=t=>{hA=t},Cu=(t,e,n,o)=>hA?.(t,e,n,o)??null});function bA(t){let{ref:e,config:n,onRemove:o}=t;if(n.renderMentionChip){let h="resolving",b,C=n.renderMentionChip({ref:e,status:h,payload:b,remove:o});return{get el(){return C},setStatus:(E,T)=>{if(E===h&&T===b)return;h=E,b=T;let R=n.renderMentionChip({ref:e,status:h,payload:b,remove:o});C.replaceWith(R),C=R}}}let r=e.iconName??n.chipIconName??"at-sign",s=F("div",{className:"persona-mention-chip",attrs:{"data-persona-mention-chip":"","data-status":"resolving",title:e.label}}),a=v("span","persona-mention-chip-icon"),l=h=>{a.replaceChildren();let b=Cu(h,13,"currentColor",2);b&&a.appendChild(b)};l(r);let c=v("span","persona-mention-chip-spinner"),p=F("span",{className:"persona-mention-chip-label",text:e.label}),u=F("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${e.label} context`}}),m=Ge(yA.X,11,"currentColor",2.5);return m?u.appendChild(m):u.textContent="\xD7",u.addEventListener("click",h=>{h.preventDefault(),h.stopPropagation(),o()}),s.appendChild(c),s.appendChild(p),s.appendChild(u),{el:s,setStatus:h=>{s.setAttribute("data-status",h),h==="resolving"?(c.parentNode!==s&&s.insertBefore(c,p),a.parentNode===s&&a.remove(),s.setAttribute("title",e.label)):(c.parentNode===s&&c.remove(),a.parentNode!==s&&s.insertBefore(a,p),h==="error"?(l("triangle-alert"),s.setAttribute("title",`Couldn't add ${e.label} to context`)):(l(r),s.setAttribute("title",e.label)))}}}var yA,vA=be(()=>{"use strict";je();yA=require("lucide");zn();wu()});function xu(t,e){return{sourceId:t.id,itemId:e.id,label:e.label,iconName:e.iconName,color:e.color}}var CA,Su,Th=be(()=>{"use strict";vA();fu();Yg();CA=(t,e)=>`${t}\0${e}`,Su=class{constructor(e){this.mentions=[];this.opts=e,this.updateRowVisibility()}get maxMentions(){return this.opts.mentionConfig.maxMentions??8}hasMentions(){return this.mentions.length>0}add(e,n,o=""){let r=CA(e.id,n.id);if(this.mentions.some(l=>l.key===r))return this.reject(e,n,"duplicate");if(this.atLimit())return this.reject(e,n,"limit");let s=xu(e,n),a={key:r,source:e,item:n,ref:s,status:"resolving",args:o};return a.chip=bA({ref:s,config:this.opts.mentionConfig,onRemove:()=>this.remove(r)}),a.chip.el.setAttribute("data-persona-chip-enter",""),a.chip.el.addEventListener("animationend",()=>a.chip?.el.removeAttribute("data-persona-chip-enter"),{once:!0}),this.opts.contextRow.appendChild(a.chip.el),this.startPending(a),this.updateRowVisibility(),!0}atLimit(){return this.mentions.length>=this.maxMentions}admit(e,n){return this.atLimit()?this.reject(e,n,"limit"):!0}track(e,n,o,r="",s){let a={key:e,source:n,item:o,ref:xu(n,o),status:"resolving",args:r,reportStatus:s};this.startPending(a)}reject(e,n,o){return this.opts.mentionConfig.onMentionRejected?.(n,o),this.opts.emit?.("rejected",{sourceId:e.id,itemId:n.id,reason:o}),!1}startPending(e){this.mentions.push(e),e.source.resolveOn==="submit"?(e.status="ready",e.chip?.setStatus("ready"),e.reportStatus?.("resolved")):e.resolvePromise=this.resolvePending(e),this.opts.announce(`Added ${e.ref.label} to context`)}buildResolveContext(e,n,o=this.opts.getComposerText()){return{messages:this.opts.getMessages(),config:this.opts.getConfig(),composerText:o,args:n,signal:e}}async resolvePending(e){let n=new AbortController;e.abort=n;try{let o=await e.source.resolve(e.item,this.buildResolveContext(n.signal,e.args));if(n.signal.aborted)return;e.payload=o,e.status="ready",e.chip?.setStatus("ready",o),e.reportStatus?.("resolved")}catch(o){if(n.signal.aborted)return;e.status="error",e.chip?.setStatus("error"),e.reportStatus?.("error"),(this.opts.announceError??this.opts.announce)(`Couldn't attach ${e.ref.label} to context`),this.opts.mentionConfig.onMentionResolveError?.(e.item,o),this.opts.emit?.("resolve-error",{sourceId:e.source.id,itemId:e.item.id})}}remove(e){let n=this.mentions.findIndex(r=>r.key===e);if(n===-1)return;let[o]=this.mentions.splice(n,1);o.abort?.abort(),o.chip?.el.remove(),this.updateRowVisibility(),this.opts.announce(`Removed ${o.ref.label} from context`)}getRefs(){return this.mentions.map(e=>e.ref)}removeLast(){let e=this.mentions[this.mentions.length-1];return e?(this.remove(e.key),!0):!1}clear(){for(let e of this.mentions)e.abort?.abort(),e.chip?.el.remove();this.mentions.length=0,this.updateRowVisibility()}collectForSubmit(){let e=[...this.mentions],n=e.map(s=>s.ref),o=this.opts.getComposerText();for(let s of e)s.chip?.el.remove();return this.mentions.length=0,this.updateRowVisibility(),{refs:n,finalize:async()=>{var u;let s=await Promise.all(e.map(async m=>{try{return m.source.resolveOn==="submit"?await m.source.resolve(m.item,this.buildResolveContext(new AbortController().signal,m.args,o)):(m.resolvePromise&&await m.resolvePromise,m.payload??null)}catch(g){try{this.opts.mentionConfig.onMentionResolveError?.(m.item,g)}catch(h){typeof console<"u"&&console.warn("[Persona] onMentionResolveError callback threw",h)}return this.opts.emit?.("resolve-error",{sourceId:m.source.id,itemId:m.item.id}),null}})),a=[],l=[],c={},p=new Set;for(let m=0;m<e.length;m++){let g=e[m],h=s[m];if(!h)continue;let b=CA(g.source.id,g.item.id);if(!p.has(b)){if(p.add(b),h.llmAppend&&h.llmAppend.trim())try{a.push(Zx({label:g.ref.label,text:h.llmAppend,ref:g.ref,item:g.item},a.length,this.opts.mentionConfig.llmFormat))}catch(C){typeof console<"u"&&console.warn("[Persona] context-mention llmFormat threw",C)}h.contentParts?.length&&l.push(...h.contentParts),h.context&&((c[u=g.source.id]??(c[u]={}))[g.item.id]=h.context)}}return{blocks:a,contentParts:l,context:c}}}}updateRowVisibility(){_a(this.opts.contextRow)}}});var wA,xA=be(()=>{"use strict";wA=`
|
|
20
20
|
.persona-mention-menu {
|
|
21
21
|
box-sizing: border-box;
|
|
22
22
|
display: flex;
|
|
@@ -174,13 +174,13 @@ ${e}
|
|
|
174
174
|
min-height: 36px;
|
|
175
175
|
}
|
|
176
176
|
}
|
|
177
|
-
`});function Au(t){let e=t.replace(/^\s+/,""),n=e.search(/\s/);return n===-1?{name:e,args:""}:{name:e.slice(0,n),args:e.slice(n+1).trim()}}var mA=be(()=>{"use strict"});function hA(t){let{config:e,listboxId:n}=t,o=F("div",{className:"persona-mention-menu",attrs:{"data-persona-mention-menu":""}}),r=F("div",{className:"persona-mention-search",style:{display:"none"}}),s=v("span","persona-mention-search-icon"),a=Ge(gA.Search,15,"currentColor",2);a&&s.appendChild(a);let l=F("input",{className:"persona-mention-search-input",attrs:{type:"text",role:"combobox","aria-autocomplete":"list","aria-expanded":"false","aria-controls":n,"aria-label":e.searchPlaceholder??"Search context",placeholder:e.searchPlaceholder??"Search context\u2026",autocomplete:"off",autocapitalize:"off",spellcheck:"false"}});r.append(s,l),l.addEventListener("input",()=>t.onSearchInput?.(l.value)),l.addEventListener("keydown",R=>t.onSearchKeydown?.(R));let c=F("div",{className:"persona-mention-list",attrs:{role:"listbox",id:n,"aria-label":"Context mentions"}});o.append(r,c);let p=[],u=[],m=-1,g=new Map,h=(R,S)=>`${R}\0${S}`,b=R=>`${n}-opt-${R}`,C=R=>`${n}-grp-${R}`,M=(R,S)=>{let x=p[R];x&&(S?x.setAttribute("data-active","true"):x.removeAttribute("data-active"),x.setAttribute("aria-selected",S?"true":"false"),u[R]?.(S))},E=(R,S=!0)=>{m>=0&&m!==R&&M(m,!1),m=R;let x=p[R];x?(M(R,!0),S&&x.scrollIntoView?.({block:"nearest"}),c.setAttribute("aria-activedescendant",x.id),l.setAttribute("aria-activedescendant",x.id)):(c.removeAttribute("aria-activedescendant"),l.removeAttribute("aria-activedescendant"))},T=(R,S)=>{let x=C(S),P=F("div",{className:"persona-mention-group",attrs:{role:"group","aria-labelledby":x}});return P.appendChild(F("div",{className:"persona-mention-group-header",attrs:{id:x},text:R})),P},H=()=>{let R=F("div",{className:"persona-mention-option",attrs:{role:"option","aria-selected":"false"}}),S=v("span","persona-mention-option-icon");R.appendChild(S);let x="",P=v("span","persona-mention-option-text"),L=v("span","persona-mention-option-labelline"),G=v("span","persona-mention-option-label");L.appendChild(G),P.appendChild(L),R.appendChild(P);let V=null,K=null,ee={el:R,index:0,update:(oe,ne,le)=>{ee.index=ne,R.id=b(ne),R.setAttribute("aria-setsize",String(le)),R.setAttribute("aria-posinset",String(ne+1)),R.removeAttribute("data-active"),R.setAttribute("aria-selected","false");let de=oe.iconName??e.chipIconName??"at-sign";if(de!==x){x=de;let Le=TR(de,15,2);S.replaceChildren(...Le?[Le]:[])}G.textContent!==oe.label&&(G.textContent=oe.label);let ve=oe.commandArgsPlaceholder?`\u2039${oe.commandArgsPlaceholder}\u203A`:null;ve?(V||(V=v("span","persona-mention-option-arghint"),L.appendChild(V)),V.textContent!==ve&&(V.textContent=ve)):V&&(V.remove(),V=null),oe.description?(K||(K=v("span","persona-mention-option-desc"),P.appendChild(K)),K.textContent!==oe.description&&(K.textContent=oe.description)):K&&(K.remove(),K=null)}};return R.addEventListener("mousedown",oe=>{oe.button===0&&(oe.preventDefault(),t.onSelectIndex(ee.index))}),R.addEventListener("mouseenter",()=>t.onHoverIndex(ee.index)),ee},A=(R,S,x,P,L)=>{let G=F("div",{className:"persona-mention-option",attrs:{role:"option",id:b(P),"aria-selected":"false","aria-setsize":String(L),"aria-posinset":String(P+1)}}),V=K=>{G.replaceChildren(e.renderMentionItem({item:R,source:S,query:x,active:K,index:P}))};return V(!1),G.addEventListener("mousedown",K=>{K.button===0&&(K.preventDefault(),t.onSelectIndex(P))}),G.addEventListener("mouseenter",()=>t.onHoverIndex(P)),{el:G,paint:V}},D=R=>{let S=F("div",{className:"persona-mention-status persona-mention-error"});if(S.appendChild(F("span",{className:"persona-mention-error-text",text:`Couldn't load ${R.label}`})),t.onRetry){let x=F("button",{className:"persona-mention-retry",attrs:{type:"button"},text:"Retry"});x.addEventListener("mousedown",P=>P.preventDefault()),x.addEventListener("click",P=>{P.preventDefault(),t.onRetry(R.id)}),S.appendChild(x)}return S};return{el:o,render:R=>{c.replaceChildren(),p=[],u=[],m=-1;let S=new Set,x=0,P=0,L=0,G=0,V=0,K=R.groups.reduce((ee,oe)=>oe.status==="ready"?ee+oe.items.length:ee,0);for(let ee of R.groups)if(ee.status==="loading"){L++;let oe=T(ee.source.label,V++);oe.appendChild(F("div",{className:"persona-mention-status persona-mention-loading",attrs:{role:"presentation"},text:"Loading\u2026"})),c.appendChild(oe)}else if(ee.status==="error"){G++;let oe=T(ee.source.label,V++);oe.appendChild(D(ee.source)),c.appendChild(oe)}else if(ee.status==="ready"&&ee.items.length>0){let oe=new Map;for(let le of ee.items){let de=le.group??ee.source.label,ve=oe.get(de);ve?ve.push(le):oe.set(de,[le])}let ne=Array.from(oe.entries());ne.forEach(([le,de],ve)=>{let Le=T(le,V++);for(let se of de){let _=x++,Te;if(e.renderMentionItem){let He=A(se,ee.source,R.query,_,K);Te=He.el,u.push(He.paint)}else{let He=h(ee.source.id,se.id),ut=S.has(He)?void 0:g.get(He);ut||(ut=H(),S.has(He)||g.set(He,ut)),S.add(He),ut.update(se,_,K),Te=ut.el,u.push(null)}p.push(Te),Le.appendChild(Te),P++}ee.truncated&&ve===ne.length-1&&Le.appendChild(F("div",{className:"persona-mention-hint",attrs:{role:"presentation"},text:"Keep typing to narrow\u2026"})),c.appendChild(Le)})}for(let ee of g.keys())S.has(ee)||g.delete(ee);P===0&&L===0&&G===0&&c.appendChild(F("div",{className:"persona-mention-empty",attrs:{role:"presentation"},text:"No matches"})),p.length>0?E(Math.min(Math.max(0,R.activeIndex),p.length-1)):(c.removeAttribute("aria-activedescendant"),l.removeAttribute("aria-activedescendant"))},setActiveIndex:E,destroy:()=>{c.replaceChildren(),p=[],g.clear(),o.remove()},showSearch:(R,S)=>{l.value=R,S&&(l.placeholder=S),r.style.display="",l.setAttribute("aria-expanded","true"),l.focus(),typeof requestAnimationFrame=="function"&&requestAnimationFrame(()=>{r.style.display!=="none"&&l.focus()})},hideSearch:()=>{r.style.display="none",l.value="",l.setAttribute("aria-expanded","false"),l.removeAttribute("aria-activedescendant")}}}var gA,fA,TR,yA=be(()=>{"use strict";je();gA=require("lucide");zn();wu();fA=new Map,TR=(t,e,n)=>{let o=`${t}|${e}|${n}`,r=fA.get(o);return r===void 0&&(r=Cu(t,e,"currentColor",n),fA.set(o,r)),r?r.cloneNode(!0):null}});var ER,kR,Mu,bA=be(()=>{"use strict";Oa();uA();bu();xh();mA();yA();Ah();ER=t=>!!t&&(typeof t=="object"||typeof t=="function")&&typeof t.then=="function",kR=0,Mu=class{constructor(e){this.popover=null;this.resizeObserver=null;this.isOpenState=!1;this.query="";this.triggerMatch=null;this.activeIndex=0;this.activeKey=null;this.pickerMode=!1;this.pickerTrigger=null;this.groups=[];this.flat=[];this.searchToken=0;this.searchAbort=null;this.debounceTimer=null;this.knownAsync=new Set;this.invokedForToken=new Set;this.lastAnnouncedCount=-1;this.triggerAnchorOffset=null;this.measuredTriggerIndex=null;this.opts=e;let n=e.mentionConfig,o=vu(n),r=o.filter(a=>a.sources.length>0);this.channels=r.length>0?r:[o[0]],this.activeChannel=this.channels[0],this.maxPerGroup=n.maxItemsPerGroup??6,this.debounceMs=n.searchDebounceMs??150,this.listboxId=`persona-mention-listbox-${++kR}`,this.menu=e.mentionConfig.renderMentionMenu?this.createHostMenu():hA({config:e.mentionConfig,listboxId:this.listboxId,onSelectIndex:a=>this.selectIndex(a),onHoverIndex:a=>this.setActiveIndex(a,!1),onRetry:a=>this.retrySource(a),onSearchInput:a=>this.setQuery(a),onSearchKeydown:a=>{this.handleKeydown(a)}});let s=e.composerInput.element;s.setAttribute("aria-haspopup","listbox"),s.setAttribute("aria-controls",this.listboxId)}get input(){return this.opts.composerInput}createHostMenu(){let e=document.createElement("div");e.setAttribute("data-persona-mention-menu",""),e.setAttribute("role","listbox"),e.id=this.listboxId;let n=()=>{let o=this.opts.mentionConfig.renderMentionMenu({query:this.query,groups:this.groups.map(r=>({source:r.source,items:r.items})),status:Object.fromEntries(this.groups.map(r=>[r.source.id,r.status])),activeIndex:this.activeIndex,select:r=>{let s=this.groups.find(a=>a.items.includes(r));s&&this.commit(s.source,r)},close:()=>this.close()});e.replaceChildren(o)};return{el:e,render:n,setActiveIndex:n,destroy:()=>e.remove()}}isOpen(){return this.isOpenState}openFromButton(e){let n=e&&this.channels.find(a=>a.trigger===e)||this.channels[0],o=this.input.getSelection().start,r=ic(this.input.getLogicalText(),o,[n]);if(r){this.pickerMode=!1,this.triggerMatch=r.match,this.isOpenState?(this.switchChannel(n),this.setQuery(r.match.query)):this.open(r.match.query,n),this.input.focus();return}let s=this.pickerTrigger;this.pickerMode=!0,this.pickerTrigger=n.trigger,this.triggerMatch=null,this.isOpenState?(s&&s!==n.trigger&&this.opts.onPickerOpenChange?.(!1,s,this.listboxId),this.switchChannel(n),this.setQuery("")):this.open("",n),this.menu.showSearch?this.menu.showSearch("",n.searchPlaceholder):this.input.focus(),this.opts.onPickerOpenChange?.(!0,n.trigger,this.listboxId)}onInput(){let e=this.input.getSelection().start,n=ic(this.input.getLogicalText(),e,this.channels);if(!n){this.isOpenState&&this.close();return}if(this.isInlineArgTail(n.channel,n.match.query)){this.triggerMatch=null,this.isOpenState&&this.close(!1);return}this.triggerMatch=n.match,this.isOpenState?(this.switchChannel(n.channel),this.measuredTriggerIndex!==n.match.triggerIndex&&this.updateTriggerAnchor(),this.setQuery(n.match.query)):this.open(n.match.query,n.channel)}switchChannel(e){e!==this.activeChannel&&(this.activeChannel=e,this.groups=[],this.activeIndex=0)}open(e,n){if(this.isOpenState=!0,this.activeChannel=n,this.groups=[],this.activeIndex=0,this.lastAnnouncedCount=-1,!this.popover){let o=this.canAnchorMenu();if(this.popover=Ps({anchor:this.opts.anchor,content:this.menu.el,placement:"top-start",matchAnchorWidth:!o,offset:6,container:this.opts.popoverContainer,horizontalOffset:o?()=>this.triggerAnchorOffset?.x??null:void 0,verticalOffset:o?()=>this.triggerAnchorOffset?.y??null:void 0,onDismiss:()=>this.close(!1)}),o){let r=this.opts.anchor.getBoundingClientRect().width;this.menu.el.style.minWidth=`${Math.min(220,r)}px`}}this.updateTriggerAnchor(),this.popover.open(),mu(this.menu.el,"persona-mention-menu",pA),this.observeComposerResize(),this.opts.emit?.("opened",{trigger:n.trigger}),this.setQuery(e)}observeComposerResize(){typeof ResizeObserver>"u"||this.resizeObserver||(this.resizeObserver=new ResizeObserver(()=>{this.isOpenState&&(this.updateTriggerAnchor(),this.popover?.reposition())}),this.resizeObserver.observe(this.opts.anchor))}disconnectComposerResize(){this.resizeObserver?.disconnect(),this.resizeObserver=null}canAnchorMenu(){return this.isInlineDisplay()&&!!this.input.getLogicalRangeRect}updateTriggerAnchor(){let e=this.triggerMatch,n=this.input.getLogicalRangeRect;if(this.measuredTriggerIndex=e?.triggerIndex??null,this.triggerAnchorOffset=null,!e||!n)return;let o=n(e.triggerIndex,e.triggerIndex+1);if(!o)return;let r=this.opts.anchor.getBoundingClientRect(),s=o.top-r.top,a=this.input.element,l=typeof getComputedStyle=="function"&&getComputedStyle(a).direction==="rtl";this.triggerAnchorOffset={x:l?null:o.left-r.left,y:s}}close(e=!0){this.isOpenState&&(this.isOpenState=!1,this.disconnectComposerResize(),this.debounceTimer&&clearTimeout(this.debounceTimer),this.searchAbort?.abort(),this.searchToken++,this.popover?.close(),this.input.element.removeAttribute("aria-activedescendant"),this.pickerMode&&(this.pickerMode=!1,this.menu.hideSearch?.(),this.opts.onPickerOpenChange?.(!1,this.pickerTrigger??this.activeChannel.trigger,this.listboxId),this.pickerTrigger=null,e&&this.input.focus()))}setQuery(e){this.query=e,this.activeIndex=0,this.activeKey=null;let n=++this.searchToken;this.invokedForToken.clear(),this.searchAbort?.abort(),this.searchAbort=new AbortController;for(let o of this.activeChannel.sources)this.knownAsync.has(o.id)?this.setGroupStatus(o.id,"loading"):(this.invokedForToken.add(o.id),this.invokeSource(o,n));this.render(),this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{if(n===this.searchToken)for(let o of this.activeChannel.sources)this.knownAsync.has(o.id)&&!this.invokedForToken.has(o.id)&&this.invokeSource(o,n)},this.debounceMs)}invokeSource(e,n){let o={messages:this.opts.getMessages(),config:this.opts.getConfig(),signal:this.searchAbort.signal},r;try{r=e.search(this.query,o)}catch{this.setGroupStatus(e.id,"error"),this.render();return}ER(r)?(this.knownAsync.add(e.id),this.setGroupStatus(e.id,"loading"),r.then(s=>{n===this.searchToken&&(this.setGroupItems(e.id,s),this.render())}).catch(()=>{n===this.searchToken&&(this.setGroupStatus(e.id,"error"),this.render())})):this.setGroupItems(e.id,r)}getOrCreateGroup(e){let n=this.groups.find(o=>o.source.id===e.id);if(!n){n={source:e,items:[],status:"loading",truncated:!1};let o=this.activeChannel.sources;this.groups.push(n),this.groups.sort((r,s)=>o.findIndex(a=>a.id===r.source.id)-o.findIndex(a=>a.id===s.source.id))}return n}setGroupStatus(e,n){let o=this.activeChannel.sources.find(r=>r.id===e);o&&(this.getOrCreateGroup(o).status=n)}setGroupItems(e,n){let o=this.activeChannel.sources.find(s=>s.id===e);if(!o)return;let r=this.getOrCreateGroup(o);r.truncated=n.length>this.maxPerGroup,r.items=n.slice(0,this.maxPerGroup),r.status=r.items.length===0?"empty":"ready"}keyOf(e){return JSON.stringify([e.source.id,e.item.id])}rebuildFlat(){this.flat=[];for(let e of this.groups)if(e.status==="ready")for(let n of e.items)this.flat.push({source:e.source,item:n});if(this.activeKey){let e=this.flat.findIndex(n=>this.keyOf(n)===this.activeKey);this.activeIndex=e>=0?e:Math.min(this.activeIndex,Math.max(0,this.flat.length-1))}else this.activeIndex>=this.flat.length&&(this.activeIndex=Math.max(0,this.flat.length-1))}viewModel(){return{query:this.query,groups:this.groups,activeIndex:this.activeIndex}}render(){this.rebuildFlat(),this.menu.render(this.viewModel()),this.syncActiveDescendant(),this.popover?.reposition();let e=this.groups.some(n=>n.status==="loading");this.flat.length===0&&e||this.flat.length!==this.lastAnnouncedCount&&(this.lastAnnouncedCount=this.flat.length,this.opts.announce(this.flat.length===0?"No matches":this.flat.length===1?"1 result":`${this.flat.length} results`),this.opts.emit?.("searched",{query:this.query,results:this.flat.length}))}setActiveIndex(e,n=!0){e<0||e>=this.flat.length||(this.activeIndex=e,this.activeKey=this.keyOf(this.flat[e]),this.menu.setActiveIndex(e,n),this.syncActiveDescendant())}syncActiveDescendant(){this.isOpenState&&!this.pickerMode&&this.activeIndex>=0&&this.activeIndex<this.flat.length?this.input.element.setAttribute("aria-activedescendant",`${this.listboxId}-opt-${this.activeIndex}`):this.input.element.removeAttribute("aria-activedescendant")}retrySource(e){let n=this.activeChannel.sources.find(o=>o.id===e);!n||!this.searchAbort||(this.setGroupStatus(e,"loading"),this.render(),this.invokeSource(n,this.searchToken),this.render())}handleKeydown(e){if(!this.isOpenState)return!1;switch(e.key){case"ArrowDown":return this.flat.length===0||(e.preventDefault(),this.setActiveIndex((this.activeIndex+1)%this.flat.length)),!0;case"ArrowUp":return this.flat.length===0||(e.preventDefault(),this.setActiveIndex((this.activeIndex-1+this.flat.length)%this.flat.length)),!0;case"Home":return this.flat.length===0||(e.preventDefault(),this.setActiveIndex(0)),!0;case"End":return this.flat.length===0||(e.preventDefault(),this.setActiveIndex(this.flat.length-1)),!0;case"Enter":case"Tab":return this.flat.length===0?(this.close(),!1):(e.preventDefault(),this.selectIndex(this.activeIndex),!0);case"Escape":return e.preventDefault(),this.close(),!0;case"Backspace":return this.query.length===0&&this.close(),!1;default:return!1}}selectIndex(e){let n=this.flat[e];n&&this.commit(n.source,n.item)}deriveArgs(e){return Au(e).args}isInlineCommand(e){return e.command==="server"||e.commandArgsPlaceholder!=null}commit(e,n){let o=n.command;if(this.isInlineCommand(n)){this.completeCommandInline(e,n);return}if(o==="action"){let s=this.deriveArgs(this.query);this.stripQuery(),this.close(),this.runAction(n,s),this.opts.emit?.("command",{sourceId:e.id,itemId:n.id,kind:"action",args:s}),this.input.focus();return}if(o==="prompt"){let s=this.deriveArgs(this.query),a=this.captureStripTarget();this.close(),this.runPromptMacro(e,n,s,a),this.opts.emit?.("command",{sourceId:e.id,itemId:n.id,kind:"prompt",args:s});return}if(this.isInlineDisplay()){this.commitInlineMention(e,n);return}this.opts.onSelect(e,n,"")&&(this.stripQuery(),this.opts.emit?.("selected",{sourceId:e.id,itemId:n.id,label:n.label})),this.close(),this.input.focus()}isInlineDisplay(){return this.opts.mentionConfig.display==="inline"&&!!this.opts.onInsertMention&&!!this.input.insertMentionAtTrigger}commitInlineMention(e,n){if(this.opts.admitMention&&!this.opts.admitMention(e,n)){this.close(),this.input.focus();return}let o=xu(e,n),r=this.triggerMatch?this.input.insertMentionAtTrigger(o,this.triggerMatch):this.input.insertMentionAtSelection?.(o)??null;r?(this.opts.onInsertMention(r,e,n,""),this.opts.emit?.("selected",{sourceId:e.id,itemId:n.id,label:n.label})):(this.opts.mentionConfig.onMentionRejected?.(n,"stale"),this.opts.emit?.("rejected",{sourceId:e.id,itemId:n.id,reason:"stale"})),this.triggerMatch=null,this.close(),this.input.focus()}completeCommandInline(e,n){let o=`${this.activeChannel.trigger}${n.label} `,r=this.input.getSelection().start,s=this.triggerMatch?this.triggerMatch.triggerIndex:r;if(this.input.replaceLogicalRange)this.input.replaceLogicalRange(s,r,o);else{let a=this.input.getValue();this.input.setValueWithCaret(a.slice(0,s)+o+a.slice(r),s+o.length)}this.triggerMatch=null,this.close(),this.opts.emit?.("command",{sourceId:e.id,itemId:n.id,kind:n.command??"prompt",phase:"armed"}),this.input.dispatchInput(),this.input.focus()}isInlineArgTail(e,n){let{name:o}=Au(n);return!o||n.length<=o.length?!1:e.sources.some(r=>{let s=r.matchCommand?.(o);return!!s&&this.isInlineCommand(s)})}matchInlineCommand(e){for(let n of this.channels){if(!n.trigger)continue;let o=n.position==="anywhere"?[e]:n.position==="line-start"?e.split(`
|
|
177
|
+
`});function Au(t){let e=t.replace(/^\s+/,""),n=e.search(/\s/);return n===-1?{name:e,args:""}:{name:e.slice(0,n),args:e.slice(n+1).trim()}}var SA=be(()=>{"use strict"});function TA(t){let{config:e,listboxId:n}=t,o=F("div",{className:"persona-mention-menu",attrs:{"data-persona-mention-menu":""}}),r=F("div",{className:"persona-mention-search",style:{display:"none"}}),s=v("span","persona-mention-search-icon"),a=Ge(MA.Search,15,"currentColor",2);a&&s.appendChild(a);let l=F("input",{className:"persona-mention-search-input",attrs:{type:"text",role:"combobox","aria-autocomplete":"list","aria-expanded":"false","aria-controls":n,"aria-label":e.searchPlaceholder??"Search context",placeholder:e.searchPlaceholder??"Search context\u2026",autocomplete:"off",autocapitalize:"off",spellcheck:"false"}});r.append(s,l),l.addEventListener("input",()=>t.onSearchInput?.(l.value)),l.addEventListener("keydown",H=>t.onSearchKeydown?.(H));let c=F("div",{className:"persona-mention-list",attrs:{role:"listbox",id:n,"aria-label":"Context mentions"}});o.append(r,c);let p=[],u=[],m=-1,g=new Map,h=(H,S)=>`${H}\0${S}`,b=H=>`${n}-opt-${H}`,C=H=>`${n}-grp-${H}`,M=(H,S)=>{let x=p[H];x&&(S?x.setAttribute("data-active","true"):x.removeAttribute("data-active"),x.setAttribute("aria-selected",S?"true":"false"),u[H]?.(S))},E=(H,S=!0)=>{m>=0&&m!==H&&M(m,!1),m=H;let x=p[H];x?(M(H,!0),S&&x.scrollIntoView?.({block:"nearest"}),c.setAttribute("aria-activedescendant",x.id),l.setAttribute("aria-activedescendant",x.id)):(c.removeAttribute("aria-activedescendant"),l.removeAttribute("aria-activedescendant"))},T=(H,S)=>{let x=C(S),P=F("div",{className:"persona-mention-group",attrs:{role:"group","aria-labelledby":x}});return P.appendChild(F("div",{className:"persona-mention-group-header",attrs:{id:x},text:H})),P},R=()=>{let H=F("div",{className:"persona-mention-option",attrs:{role:"option","aria-selected":"false"}}),S=v("span","persona-mention-option-icon");H.appendChild(S);let x="",P=v("span","persona-mention-option-text"),L=v("span","persona-mention-option-labelline"),G=v("span","persona-mention-option-label");L.appendChild(G),P.appendChild(L),H.appendChild(P);let V=null,K=null,ee={el:H,index:0,update:(oe,ne,le)=>{ee.index=ne,H.id=b(ne),H.setAttribute("aria-setsize",String(le)),H.setAttribute("aria-posinset",String(ne+1)),H.removeAttribute("data-active"),H.setAttribute("aria-selected","false");let de=oe.iconName??e.chipIconName??"at-sign";if(de!==x){x=de;let Le=$H(de,15,2);S.replaceChildren(...Le?[Le]:[])}G.textContent!==oe.label&&(G.textContent=oe.label);let ve=oe.commandArgsPlaceholder?`\u2039${oe.commandArgsPlaceholder}\u203A`:null;ve?(V||(V=v("span","persona-mention-option-arghint"),L.appendChild(V)),V.textContent!==ve&&(V.textContent=ve)):V&&(V.remove(),V=null),oe.description?(K||(K=v("span","persona-mention-option-desc"),P.appendChild(K)),K.textContent!==oe.description&&(K.textContent=oe.description)):K&&(K.remove(),K=null)}};return H.addEventListener("mousedown",oe=>{oe.button===0&&(oe.preventDefault(),t.onSelectIndex(ee.index))}),H.addEventListener("mouseenter",()=>t.onHoverIndex(ee.index)),ee},A=(H,S,x,P,L)=>{let G=F("div",{className:"persona-mention-option",attrs:{role:"option",id:b(P),"aria-selected":"false","aria-setsize":String(L),"aria-posinset":String(P+1)}}),V=K=>{G.replaceChildren(e.renderMentionItem({item:H,source:S,query:x,active:K,index:P}))};return V(!1),G.addEventListener("mousedown",K=>{K.button===0&&(K.preventDefault(),t.onSelectIndex(P))}),G.addEventListener("mouseenter",()=>t.onHoverIndex(P)),{el:G,paint:V}},D=H=>{let S=F("div",{className:"persona-mention-status persona-mention-error"});if(S.appendChild(F("span",{className:"persona-mention-error-text",text:`Couldn't load ${H.label}`})),t.onRetry){let x=F("button",{className:"persona-mention-retry",attrs:{type:"button"},text:"Retry"});x.addEventListener("mousedown",P=>P.preventDefault()),x.addEventListener("click",P=>{P.preventDefault(),t.onRetry(H.id)}),S.appendChild(x)}return S};return{el:o,render:H=>{c.replaceChildren(),p=[],u=[],m=-1;let S=new Set,x=0,P=0,L=0,G=0,V=0,K=H.groups.reduce((ee,oe)=>oe.status==="ready"?ee+oe.items.length:ee,0);for(let ee of H.groups)if(ee.status==="loading"){L++;let oe=T(ee.source.label,V++);oe.appendChild(F("div",{className:"persona-mention-status persona-mention-loading",attrs:{role:"presentation"},text:"Loading\u2026"})),c.appendChild(oe)}else if(ee.status==="error"){G++;let oe=T(ee.source.label,V++);oe.appendChild(D(ee.source)),c.appendChild(oe)}else if(ee.status==="ready"&&ee.items.length>0){let oe=new Map;for(let le of ee.items){let de=le.group??ee.source.label,ve=oe.get(de);ve?ve.push(le):oe.set(de,[le])}let ne=Array.from(oe.entries());ne.forEach(([le,de],ve)=>{let Le=T(le,V++);for(let se of de){let _=x++,Te;if(e.renderMentionItem){let Re=A(se,ee.source,H.query,_,K);Te=Re.el,u.push(Re.paint)}else{let Re=h(ee.source.id,se.id),ut=S.has(Re)?void 0:g.get(Re);ut||(ut=R(),S.has(Re)||g.set(Re,ut)),S.add(Re),ut.update(se,_,K),Te=ut.el,u.push(null)}p.push(Te),Le.appendChild(Te),P++}ee.truncated&&ve===ne.length-1&&Le.appendChild(F("div",{className:"persona-mention-hint",attrs:{role:"presentation"},text:"Keep typing to narrow\u2026"})),c.appendChild(Le)})}for(let ee of g.keys())S.has(ee)||g.delete(ee);P===0&&L===0&&G===0&&c.appendChild(F("div",{className:"persona-mention-empty",attrs:{role:"presentation"},text:"No matches"})),p.length>0?E(Math.min(Math.max(0,H.activeIndex),p.length-1)):(c.removeAttribute("aria-activedescendant"),l.removeAttribute("aria-activedescendant"))},setActiveIndex:E,destroy:()=>{c.replaceChildren(),p=[],g.clear(),o.remove()},showSearch:(H,S)=>{l.value=H,S&&(l.placeholder=S),r.style.display="",l.setAttribute("aria-expanded","true"),l.focus(),typeof requestAnimationFrame=="function"&&requestAnimationFrame(()=>{r.style.display!=="none"&&l.focus()})},hideSearch:()=>{r.style.display="none",l.value="",l.setAttribute("aria-expanded","false"),l.removeAttribute("aria-activedescendant")}}}var MA,AA,$H,EA=be(()=>{"use strict";je();MA=require("lucide");zn();wu();AA=new Map,$H=(t,e,n)=>{let o=`${t}|${e}|${n}`,r=AA.get(o);return r===void 0&&(r=Cu(t,e,"currentColor",n),AA.set(o,r)),r?r.cloneNode(!0):null}});var zH,UH,Mu,kA=be(()=>{"use strict";Oa();xA();bu();Ah();SA();EA();Th();zH=t=>!!t&&(typeof t=="object"||typeof t=="function")&&typeof t.then=="function",UH=0,Mu=class{constructor(e){this.popover=null;this.resizeObserver=null;this.isOpenState=!1;this.query="";this.triggerMatch=null;this.activeIndex=0;this.activeKey=null;this.pickerMode=!1;this.pickerTrigger=null;this.groups=[];this.flat=[];this.searchToken=0;this.searchAbort=null;this.debounceTimer=null;this.knownAsync=new Set;this.invokedForToken=new Set;this.lastAnnouncedCount=-1;this.triggerAnchorOffset=null;this.measuredTriggerIndex=null;this.opts=e;let n=e.mentionConfig,o=vu(n),r=o.filter(a=>a.sources.length>0);this.channels=r.length>0?r:[o[0]],this.activeChannel=this.channels[0],this.maxPerGroup=n.maxItemsPerGroup??6,this.debounceMs=n.searchDebounceMs??150,this.listboxId=`persona-mention-listbox-${++UH}`,this.menu=e.mentionConfig.renderMentionMenu?this.createHostMenu():TA({config:e.mentionConfig,listboxId:this.listboxId,onSelectIndex:a=>this.selectIndex(a),onHoverIndex:a=>this.setActiveIndex(a,!1),onRetry:a=>this.retrySource(a),onSearchInput:a=>this.setQuery(a),onSearchKeydown:a=>{this.handleKeydown(a)}});let s=e.composerInput.element;s.setAttribute("aria-haspopup","listbox"),s.setAttribute("aria-controls",this.listboxId)}get input(){return this.opts.composerInput}createHostMenu(){let e=document.createElement("div");e.setAttribute("data-persona-mention-menu",""),e.setAttribute("role","listbox"),e.id=this.listboxId;let n=()=>{let o=this.opts.mentionConfig.renderMentionMenu({query:this.query,groups:this.groups.map(r=>({source:r.source,items:r.items})),status:Object.fromEntries(this.groups.map(r=>[r.source.id,r.status])),activeIndex:this.activeIndex,select:r=>{let s=this.groups.find(a=>a.items.includes(r));s&&this.commit(s.source,r)},close:()=>this.close()});e.replaceChildren(o)};return{el:e,render:n,setActiveIndex:n,destroy:()=>e.remove()}}isOpen(){return this.isOpenState}openFromButton(e){let n=e&&this.channels.find(a=>a.trigger===e)||this.channels[0],o=this.input.getSelection().start,r=ic(this.input.getLogicalText(),o,[n]);if(r){this.pickerMode=!1,this.triggerMatch=r.match,this.isOpenState?(this.switchChannel(n),this.setQuery(r.match.query)):this.open(r.match.query,n),this.input.focus();return}let s=this.pickerTrigger;this.pickerMode=!0,this.pickerTrigger=n.trigger,this.triggerMatch=null,this.isOpenState?(s&&s!==n.trigger&&this.opts.onPickerOpenChange?.(!1,s,this.listboxId),this.switchChannel(n),this.setQuery("")):this.open("",n),this.menu.showSearch?this.menu.showSearch("",n.searchPlaceholder):this.input.focus(),this.opts.onPickerOpenChange?.(!0,n.trigger,this.listboxId)}onInput(){let e=this.input.getSelection().start,n=ic(this.input.getLogicalText(),e,this.channels);if(!n){this.isOpenState&&this.close();return}if(this.isInlineArgTail(n.channel,n.match.query)){this.triggerMatch=null,this.isOpenState&&this.close(!1);return}this.triggerMatch=n.match,this.isOpenState?(this.switchChannel(n.channel),this.measuredTriggerIndex!==n.match.triggerIndex&&this.updateTriggerAnchor(),this.setQuery(n.match.query)):this.open(n.match.query,n.channel)}switchChannel(e){e!==this.activeChannel&&(this.activeChannel=e,this.groups=[],this.activeIndex=0)}open(e,n){if(this.isOpenState=!0,this.activeChannel=n,this.groups=[],this.activeIndex=0,this.lastAnnouncedCount=-1,!this.popover){let o=this.canAnchorMenu();if(this.popover=Ps({anchor:this.opts.anchor,content:this.menu.el,placement:"top-start",matchAnchorWidth:!o,offset:6,container:this.opts.popoverContainer,horizontalOffset:o?()=>this.triggerAnchorOffset?.x??null:void 0,verticalOffset:o?()=>this.triggerAnchorOffset?.y??null:void 0,onDismiss:()=>this.close(!1)}),o){let r=this.opts.anchor.getBoundingClientRect().width;this.menu.el.style.minWidth=`${Math.min(220,r)}px`}}this.updateTriggerAnchor(),this.popover.open(),mu(this.menu.el,"persona-mention-menu",wA),this.observeComposerResize(),this.opts.emit?.("opened",{trigger:n.trigger}),this.setQuery(e)}observeComposerResize(){typeof ResizeObserver>"u"||this.resizeObserver||(this.resizeObserver=new ResizeObserver(()=>{this.isOpenState&&(this.updateTriggerAnchor(),this.popover?.reposition())}),this.resizeObserver.observe(this.opts.anchor))}disconnectComposerResize(){this.resizeObserver?.disconnect(),this.resizeObserver=null}canAnchorMenu(){return this.isInlineDisplay()&&!!this.input.getLogicalRangeRect}updateTriggerAnchor(){let e=this.triggerMatch,n=this.input.getLogicalRangeRect;if(this.measuredTriggerIndex=e?.triggerIndex??null,this.triggerAnchorOffset=null,!e||!n)return;let o=n(e.triggerIndex,e.triggerIndex+1);if(!o)return;let r=this.opts.anchor.getBoundingClientRect(),s=o.top-r.top,a=this.input.element,l=typeof getComputedStyle=="function"&&getComputedStyle(a).direction==="rtl";this.triggerAnchorOffset={x:l?null:o.left-r.left,y:s}}close(e=!0){this.isOpenState&&(this.isOpenState=!1,this.disconnectComposerResize(),this.debounceTimer&&clearTimeout(this.debounceTimer),this.searchAbort?.abort(),this.searchToken++,this.popover?.close(),this.input.element.removeAttribute("aria-activedescendant"),this.pickerMode&&(this.pickerMode=!1,this.menu.hideSearch?.(),this.opts.onPickerOpenChange?.(!1,this.pickerTrigger??this.activeChannel.trigger,this.listboxId),this.pickerTrigger=null,e&&this.input.focus()))}setQuery(e){this.query=e,this.activeIndex=0,this.activeKey=null;let n=++this.searchToken;this.invokedForToken.clear(),this.searchAbort?.abort(),this.searchAbort=new AbortController;for(let o of this.activeChannel.sources)this.knownAsync.has(o.id)?this.setGroupStatus(o.id,"loading"):(this.invokedForToken.add(o.id),this.invokeSource(o,n));this.render(),this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{if(n===this.searchToken)for(let o of this.activeChannel.sources)this.knownAsync.has(o.id)&&!this.invokedForToken.has(o.id)&&this.invokeSource(o,n)},this.debounceMs)}invokeSource(e,n){let o={messages:this.opts.getMessages(),config:this.opts.getConfig(),signal:this.searchAbort.signal},r;try{r=e.search(this.query,o)}catch{this.setGroupStatus(e.id,"error"),this.render();return}zH(r)?(this.knownAsync.add(e.id),this.setGroupStatus(e.id,"loading"),r.then(s=>{n===this.searchToken&&(this.setGroupItems(e.id,s),this.render())}).catch(()=>{n===this.searchToken&&(this.setGroupStatus(e.id,"error"),this.render())})):this.setGroupItems(e.id,r)}getOrCreateGroup(e){let n=this.groups.find(o=>o.source.id===e.id);if(!n){n={source:e,items:[],status:"loading",truncated:!1};let o=this.activeChannel.sources;this.groups.push(n),this.groups.sort((r,s)=>o.findIndex(a=>a.id===r.source.id)-o.findIndex(a=>a.id===s.source.id))}return n}setGroupStatus(e,n){let o=this.activeChannel.sources.find(r=>r.id===e);o&&(this.getOrCreateGroup(o).status=n)}setGroupItems(e,n){let o=this.activeChannel.sources.find(s=>s.id===e);if(!o)return;let r=this.getOrCreateGroup(o);r.truncated=n.length>this.maxPerGroup,r.items=n.slice(0,this.maxPerGroup),r.status=r.items.length===0?"empty":"ready"}keyOf(e){return JSON.stringify([e.source.id,e.item.id])}rebuildFlat(){this.flat=[];for(let e of this.groups)if(e.status==="ready")for(let n of e.items)this.flat.push({source:e.source,item:n});if(this.activeKey){let e=this.flat.findIndex(n=>this.keyOf(n)===this.activeKey);this.activeIndex=e>=0?e:Math.min(this.activeIndex,Math.max(0,this.flat.length-1))}else this.activeIndex>=this.flat.length&&(this.activeIndex=Math.max(0,this.flat.length-1))}viewModel(){return{query:this.query,groups:this.groups,activeIndex:this.activeIndex}}render(){this.rebuildFlat(),this.menu.render(this.viewModel()),this.syncActiveDescendant(),this.popover?.reposition();let e=this.groups.some(n=>n.status==="loading");this.flat.length===0&&e||this.flat.length!==this.lastAnnouncedCount&&(this.lastAnnouncedCount=this.flat.length,this.opts.announce(this.flat.length===0?"No matches":this.flat.length===1?"1 result":`${this.flat.length} results`),this.opts.emit?.("searched",{query:this.query,results:this.flat.length}))}setActiveIndex(e,n=!0){e<0||e>=this.flat.length||(this.activeIndex=e,this.activeKey=this.keyOf(this.flat[e]),this.menu.setActiveIndex(e,n),this.syncActiveDescendant())}syncActiveDescendant(){this.isOpenState&&!this.pickerMode&&this.activeIndex>=0&&this.activeIndex<this.flat.length?this.input.element.setAttribute("aria-activedescendant",`${this.listboxId}-opt-${this.activeIndex}`):this.input.element.removeAttribute("aria-activedescendant")}retrySource(e){let n=this.activeChannel.sources.find(o=>o.id===e);!n||!this.searchAbort||(this.setGroupStatus(e,"loading"),this.render(),this.invokeSource(n,this.searchToken),this.render())}handleKeydown(e){if(!this.isOpenState)return!1;switch(e.key){case"ArrowDown":return this.flat.length===0||(e.preventDefault(),this.setActiveIndex((this.activeIndex+1)%this.flat.length)),!0;case"ArrowUp":return this.flat.length===0||(e.preventDefault(),this.setActiveIndex((this.activeIndex-1+this.flat.length)%this.flat.length)),!0;case"Home":return this.flat.length===0||(e.preventDefault(),this.setActiveIndex(0)),!0;case"End":return this.flat.length===0||(e.preventDefault(),this.setActiveIndex(this.flat.length-1)),!0;case"Enter":case"Tab":return this.flat.length===0?(this.close(),!1):(e.preventDefault(),this.selectIndex(this.activeIndex),!0);case"Escape":return e.preventDefault(),this.close(),!0;case"Backspace":return this.query.length===0&&this.close(),!1;default:return!1}}selectIndex(e){let n=this.flat[e];n&&this.commit(n.source,n.item)}deriveArgs(e){return Au(e).args}isInlineCommand(e){return e.command==="server"||e.commandArgsPlaceholder!=null}commit(e,n){let o=n.command;if(this.isInlineCommand(n)){this.completeCommandInline(e,n);return}if(o==="action"){let s=this.deriveArgs(this.query);this.stripQuery(),this.close(),this.runAction(n,s),this.opts.emit?.("command",{sourceId:e.id,itemId:n.id,kind:"action",args:s}),this.input.focus();return}if(o==="prompt"){let s=this.deriveArgs(this.query),a=this.captureStripTarget();this.close(),this.runPromptMacro(e,n,s,a),this.opts.emit?.("command",{sourceId:e.id,itemId:n.id,kind:"prompt",args:s});return}if(this.isInlineDisplay()){this.commitInlineMention(e,n);return}this.opts.onSelect(e,n,"")&&(this.stripQuery(),this.opts.emit?.("selected",{sourceId:e.id,itemId:n.id,label:n.label})),this.close(),this.input.focus()}isInlineDisplay(){return this.opts.mentionConfig.display==="inline"&&!!this.opts.onInsertMention&&!!this.input.insertMentionAtTrigger}commitInlineMention(e,n){if(this.opts.admitMention&&!this.opts.admitMention(e,n)){this.close(),this.input.focus();return}let o=xu(e,n),r=this.triggerMatch?this.input.insertMentionAtTrigger(o,this.triggerMatch):this.input.insertMentionAtSelection?.(o)??null;r?(this.opts.onInsertMention(r,e,n,""),this.opts.emit?.("selected",{sourceId:e.id,itemId:n.id,label:n.label})):(this.opts.mentionConfig.onMentionRejected?.(n,"stale"),this.opts.emit?.("rejected",{sourceId:e.id,itemId:n.id,reason:"stale"})),this.triggerMatch=null,this.close(),this.input.focus()}completeCommandInline(e,n){let o=`${this.activeChannel.trigger}${n.label} `,r=this.input.getSelection().start,s=this.triggerMatch?this.triggerMatch.triggerIndex:r;if(this.input.replaceLogicalRange)this.input.replaceLogicalRange(s,r,o);else{let a=this.input.getValue();this.input.setValueWithCaret(a.slice(0,s)+o+a.slice(r),s+o.length)}this.triggerMatch=null,this.close(),this.opts.emit?.("command",{sourceId:e.id,itemId:n.id,kind:n.command??"prompt",phase:"armed"}),this.input.dispatchInput(),this.input.focus()}isInlineArgTail(e,n){let{name:o}=Au(n);return!o||n.length<=o.length?!1:e.sources.some(r=>{let s=r.matchCommand?.(o);return!!s&&this.isInlineCommand(s)})}matchInlineCommand(e){for(let n of this.channels){if(!n.trigger)continue;let o=n.position==="anywhere"?[e]:n.position==="line-start"?e.split(`
|
|
178
178
|
`):[e.split(`
|
|
179
|
-
`)[0]];for(let r of o){if(!r.startsWith(n.trigger))continue;let{name:s,args:a}=Au(r.slice(n.trigger.length));if(s)for(let l of n.sources){let c=l.matchCommand?.(s);if(c&&this.isInlineCommand(c))return{source:l,item:c,args:a}}}}return null}async dispatchInlineCommand(e){let n=this.matchInlineCommand(e);if(!n)return null;let{source:o,item:r,args:s}=n,a=r.command??"prompt";if(this.opts.emit?.("command",{sourceId:o.id,itemId:r.id,kind:a,args:s}),a==="action")return this.runAction(r,s),{kind:"action"};if(a==="prompt"){let c;try{c=await o.resolve(r,this.resolveContext(s,e))}catch(p){return typeof console<"u"&&console.warn("[Persona] inline prompt command resolve failed",p),null}return{kind:"prompt",sendText:c.insertText??c.llmAppend??e}}return{kind:"server",mentions:{refs:[],finalize:async()=>{let c=await o.resolve(r,this.resolveContext(s,e)),p={};return c.context&&(p[o.id]={[r.id]:c.context}),{blocks:[],contentParts:c.contentParts??[],context:p}}}}}resolveContext(e,n){return{messages:this.opts.getMessages(),config:this.opts.getConfig(),composerText:n,args:e,signal:new AbortController().signal}}runAction(e,n){if(e.action)try{Promise.resolve(e.action({args:n,config:this.opts.getConfig(),messages:this.opts.getMessages(),composer:this.input})).catch(o=>{typeof console<"u"&&console.warn("[Persona] context-mention command action failed",o)})}catch(o){typeof console<"u"&&console.warn("[Persona] context-mention command action failed",o)}}captureStripTarget(){return this.triggerMatch?{value:this.input.getValue(),start:this.triggerMatch.triggerIndex,end:this.input.getSelection().start}:null}async runPromptMacro(e,n,o,r){let s=this.input,a;try{a=await e.resolve(n,{messages:this.opts.getMessages(),config:this.opts.getConfig(),composerText:s.getValue(),args:o,signal:new AbortController().signal})}catch(c){typeof console<"u"&&console.warn("[Persona] context-mention prompt resolve failed",c);return}let l=a.insertText??a.llmAppend??"";n.insertMode==="insert-at-caret"&&r?s.replaceLogicalRange?(s.replaceLogicalRange(r.start,r.end,l),s.dispatchInput()):s.setValue(r.value.slice(0,r.start)+l+r.value.slice(r.end)):s.setValue(l),n.submitOnSelect&&s.submit()}stripQuery(){if(!this.triggerMatch)return;let e=this.input.getSelection().start;if(this.input.replaceLogicalRange)this.input.replaceLogicalRange(this.triggerMatch.triggerIndex,e,"");else{let n=
|
|
180
|
-
`,p=
|
|
181
|
-
`?0:1);return{doc:{blocks:p},caret:u}}function
|
|
182
|
-
`});function
|
|
183
|
-
`);return s<0?"":t.slice(0,s)}return t},
|
|
179
|
+
`)[0]];for(let r of o){if(!r.startsWith(n.trigger))continue;let{name:s,args:a}=Au(r.slice(n.trigger.length));if(s)for(let l of n.sources){let c=l.matchCommand?.(s);if(c&&this.isInlineCommand(c))return{source:l,item:c,args:a}}}}return null}async dispatchInlineCommand(e){let n=this.matchInlineCommand(e);if(!n)return null;let{source:o,item:r,args:s}=n,a=r.command??"prompt";if(this.opts.emit?.("command",{sourceId:o.id,itemId:r.id,kind:a,args:s}),a==="action")return this.runAction(r,s),{kind:"action"};if(a==="prompt"){let c;try{c=await o.resolve(r,this.resolveContext(s,e))}catch(p){return typeof console<"u"&&console.warn("[Persona] inline prompt command resolve failed",p),null}return{kind:"prompt",sendText:c.insertText??c.llmAppend??e}}return{kind:"server",mentions:{refs:[],finalize:async()=>{let c=await o.resolve(r,this.resolveContext(s,e)),p={};return c.context&&(p[o.id]={[r.id]:c.context}),{blocks:[],contentParts:c.contentParts??[],context:p}}}}}resolveContext(e,n){return{messages:this.opts.getMessages(),config:this.opts.getConfig(),composerText:n,args:e,signal:new AbortController().signal}}runAction(e,n){if(e.action)try{Promise.resolve(e.action({args:n,config:this.opts.getConfig(),messages:this.opts.getMessages(),composer:this.input})).catch(o=>{typeof console<"u"&&console.warn("[Persona] context-mention command action failed",o)})}catch(o){typeof console<"u"&&console.warn("[Persona] context-mention command action failed",o)}}captureStripTarget(){return this.triggerMatch?{value:this.input.getValue(),start:this.triggerMatch.triggerIndex,end:this.input.getSelection().start}:null}async runPromptMacro(e,n,o,r){let s=this.input,a;try{a=await e.resolve(n,{messages:this.opts.getMessages(),config:this.opts.getConfig(),composerText:s.getValue(),args:o,signal:new AbortController().signal})}catch(c){typeof console<"u"&&console.warn("[Persona] context-mention prompt resolve failed",c);return}let l=a.insertText??a.llmAppend??"";n.insertMode==="insert-at-caret"&&r?s.replaceLogicalRange?(s.replaceLogicalRange(r.start,r.end,l),s.dispatchInput()):s.setValue(r.value.slice(0,r.start)+l+r.value.slice(r.end)):s.setValue(l),n.submitOnSelect&&s.submit()}stripQuery(){if(!this.triggerMatch)return;let e=this.input.getSelection().start;if(this.input.replaceLogicalRange)this.input.replaceLogicalRange(this.triggerMatch.triggerIndex,e,"");else{let n=fA(this.input.getValue(),this.triggerMatch,e);this.input.setValueWithCaret(n.value,n.caret)}this.input.dispatchInput(),this.triggerMatch=null}destroy(){this.disconnectComposerResize(),this.debounceTimer&&clearTimeout(this.debounceTimer),this.searchAbort?.abort(),this.popover?.destroy(),this.menu.destroy();let e=this.input.element;e.removeAttribute("aria-haspopup"),e.removeAttribute("aria-controls"),e.removeAttribute("aria-activedescendant")}}});function Eh(t,e){let n=document.createElement("div");n.className="persona-sr-only",n.setAttribute("aria-live",t),n.setAttribute("aria-atomic","true"),n.setAttribute("role",t==="assertive"?"alert":"status"),n.setAttribute("data-persona-mention-live-region","");let o=e.getRootNode();typeof ShadowRoot<"u"&&o instanceof ShadowRoot?(Object.assign(n.style,qH),document.body.appendChild(n)):e.appendChild(n);let s;return{announce:a=>{s!==void 0&&clearTimeout(s),n.textContent="",s=setTimeout(()=>{s=void 0,n.textContent=a},0)},destroy:()=>{s!==void 0&&clearTimeout(s),n.remove()}}}var qH,PA=be(()=>{"use strict";qH={position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}});function LA(t){let e=t.composerInput??lA(t.textarea),n=Eh("polite",t.liveRegionHost),o=Eh("assertive",t.liveRegionHost),r=p=>n.announce(p),s=p=>o.announce(p),a=new Su({mentionConfig:t.mentionConfig,contextRow:t.contextRow,getMessages:t.getMessages,getConfig:t.getConfig,getComposerText:()=>e.getValue(),announce:r,announceError:s,emit:t.emit}),l=()=>new Mu({mentionConfig:t.mentionConfig,composerInput:e,anchor:t.anchor,getMessages:t.getMessages,getConfig:t.getConfig,onSelect:(p,u,m)=>a.add(p,u,m),onInsertMention:(p,u,m,g)=>a.track(p,u,m,g,h=>e.setMentionStatus?.(p,h)),admitMention:(p,u)=>a.admit(p,u),announce:r,popoverContainer:t.popoverContainer,onPickerOpenChange:t.onPickerOpenChange,emit:t.emit}),c=l();return{openMenu:p=>c.openFromButton(p),isMenuOpen:()=>c.isOpen(),handleInput:()=>c.onInput(),handleKeydown:p=>c.handleKeydown(p),hasMentions:()=>a.hasMentions(),getMentionRefs:()=>a.getRefs(),removeLastChip:()=>a.removeLast(),dispatchInlineCommand:p=>c.dispatchInlineCommand(p),collectForSubmit:()=>a.hasMentions()?a.collectForSubmit():null,untrackMention:p=>a.remove(p),rebindComposer:p=>{p!==e&&(c.destroy(),e=p,c=l())},clear:()=>a.clear(),destroy:()=>{c.destroy(),a.clear(),n.destroy(),o.destroy()}}}var IA=be(()=>{"use strict";Th();kA();yu();PA();wu()});var HA={};$n(HA,{mountContextMentions:()=>LA,setMentionIconRenderer:()=>Mh});var RA=be(()=>{"use strict";IA()});function Lh(t){return t.kind==="text"?t.value.length:1}function Ih(t){let e=[],n=r=>{let s=e[e.length-1];s&&s.kind==="text"?s.value+=r:e.push({kind:"text",value:r})};(t.length===0||t[0].kind!=="text")&&e.push({kind:"text",value:""});for(let r of t){if(r.kind==="text"){n(r.value);continue}let s=e[e.length-1];(!s||s.kind!=="text")&&e.push({kind:"text",value:""}),e.push({kind:"mention",id:r.id,ref:r.ref}),e.push({kind:"text",value:""})}let o=e[e.length-1];return(!o||o.kind!=="text")&&e.push({kind:"text",value:""}),e}function WA(){return{blocks:[{kind:"text",value:""}]}}function Hh(t){return{blocks:[{kind:"text",value:t}]}}function Rh(t){return t.blocks.map(e=>e.kind==="text"?e.value:`${KH}${e.ref.label}`).join("")}function Eu(t){return t.blocks.map(e=>e.kind==="text"?e.value:"\uFFFC").join("")}function ku(t){return t.blocks.reduce((e,n)=>e+Lh(n),0)}function GH(t){let e=[];for(let n of t.blocks)n.kind==="mention"&&e.push({id:n.id,ref:n.ref});return e}function Tu(t,e){let n=[],o=[],r=0;for(let s of t){let a=Lh(s),l=r+a;if(l<=e)n.push(s);else if(r>=e)o.push(s);else if(s.kind==="text"){let c=e-r;c>0&&n.push({kind:"text",value:s.value.slice(0,c)}),c<a&&o.push({kind:"text",value:s.value.slice(c)})}else o.push(s);r=l}return{left:n,right:o}}function Wh(t,e,n,o){let r=Tu(t.blocks,e.start).left,s=Tu(t.blocks,e.end).right,a=s[0],l=a?.kind==="text"?a.value.charAt(0):"",c=l!==" "&&l!==" "&&l!==`
|
|
180
|
+
`,p=Ih([...r,{kind:"mention",id:o,ref:n},...c?[{kind:"text",value:" "}]:[],...s]),u=e.start+1+(l===`
|
|
181
|
+
`?0:1);return{doc:{blocks:p},caret:u}}function BA(t,e){let n=0,o=0,r=!1;for(let a of t.blocks)a.kind==="mention"&&a.id===e&&(n=o,r=!0),o+=Lh(a);return r?{doc:{blocks:Ih(t.blocks.filter(a=>!(a.kind==="mention"&&a.id===e)))},caret:n}:{doc:t,caret:o}}function Pu(t,e,n,o){let r=ku(t),s=Math.max(0,Math.min(e,n,r)),a=Math.min(r,Math.max(e,n,0)),l=Tu(t.blocks,s).left,c=Tu(t.blocks,a).right;return{doc:{blocks:Ih([...l,{kind:"text",value:o},...c])},caret:s+o.length}}function DA(t){let e=[];for(let n of t.blocks)n.kind==="text"?n.value.length>0&&e.push({kind:"text",text:n.value}):e.push({kind:"mention",ref:n.ref});return{content:Rh(t),contextMentions:GH(t).map(n=>n.ref),contentSegments:e}}var KH,Bh=be(()=>{"use strict";bu();KH="@"});function dc(t){return t.nodeType===1&&t.hasAttribute(cc)}function NA(t){return t.nodeType===1&&t.tagName==="BR"}function Lu(t){return t.nodeType===3?t.data.length:dc(t)||NA(t)?1:t.textContent?.length??0}function OA(t,e,n){let o=0;for(let r of Array.from(t.childNodes)){if(r===e)return r.nodeType===3?o+n:o+(n>0?Lu(r):0);if(r.contains(e))return dc(r)?o+1:o+QH(r,e,n);o+=Lu(r)}if(e===t){let r=0,s=Array.from(t.childNodes);for(let a=0;a<Math.min(n,s.length);a++)r+=Lu(s[a]);return r}return o}function QH(t,e,n){let o=0,r=s=>{if(s===e)return o+=s.nodeType===3?n:0,!0;if(s.nodeType===3)return o+=s.data.length,!1;for(let a of Array.from(s.childNodes))if(r(a))return!0;return!1};return r(t),o}function lc(t,e){let n=0,o=Array.from(t.childNodes);for(let r=0;r<o.length;r++){let s=o[r],a=Lu(s);if(e<=n+a)return s.nodeType===3?{node:s,offset:e-n}:{node:t,offset:e<=n?r:r+1};n+=a}return{node:t,offset:o.length}}function XH(t,e){let n=[];for(let o of Array.from(t.childNodes))if(dc(o)){let r=o.getAttribute(cc),s=e.get(r);s&&n.push({kind:"mention",id:r,ref:s})}else if(NA(o))n.push({kind:"text",value:_A});else if(o.nodeType===3)n.push({kind:"text",value:o.data});else{let r=o.textContent??"";r&&n.push({kind:"text",value:r})}return n.length===0&&n.push({kind:"text",value:""}),{blocks:n}}function FA(t){let e=t.renderToken,n=new Map,o=t.element??document.createElement("div");o.setAttribute("contenteditable","true"),o.setAttribute("data-persona-composer-input",""),o.setAttribute("role","textbox"),o.setAttribute("aria-multiline","true"),o.setAttribute("dir","auto"),o.classList.add("persona-composer-contenteditable"),t.placeholder!=null&&o.setAttribute("data-placeholder",t.placeholder);let r=!1,s=0,a=()=>XH(o,n),l=B=>{o.replaceChildren();for(let O of B.blocks)if(O.kind==="text")O.value.length>0&&o.appendChild(document.createTextNode(O.value));else{n.set(O.id,O.ref);let H=e(O.ref);H.setAttribute("contenteditable","false"),H.setAttribute(cc,O.id),o.appendChild(H)}},c=()=>{let O=o.getRootNode().activeElement;return O===o||O!=null&&o.contains(O)},p=(B,O)=>{if(s=B,!O?.focus&&!c())return;let H=typeof window<"u"?window.getSelection():null;if(!H)return;let S=lc(o,B);try{let x=document.createRange();x.setStart(S.node,S.offset),x.collapse(!0),H.removeAllRanges(),H.addRange(x)}catch{}},u=()=>{o.dispatchEvent(new Event("input",{bubbles:!0}))},m=()=>{let B={start:s,end:s},O=typeof window<"u"?window.getSelection():null;if(!O||O.rangeCount===0)return B;let H=O.getRangeAt(0);if(!o.contains(H.startContainer))return B;let S=OA(o,H.startContainer,H.startOffset),x=H.collapsed?S:OA(o,H.endContainer,H.endOffset);return{start:Math.min(S,x),end:Math.max(S,x)}},g=()=>{let B=new Set;for(let O of Array.from(o.childNodes))dc(O)&&B.add(O.getAttribute(cc));for(let O of Array.from(n.keys()))B.has(O)||(n.delete(O),t.onMentionRemoved?.(O))},h=()=>{r||n.size!==0&&g()},b=()=>{r=!0},C=()=>{r=!1,g()},M=B=>{B.preventDefault();let O=B.clipboardData?.getData("text/plain")??"";if(typeof document.execCommand=="function")document.execCommand("insertText",!1,O);else{let{start:H,end:S}=m(),x=Pu(a(),H,S,O);l(x.doc),p(x.caret,{focus:!0}),g()}u()},E=B=>{if(r)return;let O=B.inputType;if(O==="insertParagraph"){B.preventDefault();let{start:ee,end:oe}=m(),ne=Pu(a(),ee,oe,_A);l(ne.doc),p(ne.caret,{focus:!0}),n.size>0&&g(),u();return}if(O!=="deleteContentBackward"&&O!=="deleteContentForward"||n.size===0)return;let{start:H,end:S}=m();if(H!==S)return;let x=a(),P=Eu(x),L=O==="deleteContentBackward"?H-1:H;if(L<0||L>=P.length||P[L]!=="\uFFFC")return;let G=0,V=null;for(let ee of x.blocks){let oe=ee.kind==="text"?ee.value.length:1;if(ee.kind==="mention"&&L>=G&&L<G+oe){V=ee.id;break}G+=oe}if(!V)return;B.preventDefault();let K=BA(x,V);l(K.doc),p(K.caret,{focus:!0}),g(),u()},T=(B,O)=>{l(Hh(B)),p(O)},R=(B,O)=>{if(!Number.isFinite(B)||!Number.isFinite(O)||O<=B)return null;try{let H=lc(o,B),S=lc(o,O),x=document.createRange();x.setStart(H.node,H.offset),x.setEnd(S.node,S.offset);let P=x.getBoundingClientRect();return P.width===0&&P.height===0?null:P}catch{return null}},A=(B,O,H)=>{let S=Pu(a(),B,O,H);l(S.doc),p(S.caret,{focus:!0})},D=(B,O)=>{let H=a(),S=Eu(H),x=O.triggerIndex,P=O.triggerIndex+1+O.query.length;if(x<0||P>S.length||S.slice(x+1,P)!==O.query)return null;let L=t.generateId(),G=Wh(H,{start:x,end:P},B,L);return l(G.doc),p(G.caret,{focus:!0}),t.onMentionInserted?.(L,B),u(),L},W=B=>{let O=a(),H=m(),x=typeof window<"u"&&!!window.getSelection()?.rangeCount&&o.contains(window.getSelection().getRangeAt(0).startContainer)?{start:H.start,end:H.end}:{start:ku(O),end:ku(O)},P=t.generateId(),L=Wh(O,x,B,P);return l(L.doc),p(L.caret,{focus:!0}),t.onMentionInserted?.(P,B),u(),P},U=(B,O)=>{for(let H of Array.from(o.childNodes))if(dc(H)&&H.getAttribute(cc)===B){let S=O==="error";if(H.classList.toggle(YH,S),S){H.hasAttribute(ac)||(H.setAttribute(ac,H.getAttribute("aria-label")??""),H.setAttribute(Dh,H.getAttribute("title")??""));let x=n.get(B)?.label??"";H.setAttribute("title",`${x}: failed to attach context`),H.setAttribute("aria-label",`${x}, failed to attach context`)}else if(H.hasAttribute(ac)){let x=H.getAttribute(ac),P=H.getAttribute(Dh);x?H.setAttribute("aria-label",x):H.removeAttribute("aria-label"),P?H.setAttribute("title",P):H.removeAttribute("title"),H.removeAttribute(ac),H.removeAttribute(Dh)}return}};return o.addEventListener("input",h),o.addEventListener("compositionstart",b),o.addEventListener("compositionend",C),o.addEventListener("paste",M),o.addEventListener("beforeinput",E),l(WA()),{element:o,getValue:()=>Rh(a()),getLogicalText:()=>Eu(a()),getDocument:a,getSelection:m,setSelection:(B,O=B)=>{let H=typeof window<"u"?window.getSelection():null;if(H)try{let S=lc(o,B),x=lc(o,O),P=document.createRange();P.setStart(S.node,S.offset),P.setEnd(x.node,x.offset),H.removeAllRanges(),H.addRange(P)}catch{}},setValueWithCaret:T,getLogicalRangeRect:R,setValue:B=>{l(Hh(B)),o.focus(),p(B.length,{focus:!0}),u()},replaceLogicalRange:A,insertMentionAtTrigger:D,insertMentionAtSelection:W,setMentionStatus:U,submit:()=>sc(o.closest("form")),dispatchInput:u,focus:()=>o.focus(),destroy:()=>{o.removeEventListener("input",h),o.removeEventListener("compositionstart",b),o.removeEventListener("compositionend",C),o.removeEventListener("paste",M),o.removeEventListener("beforeinput",E)}}}var YH,cc,ac,Dh,_A,VA=be(()=>{"use strict";Bh();yu();YH="persona-mention-token-error",cc="data-mention-id",ac="data-mention-prev-label",Dh="data-mention-prev-title",_A=`
|
|
182
|
+
`});function eR(t,e){e.className=`${t.className} persona-composer-contenteditable`.trim();for(let r=0;r<t.style.length;r++){let s=t.style.item(r);s!=="height"&&e.style.setProperty(s,t.style.getPropertyValue(s),t.style.getPropertyPriority(s))}let n=t.getAttribute("placeholder");n&&(e.setAttribute("data-placeholder",n),e.setAttribute("aria-placeholder",n));let o=t.getAttribute("aria-label")??n;o&&e.setAttribute("aria-label",o)}function tR(t,e,n){Object.defineProperty(t,"value",{configurable:!0,get:()=>e.getValue(),set:o=>{e.setValueWithCaret(o,o.length),e.dispatchInput()}}),Object.defineProperty(t,"placeholder",{configurable:!0,get:()=>t.getAttribute("data-placeholder")??"",set:o=>{o?(t.setAttribute("data-placeholder",o),t.setAttribute("aria-placeholder",o),n||t.setAttribute("aria-label",o)):(t.removeAttribute("data-placeholder"),t.removeAttribute("aria-placeholder"),n||t.removeAttribute("aria-label"))}}),Object.defineProperty(t,"selectionStart",{configurable:!0,get:()=>e.getSelection().start}),Object.defineProperty(t,"selectionEnd",{configurable:!0,get:()=>e.getSelection().end}),t.setSelectionRange=(o,r)=>e.setSelection(o??0,r??o??0)}function $A(t){let{textarea:e}=t,n={generateId:ZH,renderToken:t.renderToken,onMentionRemoved:t.onMentionRemoved,placeholder:e.getAttribute("placeholder")??void 0},o=FA(n),r=o.element,s=e.getAttribute("aria-label")!=null;eR(e,r),tR(r,o,s),r.getInlineMessageFields=()=>DA(o.getDocument?.()??{blocks:[]});let a=e.selectionStart??e.value.length;return o.setValueWithCaret(e.value,a),{input:o,element:r,destroy:o.destroy}}var JH,ZH,zA=be(()=>{"use strict";VA();Bh();JH=0,ZH=()=>`pmention-${++JH}`});var UA={};$n(UA,{mountInlineComposer:()=>$A});var qA=be(()=>{"use strict";zA()});function uM(t){return t.role!=="assistant"||t.variant==="tool"||t.variant==="reasoning"?!1:t.variant==="approval"?!0:!!(t.content?.trim()||t.rawContent?.trim()||t.contentParts?.length)}function $u(t=!0){let e=t;return{isFollowing:()=>e,pause:()=>e?(e=!1,!0):!1,resume:()=>e?!1:(e=!0,!0)}}function br(t){return Math.max(0,t.scrollHeight-t.clientHeight)}function jr(t,e){return br(t)-t.scrollTop<=e}function zu(t){let{following:e,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:l=!1,pauseWhenAwayFromBottom:c=!0,resumeRequiresDownwardScroll:p=!1}=t,u=n-o;return a||Math.abs(u)<s?{action:"none",delta:u,nextLastScrollTop:n}:!e&&r&&(!p||u>0)?{action:"resume",delta:u,nextLastScrollTop:n}:e&&l&&u<0?{action:"pause",delta:u,nextLastScrollTop:n}:e&&c&&!r?{action:"pause",delta:u,nextLastScrollTop:n}:{action:"none",delta:u,nextLastScrollTop:n}}function Uu(t){let{following:e,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:r=!1}=t;return e&&n<0?"pause":!e&&r&&n>0&&o?"resume":"none"}function mM(t,e){return!t||t.isCollapsed?!1:e.contains(t.anchorNode)||e.contains(t.focusNode)}function qh(t){let e=Math.max(0,t.anchorOffsetTop-t.topOffset),n=Math.max(0,e+t.viewportHeight-t.contentHeight+(t.slack??0));return{targetScrollTop:e,spacerHeight:n}}function fM(t){let e=Math.max(0,t.currentContentHeight-t.contentHeightAtAnchor);return Math.max(0,t.initialSpacerHeight-e)}var jh=be(()=>{"use strict"});var bc,LR,qu,IR,Yh,hM,Ei,vc,ju,HR,RR,Kh,WR,BR,DR,Cc,Ku,wc,gM,OR,Gh,_R,yM,xc,Sc=be(()=>{"use strict";bc={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},LR=["pre","code","a","script","style"],qu=t=>({type:t?.type??bc.type,placeholder:t?.placeholder??bc.placeholder,speed:t?.speed??bc.speed,duration:t?.duration??bc.duration,buffer:t?.buffer??bc.buffer}),IR=[{name:"typewriter",containerClass:"persona-stream-typewriter",wrap:"char",useCaret:!0},{name:"pop-bubble",bubbleClass:"persona-stream-pop",wrap:"none"},{name:"letter-rise",containerClass:"persona-stream-letter-rise",wrap:"char"},{name:"word-fade",containerClass:"persona-stream-word-fade",wrap:"word"}],Yh=new Map;for(let t of IR)Yh.set(t.name,t);hM=["wipe","glyph-cycle"],Ei=t=>{Yh.set(t.name,t)},vc=(t,e)=>t==="none"?null:e&&Object.prototype.hasOwnProperty.call(e,t)?e[t]??null:Yh.get(t)??null,ju=(t,e,n,o,r)=>{if(!r)return t;if(n?.bufferContent)return n.bufferContent(t,o);if(!t)return t;if(e==="word"){let s=t.search(/\s(?=\S*$)/);return s<0?"":t.slice(0,s)}if(e==="line"){let s=t.lastIndexOf(`
|
|
183
|
+
`);return s<0?"":t.slice(0,s)}return t},HR=(t,e,n,o)=>{let r=t.createElement("span");return r.className="persona-stream-char",r.id=`stream-c-${n}-${o}`,r.style.setProperty("--char-index",String(o)),r.textContent=e,r},RR=(t,e,n,o)=>{let r=t.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${n}-${o}`,r.style.setProperty("--word-index",String(o)),r.textContent=e,r},Kh=/\s/,WR=(t,e)=>{let n=t.parentNode;for(;n;){if(n.nodeType===1){let o=n;if(e.has(o.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},BR=(t,e,n)=>{let o=t.ownerDocument,r=t.parentNode;if(!o||!r)return;let s=t.nodeValue??"";if(!s)return;let a=o.createDocumentFragment(),l=0;for(;l<s.length;)if(Kh.test(s[l])){let c=l;for(;c<s.length&&Kh.test(s[c]);)c+=1;a.appendChild(o.createTextNode(s.slice(l,c))),l=c}else{let c=o.createElement("span");c.className="persona-stream-word-group";let p=l;for(;p<s.length&&!Kh.test(s[p]);)c.appendChild(HR(o,s[p],e,n.value)),n.value+=1,p+=1;a.appendChild(c),l=p}r.replaceChild(a,t)},DR=(t,e,n)=>{let o=t.ownerDocument,r=t.parentNode;if(!o||!r)return;let s=t.nodeValue??"";if(!s)return;let a=o.createDocumentFragment(),l=s.split(/(\s+)/);for(let c of l)c&&(/^\s+$/.test(c)?a.appendChild(o.createTextNode(c)):(a.appendChild(RR(o,c,e,n.value)),n.value+=1));r.replaceChild(a,t)},Cc=(t,e,n,o)=>{if(!t||typeof document>"u")return t;let r=document.createElement("div");r.innerHTML=t;let s=new Set((o?.skipTags??LR).map(m=>m.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],c=a.nextNode();for(;c;)WR(c,s)||l.push(c),c=a.nextNode();let p={value:o?.startIndex??0},u=e==="char"?BR:DR;for(let m of l)u(m,n,p);return r.innerHTML},Ku=(t=document)=>{let e=t.createElement("span");return e.className="persona-stream-caret",e.setAttribute("aria-hidden","true"),e.setAttribute("data-preserve-animation","stream-caret"),e},wc=(t=document)=>{let e=t.createElement("div");e.className="persona-stream-skeleton",e.setAttribute("data-preserve-animation","stream-skeleton"),e.setAttribute("aria-hidden","true");let n=t.createElement("div");return n.className="persona-stream-skeleton-line",e.appendChild(n),e},gM=new WeakMap,OR=(t,e)=>{if(!t.styles)return;let n=gM.get(e);if(n||(n=new Set,gM.set(e,n)),n.has(t.name)){let s=t.name.replace(/["\\]/g,"\\$&");if(e.querySelector(`style[data-persona-animation="${s}"]`))return;n.delete(t.name)}n.add(t.name);let r=(e instanceof ShadowRoot?e.ownerDocument:e.ownerDocument??document).createElement("style");r.setAttribute("data-persona-animation",t.name),r.textContent=t.styles,e.appendChild(r)},Gh=new WeakMap,_R=(t,e)=>{if(!t.onAttach)return;let n=Gh.get(e);if(n||(n=new Map,Gh.set(e,n)),n.has(t.name))return;let o=t.onAttach(e);n.set(t.name,o)},yM=t=>{let e=Gh.get(t);if(e){for(let n of e.values())typeof n=="function"&&n();e.clear()}},xc=(t,e)=>{OR(t,e),_R(t,e)}});var NR,bM,vM,CM=be(()=>{"use strict";Sc();NR=`
|
|
184
184
|
@keyframes persona-stream-wipe {
|
|
185
185
|
from { -webkit-mask-position: 100% 0; mask-position: 100% 0; }
|
|
186
186
|
to { -webkit-mask-position: 0% 0; mask-position: 0% 0; }
|
|
@@ -216,7 +216,7 @@ ${e}
|
|
|
216
216
|
mask-image: none !important;
|
|
217
217
|
}
|
|
218
218
|
}
|
|
219
|
-
`.trim(),
|
|
219
|
+
`.trim(),bM={name:"wipe",containerClass:"persona-stream-wipe",wrap:"word",styles:NR};Ei(bM);vM=bM});var FR,Ac,VR,$R,Qh,zR,UR,qR,kM,Xh,jR,wM,xM,SM,KR,AM,MM,TM,GR,Fa,YR,QR,XR,PM,JR,EM,ZR,LM,IM,HM=be(()=>{"use strict";Sc();FR=`
|
|
220
220
|
[data-persona-root] .persona-stream-glyph-cycle .persona-stream-char {
|
|
221
221
|
animation: persona-stream-glyph-cycle-fade
|
|
222
222
|
calc(var(--persona-stream-step, 120ms) * 1.5) ease-out both;
|
|
@@ -234,13 +234,13 @@ ${e}
|
|
|
234
234
|
opacity: 1 !important;
|
|
235
235
|
}
|
|
236
236
|
}
|
|
237
|
-
`.trim(),Ac="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#$%&@",MH=10,TH=120,Gh=120,EH=.4,kH=50,PH=t=>{if(!t)return Gh;let n=(t.style.getPropertyValue("--persona-stream-step")?.trim()).match(/([\d.]+)\s*ms/);return n?parseFloat(n[1]):Gh},bM=t=>{let e=t.closest(".persona-stream-glyph-cycle"),n=PH(e);return TH*n/Gh},Yh=t=>{let e=Ac[Math.floor(Math.random()*Ac.length)];return t&&e===t&&(e=Ac[(Ac.indexOf(e)+1)%Ac.length]),e},LH=t=>{let e=t.closest(".persona-stream-glyph-cycle");if(!e)return;let n=e.querySelectorAll(".persona-stream-char[data-glyph-cycle-final]"),o=!1;for(let r of Array.from(n)){if(r===t){o=!0;continue}o&&Math.random()<EH&&(r.textContent=Yh())}},pM=new WeakMap,uM=25,mM=.5,IH=6,fM=.25,gM=new WeakMap,hM=new WeakMap,RH=(t,e)=>{if(!t)return uM*mM;let n=gM.get(t);gM.set(t,e);let o=hM.get(t)??uM;if(n!==void 0){let r=e-n;r>1&&(o=o*(1-fM)+r*fM,hM.set(t,o))}return Math.max(IH,o*mM)},Fa=new Map,HH=t=>t.closest("[data-message-id]")?.dataset.messageId??null,WH=t=>{t&&Fa.set(t,(Fa.get(t)??0)+1)},BH=t=>{if(!t)return;let e=Fa.get(t)??0;e<=1?Fa.delete(t):Fa.set(t,e-1)},vM=t=>{if(t.dataset.glyphCycleScheduled==="true")return;let e=t.textContent??"";if(!e||/\s/.test(e))return;t.dataset.glyphCycleScheduled="true",t.dataset.glyphCycleFinal=e,t.setAttribute("data-preserve-runtime","stream-glyph-cycle"),t.textContent=Yh();let n=HH(t);n&&(t.dataset.glyphCycleMessageId=n),WH(n);let o=t.closest(".persona-stream-glyph-cycle"),r=Date.now(),s=RH(o,r),a=bM(t),l=MH*a,c=r+l;if(o){let p=pM.get(o);p!==void 0&&(c=Math.max(c,p)),pM.set(o,c+s)}DH(t,e,c)},DH=(t,e,n)=>{if(t.dataset.glyphCycleStarted==="true")return;t.dataset.glyphCycleStarted="true";let o=bM(t),r=t.textContent??void 0,s=()=>{if(!t.isConnected)return;if(Date.now()>=n){t.textContent=e,t.removeAttribute("data-preserve-runtime"),delete t.dataset.glyphCycleStarted,delete t.dataset.glyphCycleFinal,BH(t.dataset.glyphCycleMessageId??null),delete t.dataset.glyphCycleMessageId;return}let a=Yh(r);t.textContent=a,r=a,LH(t),setTimeout(s,o)};setTimeout(s,o)},yM=t=>{let e=t.querySelectorAll?.(".persona-stream-glyph-cycle .persona-stream-char:not([data-glyph-cycle-scheduled])");if(e)for(let n of Array.from(e))vM(n)},OH=t=>t.nodeType===1,CM={name:"glyph-cycle",containerClass:"persona-stream-glyph-cycle",wrap:"char",skipTags:["a","script","style"],styles:AH,bufferContent(t){if(t.length<kH)return"";let e=0,n=-1,o=0;for(;o<t.length;){if(t[o]==="*"&&t[o+1]==="*"){e+=1,o+=2;continue}/\s/.test(t[o])&&e%2===0&&(n=o),o+=1}return n<0?"":t.slice(0,n)},isAnimating(t){return(Fa.get(t.id)??0)>0},onAttach(t){yM(t);let e=new MutationObserver(n=>{for(let o of n)for(let r of Array.from(o.addedNodes))OH(r)&&(r.classList.contains("persona-stream-char")&&r.closest(".persona-stream-glyph-cycle")?vM(r):yM(r))});return e.observe(t,{childList:!0,subtree:!0}),()=>e.disconnect()}};Ei(CM);wM=CM});var SM={};$n(SM,{glyphCycle:()=>wM,wipe:()=>cM});var AM=be(()=>{"use strict";dM();xM()});function Lc(t){let{items:e,onSelect:n,anchor:o,position:r="bottom-left",portal:s,onOpenChange:a}=t,l=v("div","persona-dropdown-menu persona-hidden");l.setAttribute("role","menu"),l.setAttribute("data-persona-theme-zone","dropdown"),s?(l.style.position="fixed",l.style.zIndex=String(Ba)):(l.style.position="absolute",l.style.top="100%",l.style.marginTop="4px",r==="bottom-right"?l.style.right="0":l.style.left="0");for(let b of e){if(b.dividerBefore){let E=document.createElement("hr");l.appendChild(E)}let C=document.createElement("button");if(C.type="button",C.setAttribute("role","menuitem"),C.setAttribute("data-dropdown-item-id",b.id),b.destructive&&C.setAttribute("data-destructive",""),b.icon){let E=ke(b.icon,16,"currentColor",1.5);E&&C.appendChild(E)}let M=document.createElement("span");M.textContent=b.label,C.appendChild(M),C.addEventListener("click",E=>{E.stopPropagation(),m(),n(b.id)}),l.appendChild(C)}let c=null;function p(){if(!s)return;let b=o.getBoundingClientRect();l.style.top=`${b.bottom+4}px`,r==="bottom-right"?(l.style.right=`${window.innerWidth-b.right}px`,l.style.left="auto"):(l.style.left=`${b.left}px`,l.style.right="auto")}function u(){let b=l.classList.contains("persona-hidden");p(),l.classList.remove("persona-hidden"),b&&a?.(!0),requestAnimationFrame(()=>{let C=M=>{!l.contains(M.target)&&!o.contains(M.target)&&m()};document.addEventListener("click",C,!0),c=()=>document.removeEventListener("click",C,!0)})}function m(){let b=!l.classList.contains("persona-hidden");l.classList.add("persona-hidden"),c?.(),c=null,b&&a?.(!1)}function g(){l.classList.contains("persona-hidden")?u():m()}function h(){m(),l.remove()}return s&&s.appendChild(l),{element:l,show:u,hide:m,toggle:g,destroy:h}}var ny=be(()=>{"use strict";je();Zt();ks()});function vn(t){let{icon:e,label:n,size:o,strokeWidth:r,className:s,chromeless:a,onClick:l,aria:c}=t,p=v("button",Gt(!a&&"persona-icon-btn",s));p.type="button",p.setAttribute("aria-label",n),p.title=n;let u=ke(e,o??16,"currentColor",r??2);if(u&&p.appendChild(u),l&&p.addEventListener("click",l),c)for(let[m,g]of Object.entries(c))p.setAttribute(m,g);return p}function Li(t){let{icon:e,label:n,variant:o="default",size:r="sm",iconSize:s,className:a,onClick:l,aria:c}=t,p="persona-label-btn";o!=="default"&&(p+=" persona-label-btn--"+o),p+=" persona-label-btn--"+r,a&&(p+=" "+a);let u=v("button",p);if(u.type="button",u.setAttribute("aria-label",n),e){let g=ke(e,s??14,"currentColor",2);g&&u.appendChild(g)}let m=v("span");if(m.textContent=n,u.appendChild(m),l&&u.addEventListener("click",l),c)for(let[g,h]of Object.entries(c))u.setAttribute(g,h);return u}function Yu(t){let{items:e,selectedId:n,onSelect:o,className:r}=t,s=v("div","persona-toggle-group"+(r?" "+r:""));s.setAttribute("role","group");let a=n,l=[];function c(){for(let u of l)u.btn.setAttribute("aria-pressed",u.id===a?"true":"false")}for(let u of e){let m;u.icon?m=vn({icon:u.icon,label:u.label,className:u.className,onClick:()=>{a=u.id,c(),o(u.id)}}):(m=v("button","persona-icon-btn"+(u.className?" "+u.className:"")),m.type="button",m.setAttribute("aria-label",u.label),m.title=u.label,m.textContent=u.label,m.addEventListener("click",()=>{a=u.id,c(),o(u.id)})),m.setAttribute("aria-pressed",u.id===a?"true":"false"),l.push({id:u.id,btn:m}),s.appendChild(m)}function p(u){a=u,c()}return{element:s,setSelected:p}}function PM(t){let{label:e,icon:n,iconSize:o,iconOnly:r,menuItems:s,onSelect:a,onPrimary:l,position:c="bottom-left",portal:p,chevronLabel:u="More options",chevronIconSize:m,className:g,primaryClassName:h,chevronClassName:b}=t,C=v("div","persona-split-btn"+(g?" "+g:"")),M={label:e,className:"persona-split-btn-primary"+(h?" "+h:""),onClick:l},E=r&&n?vn({...M,icon:n,size:o??14}):Li({...M,icon:n,iconSize:o??14}),T=vn({icon:"chevron-down",label:u,size:m??14,className:"persona-split-btn-chevron"+(b?" "+b:""),aria:{"aria-haspopup":"true","aria-expanded":"false"}});C.append(E,T);let H=null,A=()=>{if(H)return H;let D=(typeof p=="function"?p():p)??void 0;return H=Lc({items:s,onSelect:a,anchor:C,position:c,portal:D,onOpenChange:W=>{T.setAttribute("aria-expanded",W?"true":"false")}}),D||C.appendChild(H.element),H};return C.isConnected?A():requestAnimationFrame(()=>{H||A()}),T.addEventListener("click",D=>{D.stopPropagation(),A().toggle()}),{element:C,primaryButton:E,chevronButton:T,openMenu:()=>A().show(),closeMenu:()=>H?.hide(),toggleMenu:()=>A().toggle(),destroy:()=>{H?.destroy(),C.remove()}}}function LM(t){let{label:e,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:a,className:l,hover:c}=t,p=v("div","persona-combo-btn"+(l?" "+l:""));p.style.position="relative",p.style.display="inline-flex",p.style.alignItems="center",p.style.cursor="pointer",p.setAttribute("role","button"),p.setAttribute("tabindex","0"),p.setAttribute("aria-haspopup","true"),p.setAttribute("aria-expanded","false"),p.setAttribute("aria-label",e);let u=v("span","persona-combo-btn-label");u.textContent=e,p.appendChild(u);let m=ke(n,14,"currentColor",2);m&&(m.style.marginLeft="4px",m.style.opacity="0.6",p.appendChild(m)),c&&(p.style.borderRadius=c.borderRadius??"10px",p.style.padding=c.padding??"6px 4px 6px 12px",p.style.border="1px solid transparent",p.style.transition="background-color 0.15s ease, border-color 0.15s ease",p.addEventListener("mouseenter",()=>{p.style.backgroundColor=c.background??"",p.style.borderColor=c.border??""}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="",p.style.borderColor="transparent"}));let g=Lc({items:o,onSelect:b=>{p.setAttribute("aria-expanded","false"),r(b)},anchor:p,position:s,portal:a});a||p.appendChild(g.element);let h=()=>p.getAttribute("data-persona-menu-locked")==="true";return p.addEventListener("click",b=>{if(b.stopPropagation(),h())return;let C=!g.element.classList.contains("persona-hidden");p.setAttribute("aria-expanded",C?"false":"true"),g.toggle()}),p.addEventListener("keydown",b=>{(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),p.click())}),{element:p,setLabel:b=>{u.textContent=b,p.setAttribute("aria-label",b)},open:()=>{p.setAttribute("aria-expanded","true"),g.show()},close:()=>{p.setAttribute("aria-expanded","false"),g.hide()},toggle:()=>{let b=!g.element.classList.contains("persona-hidden");p.setAttribute("aria-expanded",b?"false":"true"),g.toggle()},destroy:()=>{g.destroy(),p.remove()}}}var Ii=be(()=>{"use strict";je();Zt();ny()});var Hs,rm=be(()=>{"use strict";je();Hs=(t,e,n)=>{let o=n;for(let r of e){let s=v("span","persona-tool-char");s.style.setProperty("--char-index",String(o)),s.textContent=r===" "?"\xA0":r,t.appendChild(s),o++}return o}});var aT,xy,sm,im=be(()=>{"use strict";aT=()=>{},xy=t=>{aT=t.webMcpToolTitle},sm=t=>aT(t)});var Oo,Hi,lT,cT,dT,Sy,Ay,My=be(()=>{"use strict";je();Ts();im();Oo=require("lucide");zn();Aa();Hi=t=>{let n=(t.startsWith(zr)?t.slice(zr.length):t).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return t;let o=n.join(" ").toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)},lT=t=>t?.approval!==!1?t?.approval:void 0,cT=(t,e,n)=>{let o=lT(n)?.detailsDisplay??"collapsed";return e.get(t)??o==="expanded"},dT=(t,e,n)=>{let o=lT(n);t.setAttribute("aria-expanded",e?"true":"false");let r=t.querySelector("[data-approval-details-label]");r&&(r.textContent=e?o?.hideDetailsLabel??"Hide details":o?.showDetailsLabel??"Show details");let s=t.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let a=Ge(e?Oo.ChevronUp:Oo.ChevronDown,14,"currentColor",2);a&&s.appendChild(a)}},Sy=(t,e,n,o=new Map)=>{let r=e.querySelector('button[data-bubble-type="approval"]'),s=e.querySelector("[data-approval-details]");if(!r||!s)return;let a=cT(t,o,n);dT(r,a,n),s.style.display=a?"":"none"},Ay=(t,e,n=new Map)=>{let o=t.approval,r=e?.approval!==!1?e?.approval:void 0,s=o?.status==="pending",a=v("div",["persona-approval-bubble","persona-w-full","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(a.id=`bubble-${t.id}`,a.setAttribute("data-message-id",t.id),a.style.backgroundColor=r?.backgroundColor??"var(--persona-approval-bg)",a.style.borderColor=r?.borderColor??"var(--persona-approval-border)",a.style.boxShadow=r?.shadow!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-approval-shadow)",!o)return a;let l=v("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),c=v("div","persona-flex-shrink-0 persona-mt-0.5");c.setAttribute("data-approval-icon","true");let p=o.status==="denied"?Oo.ShieldX:o.status==="timeout"?Oo.ShieldAlert:Oo.ShieldCheck,u=o.status==="approved"?"var(--persona-feedback-success, var(--persona-palette-colors-success-600))":o.status==="denied"?"var(--persona-feedback-error, var(--persona-palette-colors-error-600))":o.status==="timeout"?"var(--persona-feedback-warning, var(--persona-palette-colors-warning-600))":r?.titleColor??"currentColor",m=Ge(p,20,u,2);m&&c.appendChild(m);let g=v("div","persona-flex-1 persona-min-w-0"),h=v("div","persona-flex persona-items-center persona-gap-2"),b=v("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r?.titleColor&&(b.style.color=r.titleColor),b.textContent=r?.title??"Approval Required",h.appendChild(b),!s){let B=v("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");B.setAttribute("data-approval-status",o.status),o.status==="approved"?(B.style.backgroundColor="var(--persona-palette-colors-success-100)",B.style.color="var(--persona-palette-colors-success-700)",B.textContent="Approved"):o.status==="denied"?(B.style.backgroundColor="var(--persona-palette-colors-error-100)",B.style.color="var(--persona-palette-colors-error-700)",B.textContent="Denied"):o.status==="timeout"&&(B.style.backgroundColor="var(--persona-palette-colors-warning-100)",B.style.color="var(--persona-palette-colors-warning-700)",B.textContent="Timeout"),h.appendChild(B)}g.appendChild(h);let M=o.toolType==="webmcp"||o.toolName.startsWith(zr)?sm(o.toolName):void 0,E=r?.formatDescription?.({toolName:o.toolName,toolType:o.toolType,description:o.description,parameters:o.parameters,...M?{displayTitle:M}:{},...o.reason?{reason:o.reason}:{}}),T=!o.toolName,H=E||(T?o.description:`The assistant wants to use \u201C${M??Hi(o.toolName)}\u201D.`),A=v("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(A.setAttribute("data-approval-summary","true"),r?.descriptionColor&&(A.style.color=r.descriptionColor),A.textContent=H,g.appendChild(A),o.reason){let B=v("p","persona-text-sm persona-mt-1 persona-text-persona-muted");B.setAttribute("data-approval-reason","true"),r?.reasonColor?B.style.color=r.reasonColor:r?.descriptionColor&&(B.style.color=r.descriptionColor);let O=v("span","persona-font-medium");O.textContent=`${r?.reasonLabel??"Agent's stated reason:"} `,B.appendChild(O),B.appendChild(document.createTextNode(o.reason)),g.appendChild(B)}let D=r?.detailsDisplay??"collapsed",W=!!o.description&&!T,U=W||!!o.parameters;if(D!=="hidden"&&U){let B=cT(t.id,n,e),O=v("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");O.type="button",O.setAttribute("data-expand-header","true"),O.setAttribute("data-bubble-type","approval"),r?.descriptionColor&&(O.style.color=r.descriptionColor);let R=v("span");R.setAttribute("data-approval-details-label","true");let S=v("span","persona-inline-flex persona-items-center");S.setAttribute("data-approval-details-chevron","true"),O.append(R,S),dT(O,B,e),g.appendChild(O);let x=v("div");if(x.setAttribute("data-approval-details","true"),x.style.display=B?"":"none",W){let P=v("p","persona-text-sm persona-mt-1 persona-text-persona-muted");r?.descriptionColor&&(P.style.color=r.descriptionColor),P.textContent=o.description,x.appendChild(P)}if(o.parameters){let P=v("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");r?.parameterBackgroundColor&&(P.style.backgroundColor=r.parameterBackgroundColor),r?.parameterTextColor&&(P.style.color=r.parameterTextColor),P.style.fontSize="0.75rem",P.style.lineHeight="1rem",P.textContent=mr(o.parameters),x.appendChild(P)}g.appendChild(x)}if(s){let B=v("div","persona-flex persona-gap-2 persona-mt-2");B.setAttribute("data-approval-buttons","true");let O=v("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");O.type="button",O.style.backgroundColor=r?.approveButtonColor??"var(--persona-approval-approve-bg)",O.style.color=r?.approveButtonTextColor??"var(--persona-button-primary-fg)",O.setAttribute("data-approval-action","approve");let R=Ge(Oo.ShieldCheck,14,r?.approveButtonTextColor??"var(--persona-button-primary-fg)",2);R&&(R.style.marginRight="4px",O.appendChild(R));let S=document.createTextNode(r?.approveLabel??"Approve");O.appendChild(S);let x=v("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");x.type="button",x.style.backgroundColor=r?.denyButtonColor??"transparent",x.style.color=r?.denyButtonTextColor??"var(--persona-feedback-error, var(--persona-palette-colors-error-600))",x.style.border=`1px solid ${r?.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200)"}`,x.setAttribute("data-approval-action","deny");let P=Ge(Oo.ShieldX,14,r?.denyButtonTextColor??"var(--persona-feedback-error, var(--persona-palette-colors-error-600))",2);P&&(P.style.marginRight="4px",x.appendChild(P));let L=document.createTextNode(r?.denyLabel??"Deny");x.appendChild(L),B.append(O,x),g.appendChild(B)}return l.append(c,g),a.appendChild(l),a}});var Bi,_W,pT,Wi,NW,FW,Ty,VW,$W,zW,Ey,uT=be(()=>{"use strict";je();im();Bi=require("lucide");zn();Ts();Aa();Oa();My();_W=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),pT=(t,e)=>{let n=t.keyHandlers.get(e);n&&(document.removeEventListener("keydown",n),t.keyHandlers.delete(e));let o=t.popovers.get(e);o&&(o.destroy(),t.popovers.delete(e))},Wi=(t,e)=>{pT(t,e);let n=t.pendingOrder.indexOf(e);n!==-1&&t.pendingOrder.splice(n,1),t.latestPendingApprovalId===e&&(t.latestPendingApprovalId=t.pendingOrder.length?t.pendingOrder[t.pendingOrder.length-1]:null)},NW=t=>t?.approval!==!1?t?.approval:void 0,FW=(t,e,n)=>{let o=n?.detailsDisplay??"collapsed";return e.get(t)??o==="expanded"},Ty=t=>{let e=v("span","persona-approval-kbd");return e.textContent=t,e},VW=(t,e)=>{let n=v("span","persona-approval-title");e?.titleColor&&(n.style.color=e.titleColor);let r=t.toolType==="webmcp"||t.toolName.startsWith(zr)?sm(t.toolName):void 0,s=e?.formatDescription?.({toolName:t.toolName,toolType:t.toolType,description:t.description??"",parameters:t.parameters,...r?{displayTitle:r}:{},...t.reason?{reason:t.reason}:{}});if(s)return n.textContent=s,n;let a=r??Hi(t.toolName),l=t.toolType&&t.toolType!=="webmcp"?t.toolType:null;n.append("The assistant wants to use ");let c=document.createElement("strong");if(c.textContent=a,n.appendChild(c),l){n.append(" from ");let p=document.createElement("strong");p.textContent=l,n.appendChild(p)}return n},$W=t=>{let e=v("div","persona-approval-resolved"),n=Ge(Bi.Ban,15,"currentColor",2);n&&e.appendChild(n);let o=v("span","persona-approval-resolved-name");return o.textContent=t.toolName?Hi(t.toolName):"Tool",e.append(o,document.createTextNode(t.status==="timeout"?" timed out":" denied")),e},zW=(t,e,n,o,r,s,a,l)=>{let c=v("div","persona-approval-card persona-shadow-sm");c.id=`bubble-${n.id}`,c.setAttribute("data-message-id",n.id),c.setAttribute("data-bubble-type","approval"),r?.backgroundColor&&(c.style.background=r.backgroundColor),r?.borderColor&&(c.style.borderColor=r.borderColor),r?.shadow!==void 0&&(c.style.boxShadow=r.shadow.trim()===""?"none":r.shadow);let p=r?.detailsDisplay??"collapsed",u=!!o.description&&p!=="hidden",m=o.parameters!=null&&p!=="hidden",g=u||m,h=g&&FW(n.id,e,r),b=r?.showDetailsLabel??"Show details",C=r?.hideDetailsLabel??"Hide details",M=v("button","persona-approval-head");M.type="button",g?(M.setAttribute("data-action","toggle-params"),M.setAttribute("aria-expanded",h?"true":"false"),M.setAttribute("aria-label",h?C:b)):M.setAttribute("data-static","true");let E=v("span","persona-approval-logo"),T=Ge(Bi.ShieldCheck,16,"currentColor",2);T&&E.appendChild(T),M.appendChild(E);let H=VW(o,r);if(g){let O=v("span","persona-approval-toggle");O.setAttribute("aria-hidden","true");let R=Ge(Bi.ChevronDown,14,"currentColor",2);R&&O.appendChild(R),H.append(" "),H.appendChild(O)}M.appendChild(H),c.appendChild(M);let A=v("div","persona-approval-body");if(g){let O=v("div","persona-approval-details");if(O.setAttribute("data-role","params"),O.hidden=!h,u){let R=v("p","persona-approval-desc");r?.descriptionColor&&(R.style.color=r.descriptionColor),R.textContent=o.description,O.appendChild(R)}if(m){let R=v("pre","persona-approval-params");r?.parameterBackgroundColor&&(R.style.background=r.parameterBackgroundColor),r?.parameterTextColor&&(R.style.color=r.parameterTextColor),R.textContent=mr(o.parameters),O.appendChild(R)}A.appendChild(O)}if(o.reason){let O=v("p","persona-approval-reason");r?.reasonColor?O.style.color=r.reasonColor:r?.descriptionColor&&(O.style.color=r.descriptionColor);let R=v("span","persona-approval-reason-label");R.textContent=`${r?.reasonLabel??"Agent's stated reason:"} `,O.append(R,document.createTextNode(o.reason)),A.appendChild(O)}let D=v("div","persona-approval-actions"),W=null,U=O=>{r?.approveButtonColor&&(O.style.background=r.approveButtonColor),r?.approveButtonTextColor&&(O.style.color=r.approveButtonTextColor)},B=v("button","persona-approval-deny");if(B.type="button",B.setAttribute("data-action","deny"),r?.denyButtonColor&&(B.style.background=r.denyButtonColor),r?.denyButtonTextColor&&(B.style.color=r.denyButtonTextColor),B.append(r?.denyLabel??"Deny"),l){let O=v("div","persona-approval-split"),R=v("button","persona-approval-primary");R.type="button",R.setAttribute("data-action","always"),U(R),R.append(r?.approveLabel??"Always allow",Ty("\u23CE"));let S=v("button","persona-approval-caret");S.type="button",S.setAttribute("data-action","toggle-menu"),S.setAttribute("aria-label","More options"),U(S);let x=Ge(Bi.ChevronDown,15,"currentColor",2);x&&S.appendChild(x),O.append(R,S),D.append(O,B),B.append(Ty("Esc"));let P=v("div","persona-approval-menu"),L=v("button","persona-approval-menu-item");L.type="button",L.append("Allow once",Ty("\u2318\u23CE")),P.appendChild(L),W=Ps({anchor:O,content:P,placement:"bottom-start",matchAnchorWidth:!0}),t.popovers.set(n.id,W),L.addEventListener("click",()=>{Wi(t,n.id),s()})}else{let O=v("button","persona-approval-primary persona-approval-primary--solo");O.type="button",O.setAttribute("data-action","allow"),U(O),O.append(r?.approveLabel??"Allow"),D.append(O,B)}return A.appendChild(D),c.appendChild(A),c.addEventListener("click",O=>{let R=O.target instanceof Element?O.target.closest("[data-action]"):null;if(!R)return;let S=R.getAttribute("data-action");if(S==="toggle-params"){let x=c.querySelector('[data-role="params"]');if(x){let P=x.hidden;x.hidden=!P,M.setAttribute("aria-expanded",P?"true":"false"),M.setAttribute("aria-label",P?C:b),e.set(n.id,P)}return}if(S==="toggle-menu"){W?.toggle();return}if(S==="always"){Wi(t,n.id),s({remember:!0});return}if(S==="allow"){Wi(t,n.id),s();return}if(S==="deny"){Wi(t,n.id),a();return}}),c},Ey=(t=new Map)=>{let e=_W();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:r,approve:s,deny:a,config:l})=>{let c=r?.approval;if(!c)return null;let p=NW(l);if(c.status!=="pending"){if(Wi(e,r.id),c.status==="approved"){let g=document.createElement("div");return g.style.display="none",g}return $W(c)}pT(e,r.id);let u=p?.enableAlwaysAllow===!0,m=zW(e,t,r,c,p,s,a,u);if(u){e.pendingOrder.includes(r.id)||e.pendingOrder.push(r.id),e.latestPendingApprovalId=e.pendingOrder[e.pendingOrder.length-1];let g=h=>{AS(h)||r.id===e.latestPendingApprovalId&&(h.key!=="Escape"&&h.key!=="Enter"||(h.preventDefault(),h.stopImmediatePropagation(),Wi(e,r.id),h.key==="Escape"?a():h.metaKey||h.ctrlKey?s():s({remember:!0})))};e.keyHandlers.set(r.id,g),document.addEventListener("keydown",g)}return m}},teardown:()=>{for(let r of[...e.keyHandlers.keys(),...e.popovers.keys()])Wi(e,r);e.latestPendingApprovalId=null}}}});var mT=be(()=>{"use strict";My();uT();im()});var fT={};$n(fT,{createApprovalBubble:()=>Ay,createBuiltInApprovalPlugin:()=>Ey,humanizeToolName:()=>Hi,initApprovalUi:()=>xy,updateApprovalDetailsUI:()=>Sy});var gT=be(()=>{"use strict";mT()});function qa(t,e){e&&e.split(/\s+/).forEach(n=>n&&t.classList.add(n))}function bT(t,e){if(e[t])return e[t];for(let n of Object.keys(e))if(n.endsWith("_")&&t.startsWith(n))return e[n]}function YW(t,e){return(e&&bT(t,e))??bT(t,Kr)??jW}function QW(t){return/^#[0-9a-fA-F]{6}$/.test(t)?`${t}50`:`color-mix(in srgb, ${t} 31%, transparent)`}function XW(t,e){return`+${((t-e)/1e3).toFixed(3)}s`}function JW(t){let e=new Date(t),n=String(e.getHours()).padStart(2,"0"),o=String(e.getMinutes()).padStart(2,"0"),r=String(e.getSeconds()).padStart(2,"0"),s=String(e.getMilliseconds()).padStart(3,"0");return`${n}:${o}:${r}.${s}`}function ZW(t,e){try{let n=JSON.parse(t);if(typeof n!="object"||n===null)return null;for(let o of e){let r=o.split("."),s=n;for(let a of r)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function eB(t){return navigator.clipboard?.writeText?navigator.clipboard.writeText(t):new Promise(e=>{let n=document.createElement("textarea");n.value=t,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),e()})}function tB(t){let e;try{e=JSON.parse(t.payload)}catch{e=t.payload}return JSON.stringify({type:t.type,timestamp:new Date(t.timestamp).toISOString(),payload:e},null,2)}function nB(t){return t.tokensPerSecond===void 0||!Number.isFinite(t.tokensPerSecond)?"-- tok/s":`${t.tokensPerSecond.toFixed(1)} tok/s`}function oB(t){let e=[];return t.outputTokens!==void 0&&e.push(`${t.outputTokens.toLocaleString()} tok`),t.durationMs!==void 0&&e.push(`${(t.durationMs/1e3).toFixed(2)}s`),t.source&&e.push(t.source),e.join(" \xB7 ")}function rB(t,e,n){let o,r;try{r=JSON.parse(t.payload),o=JSON.stringify(r,null,2)}catch{r=t.payload,o=t.payload}let s=e.find(l=>l.renderEventStreamPayload);if(s?.renderEventStreamPayload&&n){let l=s.renderEventStreamPayload({event:t,config:n,defaultRenderer:()=>a(),parsedPayload:r});if(l)return l}return a();function a(){let l=v("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),c=v("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return c.textContent=o,l.appendChild(c),l}}function ky(t,e,n,o,r,s,a,l){let c=r.has(t.id),p=v("div","persona-border-b persona-border-persona-divider persona-text-xs");qa(p,o.classNames?.eventRow);let u=a.find(g=>g.renderEventStreamRow);if(u?.renderEventStreamRow&&l){let g=u.renderEventStreamRow({event:t,index:e,config:l,defaultRenderer:()=>m(),isExpanded:c,onToggleExpand:()=>s(t.id)});if(g)return p.appendChild(g),p}return p.appendChild(m()),p;function m(){let g=v("div",""),h=v("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");h.setAttribute("data-event-id",t.id);let b=v("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),C=Ge(c?Wn.ChevronDown:Wn.ChevronRight,"14px","currentColor",2);C&&b.appendChild(C);let M=v("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),E=o.timestampFormat??"relative";M.textContent=E==="relative"?XW(t.timestamp,n):JW(t.timestamp);let T=null;o.showSequenceNumbers!==!1&&(T=v("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),T.textContent=String(e+1));let H=YW(t.type,o.badgeColors),A=v("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");A.style.backgroundColor=H.bg,A.style.color=H.text,A.style.borderColor=QW(H.text),A.textContent=t.type;let D=o.descriptionFields??KW,W=ZW(t.payload,D),U=null;W&&(U=v("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),U.textContent=W);let B=v("div","persona-flex-1 persona-min-w-0"),O=v("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),R=Ge(Wn.Clipboard,"12px","currentColor",1.5);return R&&O.appendChild(R),O.addEventListener("click",async S=>{S.stopPropagation(),await eB(tB(t)),O.innerHTML="";let x=Ge(Wn.Check,"12px","currentColor",1.5);x&&O.appendChild(x),setTimeout(()=>{O.innerHTML="";let P=Ge(Wn.Clipboard,"12px","currentColor",1.5);P&&O.appendChild(P)},1500)}),h.appendChild(b),h.appendChild(M),T&&h.appendChild(T),h.appendChild(A),U&&h.appendChild(U),h.appendChild(B),h.appendChild(O),g.appendChild(h),c&&g.appendChild(rB(t,a,l)),g}}function Py(t){let{buffer:e,getFullHistory:n,onClose:o,config:r,plugins:s=[],getThroughput:a}=t,l=t.renderIconByName??(()=>null),c=r?.features?.scrollToBottom,p=c?.enabled!==!1,u=c?.iconName??"arrow-down",m=c?.label??"",g=r?.features?.eventStream??{},h=s.find(C=>C.renderEventStreamView);if(h?.renderEventStreamView&&r){let C=h.renderEventStreamView({config:r,events:e.getAll(),defaultRenderer:()=>b().element,onClose:o});if(C)return{element:C,update:()=>{},destroy:()=>{}}}return b();function b(){let C=g.classNames,M=v("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");qa(M,C?.panel);let E=[],T="",H="",A=null,D=[],W={},U=0,B=$u(),O=0,R=0,S=!1,x=null,P=!1,L=0,G=new Set,V=new Map,K="",ee="",oe=null,ne,le,de,ve,Le=null,se=null,_=null;function Te(){let Ie=v("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),Be=v("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");if(qa(Be,C?.headerBar),a){se=v("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),se.style.cursor="help",Le=v("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),Le.textContent="-- tok/s",_=v("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),_.style.display="none",_.style.pointerEvents="none";let ao=se,Gn=_,Zc=()=>{if(!Gn.textContent)return;let Qo=ao.getBoundingClientRect(),Cn=Ie.getBoundingClientRect();Gn.style.left=`${Qo.left-Cn.left}px`,Gn.style.top=`${Qo.bottom-Cn.top+4}px`,Gn.style.display="block"},_s=()=>{Gn.style.display="none"};se.addEventListener("mouseenter",Zc),se.addEventListener("mouseleave",_s),se.appendChild(Le)}let qe=v("div","persona-flex-1");ne=v("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let Tt=v("option","");Tt.value="",Tt.textContent="All events (0)",ne.appendChild(Tt),le=v("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),le.type="button",le.title="Copy All";let xt=Ge(Wn.ClipboardCopy,"12px","currentColor",1.5);xt&&le.appendChild(xt);let Mn=v("span","persona-event-copy-all persona-text-xs");Mn.textContent="Copy All",le.appendChild(Mn),se&&Be.appendChild(se),Be.appendChild(qe),Be.appendChild(ne),Be.appendChild(le);let ft=v("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");qa(ft,C?.searchBar);let _t=Ge(Wn.Search,"14px","var(--persona-muted, #9ca3af)",1.5),Vt=v("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");_t&&Vt.appendChild(_t),de=v("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),qa(de,C?.searchInput),de.type="text",de.placeholder="Search event payloads...",ve=v("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),ve.type="button",ve.style.display="none";let pn=Ge(Wn.X,"12px","currentColor",2);return pn&&ve.appendChild(pn),ft.appendChild(Vt),ft.appendChild(de),ft.appendChild(ve),Ie.appendChild(Be),Ie.appendChild(ft),_&&Ie.appendChild(_),Ie}let He,ut=s.find(Ie=>Ie.renderEventStreamToolbar);ut?.renderEventStreamToolbar&&r?He=ut.renderEventStreamToolbar({config:r,defaultRenderer:()=>Te(),eventCount:e.getSize(),filteredCount:0,onFilterChange:Be=>{T=Be,Y(),Ee()},onSearchChange:Be=>{H=Be,Y(),Ee()}})??Te():He=Te();let At=v("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");At.style.display="none";function Wt(){if(!a||!Le||!se)return;let Ie=a(),Be=nB(Ie);Le.textContent=Be;let qe=oB(Ie);_&&(_.textContent=qe,qe||(_.style.display="none")),se.setAttribute("aria-label",qe?`Throughput: ${Be}, ${qe}`:`Throughput: ${Be}`)}let bt=v("div","persona-flex-1 persona-min-h-0 persona-relative"),xe=v("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");xe.style.height="100%";let Ne=v("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");qa(Ne,C?.scrollIndicator),Ne.style.display="none",Ne.setAttribute("data-persona-scroll-to-bottom-has-label",m?"true":"false");let Ae=l(u,"14px","currentColor",2);Ae&&Ne.appendChild(Ae);let vt=v("span","");vt.textContent=m,Ne.appendChild(vt);let X=v("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");X.style.display="none",bt.appendChild(xe),bt.appendChild(X),bt.appendChild(Ne),M.setAttribute("tabindex","0"),M.appendChild(He),M.appendChild(At),M.appendChild(bt);function I(){let Ie=e.getAll(),Be={};for(let ft of Ie)Be[ft.type]=(Be[ft.type]||0)+1;let qe=Object.keys(Be).sort(),Tt=qe.length!==D.length||!qe.every((ft,_t)=>ft===D[_t]),mt=!Tt&&qe.some(ft=>Be[ft]!==W[ft]),xt=Ie.length!==Object.values(W).reduce((ft,_t)=>ft+_t,0);if(!Tt&&!mt&&!xt||(D=qe,W=Be,!ne))return;let Mn=ne.value;if(ne.options[0].textContent=`All events (${Ie.length})`,Tt){for(;ne.options.length>1;)ne.remove(1);for(let ft of qe){let _t=v("option","");_t.value=ft,_t.textContent=`${ft} (${Be[ft]||0})`,ne.appendChild(_t)}Mn&&qe.includes(Mn)?ne.value=Mn:Mn&&(ne.value="",T="")}else for(let ft=1;ft<ne.options.length;ft++){let _t=ne.options[ft];_t.textContent=`${_t.value} (${Be[_t.value]||0})`}}function j(){let Ie=e.getAll();if(T&&(Ie=Ie.filter(Be=>Be.type===T)),H){let Be=H.toLowerCase();Ie=Ie.filter(qe=>qe.type.toLowerCase().includes(Be)||qe.payload.toLowerCase().includes(Be))}return Ie}function J(){return T!==""||H!==""}function Y(){U=0,O=0,B.resume(),Ne.style.display="none"}function ie(Ie){G.has(Ie)?G.delete(Ie):G.add(Ie),oe=Ie;let Be=xe.scrollTop,qe=B.isFollowing();P=!0,B.pause(),Ee(),xe.scrollTop=Be,qe&&B.resume(),P=!1}function Me(){return jr(xe,50)}function Ee(){R=Date.now(),S=!1,Wt(),I();let Ie=e.getEvictedCount();Ie>0?(At.textContent=`${Ie.toLocaleString()} older events truncated`,At.style.display=""):At.style.display="none",E=j();let Be=E.length,qe=e.getSize()>0;Be===0&&qe&&J()?(X.textContent=H?`No events matching '${H}'`:"No events matching filter",X.style.display="",xe.style.display="none"):(X.style.display="none",xe.style.display=""),le&&(le.title=J()?`Copy Filtered (${Be})`:"Copy All"),p&&!B.isFollowing()&&Be>U&&(O+=Be-U,vt.textContent=m?`${m}${O>0?` (${O})`:""}`:"",Ne.style.display=""),U=Be;let Tt=e.getAll(),mt=Tt.length>0?Tt[0].timestamp:0,xt=new Set(E.map(_t=>_t.id));for(let _t of G)xt.has(_t)||G.delete(_t);let Mn=T!==K||H!==ee,ft=V.size===0&&E.length>0;if(Mn||ft||E.length===0){xe.innerHTML="",V.clear();let _t=document.createDocumentFragment();for(let Vt=0;Vt<E.length;Vt++){let pn=ky(E[Vt],Vt,mt,g,G,ie,s,r);V.set(E[Vt].id,pn),_t.appendChild(pn)}xe.appendChild(_t),K=T,ee=H,oe=null}else{if(oe!==null){let Vt=V.get(oe);if(Vt&&Vt.parentNode===xe){let pn=E.findIndex(ao=>ao.id===oe);if(pn>=0){let ao=ky(E[pn],pn,mt,g,G,ie,s,r);xe.insertBefore(ao,Vt),Vt.remove(),V.set(oe,ao)}}oe=null}let _t=new Set(E.map(Vt=>Vt.id));for(let[Vt,pn]of V)_t.has(Vt)||(pn.remove(),V.delete(Vt));for(let Vt=0;Vt<E.length;Vt++){let pn=E[Vt];if(!V.has(pn.id)){let ao=ky(pn,Vt,mt,g,G,ie,s,r);V.set(pn.id,ao),xe.appendChild(ao)}}}B.isFollowing()&&(xe.scrollTop=xe.scrollHeight)}function Oe(){if(Date.now()-R>=GW){x!==null&&(cancelAnimationFrame(x),x=null),Ee();return}S||(S=!0,x=requestAnimationFrame(()=>{x=null,Ee()}))}let Ct=(Ie,Be)=>{if(!le)return;le.innerHTML="";let qe=Ge(Ie,"12px","currentColor",1.5);qe&&le.appendChild(qe);let Tt=v("span","persona-text-xs");Tt.textContent="Copy All",le.appendChild(Tt),setTimeout(()=>{le.innerHTML="";let mt=Ge(Wn.ClipboardCopy,"12px","currentColor",1.5);mt&&le.appendChild(mt);let xt=v("span","persona-text-xs");xt.textContent="Copy All",le.appendChild(xt),le.disabled=!1},Be)},Ot=async()=>{if(le){le.disabled=!0;try{let Ie;J()?Ie=E:n?(Ie=await n(),Ie.length===0&&(Ie=e.getAll())):Ie=e.getAll();let Be=Ie.map(qe=>{try{return JSON.parse(qe.payload)}catch{return qe.payload}});await navigator.clipboard.writeText(JSON.stringify(Be,null,2)),Ct(Wn.Check,1500)}catch{Ct(Wn.X,1500)}}},rt=()=>{ne&&(T=ne.value,Y(),Ee())},Ze=()=>{!de||!ve||(ve.style.display=de.value?"":"none",A&&clearTimeout(A),A=setTimeout(()=>{H=de.value,Y(),Ee()},150))},ct=()=>{!de||!ve||(de.value="",H="",ve.style.display="none",A&&clearTimeout(A),Y(),Ee())},Rt=()=>{if(P)return;let Ie=xe.scrollTop,{action:Be,nextLastScrollTop:qe}=zu({following:B.isFollowing(),currentScrollTop:Ie,lastScrollTop:L,nearBottom:Me(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});L=qe,Be==="resume"?(B.resume(),O=0,Ne.style.display="none"):Be==="pause"&&(B.pause(),p&&(vt.textContent=m,Ne.style.display=""))},Z=Ie=>{let Be=Uu({following:B.isFollowing(),deltaY:Ie.deltaY,nearBottom:Me(),resumeWhenNearBottom:!0});Be==="pause"?(B.pause(),p&&(vt.textContent=m,Ne.style.display="")):Be==="resume"&&(B.resume(),O=0,Ne.style.display="none")},Fe=()=>{p&&(xe.scrollTop=xe.scrollHeight,B.resume(),O=0,Ne.style.display="none")},Re=Ie=>{let Be=Ie.target;if(!Be||Be.closest("button"))return;let qe=Be.closest("[data-event-id]");if(!qe)return;let Tt=qe.getAttribute("data-event-id");Tt&&ie(Tt)},nt=Ie=>{if((Ie.metaKey||Ie.ctrlKey)&&Ie.key==="f"){Ie.preventDefault(),de?.focus(),de?.select();return}Ie.key==="Escape"&&(de&&document.activeElement===de?(ct(),de.blur(),M.focus()):o&&o())};le&&le.addEventListener("click",Ot),ne&&ne.addEventListener("change",rt),de&&de.addEventListener("input",Ze),ve&&ve.addEventListener("click",ct),xe.addEventListener("scroll",Rt),xe.addEventListener("wheel",Z,{passive:!0}),xe.addEventListener("click",Re),Ne.addEventListener("click",Fe),M.addEventListener("keydown",nt);function Bt(){A&&clearTimeout(A),x!==null&&(cancelAnimationFrame(x),x=null),S=!1,V.clear(),le&&le.removeEventListener("click",Ot),ne&&ne.removeEventListener("change",rt),de&&de.removeEventListener("input",Ze),ve&&ve.removeEventListener("click",ct),xe.removeEventListener("scroll",Rt),xe.removeEventListener("wheel",Z),xe.removeEventListener("click",Re),Ne.removeEventListener("click",Fe),M.removeEventListener("keydown",nt)}return{element:M,update:Oe,destroy:Bt}}}var Wn,Kr,jW,KW,GW,vT=be(()=>{"use strict";je();Wn=require("lucide");zn();Uh();Kr={flow_:{bg:"var(--persona-event-badge-flow-bg, #dcfce7)",text:"var(--persona-event-badge-flow-fg, #15803d)"},step_:{bg:"var(--persona-event-badge-step-bg, #f5f5f5)",text:"var(--persona-event-badge-step-fg, #0a0a0a)"},reasoning_:{bg:"var(--persona-event-badge-reasoning-bg, #fef9c3)",text:"var(--persona-event-badge-reasoning-fg, #a16207)"},tool_:{bg:"var(--persona-event-badge-tool-bg, #f3e8ff)",text:"var(--persona-event-badge-tool-fg, #6b21a8)"},agent_:{bg:"var(--persona-event-badge-agent-bg, #ccfbf1)",text:"var(--persona-event-badge-agent-fg, #115e59)"},error:{bg:"var(--persona-event-badge-error-bg, #fee2e2)",text:"var(--persona-event-badge-error-fg, #b91c1c)"}};Kr.execution_error=Kr.error;Kr.execution_=Kr.flow_;Kr.turn_=Kr.agent_;Kr.text_=Kr.agent_;jW={bg:"var(--persona-event-badge-default-bg, #f3f4f6)",text:"var(--persona-event-badge-default-fg, #4b5563)"},KW=["flowName","stepName","reasoningText","text","name","tool","toolName"],GW=100});var Wc,CT=be(()=>{"use strict";Wc=class{constructor(e=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=e,this.buffer=new Array(e),this.store=n}push(e){this.buffer[this.head]=e,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(e.type),this.store?.put(e)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let e=await this.store.getAll();if(e.length===0)return 0;let n=e.length>this.maxSize?e.slice(e.length-this.maxSize):e;for(let o of n)this.buffer[this.head]=o,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(o.type);return this.totalCaptured=e.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(e){let n=this.getAll();return e>=n.length?n:n.slice(n.length-e)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.clear()}destroy(){this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}}});var Bc,wT=be(()=>{"use strict";Bc=class{constructor(e="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=e,this.storeName=n}open(){return new Promise((e,n)=>{try{let o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let r=o.result;r.objectStoreNames.contains(this.storeName)||r.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,e()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}put(e){!this.db||this.isDestroyed||(this.pendingWrites.push(e),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(e){if(!(!this.db||this.isDestroyed||e.length===0))try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of e)o.put(r)}catch{}}getAll(){return new Promise((e,n)=>{if(!this.db){e([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{e(a.result)},a.onerror=()=>{n(a.error)}}catch(o){n(o)}})}getCount(){return new Promise((e,n)=>{if(!this.db){e(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{e(s.result)},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}clear(){return new Promise((e,n)=>{if(!this.db){e();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{e()},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((e,n)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{e()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let e=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of e)o.put(r)}catch{}}}});function Ly(t){return t>0?Math.max(1,Math.ceil(t/4)):0}function am(t,e){if(!(t<=0||e===void 0||e<250))return t/(e/1e3)}function aB(t,e){return typeof e.type=="string"?e.type:t}function ST(t){let e=xT(t,"tokens")??xT(t,"totalTokens");return e?MT(e.output):void 0}function lB(t){return MT(t.durationMs)}function cB(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var sB,iB,AT,MT,xT,Dc,TT=be(()=>{"use strict";sB=new Set(["step_start","turn_start"]),iB=new Set(["step_complete","turn_complete"]),AT=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),MT=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,xT=(t,e)=>{let n=t[e];return AT(n)?n:void 0};Dc=class{constructor(e=cB){this.metric={status:"idle"};this.run=null;this.now=e}getMetric(){let e=this.run;if(e&&this.metric.status==="running"&&e.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-e.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:am(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(e){this.run={startedAt:e,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(e,n){if(!AT(n)){e==="execution_error"&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=aB(e,n),r=this.now();if(o==="execution_start"){this.startRun(r);return}if(sB.has(o)){this.run||this.startRun(r);return}if(o==="text_delta"){let s=typeof n.delta=="string"?n.delta:"";if(!s)return;this.run||this.startRun(r);let a=this.run;a.firstDeltaAt??(a.firstDeltaAt=r),a.visibleCharCount+=s.length;let l=a.exactOutputTokens+Ly(a.visibleCharCount),c=r-a.firstDeltaAt;this.metric={status:"running",tokensPerSecond:am(l,c),outputTokens:l,durationMs:c,source:a.exactOutputTokens>0?"usage":"estimate"};return}if(iB.has(o)){if(!this.run)return;let s=this.run,a=ST(n);a!==void 0&&(s.exactOutputTokens+=a,s.visibleCharCount=0);let l=s.exactOutputTokens>0,c=s.exactOutputTokens+Ly(s.visibleCharCount),p=this.resolveDuration(s,n,r);this.metric={status:"running",tokensPerSecond:am(c,p),outputTokens:c,durationMs:p,source:l?"usage":"estimate"};return}if(o==="execution_complete"){if(!this.run)return;let s=this.run,a=ST(n),l=a??s.exactOutputTokens+Ly(s.visibleCharCount),c=a!==void 0||s.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(s,n,r);this.metric={status:"complete",tokensPerSecond:am(l,p),outputTokens:l,durationMs:p,source:c},this.run=null;return}if(o==="execution_error"||o==="error"&&n.recoverable===!1){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(e,n,o){let r=e.firstDeltaAt!==void 0?o-e.firstDeltaAt:void 0;return r!==void 0&&r>=250?r:lB(n)??o-e.startedAt}}});var ET=be(()=>{"use strict";vT();CT();wT();TT()});var kT={};$n(kT,{EventStreamBuffer:()=>Wc,EventStreamStore:()=>Bc,ThroughputTracker:()=>Dc,createEventStreamView:()=>Py});var PT=be(()=>{"use strict";ET()});var Ry,Yo,Oc=be(()=>{"use strict";Ry=class{constructor(){this.components=new Map;this.options=new Map}register(e,n,o){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,n),o?this.options.set(e,o):this.options.delete(e)}unregister(e){this.components.delete(e),this.options.delete(e)}get(e){return this.components.get(e)}has(e){return this.components.has(e)}getOptions(e){return this.options.get(e)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.options.clear()}registerAll(e){Object.entries(e).forEach(([n,o])=>{this.register(n,o)})}},Yo=new Ry});function vr(t){let e=String(t).split(/[\\/]/);return e[e.length-1]??""}function LT(t){let e=vr(t),n=e.lastIndexOf(".");return n<=0?"":e.slice(n+1).toLowerCase()}function lm(t){if(typeof t!="string")return"";let e=t.indexOf(`
|
|
237
|
+
`.trim(),Ac="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#$%&@",VR=10,$R=120,Qh=120,zR=.4,UR=50,qR=t=>{if(!t)return Qh;let n=(t.style.getPropertyValue("--persona-stream-step")?.trim()).match(/([\d.]+)\s*ms/);return n?parseFloat(n[1]):Qh},kM=t=>{let e=t.closest(".persona-stream-glyph-cycle"),n=qR(e);return $R*n/Qh},Xh=t=>{let e=Ac[Math.floor(Math.random()*Ac.length)];return t&&e===t&&(e=Ac[(Ac.indexOf(e)+1)%Ac.length]),e},jR=t=>{let e=t.closest(".persona-stream-glyph-cycle");if(!e)return;let n=e.querySelectorAll(".persona-stream-char[data-glyph-cycle-final]"),o=!1;for(let r of Array.from(n)){if(r===t){o=!0;continue}o&&Math.random()<zR&&(r.textContent=Xh())}},wM=new WeakMap,xM=25,SM=.5,KR=6,AM=.25,MM=new WeakMap,TM=new WeakMap,GR=(t,e)=>{if(!t)return xM*SM;let n=MM.get(t);MM.set(t,e);let o=TM.get(t)??xM;if(n!==void 0){let r=e-n;r>1&&(o=o*(1-AM)+r*AM,TM.set(t,o))}return Math.max(KR,o*SM)},Fa=new Map,YR=t=>t.closest("[data-message-id]")?.dataset.messageId??null,QR=t=>{t&&Fa.set(t,(Fa.get(t)??0)+1)},XR=t=>{if(!t)return;let e=Fa.get(t)??0;e<=1?Fa.delete(t):Fa.set(t,e-1)},PM=t=>{if(t.dataset.glyphCycleScheduled==="true")return;let e=t.textContent??"";if(!e||/\s/.test(e))return;t.dataset.glyphCycleScheduled="true",t.dataset.glyphCycleFinal=e,t.setAttribute("data-preserve-runtime","stream-glyph-cycle"),t.textContent=Xh();let n=YR(t);n&&(t.dataset.glyphCycleMessageId=n),QR(n);let o=t.closest(".persona-stream-glyph-cycle"),r=Date.now(),s=GR(o,r),a=kM(t),l=VR*a,c=r+l;if(o){let p=wM.get(o);p!==void 0&&(c=Math.max(c,p)),wM.set(o,c+s)}JR(t,e,c)},JR=(t,e,n)=>{if(t.dataset.glyphCycleStarted==="true")return;t.dataset.glyphCycleStarted="true";let o=kM(t),r=t.textContent??void 0,s=()=>{if(!t.isConnected)return;if(Date.now()>=n){t.textContent=e,t.removeAttribute("data-preserve-runtime"),delete t.dataset.glyphCycleStarted,delete t.dataset.glyphCycleFinal,XR(t.dataset.glyphCycleMessageId??null),delete t.dataset.glyphCycleMessageId;return}let a=Xh(r);t.textContent=a,r=a,jR(t),setTimeout(s,o)};setTimeout(s,o)},EM=t=>{let e=t.querySelectorAll?.(".persona-stream-glyph-cycle .persona-stream-char:not([data-glyph-cycle-scheduled])");if(e)for(let n of Array.from(e))PM(n)},ZR=t=>t.nodeType===1,LM={name:"glyph-cycle",containerClass:"persona-stream-glyph-cycle",wrap:"char",skipTags:["a","script","style"],styles:FR,bufferContent(t){if(t.length<UR)return"";let e=0,n=-1,o=0;for(;o<t.length;){if(t[o]==="*"&&t[o+1]==="*"){e+=1,o+=2;continue}/\s/.test(t[o])&&e%2===0&&(n=o),o+=1}return n<0?"":t.slice(0,n)},isAnimating(t){return(Fa.get(t.id)??0)>0},onAttach(t){EM(t);let e=new MutationObserver(n=>{for(let o of n)for(let r of Array.from(o.addedNodes))ZR(r)&&(r.classList.contains("persona-stream-char")&&r.closest(".persona-stream-glyph-cycle")?PM(r):EM(r))});return e.observe(t,{childList:!0,subtree:!0}),()=>e.disconnect()}};Ei(LM);IM=LM});var RM={};$n(RM,{glyphCycle:()=>IM,wipe:()=>vM});var WM=be(()=>{"use strict";CM();HM()});function Lc(t){let{items:e,onSelect:n,anchor:o,position:r="bottom-left",portal:s,onOpenChange:a}=t,l=v("div","persona-dropdown-menu persona-hidden");l.setAttribute("role","menu"),l.setAttribute("data-persona-theme-zone","dropdown"),s?(l.style.position="fixed",l.style.zIndex=String(Ba)):(l.style.position="absolute",l.style.top="100%",l.style.marginTop="4px",r==="bottom-right"?l.style.right="0":l.style.left="0");for(let b of e){if(b.dividerBefore){let E=document.createElement("hr");l.appendChild(E)}let C=document.createElement("button");if(C.type="button",C.setAttribute("role","menuitem"),C.setAttribute("data-dropdown-item-id",b.id),b.destructive&&C.setAttribute("data-destructive",""),b.icon){let E=ke(b.icon,16,"currentColor",1.5);E&&C.appendChild(E)}let M=document.createElement("span");M.textContent=b.label,C.appendChild(M),C.addEventListener("click",E=>{E.stopPropagation(),m(),n(b.id)}),l.appendChild(C)}let c=null;function p(){if(!s)return;let b=o.getBoundingClientRect();l.style.top=`${b.bottom+4}px`,r==="bottom-right"?(l.style.right=`${window.innerWidth-b.right}px`,l.style.left="auto"):(l.style.left=`${b.left}px`,l.style.right="auto")}function u(){let b=l.classList.contains("persona-hidden");p(),l.classList.remove("persona-hidden"),b&&a?.(!0),requestAnimationFrame(()=>{let C=M=>{!l.contains(M.target)&&!o.contains(M.target)&&m()};document.addEventListener("click",C,!0),c=()=>document.removeEventListener("click",C,!0)})}function m(){let b=!l.classList.contains("persona-hidden");l.classList.add("persona-hidden"),c?.(),c=null,b&&a?.(!1)}function g(){l.classList.contains("persona-hidden")?u():m()}function h(){m(),l.remove()}return s&&s.appendChild(l),{element:l,show:u,hide:m,toggle:g,destroy:h}}var ry=be(()=>{"use strict";je();Zt();ks()});function vn(t){let{icon:e,label:n,size:o,strokeWidth:r,className:s,chromeless:a,onClick:l,aria:c}=t,p=v("button",Gt(!a&&"persona-icon-btn",s));p.type="button",p.setAttribute("aria-label",n),p.title=n;let u=ke(e,o??16,"currentColor",r??2);if(u&&p.appendChild(u),l&&p.addEventListener("click",l),c)for(let[m,g]of Object.entries(c))p.setAttribute(m,g);return p}function Li(t){let{icon:e,label:n,variant:o="default",size:r="sm",iconSize:s,className:a,onClick:l,aria:c}=t,p="persona-label-btn";o!=="default"&&(p+=" persona-label-btn--"+o),p+=" persona-label-btn--"+r,a&&(p+=" "+a);let u=v("button",p);if(u.type="button",u.setAttribute("aria-label",n),e){let g=ke(e,s??14,"currentColor",2);g&&u.appendChild(g)}let m=v("span");if(m.textContent=n,u.appendChild(m),l&&u.addEventListener("click",l),c)for(let[g,h]of Object.entries(c))u.setAttribute(g,h);return u}function Yu(t){let{items:e,selectedId:n,onSelect:o,className:r}=t,s=v("div","persona-toggle-group"+(r?" "+r:""));s.setAttribute("role","group");let a=n,l=[];function c(){for(let u of l)u.btn.setAttribute("aria-pressed",u.id===a?"true":"false")}for(let u of e){let m;u.icon?m=vn({icon:u.icon,label:u.label,className:u.className,onClick:()=>{a=u.id,c(),o(u.id)}}):(m=v("button","persona-icon-btn"+(u.className?" "+u.className:"")),m.type="button",m.setAttribute("aria-label",u.label),m.title=u.label,m.textContent=u.label,m.addEventListener("click",()=>{a=u.id,c(),o(u.id)})),m.setAttribute("aria-pressed",u.id===a?"true":"false"),l.push({id:u.id,btn:m}),s.appendChild(m)}function p(u){a=u,c()}return{element:s,setSelected:p}}function NM(t){let{label:e,icon:n,iconSize:o,iconOnly:r,menuItems:s,onSelect:a,onPrimary:l,position:c="bottom-left",portal:p,chevronLabel:u="More options",chevronIconSize:m,className:g,primaryClassName:h,chevronClassName:b}=t,C=v("div","persona-split-btn"+(g?" "+g:"")),M={label:e,className:"persona-split-btn-primary"+(h?" "+h:""),onClick:l},E=r&&n?vn({...M,icon:n,size:o??14}):Li({...M,icon:n,iconSize:o??14}),T=vn({icon:"chevron-down",label:u,size:m??14,className:"persona-split-btn-chevron"+(b?" "+b:""),aria:{"aria-haspopup":"true","aria-expanded":"false"}});C.append(E,T);let R=null,A=()=>{if(R)return R;let D=(typeof p=="function"?p():p)??void 0;return R=Lc({items:s,onSelect:a,anchor:C,position:c,portal:D,onOpenChange:W=>{T.setAttribute("aria-expanded",W?"true":"false")}}),D||C.appendChild(R.element),R};return C.isConnected?A():requestAnimationFrame(()=>{R||A()}),T.addEventListener("click",D=>{D.stopPropagation(),A().toggle()}),{element:C,primaryButton:E,chevronButton:T,openMenu:()=>A().show(),closeMenu:()=>R?.hide(),toggleMenu:()=>A().toggle(),destroy:()=>{R?.destroy(),C.remove()}}}function FM(t){let{label:e,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:a,className:l,hover:c}=t,p=v("div","persona-combo-btn"+(l?" "+l:""));p.style.position="relative",p.style.display="inline-flex",p.style.alignItems="center",p.style.cursor="pointer",p.setAttribute("role","button"),p.setAttribute("tabindex","0"),p.setAttribute("aria-haspopup","true"),p.setAttribute("aria-expanded","false"),p.setAttribute("aria-label",e);let u=v("span","persona-combo-btn-label");u.textContent=e,p.appendChild(u);let m=ke(n,14,"currentColor",2);m&&(m.style.marginLeft="4px",m.style.opacity="0.6",p.appendChild(m)),c&&(p.style.borderRadius=c.borderRadius??"10px",p.style.padding=c.padding??"6px 4px 6px 12px",p.style.border="1px solid transparent",p.style.transition="background-color 0.15s ease, border-color 0.15s ease",p.addEventListener("mouseenter",()=>{p.style.backgroundColor=c.background??"",p.style.borderColor=c.border??""}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="",p.style.borderColor="transparent"}));let g=Lc({items:o,onSelect:b=>{p.setAttribute("aria-expanded","false"),r(b)},anchor:p,position:s,portal:a});a||p.appendChild(g.element);let h=()=>p.getAttribute("data-persona-menu-locked")==="true";return p.addEventListener("click",b=>{if(b.stopPropagation(),h())return;let C=!g.element.classList.contains("persona-hidden");p.setAttribute("aria-expanded",C?"false":"true"),g.toggle()}),p.addEventListener("keydown",b=>{(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),p.click())}),{element:p,setLabel:b=>{u.textContent=b,p.setAttribute("aria-label",b)},open:()=>{p.setAttribute("aria-expanded","true"),g.show()},close:()=>{p.setAttribute("aria-expanded","false"),g.hide()},toggle:()=>{let b=!g.element.classList.contains("persona-hidden");p.setAttribute("aria-expanded",b?"false":"true"),g.toggle()},destroy:()=>{g.destroy(),p.remove()}}}var Ii=be(()=>{"use strict";je();Zt();ry()});var Rs,rm=be(()=>{"use strict";je();Rs=(t,e,n)=>{let o=n;for(let r of e){let s=v("span","persona-tool-char");s.style.setProperty("--char-index",String(o)),s.textContent=r===" "?"\xA0":r,t.appendChild(s),o++}return o}});var yT,Ay,sm,im=be(()=>{"use strict";yT=()=>{},Ay=t=>{yT=t.webMcpToolTitle},sm=t=>yT(t)});var Oo,Ri,bT,vT,CT,My,Ty,Ey=be(()=>{"use strict";je();Ts();im();Oo=require("lucide");zn();Aa();Ri=t=>{let n=(t.startsWith(zr)?t.slice(zr.length):t).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return t;let o=n.join(" ").toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)},bT=t=>t?.approval!==!1?t?.approval:void 0,vT=(t,e,n)=>{let o=bT(n)?.detailsDisplay??"collapsed";return e.get(t)??o==="expanded"},CT=(t,e,n)=>{let o=bT(n);t.setAttribute("aria-expanded",e?"true":"false");let r=t.querySelector("[data-approval-details-label]");r&&(r.textContent=e?o?.hideDetailsLabel??"Hide details":o?.showDetailsLabel??"Show details");let s=t.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let a=Ge(e?Oo.ChevronUp:Oo.ChevronDown,14,"currentColor",2);a&&s.appendChild(a)}},My=(t,e,n,o=new Map)=>{let r=e.querySelector('button[data-bubble-type="approval"]'),s=e.querySelector("[data-approval-details]");if(!r||!s)return;let a=vT(t,o,n);CT(r,a,n),s.style.display=a?"":"none"},Ty=(t,e,n=new Map)=>{let o=t.approval,r=e?.approval!==!1?e?.approval:void 0,s=o?.status==="pending",a=v("div",["persona-approval-bubble","persona-w-full","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(a.id=`bubble-${t.id}`,a.setAttribute("data-message-id",t.id),a.style.backgroundColor=r?.backgroundColor??"var(--persona-approval-bg)",a.style.borderColor=r?.borderColor??"var(--persona-approval-border)",a.style.boxShadow=r?.shadow!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-approval-shadow)",!o)return a;let l=v("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),c=v("div","persona-flex-shrink-0 persona-mt-0.5");c.setAttribute("data-approval-icon","true");let p=o.status==="denied"?Oo.ShieldX:o.status==="timeout"?Oo.ShieldAlert:Oo.ShieldCheck,u=o.status==="approved"?"var(--persona-feedback-success, var(--persona-palette-colors-success-600))":o.status==="denied"?"var(--persona-feedback-error, var(--persona-palette-colors-error-600))":o.status==="timeout"?"var(--persona-feedback-warning, var(--persona-palette-colors-warning-600))":r?.titleColor??"currentColor",m=Ge(p,20,u,2);m&&c.appendChild(m);let g=v("div","persona-flex-1 persona-min-w-0"),h=v("div","persona-flex persona-items-center persona-gap-2"),b=v("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r?.titleColor&&(b.style.color=r.titleColor),b.textContent=r?.title??"Approval Required",h.appendChild(b),!s){let B=v("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");B.setAttribute("data-approval-status",o.status),o.status==="approved"?(B.style.backgroundColor="var(--persona-palette-colors-success-100)",B.style.color="var(--persona-palette-colors-success-700)",B.textContent="Approved"):o.status==="denied"?(B.style.backgroundColor="var(--persona-palette-colors-error-100)",B.style.color="var(--persona-palette-colors-error-700)",B.textContent="Denied"):o.status==="timeout"&&(B.style.backgroundColor="var(--persona-palette-colors-warning-100)",B.style.color="var(--persona-palette-colors-warning-700)",B.textContent="Timeout"),h.appendChild(B)}g.appendChild(h);let M=o.toolType==="webmcp"||o.toolName.startsWith(zr)?sm(o.toolName):void 0,E=r?.formatDescription?.({toolName:o.toolName,toolType:o.toolType,description:o.description,parameters:o.parameters,...M?{displayTitle:M}:{},...o.reason?{reason:o.reason}:{}}),T=!o.toolName,R=E||(T?o.description:`The assistant wants to use \u201C${M??Ri(o.toolName)}\u201D.`),A=v("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(A.setAttribute("data-approval-summary","true"),r?.descriptionColor&&(A.style.color=r.descriptionColor),A.textContent=R,g.appendChild(A),o.reason){let B=v("p","persona-text-sm persona-mt-1 persona-text-persona-muted");B.setAttribute("data-approval-reason","true"),r?.reasonColor?B.style.color=r.reasonColor:r?.descriptionColor&&(B.style.color=r.descriptionColor);let O=v("span","persona-font-medium");O.textContent=`${r?.reasonLabel??"Agent's stated reason:"} `,B.appendChild(O),B.appendChild(document.createTextNode(o.reason)),g.appendChild(B)}let D=r?.detailsDisplay??"collapsed",W=!!o.description&&!T,U=W||!!o.parameters;if(D!=="hidden"&&U){let B=vT(t.id,n,e),O=v("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");O.type="button",O.setAttribute("data-expand-header","true"),O.setAttribute("data-bubble-type","approval"),r?.descriptionColor&&(O.style.color=r.descriptionColor);let H=v("span");H.setAttribute("data-approval-details-label","true");let S=v("span","persona-inline-flex persona-items-center");S.setAttribute("data-approval-details-chevron","true"),O.append(H,S),CT(O,B,e),g.appendChild(O);let x=v("div");if(x.setAttribute("data-approval-details","true"),x.style.display=B?"":"none",W){let P=v("p","persona-text-sm persona-mt-1 persona-text-persona-muted");r?.descriptionColor&&(P.style.color=r.descriptionColor),P.textContent=o.description,x.appendChild(P)}if(o.parameters){let P=v("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");r?.parameterBackgroundColor&&(P.style.backgroundColor=r.parameterBackgroundColor),r?.parameterTextColor&&(P.style.color=r.parameterTextColor),P.style.fontSize="0.75rem",P.style.lineHeight="1rem",P.textContent=mr(o.parameters),x.appendChild(P)}g.appendChild(x)}if(s){let B=v("div","persona-flex persona-gap-2 persona-mt-2");B.setAttribute("data-approval-buttons","true");let O=v("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");O.type="button",O.style.backgroundColor=r?.approveButtonColor??"var(--persona-approval-approve-bg)",O.style.color=r?.approveButtonTextColor??"var(--persona-button-primary-fg)",O.setAttribute("data-approval-action","approve");let H=Ge(Oo.ShieldCheck,14,r?.approveButtonTextColor??"var(--persona-button-primary-fg)",2);H&&(H.style.marginRight="4px",O.appendChild(H));let S=document.createTextNode(r?.approveLabel??"Approve");O.appendChild(S);let x=v("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");x.type="button",x.style.backgroundColor=r?.denyButtonColor??"transparent",x.style.color=r?.denyButtonTextColor??"var(--persona-feedback-error, var(--persona-palette-colors-error-600))",x.style.border=`1px solid ${r?.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200)"}`,x.setAttribute("data-approval-action","deny");let P=Ge(Oo.ShieldX,14,r?.denyButtonTextColor??"var(--persona-feedback-error, var(--persona-palette-colors-error-600))",2);P&&(P.style.marginRight="4px",x.appendChild(P));let L=document.createTextNode(r?.denyLabel??"Deny");x.appendChild(L),B.append(O,x),g.appendChild(B)}return l.append(c,g),a.appendChild(l),a}});var Bi,eB,wT,Wi,tB,nB,ky,oB,rB,sB,Py,xT=be(()=>{"use strict";je();im();Bi=require("lucide");zn();Ts();Aa();Oa();Ey();eB=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),wT=(t,e)=>{let n=t.keyHandlers.get(e);n&&(document.removeEventListener("keydown",n),t.keyHandlers.delete(e));let o=t.popovers.get(e);o&&(o.destroy(),t.popovers.delete(e))},Wi=(t,e)=>{wT(t,e);let n=t.pendingOrder.indexOf(e);n!==-1&&t.pendingOrder.splice(n,1),t.latestPendingApprovalId===e&&(t.latestPendingApprovalId=t.pendingOrder.length?t.pendingOrder[t.pendingOrder.length-1]:null)},tB=t=>t?.approval!==!1?t?.approval:void 0,nB=(t,e,n)=>{let o=n?.detailsDisplay??"collapsed";return e.get(t)??o==="expanded"},ky=t=>{let e=v("span","persona-approval-kbd");return e.textContent=t,e},oB=(t,e)=>{let n=v("span","persona-approval-title");e?.titleColor&&(n.style.color=e.titleColor);let r=t.toolType==="webmcp"||t.toolName.startsWith(zr)?sm(t.toolName):void 0,s=e?.formatDescription?.({toolName:t.toolName,toolType:t.toolType,description:t.description??"",parameters:t.parameters,...r?{displayTitle:r}:{},...t.reason?{reason:t.reason}:{}});if(s)return n.textContent=s,n;let a=r??Ri(t.toolName),l=t.toolType&&t.toolType!=="webmcp"?t.toolType:null;n.append("The assistant wants to use ");let c=document.createElement("strong");if(c.textContent=a,n.appendChild(c),l){n.append(" from ");let p=document.createElement("strong");p.textContent=l,n.appendChild(p)}return n},rB=t=>{let e=v("div","persona-approval-resolved"),n=Ge(Bi.Ban,15,"currentColor",2);n&&e.appendChild(n);let o=v("span","persona-approval-resolved-name");return o.textContent=t.toolName?Ri(t.toolName):"Tool",e.append(o,document.createTextNode(t.status==="timeout"?" timed out":" denied")),e},sB=(t,e,n,o,r,s,a,l)=>{let c=v("div","persona-approval-card persona-shadow-sm");c.id=`bubble-${n.id}`,c.setAttribute("data-message-id",n.id),c.setAttribute("data-bubble-type","approval"),r?.backgroundColor&&(c.style.background=r.backgroundColor),r?.borderColor&&(c.style.borderColor=r.borderColor),r?.shadow!==void 0&&(c.style.boxShadow=r.shadow.trim()===""?"none":r.shadow);let p=r?.detailsDisplay??"collapsed",u=!!o.description&&p!=="hidden",m=o.parameters!=null&&p!=="hidden",g=u||m,h=g&&nB(n.id,e,r),b=r?.showDetailsLabel??"Show details",C=r?.hideDetailsLabel??"Hide details",M=v("button","persona-approval-head");M.type="button",g?(M.setAttribute("data-action","toggle-params"),M.setAttribute("aria-expanded",h?"true":"false"),M.setAttribute("aria-label",h?C:b)):M.setAttribute("data-static","true");let E=v("span","persona-approval-logo"),T=Ge(Bi.ShieldCheck,16,"currentColor",2);T&&E.appendChild(T),M.appendChild(E);let R=oB(o,r);if(g){let O=v("span","persona-approval-toggle");O.setAttribute("aria-hidden","true");let H=Ge(Bi.ChevronDown,14,"currentColor",2);H&&O.appendChild(H),R.append(" "),R.appendChild(O)}M.appendChild(R),c.appendChild(M);let A=v("div","persona-approval-body");if(g){let O=v("div","persona-approval-details");if(O.setAttribute("data-role","params"),O.hidden=!h,u){let H=v("p","persona-approval-desc");r?.descriptionColor&&(H.style.color=r.descriptionColor),H.textContent=o.description,O.appendChild(H)}if(m){let H=v("pre","persona-approval-params");r?.parameterBackgroundColor&&(H.style.background=r.parameterBackgroundColor),r?.parameterTextColor&&(H.style.color=r.parameterTextColor),H.textContent=mr(o.parameters),O.appendChild(H)}A.appendChild(O)}if(o.reason){let O=v("p","persona-approval-reason");r?.reasonColor?O.style.color=r.reasonColor:r?.descriptionColor&&(O.style.color=r.descriptionColor);let H=v("span","persona-approval-reason-label");H.textContent=`${r?.reasonLabel??"Agent's stated reason:"} `,O.append(H,document.createTextNode(o.reason)),A.appendChild(O)}let D=v("div","persona-approval-actions"),W=null,U=O=>{r?.approveButtonColor&&(O.style.background=r.approveButtonColor),r?.approveButtonTextColor&&(O.style.color=r.approveButtonTextColor)},B=v("button","persona-approval-deny");if(B.type="button",B.setAttribute("data-action","deny"),r?.denyButtonColor&&(B.style.background=r.denyButtonColor),r?.denyButtonTextColor&&(B.style.color=r.denyButtonTextColor),B.append(r?.denyLabel??"Deny"),l){let O=v("div","persona-approval-split"),H=v("button","persona-approval-primary");H.type="button",H.setAttribute("data-action","always"),U(H),H.append(r?.approveLabel??"Always allow",ky("\u23CE"));let S=v("button","persona-approval-caret");S.type="button",S.setAttribute("data-action","toggle-menu"),S.setAttribute("aria-label","More options"),U(S);let x=Ge(Bi.ChevronDown,15,"currentColor",2);x&&S.appendChild(x),O.append(H,S),D.append(O,B),B.append(ky("Esc"));let P=v("div","persona-approval-menu"),L=v("button","persona-approval-menu-item");L.type="button",L.append("Allow once",ky("\u2318\u23CE")),P.appendChild(L),W=Ps({anchor:O,content:P,placement:"bottom-start",matchAnchorWidth:!0}),t.popovers.set(n.id,W),L.addEventListener("click",()=>{Wi(t,n.id),s()})}else{let O=v("button","persona-approval-primary persona-approval-primary--solo");O.type="button",O.setAttribute("data-action","allow"),U(O),O.append(r?.approveLabel??"Allow"),D.append(O,B)}return A.appendChild(D),c.appendChild(A),c.addEventListener("click",O=>{let H=O.target instanceof Element?O.target.closest("[data-action]"):null;if(!H)return;let S=H.getAttribute("data-action");if(S==="toggle-params"){let x=c.querySelector('[data-role="params"]');if(x){let P=x.hidden;x.hidden=!P,M.setAttribute("aria-expanded",P?"true":"false"),M.setAttribute("aria-label",P?C:b),e.set(n.id,P)}return}if(S==="toggle-menu"){W?.toggle();return}if(S==="always"){Wi(t,n.id),s({remember:!0});return}if(S==="allow"){Wi(t,n.id),s();return}if(S==="deny"){Wi(t,n.id),a();return}}),c},Py=(t=new Map)=>{let e=eB();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:r,approve:s,deny:a,config:l})=>{let c=r?.approval;if(!c)return null;let p=tB(l);if(c.status!=="pending"){if(Wi(e,r.id),c.status==="approved"){let g=document.createElement("div");return g.style.display="none",g}return rB(c)}wT(e,r.id);let u=p?.enableAlwaysAllow===!0,m=sB(e,t,r,c,p,s,a,u);if(u){e.pendingOrder.includes(r.id)||e.pendingOrder.push(r.id),e.latestPendingApprovalId=e.pendingOrder[e.pendingOrder.length-1];let g=h=>{WS(h)||r.id===e.latestPendingApprovalId&&(h.key!=="Escape"&&h.key!=="Enter"||(h.preventDefault(),h.stopImmediatePropagation(),Wi(e,r.id),h.key==="Escape"?a():h.metaKey||h.ctrlKey?s():s({remember:!0})))};e.keyHandlers.set(r.id,g),document.addEventListener("keydown",g)}return m}},teardown:()=>{for(let r of[...e.keyHandlers.keys(),...e.popovers.keys()])Wi(e,r);e.latestPendingApprovalId=null}}}});var ST=be(()=>{"use strict";Ey();xT();im()});var AT={};$n(AT,{createApprovalBubble:()=>Ty,createBuiltInApprovalPlugin:()=>Py,humanizeToolName:()=>Ri,initApprovalUi:()=>Ay,updateApprovalDetailsUI:()=>My});var MT=be(()=>{"use strict";ST()});function qa(t,e){e&&e.split(/\s+/).forEach(n=>n&&t.classList.add(n))}function kT(t,e){if(e[t])return e[t];for(let n of Object.keys(e))if(n.endsWith("_")&&t.startsWith(n))return e[n]}function pB(t,e){return(e&&kT(t,e))??kT(t,Kr)??lB}function uB(t){return/^#[0-9a-fA-F]{6}$/.test(t)?`${t}50`:`color-mix(in srgb, ${t} 31%, transparent)`}function mB(t,e){return`+${((t-e)/1e3).toFixed(3)}s`}function fB(t){let e=new Date(t),n=String(e.getHours()).padStart(2,"0"),o=String(e.getMinutes()).padStart(2,"0"),r=String(e.getSeconds()).padStart(2,"0"),s=String(e.getMilliseconds()).padStart(3,"0");return`${n}:${o}:${r}.${s}`}function gB(t,e){try{let n=JSON.parse(t);if(typeof n!="object"||n===null)return null;for(let o of e){let r=o.split("."),s=n;for(let a of r)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function hB(t){return navigator.clipboard?.writeText?navigator.clipboard.writeText(t):new Promise(e=>{let n=document.createElement("textarea");n.value=t,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),e()})}function yB(t){let e;try{e=JSON.parse(t.payload)}catch{e=t.payload}return JSON.stringify({type:t.type,timestamp:new Date(t.timestamp).toISOString(),payload:e},null,2)}function bB(t){return t.tokensPerSecond===void 0||!Number.isFinite(t.tokensPerSecond)?"-- tok/s":`${t.tokensPerSecond.toFixed(1)} tok/s`}function vB(t){let e=[];return t.outputTokens!==void 0&&e.push(`${t.outputTokens.toLocaleString()} tok`),t.durationMs!==void 0&&e.push(`${(t.durationMs/1e3).toFixed(2)}s`),t.source&&e.push(t.source),e.join(" \xB7 ")}function CB(t,e,n){let o,r;try{r=JSON.parse(t.payload),o=JSON.stringify(r,null,2)}catch{r=t.payload,o=t.payload}let s=e.find(l=>l.renderEventStreamPayload);if(s?.renderEventStreamPayload&&n){let l=s.renderEventStreamPayload({event:t,config:n,defaultRenderer:()=>a(),parsedPayload:r});if(l)return l}return a();function a(){let l=v("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),c=v("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return c.textContent=o,l.appendChild(c),l}}function Ly(t,e,n,o,r,s,a,l){let c=r.has(t.id),p=v("div","persona-border-b persona-border-persona-divider persona-text-xs");qa(p,o.classNames?.eventRow);let u=a.find(g=>g.renderEventStreamRow);if(u?.renderEventStreamRow&&l){let g=u.renderEventStreamRow({event:t,index:e,config:l,defaultRenderer:()=>m(),isExpanded:c,onToggleExpand:()=>s(t.id)});if(g)return p.appendChild(g),p}return p.appendChild(m()),p;function m(){let g=v("div",""),h=v("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");h.setAttribute("data-event-id",t.id);let b=v("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),C=Ge(c?Wn.ChevronDown:Wn.ChevronRight,"14px","currentColor",2);C&&b.appendChild(C);let M=v("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),E=o.timestampFormat??"relative";M.textContent=E==="relative"?mB(t.timestamp,n):fB(t.timestamp);let T=null;o.showSequenceNumbers!==!1&&(T=v("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),T.textContent=String(e+1));let R=pB(t.type,o.badgeColors),A=v("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");A.style.backgroundColor=R.bg,A.style.color=R.text,A.style.borderColor=uB(R.text),A.textContent=t.type;let D=o.descriptionFields??cB,W=gB(t.payload,D),U=null;W&&(U=v("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),U.textContent=W);let B=v("div","persona-flex-1 persona-min-w-0"),O=v("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),H=Ge(Wn.Clipboard,"12px","currentColor",1.5);return H&&O.appendChild(H),O.addEventListener("click",async S=>{S.stopPropagation(),await hB(yB(t)),O.innerHTML="";let x=Ge(Wn.Check,"12px","currentColor",1.5);x&&O.appendChild(x),setTimeout(()=>{O.innerHTML="";let P=Ge(Wn.Clipboard,"12px","currentColor",1.5);P&&O.appendChild(P)},1500)}),h.appendChild(b),h.appendChild(M),T&&h.appendChild(T),h.appendChild(A),U&&h.appendChild(U),h.appendChild(B),h.appendChild(O),g.appendChild(h),c&&g.appendChild(CB(t,a,l)),g}}function Iy(t){let{buffer:e,getFullHistory:n,onClose:o,config:r,plugins:s=[],getThroughput:a}=t,l=t.renderIconByName??(()=>null),c=r?.features?.scrollToBottom,p=c?.enabled!==!1,u=c?.iconName??"arrow-down",m=c?.label??"",g=r?.features?.eventStream??{},h=s.find(C=>C.renderEventStreamView);if(h?.renderEventStreamView&&r){let C=h.renderEventStreamView({config:r,events:e.getAll(),defaultRenderer:()=>b().element,onClose:o});if(C)return{element:C,update:()=>{},destroy:()=>{}}}return b();function b(){let C=g.classNames,M=v("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");qa(M,C?.panel);let E=[],T="",R="",A=null,D=[],W={},U=0,B=$u(),O=0,H=0,S=!1,x=null,P=!1,L=0,G=new Set,V=new Map,K="",ee="",oe=null,ne,le,de,ve,Le=null,se=null,_=null;function Te(){let Ie=v("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),Be=v("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");if(qa(Be,C?.headerBar),a){se=v("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),se.style.cursor="help",Le=v("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),Le.textContent="-- tok/s",_=v("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),_.style.display="none",_.style.pointerEvents="none";let ao=se,Yn=_,Zc=()=>{if(!Yn.textContent)return;let Qo=ao.getBoundingClientRect(),Cn=Ie.getBoundingClientRect();Yn.style.left=`${Qo.left-Cn.left}px`,Yn.style.top=`${Qo.bottom-Cn.top+4}px`,Yn.style.display="block"},_s=()=>{Yn.style.display="none"};se.addEventListener("mouseenter",Zc),se.addEventListener("mouseleave",_s),se.appendChild(Le)}let qe=v("div","persona-flex-1");ne=v("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let Tt=v("option","");Tt.value="",Tt.textContent="All events (0)",ne.appendChild(Tt),le=v("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),le.type="button",le.title="Copy All";let xt=Ge(Wn.ClipboardCopy,"12px","currentColor",1.5);xt&&le.appendChild(xt);let Mn=v("span","persona-event-copy-all persona-text-xs");Mn.textContent="Copy All",le.appendChild(Mn),se&&Be.appendChild(se),Be.appendChild(qe),Be.appendChild(ne),Be.appendChild(le);let ft=v("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");qa(ft,C?.searchBar);let _t=Ge(Wn.Search,"14px","var(--persona-muted, #9ca3af)",1.5),Vt=v("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");_t&&Vt.appendChild(_t),de=v("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),qa(de,C?.searchInput),de.type="text",de.placeholder="Search event payloads...",ve=v("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),ve.type="button",ve.style.display="none";let pn=Ge(Wn.X,"12px","currentColor",2);return pn&&ve.appendChild(pn),ft.appendChild(Vt),ft.appendChild(de),ft.appendChild(ve),Ie.appendChild(Be),Ie.appendChild(ft),_&&Ie.appendChild(_),Ie}let Re,ut=s.find(Ie=>Ie.renderEventStreamToolbar);ut?.renderEventStreamToolbar&&r?Re=ut.renderEventStreamToolbar({config:r,defaultRenderer:()=>Te(),eventCount:e.getSize(),filteredCount:0,onFilterChange:Be=>{T=Be,Y(),Ee()},onSearchChange:Be=>{R=Be,Y(),Ee()}})??Te():Re=Te();let At=v("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");At.style.display="none";function Wt(){if(!a||!Le||!se)return;let Ie=a(),Be=bB(Ie);Le.textContent=Be;let qe=vB(Ie);_&&(_.textContent=qe,qe||(_.style.display="none")),se.setAttribute("aria-label",qe?`Throughput: ${Be}, ${qe}`:`Throughput: ${Be}`)}let bt=v("div","persona-flex-1 persona-min-h-0 persona-relative"),xe=v("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");xe.style.height="100%";let Ne=v("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");qa(Ne,C?.scrollIndicator),Ne.style.display="none",Ne.setAttribute("data-persona-scroll-to-bottom-has-label",m?"true":"false");let Ae=l(u,"14px","currentColor",2);Ae&&Ne.appendChild(Ae);let vt=v("span","");vt.textContent=m,Ne.appendChild(vt);let X=v("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");X.style.display="none",bt.appendChild(xe),bt.appendChild(X),bt.appendChild(Ne),M.setAttribute("tabindex","0"),M.appendChild(Re),M.appendChild(At),M.appendChild(bt);function I(){let Ie=e.getAll(),Be={};for(let ft of Ie)Be[ft.type]=(Be[ft.type]||0)+1;let qe=Object.keys(Be).sort(),Tt=qe.length!==D.length||!qe.every((ft,_t)=>ft===D[_t]),mt=!Tt&&qe.some(ft=>Be[ft]!==W[ft]),xt=Ie.length!==Object.values(W).reduce((ft,_t)=>ft+_t,0);if(!Tt&&!mt&&!xt||(D=qe,W=Be,!ne))return;let Mn=ne.value;if(ne.options[0].textContent=`All events (${Ie.length})`,Tt){for(;ne.options.length>1;)ne.remove(1);for(let ft of qe){let _t=v("option","");_t.value=ft,_t.textContent=`${ft} (${Be[ft]||0})`,ne.appendChild(_t)}Mn&&qe.includes(Mn)?ne.value=Mn:Mn&&(ne.value="",T="")}else for(let ft=1;ft<ne.options.length;ft++){let _t=ne.options[ft];_t.textContent=`${_t.value} (${Be[_t.value]||0})`}}function j(){let Ie=e.getAll();if(T&&(Ie=Ie.filter(Be=>Be.type===T)),R){let Be=R.toLowerCase();Ie=Ie.filter(qe=>qe.type.toLowerCase().includes(Be)||qe.payload.toLowerCase().includes(Be))}return Ie}function J(){return T!==""||R!==""}function Y(){U=0,O=0,B.resume(),Ne.style.display="none"}function ie(Ie){G.has(Ie)?G.delete(Ie):G.add(Ie),oe=Ie;let Be=xe.scrollTop,qe=B.isFollowing();P=!0,B.pause(),Ee(),xe.scrollTop=Be,qe&&B.resume(),P=!1}function Me(){return jr(xe,50)}function Ee(){H=Date.now(),S=!1,Wt(),I();let Ie=e.getEvictedCount();Ie>0?(At.textContent=`${Ie.toLocaleString()} older events truncated`,At.style.display=""):At.style.display="none",E=j();let Be=E.length,qe=e.getSize()>0;Be===0&&qe&&J()?(X.textContent=R?`No events matching '${R}'`:"No events matching filter",X.style.display="",xe.style.display="none"):(X.style.display="none",xe.style.display=""),le&&(le.title=J()?`Copy Filtered (${Be})`:"Copy All"),p&&!B.isFollowing()&&Be>U&&(O+=Be-U,vt.textContent=m?`${m}${O>0?` (${O})`:""}`:"",Ne.style.display=""),U=Be;let Tt=e.getAll(),mt=Tt.length>0?Tt[0].timestamp:0,xt=new Set(E.map(_t=>_t.id));for(let _t of G)xt.has(_t)||G.delete(_t);let Mn=T!==K||R!==ee,ft=V.size===0&&E.length>0;if(Mn||ft||E.length===0){xe.innerHTML="",V.clear();let _t=document.createDocumentFragment();for(let Vt=0;Vt<E.length;Vt++){let pn=Ly(E[Vt],Vt,mt,g,G,ie,s,r);V.set(E[Vt].id,pn),_t.appendChild(pn)}xe.appendChild(_t),K=T,ee=R,oe=null}else{if(oe!==null){let Vt=V.get(oe);if(Vt&&Vt.parentNode===xe){let pn=E.findIndex(ao=>ao.id===oe);if(pn>=0){let ao=Ly(E[pn],pn,mt,g,G,ie,s,r);xe.insertBefore(ao,Vt),Vt.remove(),V.set(oe,ao)}}oe=null}let _t=new Set(E.map(Vt=>Vt.id));for(let[Vt,pn]of V)_t.has(Vt)||(pn.remove(),V.delete(Vt));for(let Vt=0;Vt<E.length;Vt++){let pn=E[Vt];if(!V.has(pn.id)){let ao=Ly(pn,Vt,mt,g,G,ie,s,r);V.set(pn.id,ao),xe.appendChild(ao)}}}B.isFollowing()&&(xe.scrollTop=xe.scrollHeight)}function _e(){if(Date.now()-H>=dB){x!==null&&(cancelAnimationFrame(x),x=null),Ee();return}S||(S=!0,x=requestAnimationFrame(()=>{x=null,Ee()}))}let Ct=(Ie,Be)=>{if(!le)return;le.innerHTML="";let qe=Ge(Ie,"12px","currentColor",1.5);qe&&le.appendChild(qe);let Tt=v("span","persona-text-xs");Tt.textContent="Copy All",le.appendChild(Tt),setTimeout(()=>{le.innerHTML="";let mt=Ge(Wn.ClipboardCopy,"12px","currentColor",1.5);mt&&le.appendChild(mt);let xt=v("span","persona-text-xs");xt.textContent="Copy All",le.appendChild(xt),le.disabled=!1},Be)},Ot=async()=>{if(le){le.disabled=!0;try{let Ie;J()?Ie=E:n?(Ie=await n(),Ie.length===0&&(Ie=e.getAll())):Ie=e.getAll();let Be=Ie.map(qe=>{try{return JSON.parse(qe.payload)}catch{return qe.payload}});await navigator.clipboard.writeText(JSON.stringify(Be,null,2)),Ct(Wn.Check,1500)}catch{Ct(Wn.X,1500)}}},rt=()=>{ne&&(T=ne.value,Y(),Ee())},Ze=()=>{!de||!ve||(ve.style.display=de.value?"":"none",A&&clearTimeout(A),A=setTimeout(()=>{R=de.value,Y(),Ee()},150))},ct=()=>{!de||!ve||(de.value="",R="",ve.style.display="none",A&&clearTimeout(A),Y(),Ee())},Ht=()=>{if(P)return;let Ie=xe.scrollTop,{action:Be,nextLastScrollTop:qe}=zu({following:B.isFollowing(),currentScrollTop:Ie,lastScrollTop:L,nearBottom:Me(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});L=qe,Be==="resume"?(B.resume(),O=0,Ne.style.display="none"):Be==="pause"&&(B.pause(),p&&(vt.textContent=m,Ne.style.display=""))},Z=Ie=>{let Be=Uu({following:B.isFollowing(),deltaY:Ie.deltaY,nearBottom:Me(),resumeWhenNearBottom:!0});Be==="pause"?(B.pause(),p&&(vt.textContent=m,Ne.style.display="")):Be==="resume"&&(B.resume(),O=0,Ne.style.display="none")},Fe=()=>{p&&(xe.scrollTop=xe.scrollHeight,B.resume(),O=0,Ne.style.display="none")},He=Ie=>{let Be=Ie.target;if(!Be||Be.closest("button"))return;let qe=Be.closest("[data-event-id]");if(!qe)return;let Tt=qe.getAttribute("data-event-id");Tt&&ie(Tt)},nt=Ie=>{if((Ie.metaKey||Ie.ctrlKey)&&Ie.key==="f"){Ie.preventDefault(),de?.focus(),de?.select();return}Ie.key==="Escape"&&(de&&document.activeElement===de?(ct(),de.blur(),M.focus()):o&&o())};le&&le.addEventListener("click",Ot),ne&&ne.addEventListener("change",rt),de&&de.addEventListener("input",Ze),ve&&ve.addEventListener("click",ct),xe.addEventListener("scroll",Ht),xe.addEventListener("wheel",Z,{passive:!0}),xe.addEventListener("click",He),Ne.addEventListener("click",Fe),M.addEventListener("keydown",nt);function Bt(){A&&clearTimeout(A),x!==null&&(cancelAnimationFrame(x),x=null),S=!1,V.clear(),le&&le.removeEventListener("click",Ot),ne&&ne.removeEventListener("change",rt),de&&de.removeEventListener("input",Ze),ve&&ve.removeEventListener("click",ct),xe.removeEventListener("scroll",Ht),xe.removeEventListener("wheel",Z),xe.removeEventListener("click",He),Ne.removeEventListener("click",Fe),M.removeEventListener("keydown",nt)}return{element:M,update:_e,destroy:Bt}}}var Wn,Kr,lB,cB,dB,PT=be(()=>{"use strict";je();Wn=require("lucide");zn();jh();Kr={flow_:{bg:"var(--persona-event-badge-flow-bg, #dcfce7)",text:"var(--persona-event-badge-flow-fg, #15803d)"},step_:{bg:"var(--persona-event-badge-step-bg, #f5f5f5)",text:"var(--persona-event-badge-step-fg, #0a0a0a)"},reasoning_:{bg:"var(--persona-event-badge-reasoning-bg, #fef9c3)",text:"var(--persona-event-badge-reasoning-fg, #a16207)"},tool_:{bg:"var(--persona-event-badge-tool-bg, #f3e8ff)",text:"var(--persona-event-badge-tool-fg, #6b21a8)"},agent_:{bg:"var(--persona-event-badge-agent-bg, #ccfbf1)",text:"var(--persona-event-badge-agent-fg, #115e59)"},error:{bg:"var(--persona-event-badge-error-bg, #fee2e2)",text:"var(--persona-event-badge-error-fg, #b91c1c)"}};Kr.execution_error=Kr.error;Kr.execution_=Kr.flow_;Kr.turn_=Kr.agent_;Kr.text_=Kr.agent_;lB={bg:"var(--persona-event-badge-default-bg, #f3f4f6)",text:"var(--persona-event-badge-default-fg, #4b5563)"},cB=["flowName","stepName","reasoningText","text","name","tool","toolName"],dB=100});var Wc,LT=be(()=>{"use strict";Wc=class{constructor(e=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=e,this.buffer=new Array(e),this.store=n}push(e){this.buffer[this.head]=e,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(e.type),this.store?.put(e)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let e=await this.store.getAll();if(e.length===0)return 0;let n=e.length>this.maxSize?e.slice(e.length-this.maxSize):e;for(let o of n)this.buffer[this.head]=o,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(o.type);return this.totalCaptured=e.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(e){let n=this.getAll();return e>=n.length?n:n.slice(n.length-e)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.clear()}destroy(){this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}}});var Bc,IT=be(()=>{"use strict";Bc=class{constructor(e="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=e,this.storeName=n}open(){return new Promise((e,n)=>{try{let o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let r=o.result;r.objectStoreNames.contains(this.storeName)||r.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,e()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}put(e){!this.db||this.isDestroyed||(this.pendingWrites.push(e),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(e){if(!(!this.db||this.isDestroyed||e.length===0))try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of e)o.put(r)}catch{}}getAll(){return new Promise((e,n)=>{if(!this.db){e([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{e(a.result)},a.onerror=()=>{n(a.error)}}catch(o){n(o)}})}getCount(){return new Promise((e,n)=>{if(!this.db){e(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{e(s.result)},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}clear(){return new Promise((e,n)=>{if(!this.db){e();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{e()},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((e,n)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{e()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let e=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of e)o.put(r)}catch{}}}});function Hy(t){return t>0?Math.max(1,Math.ceil(t/4)):0}function am(t,e){if(!(t<=0||e===void 0||e<250))return t/(e/1e3)}function SB(t,e){return typeof e.type=="string"?e.type:t}function RT(t){let e=HT(t,"tokens")??HT(t,"totalTokens");return e?BT(e.output):void 0}function AB(t){return BT(t.durationMs)}function MB(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var wB,xB,WT,BT,HT,Dc,DT=be(()=>{"use strict";wB=new Set(["step_start","turn_start"]),xB=new Set(["step_complete","turn_complete"]),WT=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),BT=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,HT=(t,e)=>{let n=t[e];return WT(n)?n:void 0};Dc=class{constructor(e=MB){this.metric={status:"idle"};this.run=null;this.now=e}getMetric(){let e=this.run;if(e&&this.metric.status==="running"&&e.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-e.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:am(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(e){this.run={startedAt:e,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(e,n){if(!WT(n)){e==="execution_error"&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=SB(e,n),r=this.now();if(o==="execution_start"){this.startRun(r);return}if(wB.has(o)){this.run||this.startRun(r);return}if(o==="text_delta"){let s=typeof n.delta=="string"?n.delta:"";if(!s)return;this.run||this.startRun(r);let a=this.run;a.firstDeltaAt??(a.firstDeltaAt=r),a.visibleCharCount+=s.length;let l=a.exactOutputTokens+Hy(a.visibleCharCount),c=r-a.firstDeltaAt;this.metric={status:"running",tokensPerSecond:am(l,c),outputTokens:l,durationMs:c,source:a.exactOutputTokens>0?"usage":"estimate"};return}if(xB.has(o)){if(!this.run)return;let s=this.run,a=RT(n);a!==void 0&&(s.exactOutputTokens+=a,s.visibleCharCount=0);let l=s.exactOutputTokens>0,c=s.exactOutputTokens+Hy(s.visibleCharCount),p=this.resolveDuration(s,n,r);this.metric={status:"running",tokensPerSecond:am(c,p),outputTokens:c,durationMs:p,source:l?"usage":"estimate"};return}if(o==="execution_complete"){if(!this.run)return;let s=this.run,a=RT(n),l=a??s.exactOutputTokens+Hy(s.visibleCharCount),c=a!==void 0||s.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(s,n,r);this.metric={status:"complete",tokensPerSecond:am(l,p),outputTokens:l,durationMs:p,source:c},this.run=null;return}if(o==="execution_error"||o==="error"&&n.recoverable===!1){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(e,n,o){let r=e.firstDeltaAt!==void 0?o-e.firstDeltaAt:void 0;return r!==void 0&&r>=250?r:AB(n)??o-e.startedAt}}});var OT=be(()=>{"use strict";PT();LT();IT();DT()});var _T={};$n(_T,{EventStreamBuffer:()=>Wc,EventStreamStore:()=>Bc,ThroughputTracker:()=>Dc,createEventStreamView:()=>Iy});var NT=be(()=>{"use strict";OT()});var Wy,Yo,Oc=be(()=>{"use strict";Wy=class{constructor(){this.components=new Map;this.options=new Map}register(e,n,o){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,n),o?this.options.set(e,o):this.options.delete(e)}unregister(e){this.components.delete(e),this.options.delete(e)}get(e){return this.components.get(e)}has(e){return this.components.has(e)}getOptions(e){return this.options.get(e)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.options.clear()}registerAll(e){Object.entries(e).forEach(([n,o])=>{this.register(n,o)})}},Yo=new Wy});function vr(t){let e=String(t).split(/[\\/]/);return e[e.length-1]??""}function FT(t){let e=vr(t),n=e.lastIndexOf(".");return n<=0?"":e.slice(n+1).toLowerCase()}function lm(t){if(typeof t!="string")return"";let e=t.indexOf(`
|
|
238
238
|
`);if(e===-1||!t.slice(0,e).startsWith("```"))return t;let o=t.slice(e+1),r=o.lastIndexOf(`
|
|
239
|
-
`);return(r===-1?o:o.slice(0,r)).split("`\u200B``").join("```")}function Di(t){let e=
|
|
240
|
-
`).length,h=t.artifactType==="markdown"?t.file:void 0,b={artifactId:a,artifactType:t.artifactType,title:t.title,typeLabel:o,file:h,chars:m,lines:g,elapsedMs:c,content:()=>p?"":u,surface:n};try{let C=s(b);return typeof C=="string"?{label:C}:C&&typeof C=="object"&&typeof C.label=="string"?{label:C.label,detail:typeof C.detail=="string"?C.detail:void 0}:{label:r}}catch{return{label:r}}}function
|
|
239
|
+
`);return(r===-1?o:o.slice(0,r)).split("`\u200B``").join("```")}function Di(t){let e=FT(t.path);if(e)return e==="html"||e==="htm"?"html":e==="svg"?"svg":e==="md"||e==="mdx"?"markdown":"other";let n=(t.mimeType||"").toLowerCase();return n.includes("html")?"html":n.includes("svg")?"svg":n.includes("markdown")?"markdown":"other"}function Ws(t){switch(Di(t)){case"html":return"HTML";case"svg":return"SVG";case"markdown":return"Markdown";default:{let e=FT(t.path);return e?e.toUpperCase():"File"}}}function _c(t){let e=t.markdown??"";return t.file?{filename:vr(t.file.path)||"artifact",mime:t.file.mimeType||"application/octet-stream",content:lm(e)}:{filename:`${t.title||"artifact"}.md`,mime:"text/markdown",content:e}}function Nc(t){let e=new Blob([t.content],{type:t.mime}),n=URL.createObjectURL(e),o=document.createElement("a");o.href=n,o.download=t.filename,o.click(),URL.revokeObjectURL(n)}var Oi=be(()=>{"use strict"});function ja(t,e){let n=e?.documentChrome??!1,o;if(typeof t.icon=="function"){if(t.showLabel){let r="persona-label-btn persona-label-btn--sm "+cm+(n?" persona-artifact-doc-copy-btn":"");o=v("button",r)}else{let r="persona-icon-btn "+cm+(n?" persona-artifact-doc-icon-btn":"");o=v("button",r)}o.type="button",o.setAttribute("aria-label",t.label),o.title=t.label;try{let r=t.icon();r&&o.appendChild(r)}catch{}if(t.showLabel){let r=v("span");r.textContent=t.label,o.appendChild(r)}}else t.showLabel||!t.icon?o=Li({icon:t.icon,label:t.label,className:cm+(n?" persona-artifact-doc-copy-btn":"")}):o=vn({icon:t.icon,label:t.label,className:cm+(n?" persona-artifact-doc-icon-btn":"")});return e?.onClick&&o.addEventListener("click",e.onClick),o}function Fc(t){if(!t)return null;let e={artifactId:t.id,title:t.title??"",artifactType:t.artifactType};return t.artifactType==="markdown"?(e.markdown=t.markdown??"",t.file&&(e.file=t.file)):e.jsonPayload=JSON.stringify({component:t.component,props:t.props},null,2),e}var cm,dm=be(()=>{"use strict";Ii();je();cm="persona-artifact-custom-action-btn"});function VT(t){let e=document.createElementNS(By,"svg");e.setAttribute("class",Gt("persona-spinner",t)),e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("aria-hidden","true"),e.setAttribute("focusable","false");let n=document.createElementNS(By,"circle");n.setAttribute("class","persona-spinner-track"),n.setAttribute("cx","12"),n.setAttribute("cy","12"),n.setAttribute("r","9");let o=document.createElementNS(By,"circle");return o.setAttribute("class","persona-spinner-arc"),o.setAttribute("cx","12"),o.setAttribute("cy","12"),o.setAttribute("r","9"),e.appendChild(n),e.appendChild(o),e}var By,$T=be(()=>{"use strict";je();By="http://www.w3.org/2000/svg"});function zT(t,e,n){let o=n?.loadingAnimation??"shimmer",r=n?.loadingAnimationDuration??2e3;if(o==="none"){t.textContent=e;return}if(o==="pulse"){t.setAttribute("data-preserve-animation","true"),t.classList.add("persona-tool-loading-pulse"),t.style.setProperty("--persona-tool-anim-duration",`${r}ms`),t.textContent=e;return}t.setAttribute("data-preserve-animation","true"),t.classList.add(`persona-tool-loading-${o}`),t.style.setProperty("--persona-tool-anim-duration",`${r}ms`),o==="shimmer-color"&&(n?.loadingAnimationColor&&t.style.setProperty("--persona-tool-anim-color",n.loadingAnimationColor),n?.loadingAnimationSecondaryColor&&t.style.setProperty("--persona-tool-anim-secondary-color",n.loadingAnimationSecondaryColor)),Rs(t,e,0)}var UT=be(()=>{"use strict";rm()});function Ka(t){t&&Oy.delete(t)}function EB(t){let e=t.artifactType==="markdown"?t.file:void 0;return e?Ws(e):t.artifactType==="component"?"Component":"Document"}function Ga(t,e,n){let o=EB(t),r=`Generating ${o.toLowerCase()}...`,s=e?.statusLabel;if(typeof s=="string")return{label:s};if(typeof s!="function")return{label:r};let a=t.id,l=Oy.get(a);t.status!=="complete"&&l===void 0&&(l=KT(),Oy.set(a,l));let c=l===void 0?0:Math.max(0,KT()-l),p=t.artifactType==="component",u=!p&&typeof t.markdown=="string"?t.markdown:"",m=p?0:u.length,g=p||u===""?0:u.split(`
|
|
240
|
+
`).length,h=t.artifactType==="markdown"?t.file:void 0,b={artifactId:a,artifactType:t.artifactType,title:t.title,typeLabel:o,file:h,chars:m,lines:g,elapsedMs:c,content:()=>p?"":u,surface:n};try{let C=s(b);return typeof C=="string"?{label:C}:C&&typeof C=="object"&&typeof C.label=="string"?{label:C.label,detail:typeof C.detail=="string"?C.detail:void 0}:{label:r}}catch{return{label:r}}}function kB(t){t.className=Dy,t.removeAttribute("data-preserve-animation"),t.style.removeProperty("--persona-tool-anim-duration"),t.style.removeProperty("--persona-tool-anim-color"),t.style.removeProperty("--persona-tool-anim-secondary-color"),t.replaceChildren()}function _i(t,e,n){let o=t.querySelector(`:scope > .${Dy}`);o||(o=v("span",Dy),t.appendChild(o)),o.getAttribute(jT)!==e.label&&(kB(o),zT(o,e.label,n),o.setAttribute(jT,e.label));let r=t.querySelector(`:scope > .${qT}`),s=e.detail;s?(r||(r=v("span",qT),t.appendChild(r)),r.textContent!==s&&(r.textContent=s)):r&&r.remove()}var Dy,qT,jT,Oy,KT,pm=be(()=>{"use strict";je();Oi();UT();Dy="persona-artifact-status-label",qT="persona-artifact-status-detail",jT="data-artifact-status-label",Oy=new Map,KT=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()});function IB(t,e){let n=(t||"").trim().toLowerCase();if(n&&um[n])return um[n];if(e){let o=e.lastIndexOf(".");if(o>=0){let r=e.slice(o+1).toLowerCase();if(um[r])return um[r]}}return null}function mm(t,e){let n=[],o=0,r=0,s=a=>{a>r&&n.push({type:"plain",value:t.slice(r,a)})};for(;o<t.length;){let a=!1;for(let l of e){l.re.lastIndex=o;let c=l.re.exec(t);if(c&&c.index===o&&c[0].length>0){s(o);let p=l.map?l.map(c[0]):l.type;n.push({type:p,value:c[0]}),o+=c[0].length,r=o,a=!0;break}}a||(o+=1)}return s(t.length),n}function GT(t){return mm(t,RB)}function BB(t){let e=mm(t,WB);for(let n=0;n<e.length;n+=1){if(e[n].type!=="string")continue;let o=n+1;for(;o<e.length&&e[o].value.trim()==="";)o+=1;let r=e[o];r&&r.value.replace(/^\s*/,"").startsWith(":")&&(e[n].type="property")}return e}function YT(t){let e=mm(t,DB),n="";for(let o=0;o<e.length;o+=1){let r=e[o];if(r.type==="plain"&&/^[A-Za-z_-][\w-]*$/.test(r.value)){let a=o+1;for(;a<e.length&&e[a].value.trim()==="";)a+=1;let l=e[a];l&&l.value.replace(/^\s*/,"").startsWith(":")&&(n===""||n==="{"||n==="}"||n===";"||n===",")&&(r.type="property")}let s=r.value.replace(/\s+$/,"");s&&(n=s[s.length-1])}return e}function _B(t){let e=[],n=(s,a)=>{a&&e.push({type:s,value:a})},o=t.length,r=0;for(;r<o;){if(t.startsWith("<!--",r)){let a=t.indexOf("-->",r+4),l=a===-1?o:a+3;n("comment",t.slice(r,l)),r=l;continue}if(t[r]==="<"&&t[r+1]==="!"){let a=t.indexOf(">",r),l=a===-1?o:a+1;n("tag",t.slice(r,l)),r=l;continue}if(t[r]==="<"&&/[A-Za-z/]/.test(t[r+1]||"")){let a=t.indexOf(">",r),l=a===-1?o:a+1,c=t.slice(r,l);for(let u of mm(c,OB))e.push(u);r=l;let p=/^<\s*(script|style)\b/i.exec(c);if(p&&!/\/>\s*$/.test(c)){let u=p[1].toLowerCase(),g=new RegExp("</\\s*"+u+"\\s*>","i").exec(t.slice(r)),h=g?r+g.index:o,b=t.slice(r,h),C=u==="script"?GT(b):YT(b);for(let M of C)e.push(M);r=h}continue}let s=t.indexOf("<",r);if(s===r)n("plain",t[r]),r+=1;else{let a=s===-1?o:s;n("plain",t.slice(r,a)),r=a}}return e}function NB(t,e){switch(e){case"html":return _B(t);case"css":return YT(t);case"js":return GT(t);case"json":return BB(t)}}function FB(t){let e=Pw(),n=v("span","persona-code-line"),o=(r,s)=>{if(!s)return;let a=PB[r];if(a){let l=v("span",a);l.textContent=s,n.appendChild(l)}else n.appendChild(document.createTextNode(s))};for(let r of t){let s=r.value.split(`
|
|
241
241
|
`);for(let a=0;a<s.length;a+=1)a>0&&(e.appendChild(n),e.appendChild(document.createTextNode(`
|
|
242
|
-
`)),n=v("span","persona-code-line")),o(r.type,s[a])}return n.childNodes.length>0?e.appendChild(n):e.lastChild||e.appendChild(n),e}function
|
|
243
|
-
<script>(function(){var d=false;var t=`+JSON.stringify(t)+";function r(){if(d)return;d=true;try{parent.postMessage({persona:'artifact-preview-ready',token:t},'*');}catch(e){}}function s(){if(typeof requestAnimationFrame==='function'){requestAnimationFrame(function(){requestAnimationFrame(r);});}setTimeout(r,150);}if(document.readyState==='complete'){s();}else{window.addEventListener('load',s);}})();</script>"}function HB(t,e,n){let o=v("div","persona-artifact-frame-loading");if(n.renderIndicator)try{let a=n.renderIndicator({artifactId:t,config:e});if(a)return o.appendChild(a),{el:o,revealLabel:()=>{}}}catch{}let r=v("div","persona-artifact-frame-loading-indicator");r.appendChild(IT());let s=null;return n.label!==!1&&(s=v("div","persona-artifact-frame-loading-text"),s.textContent=n.label,r.appendChild(s)),o.appendChild(r),{el:o,revealLabel:()=>{s&&s.classList.add("persona-artifact-frame-loading-text--visible")}}}function WB(t,e,n,o,r,s){let a=null,l=0,c=!1,p=new Set,u=()=>{p.forEach(H=>clearTimeout(H)),p.clear()},m=(H,A)=>{let D=setTimeout(()=>{p.delete(D),!(typeof document>"u")&&H()},A);p.add(D)},g=()=>{a&&a.parentElement&&a.remove(),a=null},h=()=>{if(a||c)return;let H=HB(r,s,o);a=H.el,t.appendChild(a),l=Date.now(),o.label!==!1&&m(H.revealLabel,o.labelDelayMs)},b=()=>{a&&(a.classList.add("persona-artifact-frame-loading--out"),m(g,LB))},C=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",E):e.removeEventListener("load",T)},M=()=>{if(c||(c=!0,C(),u(),!a))return;let H=Math.max(0,o.minVisibleMs-(Date.now()-l));H>0?m(b,H):b()};function E(H){if(n===null)return;let A=H.data;!A||A.persona!=="artifact-preview-ready"||A.token!==n||H.source===e.contentWindow&&M()}function T(){let H=A=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>A()):setTimeout(A,0)};H(()=>H(()=>M()))}return m(h,o.delayMs),m(M,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",E):e.addEventListener("load",T),()=>{c=!0,u(),C(),g()}}function fm(t,e){let{config:n}=e,o=e.registry??zT()??Yo,r=e.bodyLayout,s=n.markdown?Pp(n.markdown):null,a=Ip(n.sanitize),l=t,c=!1,p=K=>{let ee=Ro()!==null;s&&!ee&&!c&&(c=!0,xa(()=>V(l)));let oe=s?s(K):$r(K);return s&&ee&&a?a(oe):oe},u=v("div","persona-artifact-preview-body"),m=null,g=null,h=null,b=()=>{h&&(h(),h=null),m=null,g=null},C=null,M=null,E=null,T=!1,H=()=>{C=null,M=null,E=null,T=!1},A=null,D=null,W=()=>{A=null,D=null},U=40,B=0,O=K=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>K()):setTimeout(K,0),R=K=>K.scrollHeight-K.clientHeight-K.scrollTop<=U,S=K=>{if(!r)return;let ee=K.scrollHeight-K.clientHeight>1,oe=K.scrollHeight-K.clientHeight-K.scrollTop;K.classList.toggle("persona-artifact-fade-top",r.fadeTop&&ee&&K.scrollTop>1),K.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&ee&&oe>1)},x=K=>{B||(B=O(()=>{B=0,K.scrollTop=K.scrollHeight,S(K)}))},P=(K,ee,oe,ne)=>{let le=!!r,de=oe.id+"|"+(le?"w":"p");if(!C||E!==de||C.parentElement!==u){b(),W(),u.replaceChildren();let se=v("pre",TB+" persona-code-pre"),_=v("code","persona-code");if(se.appendChild(_),le){let Te=v("div","persona-artifact-source-window");if(Te.appendChild(se),u.appendChild(Te),!(r?.overflow==="clip")&&typeof Te.addEventListener=="function"){let ut=()=>Te.scrollHeight-Te.clientHeight>1;Te.addEventListener("scroll",()=>{R(Te)&&(T=!1),S(Te)},{passive:!0}),Te.addEventListener("wheel",At=>{ut()&&At.deltaY<0&&(T=!0)},{passive:!0}),Te.addEventListener("touchmove",()=>{ut()&&(T=!0)},{passive:!0})}C=Te}else u.appendChild(se),C=se;M=_,E=de}let ve=le?C:null;ve&&(ve.classList.toggle("persona-artifact-source-window--fixed",ne),ve.classList.toggle("persona-artifact-source-window--clip",ne&&r?.overflow==="clip"));let Le=ve?R(ve):!0;if(M.replaceChildren(FT(K,ee?.language,ee?.path)),ve){let se=oe.status!=="complete";ne&&se&&r?.followOutput&&!T&&Le?x(ve):se||(T=!1),S(ve)}},L=K=>{b(),H(),W(),u.replaceChildren();let ee=v("div",EB);ee.innerHTML=p(K),u.appendChild(ee)},G=K=>{let ee=K.id,oe=n.features?.artifacts,ne=Ga(K,oe,"status-body");if(A&&D===ee&&A.parentElement===u){let ve=A.querySelector(".persona-artifact-status-view-text");ve&&_i(ve,ne,oe);return}b(),H(),u.replaceChildren();let le=v("div","persona-artifact-status-view"),de=v("div","persona-artifact-status-view-text");_i(de,ne,oe),le.appendChild(de),u.appendChild(le),A=le,D=ee},V=K=>{l=K;let ee=e.resolveViewMode?.(K)??r?.viewMode??"rendered",oe=K.artifactType==="markdown"?K.file:void 0,ne=K.status!=="complete";ne||Ka(K.id);let le=ne?r?.streamingHeight:r?.completeHeight,de=!!r&&typeof le=="number";if(r?.streamingView==="status"&&ne){G(K);return}if(oe){let Le=lm(K.markdown??""),se=Di(oe),_=n.features?.artifacts?.filePreview?.enabled!==!1;if(!ne&&ee==="rendered"&&_&&(se==="html"||se==="svg")){let He=K.id+"\0"+Le;if(m&&g===He&&m.parentElement===u)return;H(),W(),b(),u.replaceChildren();let ut=n.features?.artifacts?.filePreview,At=ut?.iframeSandbox??"allow-scripts";!ut?.dangerouslyAllowSameOrigin&&At.includes("allow-same-origin")&&(console.warn("[AgentWidget] Stripped allow-same-origin from filePreview.iframeSandbox: it lets artifact content run with the page origin. Set filePreview.dangerouslyAllowSameOrigin to keep it."),At=At.split(/\s+/).filter(Ae=>Ae&&Ae!=="allow-same-origin").join(" "));let Wt=PB(ut?.loading),bt=v("div","persona-artifact-frame"),xe=v("iframe","persona-artifact-iframe");xe.setAttribute("sandbox",At),xe.setAttribute("data-artifact-id",K.id);let Ne=null;Wt.enabled&&Wt.injectReadySignal?(Ne=IB(),xe.srcdoc=Le+RB(Ne)):xe.srcdoc=Le,bt.appendChild(xe),u.appendChild(bt),Wt.enabled&&(h=WB(bt,xe,Ne,Wt,K.id,n)),m=bt,g=He;return}if(b(),!ne&&se==="markdown"&&ee==="rendered"){L(Le);return}P(Le,{language:oe.language,path:oe.path},K,de);return}if(K.artifactType==="markdown"){if(ee==="source"){b(),P(K.markdown??"",void 0,K,de);return}L(K.markdown??"");return}b(),H(),W(),u.replaceChildren();let ve=K.component?o.get(K.component):void 0;if(ve){let se={message:{id:K.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let _=ve(K.props??{},se);if(_){u.appendChild(_);return}}catch{}}u.appendChild(kB(K))};return V(t),{el:u,update(K){V(K)},destroy(){b()}}}var _y,TB,EB,LB,gm=be(()=>{"use strict";je();RT();Oi();pm();VT();Lp();Si();Ig();Oc();Oy();_y=!1;TB="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",EB="persona-text-sm persona-leading-relaxed persona-markdown-bubble";LB=220});function qT(t,e){let n=e.orientation??"horizontal",o=n==="vertical"?"ArrowUp":"ArrowLeft",r=n==="vertical"?"ArrowDown":"ArrowRight";t.setAttribute("role","tablist");let s=[],a=!1,l=m=>{typeof m.scrollIntoView=="function"&&m.scrollIntoView({block:"nearest",inline:"nearest"})},c=m=>{let g=m;return s.findIndex(h=>h===g||h.contains(g))},p=m=>{let g=c(m.target);if(g<0)return;let h=g;if(m.key===r)h=Math.min(g+1,s.length-1);else if(m.key===o)h=Math.max(g-1,0);else if(m.key==="Home")h=0;else if(m.key==="End")h=s.length-1;else return;m.preventDefault(),h!==g&&e.onSelect(h)},u=m=>{let g=c(m.target);g>=0&&l(s[g])};return t.addEventListener("keydown",p),t.addEventListener("focusin",u),{beforeRender(){a=typeof document<"u"&&t.contains(document.activeElement)},render(m,g){if(s=m,m.forEach((h,b)=>{h.setAttribute("role","tab");let C=b===g;h.setAttribute("aria-selected",C?"true":"false"),h.tabIndex=C||g<0&&b===0?0:-1}),a){let h=(g>=0?m[g]:void 0)??m[0];h&&typeof h.focus=="function"&&(l(h),h.focus())}},destroy(){t.removeEventListener("keydown",p),t.removeEventListener("focusin",u)}}}var jT=be(()=>{"use strict"});function Ny(t,e){let n=t.features?.artifacts?.layout,r=(n?.toolbarPreset??"default")==="document",s=n?.toolbarTitle??"Artifacts",a=n?.closeButtonLabel??"Close",l=n?.panePadding?.trim(),c=n?.tabFadeSize?.trim(),p=Z=>({start:Z===!1?!1:typeof Z=="object"&&Z?Z.start!==!1:!0,end:Z===!1?!1:typeof Z=="object"&&Z?Z.end!==!1:!0}),{start:u,end:m}=p(n?.tabFade),g=typeof document<"u"?v("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,h=()=>{g?.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open"),S?.closeMenu()};g&&g.addEventListener("click",()=>{h(),e.onDismiss?.()});let b=v("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");b.setAttribute("data-persona-theme-zone","artifact-pane"),r&&b.classList.add("persona-artifact-pane-document");let C=v("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");C.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&C.classList.add("persona-artifact-toolbar-document");let M=v("span","persona-text-xs persona-font-medium persona-truncate");M.textContent=s;let E=vn({icon:"x",label:a});E.addEventListener("click",()=>{h(),e.onDismiss?.()});let T="rendered",H=Yu({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:r?"persona-artifact-doc-icon-btn persona-artifact-view-btn":void 0},{id:"source",icon:"code-xml",label:"Source",className:r?"persona-artifact-doc-icon-btn persona-artifact-code-btn":void 0}],selectedId:"rendered",className:"persona-artifact-toggle-group persona-shrink-0",onSelect:Z=>{T=Z==="source"?"source":"rendered",Ze()}}),A=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),D=n?.documentToolbarShowCopyLabel===!0,W=n?.documentToolbarShowCopyChevron===!0,U=n?.documentToolbarCopyMenuItems,B=!!(W&&U&&U.length>0),O=null,R,S=null;if(r&&(D||W)&&!B){if(R=D?Li({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):vn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),W){let Z=Ge(Bs.ChevronDown,14,"currentColor",2);Z&&R.appendChild(Z)}}else r&&B?(S=PM({label:"Copy",icon:"copy",iconSize:14,iconOnly:!D,primaryClassName:"persona-artifact-doc-copy-btn",chevronLabel:"More copy options",chevronClassName:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",menuItems:(U??[]).map(Z=>({id:Z.id,label:Z.label})),position:"bottom-right",portal:()=>b.closest("[data-persona-root]")??document.body,onSelect:Z=>{ve(Z)}}),O=S.element,R=S.primaryButton):r?R=vn({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(R=vn({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&R.classList.add("persona-hidden"));let x=r?vn({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):vn({icon:"refresh-cw",label:"Refresh"});n?.onDocumentToolbarRefresh||x.classList.add("persona-hidden");let P=r?vn({icon:"x",label:a,className:"persona-artifact-doc-icon-btn"}):vn({icon:"x",label:a}),L=vn({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>e.onToggleExpand?.()});n?.showExpandToggle!==!0&&L.classList.add("persona-hidden");let G=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),V=t.features?.artifacts?.toolbarActions??[],K=()=>{let Z=Ae.find(qe=>qe.id===vt)??Ae[Ae.length-1],Fe=Z?.id??null,Re=Z?.artifactType==="markdown"?Z.markdown??"":"",nt=Z?JSON.stringify({component:Z.component,props:Z.props},null,2):"",{filename:Bt,mime:Ie,content:Be}=_c({title:Z?.title,markdown:Z?.markdown??"",file:Z?.file});return{markdown:Re,jsonPayload:nt,id:Fe,file:Z?.file,suggestedFilename:Bt,mime:Ie,content:Be}},ee=()=>{let{suggestedFilename:Z,mime:Fe,content:Re}=K();Re&&Nc({filename:Z,mime:Fe,content:Re})},oe=Z=>{let{id:Fe,...Re}=K();return{actionId:Z,artifactId:Fe,...Re}},ne=async()=>{let Z=Ae.find(Fe=>Fe.id===vt)??Ae[Ae.length-1];try{return await navigator.clipboard.writeText(Vc(Z)),!0}catch{return!1}},le=null,de=()=>{le?.();let Z=R.querySelector("svg"),Fe=Number(Z?.getAttribute("width"))||16,Re=Ge(Bs.Check,Fe,"currentColor",2);if(!Z||!Re)return;Z.replaceWith(Re);let nt=R.querySelector("span");nt&&(nt.textContent="Copied");let Bt=setTimeout(()=>le?.(),2e3);le=()=>{clearTimeout(Bt),Re.replaceWith(Z),nt&&(nt.textContent="Copy"),le=null}};R.addEventListener("click",async()=>{let Z=n?.onDocumentToolbarCopyMenuSelect;if(Z&&B){try{if(await Z(oe("primary"))===!1){await ne()&&de();return}de()}catch{}return}await ne()&&de()});async function ve(Z){let Fe=n?.onDocumentToolbarCopyMenuSelect;try{if(Fe&&await Fe(oe(Z))!==!1)return;if(Z==="download"){ee();return}let{markdown:Re,jsonPayload:nt}=K();Z==="markdown"||Z==="md"?await navigator.clipboard.writeText(Re):Z==="json"||Z==="source"?await navigator.clipboard.writeText(nt):await navigator.clipboard.writeText(Re||nt),de()}catch{}}x.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}Ze()}),P.addEventListener("click",()=>{h(),e.onDismiss?.()});let Le=v("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");if(r)C.replaceChildren(),O?A.append(O,x,P):A.append(R,x,P),A.insertBefore(G,P),A.insertBefore(L,P),C.append(H.element,Le,A);else{let Z=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");Z.append(R,G,L,E),C.appendChild(M),C.appendChild(Z)}l&&(C.style.paddingLeft=l,C.style.paddingRight=l);let se=v("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border");c&&se.style.setProperty("--persona-artifact-tab-fade-size",c);let _=t.features?.artifacts?.renderTabBar,Te=v("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),He=qT(se,{onSelect:Z=>e.onSelect(Ae[Z].id)}),ut=Z=>{let Fe=Z.scrollWidth-Z.clientWidth,Re=Fe>1,nt=Math.abs(Z.scrollLeft);Z.classList.toggle("persona-artifact-tab-fade-start",u&&Re&&nt>1),Z.classList.toggle("persona-artifact-tab-fade-end",m&&Re&&nt<Fe-1)},At=0,Wt=()=>{if(At)return;let Z=()=>{At=0,ut(se)};At=typeof requestAnimationFrame=="function"?requestAnimationFrame(Z):setTimeout(Z,0)};se.addEventListener("scroll",()=>Wt(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>ut(se)).observe(se);let bt=v("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3"),xe=()=>{bt.scrollLeft=0},Ne=()=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(xe):setTimeout(xe,0)};if(l){for(let Z of[se,Te])Z.style.paddingLeft=l,Z.style.paddingRight=l;bt.style.padding=l}b.appendChild(C),b.appendChild(se),b.appendChild(Te),b.appendChild(bt);let Ae=[],vt=null,X=!1,I=!1,j=!0,J=!1,Y=null,ie="",Me=null,Ee=!1,Oe=Z=>Z.artifactType==="markdown"&&!!Z.file||r?T:"rendered",Ct=Z=>{r||(Z&&!Ee?(C.insertBefore(H.element,M),Ee=!0):!Z&&Ee&&(H.element.remove(),Ee=!1))},Ot=()=>vt&&Ae.find(Z=>Z.id===vt)||Ae[Ae.length-1],rt=()=>{let Z=Fc(Ot());if(!Z){G.replaceChildren();return}let Fe=V.filter(Re=>Re.visible===void 0||Re.visible(Z)).map(Re=>ja(Re,{documentChrome:r,onClick:()=>{let nt=Fc(Ot());if(nt)try{Promise.resolve(Re.onClick(nt)).catch(()=>{})}catch{}}}));G.replaceChildren(...Fe)},Ze=()=>{rt();let Z=r&&Ae.length<=1,Fe=!!_;if(se.classList.toggle("persona-hidden",Z||Fe),Te.classList.toggle("persona-hidden",Z||!Fe),Fe&&_){let Bt=Ae.map(Ie=>Ie.id).join("|")+" "+(vt??"");if(Bt!==ie){ie=Bt;let Ie=_({records:Ae,selectedId:vt,onSelect:e.onSelect});Te.firstElementChild!==Ie&&Te.replaceChildren(Ie)}}else{He.beforeRender(),se.replaceChildren();let Bt=[],Ie=-1;for(let[Be,qe]of Ae.entries()){let Tt=v("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");Tt.type="button";let mt=qe.artifactType==="markdown"?qe.file:void 0,xt=mt?vr(mt.path):qe.title||qe.id.slice(0,8),Mn=mt?.path||qe.title||xt;Tt.textContent=xt,Tt.title=Mn,Tt.setAttribute("aria-label",Mn),qe.id===vt&&(Tt.classList.add("persona-bg-persona-container","persona-border-persona-border"),Ie=Be),Tt.addEventListener("click",()=>e.onSelect(qe.id)),se.appendChild(Tt),Bt.push(Tt)}if(He.render(Bt,Ie),Ie>=0&&vt!==Y){Y=vt;let Be=Bt[Ie];typeof Be.scrollIntoView=="function"&&Be.scrollIntoView({block:"nearest",inline:"nearest"})}ut(se)}let Re=vt&&Ae.find(Bt=>Bt.id===vt)||Ae[Ae.length-1];if(!Re){bt.replaceChildren(),Me?.destroy(),Me=null,Ct(!1);return}let nt=Re.artifactType==="markdown"?Re.file:void 0;if(Ct(!!nt&&Di(nt)!=="other"),r){let Bt=nt?Ws(nt):Re.artifactType==="markdown"?"MD":Re.component??"Component",Ie=(Re.title||"Document").trim(),Be=nt?vr(nt.path):Ie.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Le.textContent=`${Be} \xB7 ${Bt}`}else M.textContent=nt?vr(nt.path):s;Me?(Me.el.parentElement!==bt&&bt.replaceChildren(Me.el),Me.update(Re)):(Me=fm(Re,{config:t,resolveViewMode:Oe}),bt.replaceChildren(Me.el)),bt.classList.toggle("persona-artifact-content-flush",!!bt.querySelector(".persona-code-pre"))},ct=()=>{let Z=Ae.length>0;if(b.classList.toggle("persona-hidden",!Z),g){let nt=((typeof b.closest=="function"?b.closest("[data-persona-root]"):null)?.classList.contains("persona-artifact-narrow-host")??!1)||typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches;Z&&nt&&X?(g.classList.remove("persona-hidden"),b.classList.add("persona-artifact-drawer-open")):(g.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open"))}},Rt=()=>{J=!1,Ze(),ct()};return{element:b,backdrop:g,update(Z){let Fe=Z.selectedId??Z.artifacts[Z.artifacts.length-1]?.id??null,Re=Fe!==vt;Ae=Z.artifacts,vt=Fe,Ae.length>0&&(X=!0),J=!0,j&&Rt(),Re&&xe()},setMobileOpen(Z){X=Z,!Z&&g?(g.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open")):ct()},setExpanded(Z){Z!==I&&(I=Z,Ne());let Fe=Ge(Z?Bs.Minimize:Bs.Maximize,16,"currentColor",2);Fe&&L.replaceChildren(Fe);let Re=Z?"Collapse artifacts panel":"Expand artifacts panel";L.setAttribute("aria-label",Re),L.title=Re},setExpandToggleVisible(Z){L.classList.toggle("persona-hidden",!Z)},setCopyButtonVisible(Z){r||R.classList.toggle("persona-hidden",!Z)},setRefreshButtonVisible(Z){x.classList.toggle("persona-hidden",!Z)},setCustomActions(Z){V=Z,rt()},setTabFade(Z){let Fe=p(Z);Fe.start===u&&Fe.end===m||(u=Fe.start,m=Fe.end,ut(se))},setRenderTabBar(Z){Z!==_&&(_=Z,ie="",Ze())},setVisible(Z){Z!==j&&(j=Z,Z&&J&&Rt())},destroy(){Me?.destroy(),Me=null}}}var Bs,KT=be(()=>{"use strict";je();Oi();dm();gm();Bs=require("lucide");zn();Ii();jT()});function GT(t,e){let n=t.file&&typeof t.file=="object"&&!Array.isArray(t.file)?t.file:void 0,o=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",r=n?vr(n.path):o,s=typeof t.artifactId=="string"?t.artifactId:"",a=t.status==="streaming"?"streaming":"complete",l=typeof t.artifactType=="string"?t.artifactType:"markdown",c=t.presentation&&typeof t.presentation=="object"&&!Array.isArray(t.presentation)?t.presentation:void 0,p=n?Ws(n):l==="component"?"Component":"Document",u=document.createElement("div");u.className="persona-artifact-card persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-px-4 persona-py-3",u.tabIndex=0,u.setAttribute("role","button"),u.setAttribute("aria-label",`Open ${r} in artifact panel`),s&&u.setAttribute("data-open-artifact",s);let m=document.createElement("div");m.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",m.style.border="1px solid var(--persona-border, #e5e7eb)",m.style.color="var(--persona-muted, #9ca3af)",m.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let g=document.createElement("div");g.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let h=document.createElement("div");h.className="persona-truncate persona-text-sm persona-font-medium",h.style.color="var(--persona-text, #1f2937)",h.textContent=r;let b=document.createElement("div");if(b.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",b.style.color="var(--persona-muted, #9ca3af)",a==="streaming"){let C=e?.config?.features?.artifacts,M={id:s,artifactType:l==="component"?"component":"markdown",title:o,status:"streaming",...typeof t.markdown=="string"?{markdown:t.markdown}:{},...n?{file:n}:{},...c?{presentation:c}:{}},E=Ga(M,C,"card");_i(b,E,C)}else s&&Ka(s),b.textContent=p;if(g.append(h,b),u.append(m,g),a==="complete"){let C=e?.config?.features?.artifacts?.cardActions;if(C&&C.length>0){let E={artifactId:s||null,title:r,artifactType:l,markdown:typeof t.markdown=="string"?t.markdown:void 0,file:n};for(let T of C)try{if(T.visible===void 0||T.visible(E)){let H=ja(T);H.setAttribute("data-artifact-custom-action",T.id),H.className=`${H.className} persona-flex-shrink-0`,u.append(H)}}catch{}}let M=Li({label:"Download",className:"persona-flex-shrink-0"});M.title=`Download ${r}`,M.setAttribute("data-download-artifact",s),u.append(M)}return u}var $c,Fy=be(()=>{"use strict";Oi();pm();Ii();dm();$c=(t,e)=>{let n=e?.config?.features?.artifacts?.renderCard;if(n){let o=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",r=typeof t.artifactId=="string"?t.artifactId:"",s=t.status==="streaming"?"streaming":"complete",a=typeof t.artifactType=="string"?t.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:a,status:s},config:e.config,defaultRenderer:()=>GT(t,e)});if(l)return l}return GT(t,e)}});function Vy(t,e,n){if(e.length===0)return;let o=new Map(e.map(r=>[r.id,r]));t.querySelectorAll("[data-artifact-inline]").forEach(r=>{let s=Ds.get(r);if(!s)return;let a=o.get(r.getAttribute("data-artifact-inline")??"");a&&s(a,n)})}function $y(t){return Ds.has(t)}function BB(t){let e=typeof t.artifactId=="string"?t.artifactId:"",n=typeof t.title=="string"&&t.title?t.title:void 0,o=t.status==="streaming"?"streaming":"complete",r=t.presentation&&typeof t.presentation=="object"&&!Array.isArray(t.presentation)?t.presentation:void 0;if(t.artifactType==="component"){let a=t.componentProps,l=a&&typeof a=="object"&&!Array.isArray(a)?a:{};return{id:e,artifactType:"component",title:n,status:o,component:typeof t.component=="string"?t.component:"",props:l,...r?{presentation:r}:{}}}let s=t.file&&typeof t.file=="object"&&!Array.isArray(t.file)?t.file:void 0;return{id:e,artifactType:"markdown",title:n,status:o,markdown:typeof t.markdown=="string"?t.markdown:"",...s?{file:s}:{},...r?{presentation:r}:{}}}function YT(t){let e=t.artifactType==="markdown"?t.file:void 0,n=e?vr(e.path):t.title&&t.title.trim()?t.title:"Untitled artifact",o=e?Ws(e):t.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function DB(t){let e={artifactId:t.id,title:t.title??"",status:t.status,artifactType:t.artifactType};return t.artifactType==="markdown"&&(typeof t.markdown=="string"&&(e.markdown=t.markdown),t.file&&(e.file=t.file)),e}function zB(t,e,n){let{swap:o,onSettled:r}=n,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(!e||!t.isConnected||s||typeof t.animate!="function"){o(),r();return}t.style.height=`${e}px`,t.style.overflow="hidden";let a=[];for(let l of Array.from(t.children))l instanceof HTMLElement&&a.push(l.animate([{opacity:1},{opacity:0}],{duration:QT,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let E of a)E.cancel();o();let l=()=>{t.style.removeProperty("height"),t.style.removeProperty("overflow")};if(!t.isConnected){l(),r();return}t.style.height="auto";let c=t.getBoundingClientRect().height;if(t.style.height=`${e}px`,!c||Math.abs(c-e)<1){l(),r();return}let p=Math.abs(e-c),u=Math.round(Math.min(FB,Math.max(NB,OB+p*_B))),m=Math.round(u*$B),g=t.firstElementChild instanceof HTMLElement?t.firstElementChild:null,h=g?g.animate([{opacity:0},{opacity:1}],{duration:XT,delay:m,easing:"ease-out",fill:"backwards"}):null,b=t.animate([{height:`${e}px`},{height:`${c}px`}],{duration:u,easing:VB});t.style.height=`${c}px`;let C=!1,M=()=>{C||(C=!0,l(),r())};Promise.allSettled([b.finished,h?.finished].filter(Boolean)).then(M),window.setTimeout(M,Math.max(u,m+XT)+120)},QT)}function UB(t){let e=t?.inlineChrome;if(e===!1)return{chromeEnabled:!1,showCopy:!1,showExpand:!1,showViewToggle:!1};let n=typeof e=="object"?e:void 0;return{chromeEnabled:!0,showCopy:n?.showCopy!==!1,showExpand:n?.showExpand!==!1,showViewToggle:n?.showViewToggle!==!1}}function qB(t){let e=t?.inlineBody,n=e?.streamingView==="status"?"status":"source",o=e?.viewMode==="source"?"source":"rendered",r=320,s=320,a=e?.height;typeof a=="number"||a==="auto"?(r=a,s=a):a&&typeof a=="object"&&(r=a.streaming??320,s=a.complete??320);let l=e?.overflow==="clip"?"clip":"scroll",c=l==="clip"?!1:e?.followOutput!==!1,p,u,m=e?.fadeMask;m===!0?(p=!0,u=!0):m===!1?(p=!1,u=!1):m&&typeof m=="object"?(p=m.top===!0,u=m.bottom===!0):l==="clip"?(p=!1,u=!0):(p=!0,u=!0);let g=e?.transition==="none"?"none":"auto",h=e?.completeDisplay==="card"?"card":"inline";return{streamingView:n,viewMode:o,streamingHeight:r,completeHeight:s,followOutput:c,overflow:l,fadeTop:p,fadeBottom:u,transition:g,completeDisplay:h}}function JT(t,e){let n=BB(t),o=e.config?.features?.artifacts,{chromeEnabled:r,showCopy:s,showExpand:a,showViewToggle:l}=UB(o),c=o?.inlineActions??[],p=qB(o),u=p.completeDisplay==="card",m=null,g=n,h=v("div","persona-artifact-inline persona-w-full persona-max-w-full");h.setAttribute("data-persona-theme-zone","artifact-inline"),n.id&&h.setAttribute("data-artifact-inline",n.id);let b=ne=>$c(DB(ne),e),C=null,M=ne=>{C?.destroy(),C=null,h.classList.add("persona-artifact-inline--card"),h.style.removeProperty(zc),h.replaceChildren(b(ne)),Ds.set(h,le=>{h.replaceChildren(b(le))})};if(u&&n.status==="complete")return M(n),h;let E=fm(n,{config:e.config,bodyLayout:p,resolveViewMode:()=>m??p.viewMode});C=E;let T=v("div","persona-artifact-inline-body");T.appendChild(E.el);let H=ne=>{let le=ne.status!=="complete",de=le?p.streamingHeight:p.completeHeight,ve=typeof de=="number";ve?h.style.setProperty(zc,`${de}px`):h.style.removeProperty(zc);let Le=!!E.el.querySelector(".persona-code-pre"),se=!!E.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");T.classList.toggle("persona-artifact-content-flush",Le),T.classList.toggle("persona-artifact-inline-body--sized",ve&&se),T.classList.toggle("persona-artifact-inline-body--cap",!le&&!se&&typeof p.completeHeight=="number")},A=n.status,D=(ne,le)=>{A!=="complete"&&ne.status==="complete"?(typeof p.completeHeight=="number"?h.style.setProperty(zc,`${p.completeHeight}px`):h.style.removeProperty(zc),UT(T,le?.suppressTransition?"none":p.transition,ne.id,()=>{E.update(ne),H(ne)})):E.update(ne),H(ne),A=ne.status};H(n);let W=p.overflow==="clip"&&a&&!!n.id;if(W&&(T.setAttribute("data-expand-artifact-inline",n.id),T.setAttribute("role","button"),T.setAttribute("tabindex","0"),T.classList.add("persona-cursor-pointer"),T.setAttribute("aria-label",`Open ${YT(n).title} in panel`)),!r)return h.appendChild(T),Ds.set(h,D),h;let U=v("div","persona-artifact-inline-chrome");U.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let B=v("div","persona-artifact-inline-chrome-lead"),O=v("span","persona-flex persona-items-center persona-flex-shrink-0"),R=Ge(ZT.FileText,16,"currentColor",2);R&&O.appendChild(R);let S=v("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),x=v("span","persona-artifact-inline-type");B.append(O,S,x);let P=v("div","persona-artifact-inline-chrome-actions"),L=v("span","persona-flex persona-items-center persona-gap-1"),G=()=>m??p.viewMode,V=l?Yu({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"},{id:"source",icon:"code-xml",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}],selectedId:G(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:ne=>{let le=ne==="source"?"source":"rendered";le!==G()&&(m=le,E.update(g),H(g))}}):null,K=s?vn({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;K&&n.id&&K.setAttribute("data-copy-artifact",n.id);let ee=a?vn({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;ee&&n.id&&ee.setAttribute("data-expand-artifact-inline",n.id),P.appendChild(L),V&&P.appendChild(V.element),K&&P.appendChild(K),ee&&P.appendChild(ee),U.append(B,P),h.append(U,T);let oe=ne=>{let{title:le,typeLabel:de}=YT(ne);S.textContent=le,S.title=le,W&&T.setAttribute("aria-label",`Open ${le} in panel`);let ve=ne.status!=="complete";if(ve){x.classList.contains("persona-artifact-inline-status")||(x.className="persona-artifact-inline-status",x.removeAttribute("data-preserve-animation"),x.replaceChildren());let Le=Ga(ne,o,"inline-chrome");_i(x,Le,o)}else Ka(ne.id),x.className="persona-artifact-inline-type",x.removeAttribute("data-preserve-animation"),x.replaceChildren(),x.textContent=de;if(K&&K.classList.toggle("persona-hidden",ve),V){let Le=ne.artifactType==="markdown"?ne.file:void 0,se=!1;if(!ve&&Le&&p.viewMode!=="source"){let _=Di(Le);_==="markdown"?se=!0:(_==="html"||_==="svg")&&(se=o?.filePreview?.enabled!==!1)}V.element.classList.toggle("persona-hidden",!se),V.setSelected(G())}if(L.replaceChildren(),!ve&&c.length>0){let Le=Fc(ne);if(Le)for(let se of c)try{if(se.visible===void 0||se.visible(Le)){let _=ja(se,{documentChrome:!0});_.setAttribute("data-artifact-custom-action",se.id),_.classList.add("persona-flex-shrink-0"),L.appendChild(_)}}catch{}}};return oe(n),Ds.set(h,(ne,le)=>{if(u&&A!=="complete"&&ne.status==="complete"){let de=h.isConnected?h.getBoundingClientRect().height:0;A="complete";let ve=ne,Le=!1,se=_=>{ve=_,Le=!0};Ds.set(h,se),zB(h,de,{swap:()=>{M(ve),Le=!1,Ds.set(h,se)},onSettled:()=>{Le?M(ve):Ds.set(h,_=>{h.replaceChildren(b(_))})}});return}(ne.status!=="complete"||ne.id!==g.id)&&(m=null),g=ne,D(ne,le),oe(ne)}),h}var ZT,Ds,QT,OB,_B,NB,FB,VB,XT,$B,zc,zy,eE=be(()=>{"use strict";je();Oi();pm();dm();Ii();ZT=require("lucide");zn();gm();Fy();Ds=new WeakMap;QT=180,OB=240,_B=.8,NB=300,FB=500,VB="cubic-bezier(0.2, 0, 0, 1)",XT=240,$B=.35;zc="--persona-artifact-inline-body-height";zy=(t,e)=>{let n=e?.config?.features?.artifacts?.renderInline;if(n){let o=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",r=typeof t.artifactId=="string"?t.artifactId:"",s=t.status==="streaming"?"streaming":"complete",a=typeof t.artifactType=="string"?t.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:a,status:s},config:e.config,defaultRenderer:()=>JT(t,e)});if(l)return l}return JT(t,e)}});var tE=be(()=>{"use strict";KT();eE();Fy();gm();Oi();Oy();Si();yp()});var nE={};$n(nE,{PersonaArtifactCard:()=>$c,PersonaArtifactInline:()=>zy,__provideMarkdownParsers:()=>Pg,__setIconsExtraLoader:()=>Sg,artifactCopyText:()=>Vc,createArtifactPane:()=>Ny,downloadInfoFor:()=>_c,hasLiveInlineArtifactBlock:()=>$y,initArtifactsUi:()=>Dy,triggerArtifactDownload:()=>Nc,updateInlineArtifactBlocks:()=>Vy});var oE=be(()=>{"use strict";tE()});var Cm,fE,gE=be(()=>{"use strict";je();Cm={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},fE=(t,e,n,o)=>{let r=t.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{if(s.dataset.enhanced==="true")return;let a=s.dataset.tvForm??"init";s.dataset.enhanced="true";let l=Cm[a]??Cm.init;s.classList.add("persona-form-card","persona-space-y-4");let c=v("div","persona-space-y-1"),p=v("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(p.textContent=l.title,c.appendChild(p),l.description){let b=v("p","persona-text-sm persona-text-persona-muted");b.textContent=l.description,c.appendChild(b)}let u=document.createElement("form");u.className="persona-form-grid persona-space-y-3",l.fields.forEach(b=>{let C=v("label","persona-form-field persona-flex persona-flex-col persona-gap-1");C.htmlFor=`${e.id}-${a}-${b.name}`;let M=v("span","persona-text-xs persona-font-medium persona-text-persona-muted");M.textContent=b.label,C.appendChild(M);let E=b.type??"text",T;E==="textarea"?(T=document.createElement("textarea"),T.rows=3):(T=document.createElement("input"),T.type=E),T.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",T.id=`${e.id}-${a}-${b.name}`,T.name=b.name,T.placeholder=b.placeholder??"",b.required&&(T.required=!0),C.appendChild(T),u.appendChild(C)});let m=v("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),g=v("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),h=v("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");h.type="submit",h.textContent=l.submitLabel??"Submit",m.appendChild(g),m.appendChild(h),u.appendChild(m),s.replaceChildren(c,u),u.addEventListener("submit",async b=>{b.preventDefault();let C=n.formEndpoint??"/form",M=new FormData(u),E={};M.forEach((T,H)=>{E[H]=T}),E.type=a,h.disabled=!0,g.textContent="Submitting\u2026";try{let T=await fetch(C,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(E)});if(!T.ok)throw new Error(`Form submission failed (${T.status})`);let H=await T.json();g.textContent=H.message??"Thanks! We'll be in touch soon.",H.success&&H.nextPrompt&&await o.sendMessage(String(H.nextPrompt))}catch(T){g.textContent=T instanceof Error?T.message:"Something went wrong. Please try again."}finally{h.disabled=!1}})})}});var hE={};$n(hE,{enhanceWithForms:()=>fE,formDefinitions:()=>Cm});var yE=be(()=>{"use strict";gE()});function kE(){let t=document.createElement("div");t.className="persona-history-sr-only",t.setAttribute("role","status"),t.setAttribute("aria-live","polite"),t.setAttribute("aria-atomic","true"),t.setAttribute("data-persona-history-live-region","");let e;return{element:t,announce(n){e!==void 0&&clearTimeout(e),t.textContent="",e=setTimeout(()=>{e=void 0,t.textContent=n},0)},destroy(){e!==void 0&&clearTimeout(e),t.remove()}}}var PE=be(()=>{"use strict"});var LE,IE=be(()=>{"use strict";LE=`
|
|
242
|
+
`)),n=v("span","persona-code-line")),o(r.type,s[a])}return n.childNodes.length>0?e.appendChild(n):e.lastChild||e.appendChild(n),e}function QT(t,e,n){let o=t.length<=LB?IB(e,n):null,r=o?NB(t,o):[{type:"plain",value:t}];return FB(r)}var PB,LB,um,HB,RB,WB,DB,OB,XT=be(()=>{"use strict";je();PB={keyword:"persona-code-token-keyword",string:"persona-code-token-string",comment:"persona-code-token-comment",number:"persona-code-token-number",tag:"persona-code-token-tag",attr:"persona-code-token-attr",property:"persona-code-token-property"},LB=15e4,um={html:"html",htm:"html",xhtml:"html",xml:"html",svg:"html",css:"css",js:"js",jsx:"js",mjs:"js",cjs:"js",ts:"js",tsx:"js",mts:"js",cts:"js",javascript:"js",typescript:"js",ecmascript:"js",json:"json",jsonc:"json",json5:"json"};HB=new Set(["abstract","any","as","async","await","boolean","break","case","catch","class","const","continue","debugger","declare","default","delete","do","else","enum","export","extends","false","finally","for","from","function","get","if","implements","import","in","instanceof","interface","keyof","let","namespace","never","new","null","number","object","of","private","protected","public","readonly","return","satisfies","set","static","string","super","switch","symbol","this","throw","true","try","type","typeof","undefined","unknown","var","void","while","yield"]),RB=[{type:"comment",re:/\/\/[^\n]*/y},{type:"comment",re:/\/\*[\s\S]*?\*\//y},{type:"string",re:/`(?:\\[\s\S]|[^\\`])*`/y},{type:"string",re:/"(?:\\.|[^"\\\n])*"/y},{type:"string",re:/'(?:\\.|[^'\\\n])*'/y},{type:"number",re:/0[xX][0-9a-fA-F]+|(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y},{type:"plain",re:/[A-Za-z_$][\w$]*/y,map:t=>HB.has(t)?"keyword":"plain"}];WB=[{type:"string",re:/"(?:\\.|[^"\\])*"/y},{type:"number",re:/-?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y},{type:"plain",re:/[A-Za-z_]\w*/y,map:t=>t==="true"||t==="false"||t==="null"?"keyword":"plain"}];DB=[{type:"comment",re:/\/\*[\s\S]*?\*\//y},{type:"string",re:/"(?:\\.|[^"\\\n])*"/y},{type:"string",re:/'(?:\\.|[^'\\\n])*'/y},{type:"keyword",re:/@[A-Za-z-]+/y},{type:"number",re:/#[0-9a-fA-F]{3,8}\b/y},{type:"number",re:/-?(?:\d+\.?\d*|\.\d+)(?:[a-z%]+)?/y},{type:"plain",re:/[A-Za-z_-][\w-]*/y}];OB=[{type:"tag",re:/<\/?\s*[A-Za-z][\w:-]*/y},{type:"string",re:/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'/y},{type:"attr",re:/[A-Za-z_:@][\w:.-]*(?=\s*=)/y},{type:"attr",re:/[A-Za-z_:@][\w:.-]*/y},{type:"tag",re:/\/?>/y}]});var JT,_y,ZT,Ny=be(()=>{"use strict";JT=null,_y=t=>{JT=t.componentRegistry},ZT=()=>JT});function Vc(t){if(!t)return"";if(t.artifactType==="markdown"){let e=t.markdown??"";return t.file?lm(e):e}return JSON.stringify({component:t.component,props:t.props},null,2)}function VB(t){return"persona-artifact-vt-"+((t||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function eE(t,e,n,o){let r=typeof document<"u"?document.startViewTransition:void 0,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(e!=="auto"||!t||typeof r!="function"||Fy||s){o();return}Fy=!0;let a=VB(n);t.style.setProperty("view-transition-name",a);let l=()=>{Fy=!1,t.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(l,l)}catch{l(),o()}}function UB(t){let e=v("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=v("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=t.component?`Component: ${t.component}`:"Component";let o=v("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify(t.props??{},null,2),e.appendChild(n),e.appendChild(o),e}function qB(t){if(t===!1)return{enabled:!1,delayMs:0,minVisibleMs:0,timeoutMs:0,injectReadySignal:!1,label:"Starting preview...",labelDelayMs:2e3};let e=t&&typeof t=="object"?t:void 0;return{enabled:!0,delayMs:e?.delayMs??200,minVisibleMs:e?.minVisibleMs??300,timeoutMs:e?.timeoutMs??8e3,injectReadySignal:e?.injectReadySignal!==!1,label:e?.label===!1?!1:e?.label??"Starting preview...",labelDelayMs:e?.labelDelayMs??2e3,renderIndicator:e?.renderIndicator}}function KB(){try{if(typeof crypto<"u"&&crypto.getRandomValues){let t=new Uint32Array(2);return crypto.getRandomValues(t),t[0].toString(36)+t[1].toString(36)}}catch{}return Math.random().toString(36).slice(2)+Math.random().toString(36).slice(2)}function GB(t){return`
|
|
243
|
+
<script>(function(){var d=false;var t=`+JSON.stringify(t)+";function r(){if(d)return;d=true;try{parent.postMessage({persona:'artifact-preview-ready',token:t},'*');}catch(e){}}function s(){if(typeof requestAnimationFrame==='function'){requestAnimationFrame(function(){requestAnimationFrame(r);});}setTimeout(r,150);}if(document.readyState==='complete'){s();}else{window.addEventListener('load',s);}})();</script>"}function YB(t,e,n){let o=v("div","persona-artifact-frame-loading");if(n.renderIndicator)try{let a=n.renderIndicator({artifactId:t,config:e});if(a)return o.appendChild(a),{el:o,revealLabel:()=>{}}}catch{}let r=v("div","persona-artifact-frame-loading-indicator");r.appendChild(VT());let s=null;return n.label!==!1&&(s=v("div","persona-artifact-frame-loading-text"),s.textContent=n.label,r.appendChild(s)),o.appendChild(r),{el:o,revealLabel:()=>{s&&s.classList.add("persona-artifact-frame-loading-text--visible")}}}function QB(t,e,n,o,r,s){let a=null,l=0,c=!1,p=new Set,u=()=>{p.forEach(R=>clearTimeout(R)),p.clear()},m=(R,A)=>{let D=setTimeout(()=>{p.delete(D),!(typeof document>"u")&&R()},A);p.add(D)},g=()=>{a&&a.parentElement&&a.remove(),a=null},h=()=>{if(a||c)return;let R=YB(r,s,o);a=R.el,t.appendChild(a),l=Date.now(),o.label!==!1&&m(R.revealLabel,o.labelDelayMs)},b=()=>{a&&(a.classList.add("persona-artifact-frame-loading--out"),m(g,jB))},C=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",E):e.removeEventListener("load",T)},M=()=>{if(c||(c=!0,C(),u(),!a))return;let R=Math.max(0,o.minVisibleMs-(Date.now()-l));R>0?m(b,R):b()};function E(R){if(n===null)return;let A=R.data;!A||A.persona!=="artifact-preview-ready"||A.token!==n||R.source===e.contentWindow&&M()}function T(){let R=A=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>A()):setTimeout(A,0)};R(()=>R(()=>M()))}return m(h,o.delayMs),m(M,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",E):e.addEventListener("load",T),()=>{c=!0,u(),C(),g()}}function fm(t,e){let{config:n}=e,o=e.registry??ZT()??Yo,r=e.bodyLayout,s=n.markdown?Pp(n.markdown):null,a=Ip(n.sanitize),l=t,c=!1,p=K=>{let ee=Ho()!==null;s&&!ee&&!c&&(c=!0,xa(()=>V(l)));let oe=s?s(K):$r(K);return s&&ee&&a?a(oe):oe},u=v("div","persona-artifact-preview-body"),m=null,g=null,h=null,b=()=>{h&&(h(),h=null),m=null,g=null},C=null,M=null,E=null,T=!1,R=()=>{C=null,M=null,E=null,T=!1},A=null,D=null,W=()=>{A=null,D=null},U=40,B=0,O=K=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>K()):setTimeout(K,0),H=K=>K.scrollHeight-K.clientHeight-K.scrollTop<=U,S=K=>{if(!r)return;let ee=K.scrollHeight-K.clientHeight>1,oe=K.scrollHeight-K.clientHeight-K.scrollTop;K.classList.toggle("persona-artifact-fade-top",r.fadeTop&&ee&&K.scrollTop>1),K.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&ee&&oe>1)},x=K=>{B||(B=O(()=>{B=0,K.scrollTop=K.scrollHeight,S(K)}))},P=(K,ee,oe,ne)=>{let le=!!r,de=oe.id+"|"+(le?"w":"p");if(!C||E!==de||C.parentElement!==u){b(),W(),u.replaceChildren();let se=v("pre",$B+" persona-code-pre"),_=v("code","persona-code");if(se.appendChild(_),le){let Te=v("div","persona-artifact-source-window");if(Te.appendChild(se),u.appendChild(Te),!(r?.overflow==="clip")&&typeof Te.addEventListener=="function"){let ut=()=>Te.scrollHeight-Te.clientHeight>1;Te.addEventListener("scroll",()=>{H(Te)&&(T=!1),S(Te)},{passive:!0}),Te.addEventListener("wheel",At=>{ut()&&At.deltaY<0&&(T=!0)},{passive:!0}),Te.addEventListener("touchmove",()=>{ut()&&(T=!0)},{passive:!0})}C=Te}else u.appendChild(se),C=se;M=_,E=de}let ve=le?C:null;ve&&(ve.classList.toggle("persona-artifact-source-window--fixed",ne),ve.classList.toggle("persona-artifact-source-window--clip",ne&&r?.overflow==="clip"));let Le=ve?H(ve):!0;if(M.replaceChildren(QT(K,ee?.language,ee?.path)),ve){let se=oe.status!=="complete";ne&&se&&r?.followOutput&&!T&&Le?x(ve):se||(T=!1),S(ve)}},L=K=>{b(),R(),W(),u.replaceChildren();let ee=v("div",zB);ee.innerHTML=p(K),u.appendChild(ee)},G=K=>{let ee=K.id,oe=n.features?.artifacts,ne=Ga(K,oe,"status-body");if(A&&D===ee&&A.parentElement===u){let ve=A.querySelector(".persona-artifact-status-view-text");ve&&_i(ve,ne,oe);return}b(),R(),u.replaceChildren();let le=v("div","persona-artifact-status-view"),de=v("div","persona-artifact-status-view-text");_i(de,ne,oe),le.appendChild(de),u.appendChild(le),A=le,D=ee},V=K=>{l=K;let ee=e.resolveViewMode?.(K)??r?.viewMode??"rendered",oe=K.artifactType==="markdown"?K.file:void 0,ne=K.status!=="complete";ne||Ka(K.id);let le=ne?r?.streamingHeight:r?.completeHeight,de=!!r&&typeof le=="number";if(r?.streamingView==="status"&&ne){G(K);return}if(oe){let Le=lm(K.markdown??""),se=Di(oe),_=n.features?.artifacts?.filePreview?.enabled!==!1;if(!ne&&ee==="rendered"&&_&&(se==="html"||se==="svg")){let Re=K.id+"\0"+Le;if(m&&g===Re&&m.parentElement===u)return;R(),W(),b(),u.replaceChildren();let ut=n.features?.artifacts?.filePreview,At=ut?.iframeSandbox??"allow-scripts";!ut?.dangerouslyAllowSameOrigin&&At.includes("allow-same-origin")&&(console.warn("[AgentWidget] Stripped allow-same-origin from filePreview.iframeSandbox: it lets artifact content run with the page origin. Set filePreview.dangerouslyAllowSameOrigin to keep it."),At=At.split(/\s+/).filter(Ae=>Ae&&Ae!=="allow-same-origin").join(" "));let Wt=qB(ut?.loading),bt=v("div","persona-artifact-frame"),xe=v("iframe","persona-artifact-iframe");xe.setAttribute("sandbox",At),xe.setAttribute("data-artifact-id",K.id);let Ne=null;Wt.enabled&&Wt.injectReadySignal?(Ne=KB(),xe.srcdoc=Le+GB(Ne)):xe.srcdoc=Le,bt.appendChild(xe),u.appendChild(bt),Wt.enabled&&(h=QB(bt,xe,Ne,Wt,K.id,n)),m=bt,g=Re;return}if(b(),!ne&&se==="markdown"&&ee==="rendered"){L(Le);return}P(Le,{language:oe.language,path:oe.path},K,de);return}if(K.artifactType==="markdown"){if(ee==="source"){b(),P(K.markdown??"",void 0,K,de);return}L(K.markdown??"");return}b(),R(),W(),u.replaceChildren();let ve=K.component?o.get(K.component):void 0;if(ve){let se={message:{id:K.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let _=ve(K.props??{},se);if(_){u.appendChild(_);return}}catch{}}u.appendChild(UB(K))};return V(t),{el:u,update(K){V(K)},destroy(){b()}}}var Fy,$B,zB,jB,gm=be(()=>{"use strict";je();$T();Oi();pm();XT();Lp();Si();Rg();Oc();Ny();Fy=!1;$B="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",zB="persona-text-sm persona-leading-relaxed persona-markdown-bubble";jB=220});function tE(t,e){let n=e.orientation??"horizontal",o=n==="vertical"?"ArrowUp":"ArrowLeft",r=n==="vertical"?"ArrowDown":"ArrowRight";t.setAttribute("role","tablist");let s=[],a=!1,l=m=>{typeof m.scrollIntoView=="function"&&m.scrollIntoView({block:"nearest",inline:"nearest"})},c=m=>{let g=m;return s.findIndex(h=>h===g||h.contains(g))},p=m=>{let g=c(m.target);if(g<0)return;let h=g;if(m.key===r)h=Math.min(g+1,s.length-1);else if(m.key===o)h=Math.max(g-1,0);else if(m.key==="Home")h=0;else if(m.key==="End")h=s.length-1;else return;m.preventDefault(),h!==g&&e.onSelect(h)},u=m=>{let g=c(m.target);g>=0&&l(s[g])};return t.addEventListener("keydown",p),t.addEventListener("focusin",u),{beforeRender(){a=typeof document<"u"&&t.contains(document.activeElement)},render(m,g){if(s=m,m.forEach((h,b)=>{h.setAttribute("role","tab");let C=b===g;h.setAttribute("aria-selected",C?"true":"false"),h.tabIndex=C||g<0&&b===0?0:-1}),a){let h=(g>=0?m[g]:void 0)??m[0];h&&typeof h.focus=="function"&&(l(h),h.focus())}},destroy(){t.removeEventListener("keydown",p),t.removeEventListener("focusin",u)}}}var nE=be(()=>{"use strict"});function Vy(t,e){let n=t.features?.artifacts?.layout,r=(n?.toolbarPreset??"default")==="document",s=n?.toolbarTitle??"Artifacts",a=n?.closeButtonLabel??"Close",l=n?.panePadding?.trim(),c=n?.tabFadeSize?.trim(),p=Z=>({start:Z===!1?!1:typeof Z=="object"&&Z?Z.start!==!1:!0,end:Z===!1?!1:typeof Z=="object"&&Z?Z.end!==!1:!0}),{start:u,end:m}=p(n?.tabFade),g=typeof document<"u"?v("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,h=()=>{g?.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open"),S?.closeMenu()};g&&g.addEventListener("click",()=>{h(),e.onDismiss?.()});let b=v("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");b.setAttribute("data-persona-theme-zone","artifact-pane"),r&&b.classList.add("persona-artifact-pane-document");let C=v("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");C.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&C.classList.add("persona-artifact-toolbar-document");let M=v("span","persona-text-xs persona-font-medium persona-truncate");M.textContent=s;let E=vn({icon:"x",label:a});E.addEventListener("click",()=>{h(),e.onDismiss?.()});let T="rendered",R=Yu({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:r?"persona-artifact-doc-icon-btn persona-artifact-view-btn":void 0},{id:"source",icon:"code-xml",label:"Source",className:r?"persona-artifact-doc-icon-btn persona-artifact-code-btn":void 0}],selectedId:"rendered",className:"persona-artifact-toggle-group persona-shrink-0",onSelect:Z=>{T=Z==="source"?"source":"rendered",Ze()}}),A=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),D=n?.documentToolbarShowCopyLabel===!0,W=n?.documentToolbarShowCopyChevron===!0,U=n?.documentToolbarCopyMenuItems,B=!!(W&&U&&U.length>0),O=null,H,S=null;if(r&&(D||W)&&!B){if(H=D?Li({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):vn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),W){let Z=Ge(Bs.ChevronDown,14,"currentColor",2);Z&&H.appendChild(Z)}}else r&&B?(S=NM({label:"Copy",icon:"copy",iconSize:14,iconOnly:!D,primaryClassName:"persona-artifact-doc-copy-btn",chevronLabel:"More copy options",chevronClassName:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",menuItems:(U??[]).map(Z=>({id:Z.id,label:Z.label})),position:"bottom-right",portal:()=>b.closest("[data-persona-root]")??document.body,onSelect:Z=>{ve(Z)}}),O=S.element,H=S.primaryButton):r?H=vn({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(H=vn({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&H.classList.add("persona-hidden"));let x=r?vn({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):vn({icon:"refresh-cw",label:"Refresh"});n?.onDocumentToolbarRefresh||x.classList.add("persona-hidden");let P=r?vn({icon:"x",label:a,className:"persona-artifact-doc-icon-btn"}):vn({icon:"x",label:a}),L=vn({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>e.onToggleExpand?.()});n?.showExpandToggle!==!0&&L.classList.add("persona-hidden");let G=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),V=t.features?.artifacts?.toolbarActions??[],K=()=>{let Z=Ae.find(qe=>qe.id===vt)??Ae[Ae.length-1],Fe=Z?.id??null,He=Z?.artifactType==="markdown"?Z.markdown??"":"",nt=Z?JSON.stringify({component:Z.component,props:Z.props},null,2):"",{filename:Bt,mime:Ie,content:Be}=_c({title:Z?.title,markdown:Z?.markdown??"",file:Z?.file});return{markdown:He,jsonPayload:nt,id:Fe,file:Z?.file,suggestedFilename:Bt,mime:Ie,content:Be}},ee=()=>{let{suggestedFilename:Z,mime:Fe,content:He}=K();He&&Nc({filename:Z,mime:Fe,content:He})},oe=Z=>{let{id:Fe,...He}=K();return{actionId:Z,artifactId:Fe,...He}},ne=async()=>{let Z=Ae.find(Fe=>Fe.id===vt)??Ae[Ae.length-1];try{return await navigator.clipboard.writeText(Vc(Z)),!0}catch{return!1}},le=null,de=()=>{le?.();let Z=H.querySelector("svg"),Fe=Number(Z?.getAttribute("width"))||16,He=Ge(Bs.Check,Fe,"currentColor",2);if(!Z||!He)return;Z.replaceWith(He);let nt=H.querySelector("span");nt&&(nt.textContent="Copied");let Bt=setTimeout(()=>le?.(),2e3);le=()=>{clearTimeout(Bt),He.replaceWith(Z),nt&&(nt.textContent="Copy"),le=null}};H.addEventListener("click",async()=>{let Z=n?.onDocumentToolbarCopyMenuSelect;if(Z&&B){try{if(await Z(oe("primary"))===!1){await ne()&&de();return}de()}catch{}return}await ne()&&de()});async function ve(Z){let Fe=n?.onDocumentToolbarCopyMenuSelect;try{if(Fe&&await Fe(oe(Z))!==!1)return;if(Z==="download"){ee();return}let{markdown:He,jsonPayload:nt}=K();Z==="markdown"||Z==="md"?await navigator.clipboard.writeText(He):Z==="json"||Z==="source"?await navigator.clipboard.writeText(nt):await navigator.clipboard.writeText(He||nt),de()}catch{}}x.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}Ze()}),P.addEventListener("click",()=>{h(),e.onDismiss?.()});let Le=v("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");if(r)C.replaceChildren(),O?A.append(O,x,P):A.append(H,x,P),A.insertBefore(G,P),A.insertBefore(L,P),C.append(R.element,Le,A);else{let Z=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");Z.append(H,G,L,E),C.appendChild(M),C.appendChild(Z)}l&&(C.style.paddingLeft=l,C.style.paddingRight=l);let se=v("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border");c&&se.style.setProperty("--persona-artifact-tab-fade-size",c);let _=t.features?.artifacts?.renderTabBar,Te=v("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),Re=tE(se,{onSelect:Z=>e.onSelect(Ae[Z].id)}),ut=Z=>{let Fe=Z.scrollWidth-Z.clientWidth,He=Fe>1,nt=Math.abs(Z.scrollLeft);Z.classList.toggle("persona-artifact-tab-fade-start",u&&He&&nt>1),Z.classList.toggle("persona-artifact-tab-fade-end",m&&He&&nt<Fe-1)},At=0,Wt=()=>{if(At)return;let Z=()=>{At=0,ut(se)};At=typeof requestAnimationFrame=="function"?requestAnimationFrame(Z):setTimeout(Z,0)};se.addEventListener("scroll",()=>Wt(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>ut(se)).observe(se);let bt=v("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3"),xe=()=>{bt.scrollLeft=0},Ne=()=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(xe):setTimeout(xe,0)};if(l){for(let Z of[se,Te])Z.style.paddingLeft=l,Z.style.paddingRight=l;bt.style.padding=l}b.appendChild(C),b.appendChild(se),b.appendChild(Te),b.appendChild(bt);let Ae=[],vt=null,X=!1,I=!1,j=!0,J=!1,Y=null,ie="",Me=null,Ee=!1,_e=Z=>Z.artifactType==="markdown"&&!!Z.file||r?T:"rendered",Ct=Z=>{r||(Z&&!Ee?(C.insertBefore(R.element,M),Ee=!0):!Z&&Ee&&(R.element.remove(),Ee=!1))},Ot=()=>vt&&Ae.find(Z=>Z.id===vt)||Ae[Ae.length-1],rt=()=>{let Z=Fc(Ot());if(!Z){G.replaceChildren();return}let Fe=V.filter(He=>He.visible===void 0||He.visible(Z)).map(He=>ja(He,{documentChrome:r,onClick:()=>{let nt=Fc(Ot());if(nt)try{Promise.resolve(He.onClick(nt)).catch(()=>{})}catch{}}}));G.replaceChildren(...Fe)},Ze=()=>{rt();let Z=r&&Ae.length<=1,Fe=!!_;if(se.classList.toggle("persona-hidden",Z||Fe),Te.classList.toggle("persona-hidden",Z||!Fe),Fe&&_){let Bt=Ae.map(Ie=>Ie.id).join("|")+" "+(vt??"");if(Bt!==ie){ie=Bt;let Ie=_({records:Ae,selectedId:vt,onSelect:e.onSelect});Te.firstElementChild!==Ie&&Te.replaceChildren(Ie)}}else{Re.beforeRender(),se.replaceChildren();let Bt=[],Ie=-1;for(let[Be,qe]of Ae.entries()){let Tt=v("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");Tt.type="button";let mt=qe.artifactType==="markdown"?qe.file:void 0,xt=mt?vr(mt.path):qe.title||qe.id.slice(0,8),Mn=mt?.path||qe.title||xt;Tt.textContent=xt,Tt.title=Mn,Tt.setAttribute("aria-label",Mn),qe.id===vt&&(Tt.classList.add("persona-bg-persona-container","persona-border-persona-border"),Ie=Be),Tt.addEventListener("click",()=>e.onSelect(qe.id)),se.appendChild(Tt),Bt.push(Tt)}if(Re.render(Bt,Ie),Ie>=0&&vt!==Y){Y=vt;let Be=Bt[Ie];typeof Be.scrollIntoView=="function"&&Be.scrollIntoView({block:"nearest",inline:"nearest"})}ut(se)}let He=vt&&Ae.find(Bt=>Bt.id===vt)||Ae[Ae.length-1];if(!He){bt.replaceChildren(),Me?.destroy(),Me=null,Ct(!1);return}let nt=He.artifactType==="markdown"?He.file:void 0;if(Ct(!!nt&&Di(nt)!=="other"),r){let Bt=nt?Ws(nt):He.artifactType==="markdown"?"MD":He.component??"Component",Ie=(He.title||"Document").trim(),Be=nt?vr(nt.path):Ie.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Le.textContent=`${Be} \xB7 ${Bt}`}else M.textContent=nt?vr(nt.path):s;Me?(Me.el.parentElement!==bt&&bt.replaceChildren(Me.el),Me.update(He)):(Me=fm(He,{config:t,resolveViewMode:_e}),bt.replaceChildren(Me.el)),bt.classList.toggle("persona-artifact-content-flush",!!bt.querySelector(".persona-code-pre"))},ct=()=>{let Z=Ae.length>0;if(b.classList.toggle("persona-hidden",!Z),g){let nt=((typeof b.closest=="function"?b.closest("[data-persona-root]"):null)?.classList.contains("persona-artifact-narrow-host")??!1)||typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches;Z&&nt&&X?(g.classList.remove("persona-hidden"),b.classList.add("persona-artifact-drawer-open")):(g.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open"))}},Ht=()=>{J=!1,Ze(),ct()};return{element:b,backdrop:g,update(Z){let Fe=Z.selectedId??Z.artifacts[Z.artifacts.length-1]?.id??null,He=Fe!==vt;Ae=Z.artifacts,vt=Fe,Ae.length>0&&(X=!0),J=!0,j&&Ht(),He&&xe()},setMobileOpen(Z){X=Z,!Z&&g?(g.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open")):ct()},setExpanded(Z){Z!==I&&(I=Z,Ne());let Fe=Ge(Z?Bs.Minimize:Bs.Maximize,16,"currentColor",2);Fe&&L.replaceChildren(Fe);let He=Z?"Collapse artifacts panel":"Expand artifacts panel";L.setAttribute("aria-label",He),L.title=He},setExpandToggleVisible(Z){L.classList.toggle("persona-hidden",!Z)},setCopyButtonVisible(Z){r||H.classList.toggle("persona-hidden",!Z)},setRefreshButtonVisible(Z){x.classList.toggle("persona-hidden",!Z)},setCustomActions(Z){V=Z,rt()},setTabFade(Z){let Fe=p(Z);Fe.start===u&&Fe.end===m||(u=Fe.start,m=Fe.end,ut(se))},setRenderTabBar(Z){Z!==_&&(_=Z,ie="",Ze())},setVisible(Z){Z!==j&&(j=Z,Z&&J&&Ht())},destroy(){Me?.destroy(),Me=null}}}var Bs,oE=be(()=>{"use strict";je();Oi();dm();gm();Bs=require("lucide");zn();Ii();nE()});function rE(t,e){let n=t.file&&typeof t.file=="object"&&!Array.isArray(t.file)?t.file:void 0,o=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",r=n?vr(n.path):o,s=typeof t.artifactId=="string"?t.artifactId:"",a=t.status==="streaming"?"streaming":"complete",l=typeof t.artifactType=="string"?t.artifactType:"markdown",c=t.presentation&&typeof t.presentation=="object"&&!Array.isArray(t.presentation)?t.presentation:void 0,p=n?Ws(n):l==="component"?"Component":"Document",u=document.createElement("div");u.className="persona-artifact-card persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-px-4 persona-py-3",u.tabIndex=0,u.setAttribute("role","button"),u.setAttribute("aria-label",`Open ${r} in artifact panel`),s&&u.setAttribute("data-open-artifact",s);let m=document.createElement("div");m.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",m.style.border="1px solid var(--persona-border, #e5e7eb)",m.style.color="var(--persona-muted, #9ca3af)",m.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let g=document.createElement("div");g.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let h=document.createElement("div");h.className="persona-truncate persona-text-sm persona-font-medium",h.style.color="var(--persona-text, #1f2937)",h.textContent=r;let b=document.createElement("div");if(b.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",b.style.color="var(--persona-muted, #9ca3af)",a==="streaming"){let C=e?.config?.features?.artifacts,M={id:s,artifactType:l==="component"?"component":"markdown",title:o,status:"streaming",...typeof t.markdown=="string"?{markdown:t.markdown}:{},...n?{file:n}:{},...c?{presentation:c}:{}},E=Ga(M,C,"card");_i(b,E,C)}else s&&Ka(s),b.textContent=p;if(g.append(h,b),u.append(m,g),a==="complete"){let C=e?.config?.features?.artifacts?.cardActions;if(C&&C.length>0){let E={artifactId:s||null,title:r,artifactType:l,markdown:typeof t.markdown=="string"?t.markdown:void 0,file:n};for(let T of C)try{if(T.visible===void 0||T.visible(E)){let R=ja(T);R.setAttribute("data-artifact-custom-action",T.id),R.className=`${R.className} persona-flex-shrink-0`,u.append(R)}}catch{}}let M=Li({label:"Download",className:"persona-flex-shrink-0"});M.title=`Download ${r}`,M.setAttribute("data-download-artifact",s),u.append(M)}return u}var $c,$y=be(()=>{"use strict";Oi();pm();Ii();dm();$c=(t,e)=>{let n=e?.config?.features?.artifacts?.renderCard;if(n){let o=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",r=typeof t.artifactId=="string"?t.artifactId:"",s=t.status==="streaming"?"streaming":"complete",a=typeof t.artifactType=="string"?t.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:a,status:s},config:e.config,defaultRenderer:()=>rE(t,e)});if(l)return l}return rE(t,e)}});function zy(t,e,n){if(e.length===0)return;let o=new Map(e.map(r=>[r.id,r]));t.querySelectorAll("[data-artifact-inline]").forEach(r=>{let s=Ds.get(r);if(!s)return;let a=o.get(r.getAttribute("data-artifact-inline")??"");a&&s(a,n)})}function Uy(t){return Ds.has(t)}function XB(t){let e=typeof t.artifactId=="string"?t.artifactId:"",n=typeof t.title=="string"&&t.title?t.title:void 0,o=t.status==="streaming"?"streaming":"complete",r=t.presentation&&typeof t.presentation=="object"&&!Array.isArray(t.presentation)?t.presentation:void 0;if(t.artifactType==="component"){let a=t.componentProps,l=a&&typeof a=="object"&&!Array.isArray(a)?a:{};return{id:e,artifactType:"component",title:n,status:o,component:typeof t.component=="string"?t.component:"",props:l,...r?{presentation:r}:{}}}let s=t.file&&typeof t.file=="object"&&!Array.isArray(t.file)?t.file:void 0;return{id:e,artifactType:"markdown",title:n,status:o,markdown:typeof t.markdown=="string"?t.markdown:"",...s?{file:s}:{},...r?{presentation:r}:{}}}function sE(t){let e=t.artifactType==="markdown"?t.file:void 0,n=e?vr(e.path):t.title&&t.title.trim()?t.title:"Untitled artifact",o=e?Ws(e):t.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function JB(t){let e={artifactId:t.id,title:t.title??"",status:t.status,artifactType:t.artifactType};return t.artifactType==="markdown"&&(typeof t.markdown=="string"&&(e.markdown=t.markdown),t.file&&(e.file=t.file)),e}function s1(t,e,n){let{swap:o,onSettled:r}=n,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(!e||!t.isConnected||s||typeof t.animate!="function"){o(),r();return}t.style.height=`${e}px`,t.style.overflow="hidden";let a=[];for(let l of Array.from(t.children))l instanceof HTMLElement&&a.push(l.animate([{opacity:1},{opacity:0}],{duration:iE,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let E of a)E.cancel();o();let l=()=>{t.style.removeProperty("height"),t.style.removeProperty("overflow")};if(!t.isConnected){l(),r();return}t.style.height="auto";let c=t.getBoundingClientRect().height;if(t.style.height=`${e}px`,!c||Math.abs(c-e)<1){l(),r();return}let p=Math.abs(e-c),u=Math.round(Math.min(n1,Math.max(t1,ZB+p*e1))),m=Math.round(u*r1),g=t.firstElementChild instanceof HTMLElement?t.firstElementChild:null,h=g?g.animate([{opacity:0},{opacity:1}],{duration:aE,delay:m,easing:"ease-out",fill:"backwards"}):null,b=t.animate([{height:`${e}px`},{height:`${c}px`}],{duration:u,easing:o1});t.style.height=`${c}px`;let C=!1,M=()=>{C||(C=!0,l(),r())};Promise.allSettled([b.finished,h?.finished].filter(Boolean)).then(M),window.setTimeout(M,Math.max(u,m+aE)+120)},iE)}function i1(t){let e=t?.inlineChrome;if(e===!1)return{chromeEnabled:!1,showCopy:!1,showExpand:!1,showViewToggle:!1};let n=typeof e=="object"?e:void 0;return{chromeEnabled:!0,showCopy:n?.showCopy!==!1,showExpand:n?.showExpand!==!1,showViewToggle:n?.showViewToggle!==!1}}function a1(t){let e=t?.inlineBody,n=e?.streamingView==="status"?"status":"source",o=e?.viewMode==="source"?"source":"rendered",r=320,s=320,a=e?.height;typeof a=="number"||a==="auto"?(r=a,s=a):a&&typeof a=="object"&&(r=a.streaming??320,s=a.complete??320);let l=e?.overflow==="clip"?"clip":"scroll",c=l==="clip"?!1:e?.followOutput!==!1,p,u,m=e?.fadeMask;m===!0?(p=!0,u=!0):m===!1?(p=!1,u=!1):m&&typeof m=="object"?(p=m.top===!0,u=m.bottom===!0):l==="clip"?(p=!1,u=!0):(p=!0,u=!0);let g=e?.transition==="none"?"none":"auto",h=e?.completeDisplay==="card"?"card":"inline";return{streamingView:n,viewMode:o,streamingHeight:r,completeHeight:s,followOutput:c,overflow:l,fadeTop:p,fadeBottom:u,transition:g,completeDisplay:h}}function lE(t,e){let n=XB(t),o=e.config?.features?.artifacts,{chromeEnabled:r,showCopy:s,showExpand:a,showViewToggle:l}=i1(o),c=o?.inlineActions??[],p=a1(o),u=p.completeDisplay==="card",m=null,g=n,h=v("div","persona-artifact-inline persona-w-full persona-max-w-full");h.setAttribute("data-persona-theme-zone","artifact-inline"),n.id&&h.setAttribute("data-artifact-inline",n.id);let b=ne=>$c(JB(ne),e),C=null,M=ne=>{C?.destroy(),C=null,h.classList.add("persona-artifact-inline--card"),h.style.removeProperty(zc),h.replaceChildren(b(ne)),Ds.set(h,le=>{h.replaceChildren(b(le))})};if(u&&n.status==="complete")return M(n),h;let E=fm(n,{config:e.config,bodyLayout:p,resolveViewMode:()=>m??p.viewMode});C=E;let T=v("div","persona-artifact-inline-body");T.appendChild(E.el);let R=ne=>{let le=ne.status!=="complete",de=le?p.streamingHeight:p.completeHeight,ve=typeof de=="number";ve?h.style.setProperty(zc,`${de}px`):h.style.removeProperty(zc);let Le=!!E.el.querySelector(".persona-code-pre"),se=!!E.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");T.classList.toggle("persona-artifact-content-flush",Le),T.classList.toggle("persona-artifact-inline-body--sized",ve&&se),T.classList.toggle("persona-artifact-inline-body--cap",!le&&!se&&typeof p.completeHeight=="number")},A=n.status,D=(ne,le)=>{A!=="complete"&&ne.status==="complete"?(typeof p.completeHeight=="number"?h.style.setProperty(zc,`${p.completeHeight}px`):h.style.removeProperty(zc),eE(T,le?.suppressTransition?"none":p.transition,ne.id,()=>{E.update(ne),R(ne)})):E.update(ne),R(ne),A=ne.status};R(n);let W=p.overflow==="clip"&&a&&!!n.id;if(W&&(T.setAttribute("data-expand-artifact-inline",n.id),T.setAttribute("role","button"),T.setAttribute("tabindex","0"),T.classList.add("persona-cursor-pointer"),T.setAttribute("aria-label",`Open ${sE(n).title} in panel`)),!r)return h.appendChild(T),Ds.set(h,D),h;let U=v("div","persona-artifact-inline-chrome");U.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let B=v("div","persona-artifact-inline-chrome-lead"),O=v("span","persona-flex persona-items-center persona-flex-shrink-0"),H=Ge(cE.FileText,16,"currentColor",2);H&&O.appendChild(H);let S=v("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),x=v("span","persona-artifact-inline-type");B.append(O,S,x);let P=v("div","persona-artifact-inline-chrome-actions"),L=v("span","persona-flex persona-items-center persona-gap-1"),G=()=>m??p.viewMode,V=l?Yu({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"},{id:"source",icon:"code-xml",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}],selectedId:G(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:ne=>{let le=ne==="source"?"source":"rendered";le!==G()&&(m=le,E.update(g),R(g))}}):null,K=s?vn({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;K&&n.id&&K.setAttribute("data-copy-artifact",n.id);let ee=a?vn({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;ee&&n.id&&ee.setAttribute("data-expand-artifact-inline",n.id),P.appendChild(L),V&&P.appendChild(V.element),K&&P.appendChild(K),ee&&P.appendChild(ee),U.append(B,P),h.append(U,T);let oe=ne=>{let{title:le,typeLabel:de}=sE(ne);S.textContent=le,S.title=le,W&&T.setAttribute("aria-label",`Open ${le} in panel`);let ve=ne.status!=="complete";if(ve){x.classList.contains("persona-artifact-inline-status")||(x.className="persona-artifact-inline-status",x.removeAttribute("data-preserve-animation"),x.replaceChildren());let Le=Ga(ne,o,"inline-chrome");_i(x,Le,o)}else Ka(ne.id),x.className="persona-artifact-inline-type",x.removeAttribute("data-preserve-animation"),x.replaceChildren(),x.textContent=de;if(K&&K.classList.toggle("persona-hidden",ve),V){let Le=ne.artifactType==="markdown"?ne.file:void 0,se=!1;if(!ve&&Le&&p.viewMode!=="source"){let _=Di(Le);_==="markdown"?se=!0:(_==="html"||_==="svg")&&(se=o?.filePreview?.enabled!==!1)}V.element.classList.toggle("persona-hidden",!se),V.setSelected(G())}if(L.replaceChildren(),!ve&&c.length>0){let Le=Fc(ne);if(Le)for(let se of c)try{if(se.visible===void 0||se.visible(Le)){let _=ja(se,{documentChrome:!0});_.setAttribute("data-artifact-custom-action",se.id),_.classList.add("persona-flex-shrink-0"),L.appendChild(_)}}catch{}}};return oe(n),Ds.set(h,(ne,le)=>{if(u&&A!=="complete"&&ne.status==="complete"){let de=h.isConnected?h.getBoundingClientRect().height:0;A="complete";let ve=ne,Le=!1,se=_=>{ve=_,Le=!0};Ds.set(h,se),s1(h,de,{swap:()=>{M(ve),Le=!1,Ds.set(h,se)},onSettled:()=>{Le?M(ve):Ds.set(h,_=>{h.replaceChildren(b(_))})}});return}(ne.status!=="complete"||ne.id!==g.id)&&(m=null),g=ne,D(ne,le),oe(ne)}),h}var cE,Ds,iE,ZB,e1,t1,n1,o1,aE,r1,zc,qy,dE=be(()=>{"use strict";je();Oi();pm();dm();Ii();cE=require("lucide");zn();gm();$y();Ds=new WeakMap;iE=180,ZB=240,e1=.8,t1=300,n1=500,o1="cubic-bezier(0.2, 0, 0, 1)",aE=240,r1=.35;zc="--persona-artifact-inline-body-height";qy=(t,e)=>{let n=e?.config?.features?.artifacts?.renderInline;if(n){let o=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",r=typeof t.artifactId=="string"?t.artifactId:"",s=t.status==="streaming"?"streaming":"complete",a=typeof t.artifactType=="string"?t.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:a,status:s},config:e.config,defaultRenderer:()=>lE(t,e)});if(l)return l}return lE(t,e)}});var pE=be(()=>{"use strict";oE();dE();$y();gm();Oi();Ny();Si();yp()});var uE={};$n(uE,{PersonaArtifactCard:()=>$c,PersonaArtifactInline:()=>qy,__provideMarkdownParsers:()=>Ig,__setIconsExtraLoader:()=>Mg,artifactCopyText:()=>Vc,createArtifactPane:()=>Vy,downloadInfoFor:()=>_c,hasLiveInlineArtifactBlock:()=>Uy,initArtifactsUi:()=>_y,triggerArtifactDownload:()=>Nc,updateInlineArtifactBlocks:()=>zy});var mE=be(()=>{"use strict";pE()});var Cm,AE,ME=be(()=>{"use strict";je();Cm={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},AE=(t,e,n,o)=>{let r=t.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{if(s.dataset.enhanced==="true")return;let a=s.dataset.tvForm??"init";s.dataset.enhanced="true";let l=Cm[a]??Cm.init;s.classList.add("persona-form-card","persona-space-y-4");let c=v("div","persona-space-y-1"),p=v("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(p.textContent=l.title,c.appendChild(p),l.description){let b=v("p","persona-text-sm persona-text-persona-muted");b.textContent=l.description,c.appendChild(b)}let u=document.createElement("form");u.className="persona-form-grid persona-space-y-3",l.fields.forEach(b=>{let C=v("label","persona-form-field persona-flex persona-flex-col persona-gap-1");C.htmlFor=`${e.id}-${a}-${b.name}`;let M=v("span","persona-text-xs persona-font-medium persona-text-persona-muted");M.textContent=b.label,C.appendChild(M);let E=b.type??"text",T;E==="textarea"?(T=document.createElement("textarea"),T.rows=3):(T=document.createElement("input"),T.type=E),T.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",T.id=`${e.id}-${a}-${b.name}`,T.name=b.name,T.placeholder=b.placeholder??"",b.required&&(T.required=!0),C.appendChild(T),u.appendChild(C)});let m=v("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),g=v("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),h=v("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");h.type="submit",h.textContent=l.submitLabel??"Submit",m.appendChild(g),m.appendChild(h),u.appendChild(m),s.replaceChildren(c,u),u.addEventListener("submit",async b=>{b.preventDefault();let C=n.formEndpoint??"/form",M=new FormData(u),E={};M.forEach((T,R)=>{E[R]=T}),E.type=a,h.disabled=!0,g.textContent="Submitting\u2026";try{let T=await fetch(C,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(E)});if(!T.ok)throw new Error(`Form submission failed (${T.status})`);let R=await T.json();g.textContent=R.message??"Thanks! We'll be in touch soon.",R.success&&R.nextPrompt&&await o.sendMessage(String(R.nextPrompt))}catch(T){g.textContent=T instanceof Error?T.message:"Something went wrong. Please try again."}finally{h.disabled=!1}})})}});var TE={};$n(TE,{enhanceWithForms:()=>AE,formDefinitions:()=>Cm});var EE=be(()=>{"use strict";ME()});function _E(){let t=document.createElement("div");t.className="persona-history-sr-only",t.setAttribute("role","status"),t.setAttribute("aria-live","polite"),t.setAttribute("aria-atomic","true"),t.setAttribute("data-persona-history-live-region","");let e;return{element:t,announce(n){e!==void 0&&clearTimeout(e),t.textContent="",e=setTimeout(()=>{e=void 0,t.textContent=n},0)},destroy(){e!==void 0&&clearTimeout(e),t.remove()}}}var NE=be(()=>{"use strict"});var FE,VE=be(()=>{"use strict";FE=`
|
|
244
244
|
.persona-history-view {
|
|
245
245
|
--persona-history-surface-bg: var(--persona-surface, #ffffff);
|
|
246
246
|
--persona-history-topbar-bg: var(--persona-header-bg, var(--persona-surface, #ffffff));
|
|
@@ -1137,25 +1137,25 @@ ${e}
|
|
|
1137
1137
|
.persona-history-view .persona-history-skeleton-bar { animation: none; }
|
|
1138
1138
|
.persona-history-rail-host { transition: none; }
|
|
1139
1139
|
}
|
|
1140
|
-
`});function nb(t){if(!t)return wm;let e={...wm};for(let n of w1){let o=t[n];typeof o=="string"&&o.length>0&&(e[n]=o)}return e}var w1,wm,ob=be(()=>{"use strict";w1=["viewTitle","openHistoryLabel","openHistoryBusyLabel","newConversationLabel","expandLabel","collapseLabel","resizeLabel","showEarlierMessagesLabel","openConversationLoadingLabel","openConversationErrorTitle","openConversationRetryLabel","openConversationBackLabel","confirmCancelLabel","deleteConversationConfirmTitle","deleteConversationConfirm","deleteConversationConfirmLabel","clearHistoryConfirmTitle","clearHistoryConfirm","clearHistoryVerifiedConfirm","clearHistoryConfirmLabel","resetIdentityConfirmTitle","resetIdentityConfirm","resetIdentityConfirmLabel","conversationDeletedNotice","identityResetNotice","identityResetUnconfirmedNotice"],wm={viewTitle:"Messages",openHistoryLabel:"Messages",openHistoryBusyLabel:"Messages, available once the reply finishes",newConversationLabel:"New conversation",expandLabel:"Expand conversation list",collapseLabel:"Collapse conversation list",resizeLabel:"Resize conversation list",showEarlierMessagesLabel:"Show earlier messages",openConversationLoadingLabel:"Loading conversation",openConversationErrorTitle:"Could not open the conversation.",openConversationRetryLabel:"Try again",openConversationBackLabel:"Back to messages",confirmCancelLabel:"Cancel",deleteConversationConfirmTitle:"Delete conversation",deleteConversationConfirm:"Delete this conversation? This cannot be undone.",deleteConversationConfirmLabel:"Delete",clearHistoryConfirmTitle:"Delete all conversations",clearHistoryConfirm:"Delete all conversations for this assistant on this browser? This cannot be undone.",clearHistoryVerifiedConfirm:"Delete all conversations for this assistant and signed-in user? This cannot be undone.",clearHistoryConfirmLabel:"Delete all",resetIdentityConfirmTitle:"Forget this device",resetIdentityConfirm:"Forget this device? All Persona data stored in this browser is cleared. Records are not deleted elsewhere.",resetIdentityConfirmLabel:"Forget this device",conversationDeletedNotice:"That conversation was deleted. You are now in a new conversation.",identityResetNotice:"This device was forgotten.",identityResetUnconfirmedNotice:"This device was cleared here, but the server could not confirm it."}});function Gc(t){if(!t)return Kc;let e={...Kc};for(let[n,o]of Object.entries(t))typeof o=="string"&&o.length>0&&(e[n]=o);return e}function wr(t,e){return t.replace(/\{(\w+)\}/g,(n,o)=>o in e?String(e[o]):n)}var Kc,Yc=be(()=>{"use strict";ob();Kc={...wm,emptyTitle:"No conversations yet",emptyDescription:"Start a conversation and it will show up here.",errorTitle:"Could not load conversations",errorDescription:"Something went wrong. Please try again.",retryLabel:"Retry",rateLimitedTitle:"Too many requests",rateLimitedDescription:"Please wait a moment before trying again.",groupStarred:"Starred",groupToday:"Today",groupYesterday:"Yesterday",groupPrevious7Days:"Previous 7 days",groupPrevious30Days:"Previous 30 days",groupMonthYear:"{month} {year}",browserOnlyTitle:"On this device",browserOnlyDescription:"Another browser or device keeps its own separate history.",verifyingTitle:"Checking your account",verifyingDescription:"Looking for messages linked to your account.",verifiedTitle:"Available across signed-in devices",verifiedDescription:"This list refreshes when the chat opens rather than syncing live.",authenticationRequiredTitle:"Sign in to see your messages",authenticationRequiredDescription:"Your session expired. Sign in again to load account history.",identityProviderFailedTitle:"Account history is unavailable",identityProviderFailedDescription:"We could not verify your account, so account history is not shown here.",proofNotAdmittedTitle:"Account history is unavailable",proofNotAdmittedDescription:"This assistant is not set up to accept your account identity.",retryIdentityLabel:"Try again",backLabel:"Back to conversation",closeLabel:"Close conversation list",loadingLabel:"Loading conversations",loadMoreLabel:"Load more",loadingMoreLabel:"Loading more conversations",conversationsTitle:"Conversations",rowActionsLabel:"Conversation options",listOptionsLabel:"Conversation options",deleteConversationLabel:"Delete",clearHistoryLabel:"Delete all conversations",resetIdentityLabel:"Forget this device",messageCountLabel:"{count} messages",messageCountLabelOne:"1 message",conversationRemovedNotice:"Conversation deleted.",historyClearedNotice:"All conversations were deleted.",unavailableTitle:"Conversation history is unavailable",unavailableDescription:"Try again later.",newConversationRequiredTitle:"Start a new conversation",newConversationRequiredDescription:"The previous conversation is gone. Start a new one to keep chatting.",rateLimitedWaitDescription:"You can try again in {seconds} seconds.",openFailedLabel:"Could not open that conversation.",deleteFailedLabel:"Could not delete that conversation.",relativeNow:"now",relativeMinutes:"{value}m",relativeHours:"{value}h",relativeDays:"{value}d",relativeWeeks:"{value}w",relativeYears:"{value}y"}});function x1(t){let e=new Date(t);return e.setHours(0,0,0,0),e.getTime()}function sb(t,e){let n=Date.parse(t);return Number.isFinite(n)?n:e}function S1(t,e){let n=sb(t,e),o=x1(e);if(n>=o)return"today";if(n>=o-rb)return"yesterday";if(n>=o-7*rb)return"previous-7-days";if(n>=o-30*rb)return"previous-30-days";let r=new Date(n);return`month:${r.getFullYear()}-${r.getMonth()}`}function A1(t,e,n,o){if(t==="today")return o.groupToday;if(t==="yesterday")return o.groupYesterday;if(t==="previous-7-days")return o.groupPrevious7Days;if(t==="previous-30-days")return o.groupPrevious30Days;let r=new Date(sb(e,n));return wr(o.groupMonthYear,{month:r.toLocaleString(void 0,{month:"long"}),year:r.getFullYear()})}function RE(t,e,n,o="time"){let r=t.filter(a=>a.starred),s=r.length>0?[{key:"starred",label:n.groupStarred,items:r}]:[];if(o==="none"){let a=t.filter(l=>!l.starred);return a.length>0&&s.push({key:"recent",label:n.conversationsTitle,items:a}),s}for(let a of t){if(a.starred)continue;let l=S1(a.updatedAt,e),c=s[s.length-1];if(c&&c.key===l){c.items.push(a);continue}s.push({key:l,label:A1(l,a.updatedAt,e,n),items:[a]})}return s}function HE(t,e,n){let o=Math.max(0,e-sb(t,e)),r=Math.floor(o/6e4);if(r<1)return n.relativeNow;if(r<60)return wr(n.relativeMinutes,{value:r});let s=Math.floor(r/60);if(s<24)return wr(n.relativeHours,{value:s});let a=Math.floor(s/24);if(a<7)return wr(n.relativeDays,{value:a});let l=Math.floor(a/7);return a<365?wr(n.relativeWeeks,{value:l}):wr(n.relativeYears,{value:Math.floor(a/365)})}function WE(t,e){return t===1?e.messageCountLabelOne:wr(e.messageCountLabel,{count:t})}var rb,ib=be(()=>{"use strict";Yc();rb=864e5});function Os(t,e=20){let n=document.createElementNS(xm,"svg");if(n.setAttribute("width",String(e)),n.setAttribute("height",String(e)),n.setAttribute("viewBox","0 0 24 24"),n.setAttribute("fill","none"),n.setAttribute("stroke","currentColor"),n.setAttribute("stroke-width","2"),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.setAttribute("aria-hidden","true"),n.setAttribute("focusable","false"),t==="ellipsis"){for(let r of[12,19,5]){let s=document.createElementNS(xm,"circle");s.setAttribute("cx",String(r)),s.setAttribute("cy","12"),s.setAttribute("r","1"),n.appendChild(s)}return n}let o=T1[t];if(o){let r=document.createElementNS(xm,"rect");r.setAttribute("x",String(o[0])),r.setAttribute("y",String(o[1])),r.setAttribute("width",String(o[2])),r.setAttribute("height",String(o[3])),r.setAttribute("rx","2"),n.appendChild(r)}for(let r of M1[t]){let s=document.createElementNS(xm,"path");s.setAttribute("d",r),n.appendChild(s)}return n}var xm,M1,T1,ab=be(()=>{"use strict";xm="http://www.w3.org/2000/svg",M1={"arrow-left":["m12 19-7-7 7-7","M19 12H5"],plus:["M5 12h14","M12 5v14"],star:["m12 2 2.9 6.2 6.8.7-5.1 4.5 1.4 6.6-6-3.4-6 3.4 1.4-6.6-5.1-4.5 6.8-.7z"],x:["M18 6 6 18","m6 6 12 12"],"panel-left":["M9 3v18"],monitor:["M8 21h8","M12 17v4"],ellipsis:[]},T1={"panel-left":[3,3,18,18],monitor:[2,3,20,14]}});function k1(t){let e=F("span",{className:"persona-history-row-avatar",attrs:{"aria-hidden":"true"}});return E1.test(t)?e.appendChild(F("img",{attrs:{src:t,alt:"",loading:"lazy"}})):e.textContent=t,e}function BE(t){let{conversation:e,copy:n,busy:o,pending:r}=t,s=o||r!==null,a=e.title.trim().length>0,l=e.starred?(()=>{let h=Os("star",11);return h.setAttribute("fill","currentColor"),h.setAttribute("stroke-width","1"),F("span",{className:"persona-history-row-star"},h,F("span",{className:"persona-history-sr-only",text:n.groupStarred}))})():null,c=F("div",{className:"persona-history-row-head"},F("span",{className:"persona-history-row-title persona-history-truncate",text:a?e.title:e.preview??""}),l,F("time",{className:"persona-history-row-time",attrs:{datetime:e.updatedAt},text:HE(e.updatedAt,t.nowMs,n)})),p=a&&e.preview?F("span",{className:"persona-history-row-preview persona-history-truncate",text:e.preview}):null,u=F("button",{className:Gt("persona-history-row",t.active&&"persona-history-row--active",r&&`persona-history-row--${r}`),attrs:{type:"button","data-persona-history-focus":P1(e.id),"data-persona-history-conversation":e.id,...t.active?{"aria-current":"page"}:{},...s?{"aria-disabled":"true"}:{},...r?{"aria-busy":"true"}:{}}},t.avatar?k1(t.avatar):null,F("div",{className:"persona-history-row-body"},c,p,F("span",{className:"persona-history-row-count persona-history-sr-only",text:WE(e.messageCount,n)})));u.addEventListener("click",()=>{s||t.onOpen()});let m=t.showDelete?lb({className:"persona-history-row-menu-button",label:`${n.rowActionsLabel}: ${e.title}`,focusKey:L1(e.id),open:t.menuOpen,inert:s,onToggle:t.onToggleMenu}):null;return F("li",{className:Gt("persona-history-item",!t.showDelete&&"persona-history-item--no-menu"),attrs:{"data-persona-history-item":e.id}},u,m,t.menuOpen&&t.showDelete?I1(t):null,t.error?R1(t.error,n,e.id):null)}function I1(t){let{conversation:e,copy:n}=t;return cb({label:`${n.rowActionsLabel}: ${e.title}`,items:[{label:n.deleteConversationLabel,focusKey:Qc(e.id),danger:!0,onSelect:t.onDelete}],onCloseMenu:t.onCloseMenu})}function lb(t){let e=F("button",{className:Gt("persona-history-icon-button",t.className),attrs:{type:"button","aria-label":t.label,"aria-haspopup":"menu","aria-expanded":t.open?"true":"false","data-persona-history-focus":t.focusKey,...t.inert?{"aria-disabled":"true"}:{}}});e.appendChild(Os("ellipsis",t.iconSize));let n=()=>e.getAttribute("aria-disabled")==="true";return e.addEventListener("click",o=>{o.stopPropagation(),!n()&&t.onToggle()}),e.addEventListener("keydown",o=>{o.key!=="ArrowDown"&&o.key!=="ArrowUp"||(o.preventDefault(),!(n()||e.getAttribute("aria-expanded")==="true")&&t.onToggle())}),e}function cb(t){let e=F("div",{className:"persona-history-menu",attrs:{role:"menu","aria-label":t.label}});for(let n of t.items){let o=F("button",{className:Gt("persona-history-menu-item",n.danger&&"persona-history-menu-item--danger"),text:n.label,attrs:{type:"button",role:"menuitem",tabindex:"0","data-persona-history-focus":n.focusKey}});o.addEventListener("click",()=>{t.onCloseMenu(),n.onSelect()}),e.appendChild(o)}return e.addEventListener("keydown",n=>{let o=Array.from(e.querySelectorAll('[role="menuitem"]'));if(o.length===0)return;let r=o.indexOf(document.activeElement);if(n.key==="Tab"){t.onCloseMenu({restoreFocus:!0});return}if(n.key==="ArrowDown"){n.preventDefault(),o[(r+1+o.length)%o.length]?.focus();return}if(n.key==="ArrowUp"){n.preventDefault(),o[(r-1+o.length)%o.length]?.focus();return}if(n.key==="Home"){n.preventDefault(),o[0]?.focus();return}n.key==="End"&&(n.preventDefault(),o[o.length-1]?.focus())}),e}function R1(t,e,n){let o=F("button",{className:"persona-history-secondary persona-history-state-action",text:e.retryLabel,attrs:{type:"button","data-persona-history-focus":`row-retry:${n}`}});return o.addEventListener("click",t.retry),F("div",{className:"persona-history-row-error",attrs:{role:"alert"}},F("span",{text:t.message}),o)}var E1,P1,L1,Qc,DE=be(()=>{"use strict";je();ab();ib();E1=/^(https?:|\/|data:)/i;P1=t=>`row:${t}`,L1=t=>`menu:${t}`,Qc=t=>`menu-item:${t}`});function H1(t){switch(t){case"authentication_failed":case"authentication_required":case"identity_provider_failed":case"proof_not_admitted":case"unsupported_scope":case"unavailable":return t;default:return"unknown"}}function OE(t){if(Gp(t)){if(t.code==="rate_limited")return{kind:"rate_limited",retryAfterSeconds:t.retryAfterSeconds??0};let e=H1(t.code);return{kind:"error",reason:e,retryable:e!=="unsupported_scope"}}return{kind:"error",reason:"unknown",retryable:!0}}function W1(t,e){switch(t.state){case"authentication_required":return{title:e.authenticationRequiredTitle,description:e.authenticationRequiredDescription};case"identity_provider_failed":return{title:e.identityProviderFailedTitle,description:e.identityProviderFailedDescription};case"configuration_error":return{title:e.proofNotAdmittedTitle,description:e.proofNotAdmittedDescription};default:return null}}function B1(t,e){switch(t){case"authentication_required":case"authentication_failed":return{title:e.authenticationRequiredTitle,description:e.authenticationRequiredDescription};case"identity_provider_failed":return{title:e.identityProviderFailedTitle,description:e.identityProviderFailedDescription};case"proof_not_admitted":case"unsupported_scope":return{title:e.proofNotAdmittedTitle,description:e.proofNotAdmittedDescription};case"unavailable":return{title:e.unavailableTitle,description:e.unavailableDescription};default:return{title:e.errorTitle,description:e.errorDescription}}}function Sm(t,e,n,o){let r=F("button",{className:"persona-history-secondary persona-history-state-action",text:t,attrs:{type:"button","data-persona-history-focus":e,...n?{"aria-disabled":"true"}:{}}});return r.addEventListener("click",()=>{n||o()}),r}function Xc(t,e,n,o,r){return F("div",{className:"persona-history-state",attrs:{"data-persona-history-state":t,...r?{role:"alert"}:{role:"status"}}},F("p",{className:"persona-history-state-title",text:e}),F("p",{className:"persona-history-state-description",text:n}),o)}function D1(t){let e=["42%","58%","34%"],n=["94%","78%","88%"],o=[0,1,2].map(r=>F("div",{className:"persona-history-skeleton-row",attrs:{"aria-hidden":"true"}},F("div",{className:"persona-history-skeleton-head"},F("div",{className:"persona-history-skeleton-bar persona-history-skeleton-bar--title",style:{width:e[r]}}),F("div",{className:"persona-history-skeleton-bar persona-history-skeleton-bar--time"})),F("div",{className:"persona-history-skeleton-bar persona-history-skeleton-bar--preview",style:{width:n[r]}})));return F("div",{className:"persona-history-view-loading",attrs:{"data-persona-history-state":"loading",role:"status","aria-label":t.loadingLabel}},...o)}function _E(t){let{state:e,copy:n,busy:o}=t;if(e.kind==="loading")return D1(n);if(e.kind==="empty"){let l=W1(t.identityStatus,n);return l?Xc("identity",l.title,l.description,t.onRetry?Sm(n.retryIdentityLabel,"state-retry",o,t.onRetry):null,!0):Xc("empty",n.emptyTitle,n.emptyDescription,null,!1)}if(e.kind==="rate_limited"){let l=e.retryAfterSeconds>0?wr(n.rateLimitedWaitDescription,{seconds:e.retryAfterSeconds}):n.rateLimitedDescription;return Xc("rate_limited",n.rateLimitedTitle,l,t.onRetry?Sm(n.retryLabel,"state-retry",o,t.onRetry):null,!1)}if(e.kind==="new_conversation_required")return Xc("new_conversation_required",n.newConversationRequiredTitle,n.newConversationRequiredDescription,t.onStartNew?Sm(n.newConversationLabel,"state-retry",o,t.onStartNew):null,!0);let{title:r,description:s}=B1(e.reason,n),a=e.reason==="authentication_required"||e.reason==="authentication_failed"||e.reason==="identity_provider_failed"?n.retryIdentityLabel:n.retryLabel;return Xc("error",r,s,e.retryable&&t.onRetry?Sm(a,"state-retry",o,t.onRetry):null,!0)}var NE=be(()=>{"use strict";je();Yc();Zl()});function Am(t){return`${t.state}:${"reason"in t?t.reason:""}`}function VE(t,e){switch(t.state){case"verified":return{title:e.verifiedTitle,description:e.verifiedDescription,pending:!1};case"verifying":case"resetting":return{title:e.verifyingTitle,description:e.verifyingDescription,pending:!0};case"authentication_required":return{title:e.authenticationRequiredTitle,description:e.authenticationRequiredDescription,pending:!1};case"identity_provider_failed":return{title:e.identityProviderFailedTitle,description:e.identityProviderFailedDescription,pending:!1};case"configuration_error":return{title:e.proofNotAdmittedTitle,description:e.proofNotAdmittedDescription,pending:!1};case"unavailable":return{title:e.unavailableTitle,description:e.unavailableDescription,pending:!1};default:return{title:e.browserOnlyTitle,description:e.browserOnlyDescription,pending:!1}}}function U1(t){return t.state==="verified"||t.state==="browser_only"}function q1(t){return t.state==="authentication_required"||t.state==="identity_provider_failed"||t.state==="configuration_error"}function db(t){let e=Gc(t.copy),n=t.now??(()=>Date.now()),o=t.pageSize??O1,r=`persona-history-title-${Math.random().toString(36).slice(2,8)}`,s=[],a=null,l={kind:"loading",phase:"initial"},c=null,p=t.activeConversationId,u=t.provider.getIdentityStatus(),m=Am(u),g=null,h=!1,b=!1,C=0,M=t.presentation,E=t.collapsible!==!1,T=t.collapsed===!0,H=t.railSide==="right",A=t.renderDom!==!1,D=new Map,W=null,U=kE(),B=z=>{!A&&t.onAnnounce?t.onAnnounce(z):U.announce(z)},O=()=>c!==null,R=`${r}-body`,S=F("button",{className:"persona-history-icon-button persona-history-back",attrs:{type:"button"}}),x=()=>M==="rail"&&E,P,L=()=>{if(t.railBrand){if(!x()){S.classList.remove("persona-history-back--branded");return}if(P===void 0){let z=t.railBrand(!0);P=z?F("span",{className:"persona-history-brand-mark persona-history-toggle-brand",attrs:{"aria-hidden":"true"}},z):null}P&&(S.classList.add("persona-history-back--branded"),S.appendChild(P))}},G=()=>{let z=x(),ge=M==="rail";S.setAttribute("data-persona-history-focus",z?"collapse":"close"),S.setAttribute("aria-label",z?T?e.expandLabel:e.collapseLabel:ge?e.closeLabel:e.backLabel),z?(S.setAttribute("aria-expanded",T?"false":"true"),S.setAttribute("aria-controls",R),t.collapseShortcut?.aria&&S.setAttribute("aria-keyshortcuts",t.collapseShortcut.aria)):(S.removeAttribute("aria-expanded"),S.removeAttribute("aria-controls"),S.removeAttribute("aria-keyshortcuts")),S.replaceChildren(Os(z?"panel-left":ge?"x":"arrow-left")),L()};G(),S.addEventListener("click",()=>{x()?t.onToggleCollapse?.():t.onClose()});let V=F("h2",{className:"persona-history-title",text:e.viewTitle,attrs:{id:r}}),K=F("span",{className:"persona-history-scope-title"}),ee=F("p",{className:"persona-history-scope"},F("span",{className:"persona-history-scope-icon",attrs:{"aria-hidden":"true"}},Os("monitor",14)),K),oe=F("div",{className:"persona-history-heading-group"},V),ne=!1,le,de=()=>{let z=M==="rail",ge=z?t.renderRailHeader:void 0,Ue=null,at=ge!==void 0;if(ge)try{Ue=ge({collapsed:T,defaultTitle:e.viewTitle})}catch(Ce){at=!1,ne||(ne=!0,console.warn("[persona] history rail renderHeader threw",Ce))}if(!at&&z&&t.railBrand){if(le===void 0){let Ce=t.railBrand(!1);le=Ce?F("span",{className:"persona-history-heading-brand",attrs:{"aria-hidden":"true"}},F("span",{className:"persona-history-brand-mark"},Ce),F("span",{className:"persona-history-wordmark",text:e.viewTitle})):null}le&&(at=!0,Ue=le)}V.classList.toggle("persona-history-sr-only",at),oe.replaceChildren(V),Ue&&oe.appendChild(Ue)};de();let ve=F("button",{className:"persona-history-icon-button persona-history-new-icon",attrs:{type:"button","data-persona-history-focus":"new-icon","aria-label":e.newConversationLabel}});ve.appendChild(Os("plus")),ve.addEventListener("click",()=>{we()});let Le=[S,ve].map(z=>t.attachTooltip?.({anchor:z,text:()=>z.getAttribute("aria-label")??"",...z===S&&t.collapseShortcut?{hint:()=>x()?t.collapseShortcut.hint:""}:{}})),se=F("div",{className:"persona-history-topbar"}),_=null,Te=()=>{let z=M==="rail",ge=z?H?"rail-right":"rail":"panel";ge!==_&&(_=ge,ge==="rail"?se.append(oe,S):se.append(S,oe),z?ve.remove():se.appendChild(ve),Y.classList.toggle("persona-history-view--rail-right",ge==="rail-right"))},He=F("div",{className:"persona-history-scope-alert"}),ut=`${r}-scope`,At=Os("plus",18),Wt=F("button",{className:"persona-history-new",attrs:{type:"button","data-persona-history-focus":"new"}},At,F("span",{text:e.newConversationLabel}));Wt.addEventListener("click",()=>{we()});let bt=F("div",{className:"persona-history-list-region"}),xe=t.showDeleteAll!==!1,Ne=!!t.provider.resetDevice,Ae=t.listActions??[],vt=xe||Ne||Ae.length>0?lb({className:"persona-history-list-options",label:e.listOptionsLabel,focusKey:`menu:${Vi}`,open:!1,inert:!0,iconSize:16,onToggle:()=>ot(Vi)}):null,X=F("h3",{className:"persona-history-conversations-title",text:e.conversationsTitle}),I=F("div",{className:"persona-history-caption",attrs:{"data-persona-history-item":Vi}},X,t.showScopeStatus?ee:null,vt),j=F("div",{className:"persona-history-body",attrs:{id:R}},t.showScopeStatus?He:null,Wt,I,bt),J=t.headerPlacement??"inline";J==="external"&&se.classList.add("persona-history-topbar--shell","persona-history-topbar--shell-enter");let Y=F("div",{className:Gt("persona-history-view",`persona-history-view--${t.presentation}`,"persona-history-view--enter"),attrs:{role:"region","aria-labelledby":r,"data-persona-history-presentation":t.presentation}},U.element,J==="inline"?se:null,j),ie=()=>{Y.classList.toggle("persona-history-view--rail-collapsed",T&&x())};ie(),Te();let Me=(z,ge)=>{let Ue=`${r}-s${ge}`,at=F("div",{className:Gt("persona-history-nav",z.placement==="footer"&&"persona-history-nav--footer"),attrs:{role:"group","data-persona-rail-section":z.id,...z.title?{"aria-labelledby":Ue}:{"aria-label":z.id}}});z.title&&at.appendChild(F("h3",{className:"persona-history-group-heading",text:z.title,attrs:{id:Ue}}));for(let Ce of z.items){let St=Ce.iconNode?.()??null,Bn=F("button",{className:Gt("persona-history-nav-item",St&&"persona-history-nav-item--icon"),attrs:{type:"button","aria-label":Ce.label,"data-persona-rail-item":Ce.id}},St?F("span",{className:"persona-history-nav-icon"},St):null,F("span",{className:"persona-history-nav-label persona-history-truncate",text:Ce.label}),Ce.badge?F("span",{className:"persona-history-nav-badge",text:Ce.badge}):null);Bn.addEventListener("click",()=>Ce.onSelect()),at.appendChild(Bn)}return at},Ee=null,Oe=null,Ct=()=>{!Ee||!A||M!=="rail"||T===Oe||(Oe=T,t.railSections.forEach((z,ge)=>{if(!z.render)return;let Ue=Ee[ge],at=z.title?Ue.firstElementChild:null,Ce=null;try{Ce=z.render(T)}catch(St){z.render=void 0,console.warn("[persona] history rail section threw",z.id,St)}Ue.replaceChildren(...at?[at]:[],...Ce?[Ce]:[]),Ue.hidden=!Ce}))},Ot=()=>{let z=t.railSections;if(Y.classList.toggle("persona-history-view--has-nav",M==="rail"&&!!z?.some(ge=>ge.placement==="above-conversations")),!!z?.length){if(M!=="rail"){Ee?.forEach(ge=>ge.remove());return}Ee??(Ee=z.map(Me));for(let ge of["above-conversations","below-conversations","footer"]){let Ue=ge==="above-conversations"?I.parentNode===j?I:bt:null;z.forEach((at,Ce)=>{at.placement===ge&&j.insertBefore(Ee[Ce],Ue)})}Ct()}};Ot(),mu(Y,"persona-history-view",LE);let rt=(z,ge)=>{let Ue=Y.ownerDocument.defaultView?.getComputedStyle(Y).getPropertyValue(z),at=Number.parseFloat(Ue??"");return Number.isFinite(at)&&at>=0?at:ge},Ze=(z,ge)=>Y.ownerDocument.defaultView?.getComputedStyle(Y).getPropertyValue(z).trim()||ge,ct=null,Rt=()=>{ct!==null&&(clearTimeout(ct),ct=null),Y.removeEventListener("animationend",Rt),Y.classList.remove("persona-history-view--enter")};Y.addEventListener("animationend",Rt),ct=setTimeout(()=>{ct=setTimeout(Rt,rt("--persona-history-enter-ms",_1)+60)},0);let Z=null,Fe=()=>{Z!==null&&(clearTimeout(Z),Z=null),se.classList.remove("persona-history-topbar--shell-enter")},Re=()=>{Fe(),se.classList.add("persona-history-topbar--shell-enter"),Z=setTimeout(Fe,FE+60)};J==="external"&&(Z=setTimeout(Fe,FE+60));let nt=[],Bt=null,Ie=()=>{if(Bt)return Bt;if(b||$1()||typeof Y.animate!="function")return Rt(),null;let z=Y.ownerDocument.defaultView?.getComputedStyle(j).opacity||"1";Rt(),Y.style.pointerEvents="none",qe.style.pointerEvents="none";let ge={duration:rt("--persona-history-exit-ms",N1),easing:Ze("--persona-history-exit-easing",F1),fill:"forwards"},Ue=V1[M];return nt=[j.animate([{opacity:z,transform:"none"},{opacity:0,transform:`translateX(${Ue}px)`}],ge)],Bt=Promise.all(nt.map(z1)).then(()=>{}),Bt},Be=(z,ge)=>{z&&(ge?z.setAttribute("aria-disabled","true"):z.removeAttribute("aria-disabled"))},qe=se,Tt=null,mt=()=>{let z=t.slots?.header;if(!z)return;let ge=`${M}|${Am(u)}|${c?`${c.kind}:${"conversationId"in c?c.conversationId:""}`:""}`;if(ge===Tt)return;Tt=ge;let Ue=z({identityStatus:u,pendingAction:c,copy:e,defaultRenderer:()=>se})??se;Ue!==qe&&(qe.replaceWith(Ue),qe=Ue)},xt=null,Mn=()=>{if(!t.showScopeStatus)return;let z=Am(u);if(z===xt)return;xt=z;let ge=VE(u,e);K.textContent=ge.title;let Ue=U1(u);if(ee.hidden=!Ue,He.replaceChildren(...Ue?[]:[F("span",{className:"persona-history-scope-alert-title",text:ge.title})],F("span",{className:"persona-history-scope-description",text:ge.description,attrs:{id:ut}})),He.setAttribute("data-persona-history-scope-tone",Ue?"ambient":"attention"),Ue?ee.setAttribute("aria-describedby",ut):ee.removeAttribute("aria-describedby"),ge.pending?He.setAttribute("role","status"):He.removeAttribute("role"),He.setAttribute("data-persona-history-identity",u.state),ee.setAttribute("data-persona-history-identity",u.state),q1(u)){let at=F("button",{className:"persona-history-secondary persona-history-state-action",text:e.retryIdentityLabel,attrs:{type:"button","data-persona-history-focus":"identity-retry"}});at.addEventListener("click",()=>{O()||We("refresh")}),He.appendChild(at)}},ft=z=>c?c.kind==="open"&&c.conversationId===z?"opening":c.kind==="delete"&&c.conversationId===z?"deleting":null:null,_t=()=>{let z=document.activeElement;return!(z instanceof HTMLElement)||!Y.contains(z)?null:z.getAttribute("data-persona-history-focus")},Vt=z=>{if(h&&g){h=!1;let ge=Y.querySelector(`[data-persona-history-focus="${Qc(g)}"]`);if(ge){ge.focus();return}}z&&Y.querySelector(`[data-persona-history-focus="${z}"]`)?.focus()},pn=()=>{if(!W)return null;let z=F("button",{className:"persona-history-secondary persona-history-state-action",text:e.retryLabel,attrs:{type:"button","data-persona-history-focus":"action-retry"}}),ge=W;return z.addEventListener("click",()=>{O()||ge.retry()}),F("div",{className:"persona-history-row-error",attrs:{role:"alert"}},F("span",{text:ge.message}),z)},ao=()=>RE(s,n(),e,t.grouping).map((z,ge)=>{let Ue=`${r}-g${ge}`,at=F("ul",{className:"persona-history-list",attrs:{"aria-labelledby":Ue}});for(let Ce of z.items){let St=()=>BE({conversation:Ce,active:Ce.id===p,pending:ft(Ce.id),busy:O(),menuOpen:g===Ce.id,error:D.get(Ce.id)??null,avatar:t.rowAvatar,showDelete:t.showDelete!==!1,nowMs:n(),copy:e,onOpen:()=>{Xo(Ce.id)},onToggleMenu:()=>ot(Ce.id),onCloseMenu:$e=>Nt($e),onDelete:()=>{lo(Ce.id)}}),Yn=t.slots?.conversation?.({conversation:Ce,active:Ce.id===p,pending:ft(Ce.id),open:()=>Xo(Ce.id),requestDelete:()=>lo(Ce.id),defaultRenderer:St})??St();at.appendChild(Yn instanceof HTMLLIElement?Yn:F("li",{className:"persona-history-item"},Yn))}return F("div",{className:"persona-history-group",attrs:{"data-persona-history-group":z.key}},F("h3",{className:Gt("persona-history-group-heading",z.key==="recent"&&"persona-history-sr-only"),text:z.label,attrs:{id:Ue}}),at)}),Gn=()=>{if(!a)return null;let z=c?.kind==="load-more"||l.kind==="loading"&&l.phase==="load-more",ge=F("button",{className:"persona-history-secondary persona-history-load-more",text:z?e.loadingMoreLabel:e.loadMoreLabel,attrs:{type:"button","data-persona-history-focus":"load-more",...z?{"aria-busy":"true","aria-disabled":"true"}:{},...O()&&!z?{"aria-disabled":"true"}:{}}});return ge.addEventListener("click",()=>{O()||We("load-more")}),ge},Zc=()=>{let z=_t(),ge=[pn()],Ue=s.length>0;if(Ue&&(ge.push(...ao()),ge.push(Gn())),l.kind!=="ready"&&!(l.kind==="loading"&&l.phase!=="initial"&&Ue)){let Ce=l,St=Ce.kind==="loading"?void 0:()=>We("refresh"),Bn=Ce.kind==="new_conversation_required"?()=>we():void 0,Yn=()=>_E({state:Ce,copy:e,identityStatus:u,busy:O(),...St?{onRetry:()=>{St()}}:{},...Bn?{onStartNew:()=>{Bn()}}:{}}),$e=t.slots?.state?.({state:Ce,identityStatus:u,copy:e,...St?{retry:St}:{},...Bn?{startNewConversation:Bn}:{},defaultRenderer:Yn});ge.push($e??Yn())}bt.replaceChildren(...ge.filter(Ce=>!!Ce)),Vt(z)},_s=()=>{let z=l.kind==="loading"&&s.length===0,ge=[],Ue=()=>ge.length===0?Qc(Vi):`${Qc(Vi)}-${ge.length}`;if(!z)for(let at of Ae)ge.push({label:at.label,focusKey:Ue(),danger:at.danger===!0,onSelect:()=>{at.onSelect({conversations:[...s]})}});return xe&&!(s.length===0&&(l.kind==="empty"||z))&&ge.push({label:e.clearHistoryLabel,focusKey:Ue(),danger:!0,onSelect:()=>{Ve()}}),Ne&&!z&&ge.push({label:e.resetIdentityLabel,focusKey:Ue(),danger:!0,onSelect:()=>{pt()}}),ge},Qo=()=>{if(Be(Wt,O()),Be(ve,O()),vt){let z=_s(),ge=l.kind==="loading"&&s.length===0;vt.hidden=z.length===0&&!ge,Be(vt,O()||z.length===0),vt.setAttribute("aria-expanded",g===Vi?"true":"false");let Ue=I.querySelector(".persona-history-menu");if(g!==Vi||z.length===0)Ue?.remove();else{let at=cb({label:e.listOptionsLabel,items:z,onCloseMenu:Ce=>Nt(Ce)});Ue?Ue.replaceWith(at):I.appendChild(at)}}I.hidden=M!=="rail"&&(!vt||vt.hidden)&&(!t.showScopeStatus||ee.hidden)},Cn,dt=()=>{let z=t.onActiveConversationChange;if(!z)return;let ge=s.find(at=>at.id===p)??null,Ue=ge?`${ge.id}\0${ge.title}\0${ge.starred?1:0}`:"";Ue!==Cn&&(Cn=Ue,z(ge))},Se=()=>{if(!b){if(dt(),!A){t.onModelChange?.();return}mt(),Mn(),Qo(),Zc(),Ct()}},Nt=z=>{if(!g)return;let ge=g;g=null,h=!1,Se(),z?.restoreFocus&&Y.querySelector(`[data-persona-history-focus="menu:${ge}"]`)?.focus()},ot=z=>{if(g===z){Nt({restoreFocus:!0});return}g=z,h=!0,Se()},Pe=z=>{if(!g)return;let ge=z.target;ge instanceof Node&&Y.contains(ge)&&ge.closest?.(`[data-persona-history-item="${g}"]`)||Nt()};document.addEventListener("pointerdown",Pe,!0);let pe=z=>{z.key!=="Escape"||!g||(z.stopPropagation(),Nt({restoreFocus:!0}))};Y.addEventListener("keydown",pe);async function We(z){if(b)return;let ge=++C,Ue=z==="load-more"?a:null;if(!(z==="load-more"&&!Ue)){c={kind:z==="load-more"?"load-more":"refresh"},l={kind:"loading",phase:z},z!=="load-more"&&(D.clear(),W=null),Nt(),Se();try{let at=await t.provider.list({limit:o,context:t.context,...Ue?{cursor:Ue}:{},...t.targetId?{targetId:t.targetId}:{}});if(b||ge!==C)return;s=Ue?[...s,...at.items]:at.items,a=at.nextCursor,l=s.length===0?{kind:"empty"}:{kind:"ready"}}catch(at){if(b||ge!==C)return;l=OE(at)}finally{!b&&ge===C&&(c=null,Se())}}}let Ns=z=>{s=s.filter(ge=>ge.id!==z),D.delete(z),p===z&&(p=null),s.length===0&&!a&&(l={kind:"empty"})};async function Xo(z){if(!(O()||b)){D.delete(z),Nt(),c={kind:"open",conversationId:z},Se();try{if(await t.onSelect(z),b)return;p=z}catch{if(b)return;D.set(z,{message:e.openFailedLabel,retry:()=>{Xo(z)}})}finally{b||(c=null,Se())}}}async function lo(z){if(O()||b)return"cancelled";D.delete(z),c={kind:"delete",conversationId:z},Se();try{let ge=await t.onRequestDeleteConversation(z);return b||ge==="deleted"&&(Ns(z),B(e.conversationRemovedNotice)),ge}catch(ge){return b||(Gp(ge)&&ge.code==="not_found"?Ns(z):D.set(z,{message:e.deleteFailedLabel,retry:()=>{lo(z)}})),"cancelled"}finally{b||(c=null,Se())}}async function we(){if(!(O()||b)){W=null,Nt(),c={kind:"start-new"},Se();try{if(await t.onStartNew(),b)return;l.kind==="new_conversation_required"&&(l=s.length===0?{kind:"empty"}:{kind:"ready"})}catch{if(b)return;W={message:e.errorDescription,retry:()=>{we()}}}finally{b||(c=null,Se())}}}async function Ve(){if(O()||b)return"cancelled";W=null,Nt(),c={kind:"clear"},Se();try{let z=await t.onRequestClearHistory();return b||z==="cleared"&&(s=[],a=null,p=null,l={kind:"empty"},B(e.historyClearedNotice)),z}catch{return b||(W={message:e.errorDescription,retry:()=>{Ve()}}),"cancelled"}finally{b||(c=null,Se())}}let Tn={outcome:"cancelled"};async function pt(){if(O()||b||!t.onRequestResetIdentity)return Tn;W=null,Nt(),c={kind:"reset"},Se();try{let z=await t.onRequestResetIdentity();return b||z.outcome==="reset"&&(B(z.remoteRevocationConfirmed?e.identityResetNotice:e.identityResetUnconfirmedNotice),c=null,await We("refresh")),z}catch{return b||(W={message:e.errorDescription,retry:()=>{pt()}}),Tn}finally{!b&&c?.kind==="reset"&&(c=null,Se())}}let gn=t.provider.subscribeIdentityStatus(z=>{if(b)return;let ge=Am(z),Ue=ge!==m;u=z,m=ge,Se(),Ue&&z.state!=="verifying"&&B(VE(z,e).title)}),km=t.provider.subscribeAvailability?.(z=>{if(!b){if(z){We("refresh");return}s=[],a=null,l={kind:"error",reason:"unavailable",retryable:!1},Se()}});return Se(),We("initial"),{element:Y,copy:e,getModel:()=>({conversations:s,activeConversationId:p,state:l,pendingAction:c,identityStatus:u,nextCursor:a}),operations:{refresh:async()=>{O()||await We("refresh")},loadMore:async()=>{O()||await We("load-more")},openConversation:z=>Xo(z),startNewConversation:()=>we(),requestDeleteConversation:z=>lo(z),requestClearConversationHistory:()=>Ve(),requestResetHistoryIdentity:()=>pt()},setDomRenderEnabled:z=>{z!==A&&(A=z,z&&Se())},refresh:()=>{We("refresh")},setPresentation:z=>{if(z===M)return;Rt(),M=z,Tt=null;let ge=z==="rail";Y.classList.toggle("persona-history-view--panel",!ge),Y.classList.toggle("persona-history-view--rail",ge),Y.setAttribute("data-persona-history-presentation",z),G(),ie(),Te(),de(),Ot(),Se()},setCollapsed:z=>{z!==T&&(T=z,ie(),G(),de(),Ct())},setRailSide:z=>{H=z==="right",Te()},getHeaderElement:()=>qe,setHeaderPlacement:z=>{if(z===J)return;J=z;let ge=z==="external";if(se.classList.toggle("persona-history-topbar--shell",ge),ge){Re(),qe.remove();return}Fe(),Y.insertBefore(qe,j)},setActiveConversationId:z=>{p!==z&&(p=z,Se())},applyConversationSummary:z=>{let ge=s.findIndex(Ue=>Ue.id===z.id);ge!==-1&&(s[ge]=z,Se())},removeConversationSummary:z=>{s.some(ge=>ge.id===z)&&(Ns(z),Se())},setNewConversationRequired:z=>{z?l={kind:"new_conversation_required"}:l.kind==="new_conversation_required"&&(l=s.length===0?{kind:"empty"}:{kind:"ready"}),Se()},playExit:Ie,destroy:()=>{b=!0,C+=1,Rt(),Fe(),Le.forEach(z=>z?.destroy()),qe.remove(),nt.forEach(z=>z.cancel()),nt=[],gn(),km?.(),document.removeEventListener("pointerdown",Pe,!0),Y.removeEventListener("keydown",pe),U.destroy(),Y.remove(),Y.replaceChildren()}}}var O1,Vi,_1,FE,N1,F1,V1,$1,z1,$E=be(()=>{"use strict";Oa();je();PE();IE();Yc();ib();ab();DE();NE();Zl();O1=25,Vi="persona:list-options",_1=180,FE=120,N1=160,F1="cubic-bezier(0.4, 0, 1, 1)",V1={panel:20,rail:12},$1=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,z1=t=>t.finished?t.finished.then(()=>{},()=>{}):Promise.resolve()});var pb=be(()=>{"use strict";$E();Yc()});var zE={};$n(zE,{HISTORY_VIEW_COPY_DEFAULTS:()=>Kc,createHistoryView:()=>db,resolveHistoryViewCopy:()=>Gc});var UE=be(()=>{"use strict";pb();pb()});var kD={};$n(kD,{createThemePreview:()=>h0});module.exports=WP(kD);var Tp=require("lucide");zn();var uw=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function jo(t,e){if(!t)return e;if(!e)return t;let n={...t};for(let[o,r]of Object.entries(e)){let s=n[o];uw(s)&&uw(r)?n[o]=jo(s,r):n[o]=r}return n}var fg=Symbol("persona.defaultsProvenance"),gg=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function up(t,e=""){return Object.entries(t).flatMap(([n,o])=>{let r=e?`${e}.${n}`:n;return gg(o)?up(o,r):[r]})}function mw(t,e){for(let n of e.split(".")){if(!gg(t)||!Object.prototype.hasOwnProperty.call(t,n))return"absent";if(t=t[n],t===void 0)return"clear"}return"explicit"}function fw(t,e){return t?.[fg]??e.filter(n=>mw(t,n)==="explicit")}function hg(t,e){return Object.defineProperty(t,fg,{value:e,enumerable:!0,configurable:!0}),t}function yg(t,e,n){return hg(t,fw(e,up(n)))}function gw(t,e,n){let o=e[fg];if(o)return o;let r=new Set(fw(t,n));for(let s of n){let a=mw(e,s);a==="clear"&&r.delete(s),a==="explicit"&&r.add(s)}return[...r]}function hw(t,e,n){let o={...t};for(let r of e){if(n.includes(r))continue;let s=r.split("."),a=o;for(let l of s.slice(0,-1)){let c=a[l];if(!gg(c)){a=void 0;break}a[l]={...c},a=a[l]}a&&delete a[s[s.length-1]]}return o}var yw="var(--persona-components-panel-width)",bg=Symbol("persona.panelAliasProvenance"),vi=(t,e)=>t!=null&&Object.prototype.hasOwnProperty.call(t,e),mp=(t,e)=>vi(t,e)&&t[e]!==void 0,BP=t=>({launcherWidth:mp(t?.launcher,"width"),legacyLauncherWidth:mp(t,"launcherWidth"),sidebarWidth:mp(t?.launcher,"sidebarWidth"),dockWidth:mp(t?.launcher?.dock,"width")}),Nr=t=>{let e=t?.[bg];return e?{...e}:BP(t)},vg=(t,e)=>(Object.defineProperty(t,bg,{value:e,enumerable:!0,configurable:!0}),t),Cg=(t,e)=>vg(t,Nr(e)),bw=(t,e)=>{let n=e[bg];if(n)return{...n};let o=Nr(t);return vi(e,"launcherWidth")&&(o.legacyLauncherWidth=e.launcherWidth!==void 0),vi(e,"launcher")&&e.launcher===void 0?(o.launcherWidth=!1,o.sidebarWidth=!1,o.dockWidth=!1,o):(vi(e.launcher,"width")&&(o.launcherWidth=e.launcher?.width!==void 0),vi(e.launcher,"sidebarWidth")&&(o.sidebarWidth=e.launcher?.sidebarWidth!==void 0),vi(e.launcher,"dock")&&e.launcher?.dock===void 0?o.dockWidth=!1:vi(e.launcher?.dock,"width")&&(o.dockWidth=e.launcher?.dock?.width!==void 0),o)};var wg="min(440px, calc(100vw - 24px))";var Fl="40px",xg="How can I help...",Fr={collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",previewMaxLines:3,expandable:!0,loadingAnimation:"none"},wi={activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},DP={enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:wg,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:Fl,closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},OP={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",tooltip:{delayMs:200,skipDelayMs:300},launcher:DP,copy:{inputPlaceholder:xg,sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",borderWidth:"0px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"anchor-top",anchorTopOffset:16,showActivityWhilePinned:!0},toolCallDisplay:Fr,reasoningDisplay:wi,streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"},history:{enabled:!1,presentation:"panel",showScopeStatus:!0,showDelete:!0,showDeleteAll:!0}},suggestionChips:["Show me what you can help with","Walk me through getting started","Answer a question about this page"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1},_P={},NP={variant:"circle",width:"min(400px, calc(100vw - 24px))",headerIconSize:"20px"},Ci={launcher:NP,features:{toolCallDisplay:{variant:"row",iconVisibility:"active",autoExpand:!1,grouped:!0,groupedMode:"collapsible",loadingAnimation:"shimmer"},reasoningDisplay:{variant:"row",iconVisibility:"active",autoExpand:!1,loadingAnimation:"shimmer"}},composer:{layout:"single-row",placement:"overlay"},sendButton:{iconName:"arrow-up"},statusIndicator:{mode:"transient"},layout:{contentMaxWidth:"768px",topFade:!0,header:{showSubtitle:!1},messages:{assistant:{width:"full"}}}};function bs(t){return t?.future?.v5Defaults===!0?"v5":"v4"}function fp(t){let e=bs(t)==="v5"?Ci:_P;return jo(OP,e)}var UD=fp();function vw(t,e){if(!(!t&&!e))return t?e?jo(t,e):t:e}function gp(t){let e=fp(t);return t?yg(Cg({...e,...t,theme:vw(e.theme,t.theme),darkTheme:vw(e.darkTheme,t.darkTheme),launcher:{...e.launcher,...t.launcher,dock:{...e.launcher?.dock,...t.launcher?.dock},clearChat:{...e.launcher?.clearChat,...t.launcher?.clearChat}},...e.composer||t.composer?{composer:{...e.composer,...t.composer}}:{},tooltip:{...e.tooltip,...t.tooltip},copy:{...e.copy,...t.copy},sendButton:{...e.sendButton,...t.sendButton},statusIndicator:{...e.statusIndicator,...t.statusIndicator},voiceRecognition:{...e.voiceRecognition,...t.voiceRecognition},features:(()=>{let n=e.features?.artifacts,o=t.features?.artifacts,r=e.features?.scrollToBottom,s=t.features?.scrollToBottom,a=e.features?.scrollBehavior,l=t.features?.scrollBehavior,c=e.features?.streamAnimation,p=t.features?.streamAnimation,u=e.features?.askUserQuestion,m=t.features?.askUserQuestion,g=e.features?.history,h=t.features?.history,b=n===void 0&&o===void 0?void 0:{...n,...o,layout:{...n?.layout,...o?.layout}},C=r===void 0&&s===void 0?void 0:{...r,...s},M=a===void 0&&l===void 0?void 0:{...a,...l},E=c===void 0&&p===void 0?void 0:{...c,...p},T=u===void 0&&m===void 0?void 0:{...u,...m,styles:{...u?.styles,...m?.styles}},H=g===void 0&&h===void 0?void 0:{...g,...h,copy:{...g?.copy,...h?.copy}};return{...e.features,...t.features,toolCallDisplay:{...e.features?.toolCallDisplay,...t.features?.toolCallDisplay},reasoningDisplay:{...e.features?.reasoningDisplay,...t.features?.reasoningDisplay},...C!==void 0?{scrollToBottom:C}:{},...M!==void 0?{scrollBehavior:M}:{},...b!==void 0?{artifacts:b}:{},...E!==void 0?{streamAnimation:E}:{},...T!==void 0?{askUserQuestion:T}:{},...H!==void 0?{history:H}:{}}})(),suggestionChips:t.suggestionChips??e.suggestionChips,suggestionChipsConfig:{...e.suggestionChipsConfig,...t.suggestionChipsConfig},layout:{...e.layout,...t.layout,header:{...e.layout?.header,...t.layout?.header},messages:{...e.layout?.messages,...t.layout?.messages,...e.layout?.messages?.user||t.layout?.messages?.user?{user:{...e.layout?.messages?.user,...t.layout?.messages?.user}}:{},...e.layout?.messages?.assistant||t.layout?.messages?.assistant?{assistant:{...e.layout?.messages?.assistant,...t.layout?.messages?.assistant}}:{},avatar:{...e.layout?.messages?.avatar,...t.layout?.messages?.avatar},timestamp:{...e.layout?.messages?.timestamp,...t.layout?.messages?.timestamp}},slots:{...e.layout?.slots,...t.layout?.slots}},markdown:{...e.markdown,...t.markdown,options:{...e.markdown?.options,...t.markdown?.options}},messageActions:{...e.messageActions,...t.messageActions}},t),t,Ci):yg(Cg(e),void 0,Ci)}je();Zt();je();var Cp=require("lucide");zn();var YP=["persona-w-full","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"],QP="persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none",XP="persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none",JP=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),wp=(t,e)=>{let n=v("div",["persona-message-bubble",t,...YP].join(" "));return n.id=`bubble-${e}`,n.setAttribute("data-message-id",e),n},xp=t=>{let e=v("button",t.expandable?QP:XP);return e.type="button",t.expandable&&(e.setAttribute("aria-expanded",t.expanded?"true":"false"),e.setAttribute("data-expand-header","true")),e.setAttribute("data-bubble-type",t.bubbleType),e},Tg=(t,e,n)=>{t.innerHTML="";let o=Ge(e?Cp.ChevronUp:Cp.ChevronDown,16,n,2);o?t.appendChild(o):t.textContent=e?"Hide":"Show"},wa=(t,e,n)=>{if(!n.expandable)return t.append(e),null;let o=v("div","persona-flex persona-items-center");Tg(o,n.expanded,n.iconColor);let r=v("div",n.metaGap?"persona-flex persona-items-center persona-gap-2 persona-ml-auto":"persona-flex persona-items-center persona-ml-auto");return r.append(o),t.append(e,r),o},Sp=t=>{let e=v("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(e.setAttribute("data-persona-collapsed-preview",t.previewKind),e.style.display="none",e.style.whiteSpace="pre-wrap",!t.expanded&&t.isActive&&t.activePreview&&t.previewText){let n=t.renderPreview?.();JP(e,n)||(e.textContent=t.previewText),e.style.display=""}return!t.expanded&&t.isActive&&t.activeMinHeight&&(t.bubble.style.minHeight=t.activeMinHeight),e},Ap=t=>{t.header.setAttribute("aria-expanded",t.expanded?"true":"false"),t.toggleIcon&&Tg(t.toggleIcon,t.expanded,t.iconColor),t.content.style.display=t.expanded?"":"none",t.collapsedPreview.style.display=t.expanded?"none":t.collapsedPreview.textContent||t.collapsedPreview.childNodes.length?"":"none"},Mp=(t,e,n)=>{let o=n.stateSet.has(t),r=e.querySelector('button[data-expand-header="true"]'),s=e.querySelector(".persona-border-t"),a=e.querySelector(`[data-persona-collapsed-preview="${n.previewKind}"]`);if(!r||!s)return;r.setAttribute("aria-expanded",o?"true":"false");let c=r.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");c&&Tg(c,o,n.iconColor),s.style.display=o?"":"none",a&&(a.style.display=o?"none":a.textContent||a.childNodes.length?"":"none")};function Ep(t,e){let n=e==="tool"?"toolCallDisplay":"reasoningDisplay";return{...t,features:{...t?.features,[n]:{...e==="tool"?Fr:wi,...t?.future?.v5Defaults===!0?Ci.features?.[n]:{},...t?.features?.[n]}}}}function vs(t,e){let n=e==="tool"?"toolCallDisplay":"reasoningDisplay";return t?.features?.[n]?.variant??(t?.future?.v5Defaults?"row":"card")}function Vl(t){let e=Math.max(0,Math.floor((t??0)/1e3));return e<1?"a moment":e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function Vr(t,e,n,o){if(vs(n,o)!=="row")return t;t.className=`persona-message-bubble persona-${o}-bubble persona-activity-row`,t.dataset.activityKind=o,o==="tool"&&n.toolCall?.shadow===void 0&&(t.style.boxShadow="var(--persona-tool-bubble-shadow, none)");let r=t.querySelector(":scope > button");if(!r)return t;r.className="persona-activity-header";let s=o==="tool"?e.toolCall:e.reasoning,a=s?.status!=="complete",l=e.approval?.status??e.toolCall?.approvalStatus,c=l==="denied"?"denied":l==="pending"?"awaiting-approval":e.toolCall?.success===!1?"error":a?s?.status==="pending"?"pending":"running":"done";t.dataset.activityState=c;let p=v("span","persona-activity-icon");p.dataset.activityIcon=c;let u={pending:"circle",running:"loader-circle",done:"check",error:"x",denied:"x","awaiting-approval":"clock"},m=o==="reasoning"?n.features?.reasoningDisplay?.iconName:void 0,g=m?ke(m,16,"currentColor",2):c==="pending"?Ge(Tp.Circle,16,"currentColor",2):c==="awaiting-approval"?Ge(Tp.Clock,16,"currentColor",2):ke(u[c],16,"currentColor",2);g&&p.appendChild(g),r.querySelector(".persona-reasoning-header-icon")?.remove();let h=o==="tool"?"toolCallDisplay":"reasoningDisplay",b=n.features?.[h]?.iconVisibility??(n.future?.v5Defaults?"active":"always");if((b==="always"||b==="active"&&c!=="done")&&r.prepend(p),o==="tool"&&s){let T=v("span","persona-activity-duration");a&&s.startedAt&&T.setAttribute("data-tool-elapsed",String(s.startedAt));let H=(o==="tool"?e.toolCall?.duration:void 0)??s.durationMs??(s.completedAt!==void 0&&s.startedAt!==void 0?s.completedAt-s.startedAt:void 0);T.textContent=H===void 0?"":Vl(H),r.appendChild(T)}r.querySelector(":scope > div:not(.persona-ml-auto)")?.classList.add("persona-activity-label"),r.querySelector(".persona-ml-auto")?.classList.add("persona-activity-chevron");let E=t.querySelector(":scope > .persona-border-t");return E?.classList.add("persona-activity-body"),E&&(E.id=`activity-details-${e.id}`,r.setAttribute("aria-controls",E.id)),t}function Aw(t){let e=new Set,n=new Set,o=new Set,r=new Map,s=a=>{clearTimeout(r.get(a)),r.delete(a)};return{observe(a,l,c,p={}){let u=l==="tool"?a.toolCall:a.reasoning;if(!(!u||n.has(a.id))&&(!e.has(a.id)&&u.status!=="complete"&&u.chunks?.some(Boolean)&&(e.add(a.id),p.autoExpand!==!1&&c.add(a.id)),e.has(a.id)&&u.status==="complete"&&!o.has(a.id))){if(o.add(a.id),p.autoCollapseDelay===!1)return;r.set(a.id,setTimeout(()=>{r.delete(a.id),c.delete(a.id),t(a.id,l)},p.autoCollapseDelay??1e3))}},manual(a){n.add(a),s(a)},prune(a){for(let l of new Set([...e,...n,...o]))a.has(l)||(s(l),e.delete(l),n.delete(l),o.delete(l))},clear(){for(let a of r.keys())s(a);e.clear(),n.clear(),o.clear()}}}function Mw(t,e,n,o){let r=v("div","");r.id=`bubble-${t.id}`,r.dataset.messageId=t.id;let s=v("button","");s.type="button",s.dataset.expandHeader="true",s.dataset.bubbleType="tool",s.setAttribute("aria-expanded",String(n));let a=v("div","");typeof o=="string"?a.textContent=o:a.appendChild(o),wa(s,a,{expandable:!0,expanded:n,iconColor:e.toolCall?.toggleTextColor||e.toolCall?.headerTextColor||"currentColor",metaGap:!0});let l=v("div","persona-border-t");return l.id=`activity-details-${t.id}`,l.style.display=n?"":"none",s.setAttribute("aria-controls",l.id),r.append(s,l),Vr(r,t,{...e,features:{...e.features,toolCallDisplay:{...e.features?.toolCallDisplay,variant:"row"}}},"tool"),r.dataset.personaToolGroup="true",e.features?.toolCallDisplay?.loadingAnimation==="shimmer"&&(r.dataset.activityGroupShimmer="true"),{bubble:r,body:l}}var ZP=(t,e)=>t.visible!==!1&&(t.mode!=="transient"||e==="connecting"||e==="paused"||e==="resuming"||e==="error"),xi=(t,e,n)=>{let o=e.mode==="transient",r=t.hasAttribute("data-persona-composer-reason")||t.hasAttribute("data-persona-composer-notice");t.style.display=ZP(e,n)||o&&r&&e.visible!==!1?"":"none",t.classList.toggle("persona-mt-2",!o),t.classList.toggle("persona-mb-2",o)},Eg=(t,e,n)=>{!e.parentElement||t.parentElement!==e.parentElement||(n.mode==="transient"?t.nextElementSibling!==e&&e.before(t):e.nextElementSibling!==t&&e.after(t))};function Tw(t,e){let n=t.voiceRecognition,o=e.voiceRecognition;return n?.enabled===!0!=(o?.enabled===!0)||n?.provider?.type!==o?.provider?.type||n?.provider?.custom!==o?.provider?.custom||n?.provider?.runtype?.createPlaybackEngine!==o?.provider?.runtype?.createPlaybackEngine||JSON.stringify(n?.provider?.runtype)!==JSON.stringify(o?.provider?.runtype)||t.agentId!==e.agentId||t.clientToken!==e.clientToken||t.apiUrl!==e.apiUrl}function so(t){return t?.type==="runtype"||t?.type==="custom"}var eL=()=>typeof window<"u"&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window);function Ew(t){try{if(t?.type==="custom"&&t.custom){let e=t.custom,n=typeof e=="function"?e():e;return!!n&&typeof n.startListening=="function"}return t?.type==="runtype"&&t.runtype?!0:eL()}catch{return!1}}Lp();Ig();var Ww=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Bw=t=>t.includes("|"),Dw=t=>{let e=t.trim();return e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&(e=e.slice(0,-1)),e.split("|").map(n=>n.trim())},aL=t=>`| ${t.join(" | ")} |`,lL=t=>`| ${Array.from({length:t},()=>"---").join(" | ")} |`,cL=(t,e)=>t.length>=e?t.slice(0,e):t.concat(Array.from({length:e-t.length},()=>"")),Ow=t=>{if(!t||!t.includes("|"))return t;let e=t.split(`
|
|
1141
|
-
`),n=!1;for(let o=0;o<e.length-1;o++){let r=e[o],s=e[o+1];if(!
|
|
1142
|
-
`):t};var _w="var(--persona-md-table-scroll-fade, 24px)",Nw=new WeakSet;function Vw(t){t.querySelectorAll("table").forEach(n=>{if(n.parentElement?.classList.contains("persona-table-scroll"))return;let r=document.createElement("div");r.className="persona-table-scroll",n.replaceWith(r),r.appendChild(n)})}function Fw(t){let e=t.scrollWidth-t.clientWidth;if(e<=1){t.removeAttribute("data-persona-scroll-x");return}t.setAttribute("data-persona-scroll-x","");let o=getComputedStyle(t).direction==="rtl"?e+t.scrollLeft:t.scrollLeft,r=e-o;t.style.setProperty("--persona-fade-l",o<=1?"0px":_w),t.style.setProperty("--persona-fade-r",r<=1?"0px":_w)}function Rg(t){Nw.has(t)||(Nw.add(t),t.addEventListener("scroll",e=>{let n=e.target;n?.classList?.contains("persona-table-scroll")&&Fw(n)},!0)),t.querySelectorAll(".persona-table-scroll").forEach(Fw)}Si();Aa();ro();var{setLoader:MO,load:wL}=Qt({fallbackImport:()=>Promise.resolve().then(()=>(Qw(),Yw))});var Xw=wL;function Ho(t){return t==="card"?"collapsed":t}function Ma(t){return t.split(";",1)[0].trim().toLowerCase()}function xL(t,e){if(!t)return;let n=Object.entries(t);for(let[r,s]of n)if(Ma(r)===e)return{mode:Ho(s),selector:Ma(r)};let o=`${e.split("/",1)[0]}/*`;for(let[r,s]of n)if(Ma(r)===o)return{mode:Ho(s),selector:o}}function SL(t,e){let n=t?.display,o=typeof n=="string"?{default:n}:n??{};if(e.file&&o.files){if(typeof o.files=="string")return{mode:Ho(o.files),matchedBy:{type:"files"}};let l=e.file.mimeType?Ma(e.file.mimeType):void 0,c=l?xL(o.files.byMediaType,l):void 0;if(l&&c)return{mode:c.mode,matchedBy:{type:"mediaType",mediaType:l,selector:c.selector}};if(o.files.default)return{mode:Ho(o.files.default),matchedBy:{type:"files"}}}let r=o.byKind?.[e.artifactType];if(r)return{mode:Ho(r),matchedBy:{type:"kind",kind:e.artifactType,configuredBy:"byKind"}};let s=o.byType?.[e.artifactType];if(s)return{mode:Ho(s),matchedBy:{type:"kind",kind:e.artifactType,configuredBy:"byType"}};let a=e.presentation?.preferredMode;return a?{mode:Ho(a),matchedBy:{type:"preferredMode"}}:o.default?{mode:Ho(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function Cs(t,e){return SL(t,e).mode}function $l(t,e){return JSON.stringify({component:t==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:e.artifactId,title:e.title,artifactType:e.artifactType,status:e.status,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{},...t==="inline"&&e.component?{component:e.component}:{},...t==="inline"&&e.componentProps?{componentProps:e.componentProps}:{},...e.markdown!==void 0?{markdown:e.markdown}:{}}})}var AL="agent_",ML="flow_";function Jw(t){return t.startsWith(AL)?{kind:"agentId",agentId:t}:t.startsWith(ML)?{kind:"flowId",flowId:t}:null}function Zw(t,e){let n=t.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let a=n.slice(0,o),l=n.slice(o+1);if(a==="runtype"){let p=Jw(l);if(p)return p;throw new Error(`[Persona] target "runtype:${l}" is not a valid Runtype agent_/flow_ id.`)}let c=e?.[a];if(!c)throw new Error(`[Persona] No target provider registered for "${a}". Add a \`targetProviders.${a}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:c(l).payload}}let r=Jw(n);if(r)return r;let s=e?.default;if(s)return{kind:"payload",payload:s(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}function Dp(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${t}_${e}`}function Ta(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${t}_${e}`}function ex(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`turn_${t}_${e}`}var ws=require("partial-json");je();var Wg="ask_user_question",zl=8,Ea="data-persona-ask-sheet-for",TL="Other",EL="Other\u2026",nx="Type your own answer here",ox="Send",kL="Next",PL="Back",LL="Submit all",IL="Skip",RL=3,Bg="data-ask-current-index",Dg="data-ask-question-count",rx="data-ask-answers",Og="data-ask-grouped",sx="data-ask-layout",HL=t=>t.layout==="pills"?"pills":"rows",WL=t=>t.getAttribute(sx)==="pills"?"pills":"rows",tx=!1,ix=t=>t.replace(/["\\]/g,"\\$&"),Ai=t=>t.variant==="tool"&&!!t.toolCall&&t.toolCall.name===Wg,_g=t=>t?.features?.askUserQuestion??{},ka=t=>{let e=t.toolCall;if(!e)return{payload:null,complete:!1};let n=e.status==="complete";if(e.args&&typeof e.args=="object")return{payload:e.args,complete:n};let o=e.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=(0,ws.parse)(r,ws.STR|ws.OBJ|ws.ARR);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},Ul=t=>{let e=Array.isArray(t?.questions)?t.questions:[];return e.length>zl&&!tx&&(tx=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${zl}.`)),e.slice(0,zl)},BL=t=>Ul(t)[0]??null,DL=(t,e)=>Ul(t)[e]??null,OL=(t,e)=>{let n=e.styles;n&&(n.sheetBackground&&t.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&t.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&t.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&t.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&t.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&t.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&t.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&t.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&t.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},ax=(t,e,n)=>{if(t!=="rows")return null;let o=v("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),e){let r=v("span","persona-ask-row-check");o.appendChild(r)}else{let r=v("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},_L=(t,e,n,o)=>{let s=v("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",o?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(e)),s.setAttribute("data-option-label",t.label),n==="rows"){let a=v("span","persona-ask-row-content"),l=v("span","persona-ask-row-label");if(l.textContent=t.label,a.appendChild(l),t.description){let p=v("span","persona-ask-row-description");p.textContent=t.description,a.appendChild(p)}s.appendChild(a);let c=ax(n,o,e);c&&s.appendChild(c)}else s.textContent=t.label,t.description&&(s.title=t.description);return s},NL=t=>{let n=v("span",t==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},FL=(t,e,n,o)=>{let s=v("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!t?.multiSelect,c=(Array.isArray(t?.options)?t.options:[]).filter(u=>u&&typeof u.label=="string"&&u.label.length>0);if(c.length===0&&!n){for(let u=0;u<RL;u++)s.appendChild(NL(o));return s}if(c.forEach((u,m)=>{s.appendChild(_L(u,m,o,a))}),t?.allowFreeText!==!1){let u=o==="rows"?TL:EL;if(o==="rows"){let m=v("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");m.setAttribute("data-ask-user-action","focus-free-text"),m.setAttribute("data-option-index",String(c.length)),m.setAttribute("data-ask-other-row","true");let g=v("span","persona-ask-row-content"),h=document.createElement("input");h.type="text",h.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",h.placeholder=e.freeTextPlaceholder??nx,h.setAttribute("data-ask-free-text-input","true"),h.setAttribute("aria-label",e.freeTextLabel??u),g.appendChild(h),m.appendChild(g);let b=ax(o,a,c.length);b&&m.appendChild(b),s.appendChild(m)}else{let m=v("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");m.type="button",m.setAttribute("data-ask-user-action","open-free-text"),m.textContent=e.freeTextLabel??u,s.appendChild(m)}}return s},lx=(t,e)=>{let o=v("div",e==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");o.setAttribute("data-ask-free-text-row","true");let r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=t.freeTextPlaceholder??nx,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),e!=="rows"){let s=v("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=t.submitLabel??ox,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},VL=t=>{let e=v("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");e.setAttribute("data-ask-multi-actions","true");let n=v("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=t.submitLabel??ox,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,e.appendChild(n),e},$L=(t,e,n)=>{let o=v("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let r=v("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??PL,r.setAttribute("data-ask-user-action","back"),r.disabled=t===0,o.appendChild(r);let s=v("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=v("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=n.skipLabel??IL,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let l=v("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let c=t===e-1;return l.textContent=c?n.submitAllLabel??LL:n.nextLabel??kL,l.setAttribute("data-ask-user-action",c?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},Mi=t=>{let e=t.getAttribute(rx);if(!e)return{};try{let n=JSON.parse(e);return n&&typeof n=="object"?n:{}}catch{return{}}},cx=(t,e)=>{t.setAttribute(rx,JSON.stringify(e))},Wo=t=>{let e=Number(t.getAttribute(Bg)??"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},zL=(t,e)=>{t.setAttribute(Bg,String(Math.max(0,Math.floor(e))))},Pa=t=>{let e=Number(t.getAttribute(Dg)??"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},xs=t=>t.getAttribute(Og)==="true",UL=(t,e)=>{let n=t.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return e.forEach((r,s)=>{let a=typeof r?.question=="string"?r.question:"";if(a&&Object.prototype.hasOwnProperty.call(n,a)){let l=n[a];(typeof l=="string"||Array.isArray(l))&&(o[s]=l)}}),o},qL=(t,e)=>{let n=t.agentMetadata?.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(e-1,Math.floor(n)))},Op=(t,e)=>{let{payload:n}=ka(e),o=Ul(n),r=Mi(t),s={},a=new Set;return o.forEach((l,c)=>{let p=typeof l?.question=="string"?l.question:"";p&&(a.has(p)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${p}"; later answer wins.`),a.add(p),Object.prototype.hasOwnProperty.call(r,c)&&(s[p]=r[c]))}),s},dx=t=>{let e=Mi(t),n=Wo(t),o=e[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(c=>r.add(c));let s=t.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(c=>{let p=c.getAttribute("data-option-label")??"",u=r.has(p);c.setAttribute("aria-pressed",u?"true":"false"),c.classList.toggle("persona-ask-pill-selected",u)});let a=new Set(Array.from(s).map(c=>c.getAttribute("data-option-label")??"")),l=t.querySelector('[data-ask-free-text-input="true"]');l&&(typeof o=="string"&&o.length>0&&!a.has(o)?(l.value=o,l.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):l.value="")},px=t=>{if(!xs(t))return;let e=Mi(t),n=Wo(t),o=e[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=t.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);let a=t.querySelector('[data-ask-user-action="submit-multi"]');if(a){let l=Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=l.length===0}},Ng=(t,e,n)=>{let o=_g(n),r=WL(t),{payload:s,complete:a}=ka(e),l=xs(t),c=Wo(t),p=Pa(t),u=l?DL(s,c):BL(s),m=!!u?.multiSelect,g=t.querySelector('[data-ask-step-inline="true"]');g&&(g.textContent=l?`${c+1}/${p}`:"");let h=t.querySelector('[data-ask-stepper="true"]');h&&h.remove();let b=t.querySelector('[data-ask-question="true"]');if(b){let T=typeof u?.question=="string"?u.question:"";b.textContent=T,b.classList.toggle("persona-ask-question-skeleton",!T&&!a)}let C=t.querySelector('[data-ask-pill-list="true"]');if(C){let T=FL(u,o,a,r);C.replaceWith(T)}if(r!=="rows"){let T=t.querySelector('[data-ask-free-text-row="true"]');T&&T.replaceWith(lx(o,r))}let M=t.querySelector('[data-ask-multi-actions="true"]');!l&&m&&!M?t.appendChild(VL(o)):(!m||l)&&M&&M.remove(),t.setAttribute("data-multi-select",m?"true":"false");let E=t.querySelector('[data-ask-nav-row="true"]');if(l){let T=$L(c,p,o);E?E.replaceWith(T):t.appendChild(T)}else E&&E.remove();dx(t),px(t)},jL=(t,e,n)=>{let o=_g(e),r=HL(o),s=t.toolCall.id,a=Ul(n),l=Math.max(1,a.length),c=l>1,p=UL(t,a),u=c?qL(t,l):0,m=v("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));m.setAttribute(Ea,s),m.setAttribute("data-tool-call-id",s),m.setAttribute("data-message-id",t.id),m.setAttribute(Dg,String(l)),m.setAttribute(Bg,String(u)),m.setAttribute(Og,c?"true":"false"),m.setAttribute(sx,r),cx(m,p),m.setAttribute("role","group"),m.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&m.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),OL(m,o);let g=v("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),h=v("div","persona-ask-sheet-question persona-flex-1");h.setAttribute("data-ask-question","true"),h.textContent="",g.appendChild(h);let b=v("span","persona-ask-sheet-step-inline");b.setAttribute("data-ask-step-inline","true"),b.textContent="",g.appendChild(b),m.appendChild(g);let M=v("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return M.setAttribute("data-ask-pill-list","true"),M.setAttribute("role","group"),m.appendChild(M),r!=="rows"&&m.appendChild(lx(o,r)),Ng(m,t,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},KL=(t,e,n)=>{let{payload:o}=ka(e),r=Math.max(1,Ul(o).length);r>Pa(t)&&(t.setAttribute(Dg,String(r)),r>1&&!xs(t)&&t.setAttribute(Og,"true")),Ng(t,e,n)};var _p=(t,e,n)=>{if(!n||!Ai(t)||_g(e).enabled===!1)return;let r=t.toolCall.id;n.querySelectorAll(`[${Ea}]`).forEach(p=>{p.getAttribute(Ea)!==r&&p.remove()});let a=n.querySelector(`[${Ea}="${ix(r)}"]`);if(a){KL(a,t,e);return}let{payload:l}=ka(t),c=jL(t,e,l);n.appendChild(c)},La=(t,e)=>{if(!t)return;let n=e?`[${Ea}="${ix(e)}"]`:`[${Ea}]`;t.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(s)?s:180)})},Fg=t=>Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(e=>e.getAttribute("data-option-label")).filter(e=>typeof e=="string"&&e.length>0),Ss=(t,e)=>{let n=Mi(t),o=Wo(t);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete n[o]:n[o]=e,cx(t,n),dx(t),px(t)},Np=(t,e,n,o)=>{let r=Pa(t),s=Math.max(0,Math.min(r-1,o));zL(t,s),Ng(t,e,n)};var As="suggest_replies";var GL={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"object",properties:{label:{type:"string",minLength:1,maxLength:80},prompt:{type:"string",minLength:1,maxLength:500},description:{type:"string",minLength:1,maxLength:160}},required:["label"],additionalProperties:!1}}},required:["suggestions"],additionalProperties:!1},mx={name:As,description:"Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the last action after your reply text is complete. Give each suggestion a `label` with the short visible text, an optional `prompt` with the fuller text placed as the user's message (defaults to the label), and an optional `description` with one line of supporting copy. Suggestions are sent as the user's next message, so phrase prompts in the user's voice (e.g. \"Tell me more about pricing\"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.",parametersSchema:GL,origin:"sdk",annotations:{readOnlyHint:!0}},fx=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),ql=t=>t.variant==="tool"&&t.toolCall?.name===As,YL=t=>{let e=t;if(typeof e=="string")try{e=JSON.parse(e)}catch{return[]}let n=e?.suggestions;if(!Array.isArray(n))return[];let o=n.flatMap(r=>{if(typeof r=="string"){let l=r.trim();return l?[l]:[]}if(!r||typeof r!="object")return[];let s=r;if(typeof s.label!="string"||!s.label.trim())return[];let a={label:s.label.trim()};return typeof s.prompt=="string"&&s.prompt.trim()&&(a.prompt=s.prompt.trim()),typeof s.description=="string"&&s.description.trim()&&(a.description=s.description.trim()),[a]});return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},gx=t=>{for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role==="user")return null;if(!ql(n))continue;let o=YL(n.toolCall?.args);return o.length>0?o:null}return null},ux=new Set,QL=(t,e,n)=>{let o=`${t}:${e}:${n}`;ux.has(o)||(ux.add(o),console.warn(`[persona] suggestions.followUps.${t} and features.suggestReplies.${t} disagree; suggestions.followUps.${t} wins.`))},Ms=t=>{let e=t?.suggestions?.followUps,n=t?.features?.suggestReplies,o=a=>{let l=e?.[a],c=n?.[a];l===void 0||c===void 0||l!==c&&QL(a,c,l)};t&&(o("enabled"),o("expose"));let r=e?.enabled??n?.enabled??!0,s=r?e?.expose??n?.expose??!1:!1;return{enabled:r,expose:s}};var XL={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:zl,description:"Questions to ask the user. Prefer a single question.",items:{type:"object",properties:{question:{type:"string",description:"The complete question, ending with a question mark."},header:{type:"string",maxLength:12,description:'Short topic label, e.g. "Auth method".'},options:{type:"array",minItems:2,maxItems:4,description:'2-4 distinct choices. Do NOT add an "Other" option: free text is automatic.',items:{type:"object",properties:{label:{type:"string",description:"Concise choice text (1-5 words)."},description:{type:"string",description:"What the option means or implies."}},required:["label"],additionalProperties:!1}},multiSelect:{type:"boolean",description:"Allow selecting multiple options. Default false."},allowFreeText:{type:"boolean",description:"Show a free-text input. Default true."}},required:["question","options"],additionalProperties:!1}}},required:["questions"],additionalProperties:!1},JL={name:Wg,description:"Ask the user multiple-choice questions and wait for their answers. Use only when blocked on a decision that is the user's to make: a preference, a choice between valid approaches, or information you cannot infer. Each question offers 2-4 options plus an automatic free-text input. The result maps each question to its answer (an array when multiSelect); a question absent from the result was skipped.",parametersSchema:XL,origin:"sdk",annotations:{readOnlyHint:!0}},Fp=t=>{let e=[],n=t?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&e.push(JL),Ms(t).expose&&e.push(mx),e};var ZL=t=>t.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase().replace(/_+/g,"_").replace(/^_|_$/g,""),eI=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),tI=t=>{if(t.variant!=="tool")return null;let e=t.agentMetadata?.clientToolAnswer;if(!e||!e.toolCallId||e.result===void 0)return null;let n=ZL(e.toolName);return n?{call:{toolCallId:e.toolCallId,toolName:n,args:eI(e.args)?e.args:{}},result:{toolCallId:e.toolCallId,toolName:n,result:e.result}}:null},Vg=(t,e)=>{let n=[],o=[],r=[],s="",a,l=()=>{o.length!==0&&(n.push({role:"assistant",content:"",createdAt:s,toolCalls:o},{role:"tool",content:"",createdAt:s,toolResults:r}),o=[],r=[])};for(let c of t){let p=tI(c);if(p){let m=c.agentMetadata?.clientToolAnswer?.batch;o.length>0&&(m===void 0||m!==a)&&l(),o.length===0&&(s=c.createdAt,a=m),o.some(g=>g.toolCallId===p.call.toolCallId)||(o.push(p.call),r.push(p.result));continue}let u=e(c);u&&(l(),n.push(u))}return l(),n};Ts();var Ax="4.24.0";var Ti=Ax;var Ra="[Image]";function Mx(t){return typeof t=="string"?t:t.filter(e=>e.type==="text").map(e=>e.text).join("")}function Up(t){return typeof t=="string"?!1:t.some(e=>e.type==="image")}function fr(t){return{type:"text",text:t}}function Tx(t,e){return{type:"image",image:t,...e?.mimeType&&{mimeType:e.mimeType},...e?.alt&&{alt:e.alt}}}var Ex=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],lI=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],Ur=[...Ex,...lI];function cI(t){return Ex.includes(t)||t.startsWith("image/")}function qp(t){return cI(t.type)}function kx(t,e,n){return{type:"file",data:t,mimeType:e,filename:n}}async function Px(t){return new Promise((e,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;qp(t)?e({type:"image",image:r,mimeType:t.type,alt:t.name}):e({type:"file",data:r,mimeType:t.type,filename:t.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(t)})}function Lx(t,e=Ur,n=10*1024*1024){return e.includes(t.type)?t.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${t.type}". Accepted types: ${e.join(", ")}`}}function dI(t){let e=t.split(".");return e.length>1?e.pop().toLowerCase():""}function Ix(t,e){let n=dI(e).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[t]||n||"FILE"}var pI=["user","assistant","system"],uI=0;function Rx(t){if(typeof t!="string"||t==="")return null;let e=Date.parse(t);return Number.isNaN(e)?null:e}function jp(t){return typeof t=="string"?t:void 0}function mI(t){if(typeof t!="object"||t===null)return null;let e=t;switch(e.type){case"text":return typeof e.text=="string"?fr(e.text):null;case"image":return typeof e.image=="string"?Tx(e.image,{mimeType:jp(e.mimeType),alt:jp(e.alt)}):null;case"file":return typeof e.data=="string"&&typeof e.mimeType=="string"&&typeof e.filename=="string"?kx(e.data,e.mimeType,e.filename):null;case"audio":return typeof e.audio=="string"?{type:"audio",audio:e.audio,...jp(e.mimeType)!==void 0&&{mimeType:e.mimeType}}:null;case"video":return typeof e.video=="string"?{type:"video",video:e.video,...jp(e.mimeType)!==void 0&&{mimeType:e.mimeType}}:null;default:return null}}function fI(t,e){let n=Rx(e),o=t.map(a=>Rx(a.timestamp)),r=new Array(t.length),s=0;for(;s<o.length;){let a=o[s];if(a!==null){r[s]=a,s+=1;continue}let l=s;for(;l+1<o.length&&o[l+1]===null;)l+=1;let c=l-s+1,p=s>0?r[s-1]:null,u=l+1<o.length?o[l+1]:null,m=u!==null&&n!==null?Math.min(u,n):u??n;for(let g=0;g<c;g+=1)r[s+g]=m!==null?m-(c-g):p!==null?p+g+1:uI+g;s=l+1}return r.map(a=>new Date(a).toISOString())}function Hx(t,e){let n=fI(t,e?.beforeCreatedAt),o=[];return t.forEach((r,s)=>{if(typeof r?.id!="string"||r.id===""||!pI.includes(r.role))return;let a=r.role,l=n[s];if(r.displayAvailable===!1){let c={historyDisplayUnavailable:!0};o.push({id:r.id,role:a,content:"",createdAt:l,agentMetadata:c});return}if(typeof r.displayContent=="string"){o.push({id:r.id,role:a,content:r.displayContent,createdAt:l});return}if(typeof r.content=="string"){o.push({id:r.id,role:a,content:r.content,createdAt:l});return}if(Array.isArray(r.content)){let c=r.content.map(mI).filter(u=>u!==null),p=Mx(c);o.push({id:r.id,role:a,content:p||(Up(c)?Ra:""),createdAt:l,...c.length>0&&{contentParts:c}});return}o.push({id:r.id,role:a,content:"",createdAt:l})}),o}function Yl(t){let e=t.content;if(typeof e!="string"||e==="")return;let n=t.contentParts??t.llmContent??t.rawContent??e;if(!(typeof n=="string"&&n===e))return e}function Ql(t,e){let n=new Map;for(let o of t)n.set(o.id,o);for(let o of e)n.set(o.id,o);return[...n.values()].sort((o,r)=>{let s=new Date(o.createdAt).getTime(),a=new Date(r.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(a)&&s!==a)return s-a;let l=o.sequence??0,c=r.sequence??0;return l!==c?l-c:o.id.localeCompare(r.id)})}var gI="https://api.runtype.com/v1/dispatch",Wx="https://api.runtype.com",it=class extends Error{constructor(e,n,o){super(n),this.name="HistoryClientError",this.code=e,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}},Bx=32768,zg=49152,Dx=t=>{let e=t??{},n=typeof e.targetId=="string"?e.targetId:null;return{id:typeof e.id=="string"?e.id:"",title:typeof e.title=="string"?e.title:"",targetId:n,preview:typeof e.preview=="string"?e.preview:null,messageCount:typeof e.messageCount=="number"?e.messageCount:0,createdAt:typeof e.createdAt=="string"?e.createdAt:"",updatedAt:typeof e.updatedAt=="string"?e.updatedAt:""}},Ox=t=>"reason"in t?t.reason:void 0,_x="The identity proof was not admitted; account history is unavailable",Ug="The identity proof was rejected",Nx="The request carried no visitor credential",Fx="The stored visitor belongs to a different signed-in user",qg=(t,e)=>t instanceof it&&t.code===e;function hI(t){let e=t.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[e];if(o)return`attachment.${o}`;let r=e.indexOf("/");if(r>0){let s=e.slice(r+1).split(";")[0]?.trim()??"";if(s&&s!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(s))return`attachment.${s}`}return"attachment"}var jg=t=>!!(t.contentParts&&t.contentParts.length>0||t.llmContent&&t.llmContent.trim().length>0||t.rawContent&&t.rawContent.trim().length>0||t.content&&t.content.trim().length>0),Vx=t=>t.slice().sort((e,n)=>new Date(e.createdAt).getTime()-new Date(n.createdAt).getTime()),$x=t=>({role:t.role,content:t.contentParts??t.llmContent??t.rawContent??t.content,createdAt:t.createdAt});function yI(t){switch(t){case"json":return xx;case"regex-json":return wx;case"xml":return Sx;default:return Cx}}var zx=t=>t.startsWith("{")||t.startsWith("[")||t.startsWith("<");function bI(t,e){if(!t)return e;let n=t.trim(),o=e.trim();if(n.length===0)return e;if(o.length===0)return t;let r=zx(n);if(!zx(o))return t;if(!r||o===n||o.startsWith(n))return e;let a=Gl(t);return Gl(e)!==null&&a===null?e:t}var Xl=class{constructor(e={},n={}){this.config=e;this.historyInternals=n;this.currentClientTurnId=null;this.clientSession=null;this.sessionInitPromise=null;this.sessionWarmLatch=!1;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;this.historyUnavailable=!1;this.historyUnavailableWarned=!1;this.claimInFlight=!1;this.historyIdentityStatus=null;this.historyIdentitySubscribers=new Set;this.historyAvailabilitySubscribers=new Set;this.webMcpBridge=null;this.webMcpBridgePromise=null;if(e.target&&(e.agentId||e.flowId||e.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=e.apiUrl??gI,this.headers={"Content-Type":"application/json","X-Persona-Version":Ti,...e.headers},this.debug=!!e.debug,this.createStreamParser=e.streamParser??yI(e.parserType),this.contextProviders=e.contextProviders??[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders,e.webmcp?.enabled===!0&&(this.webMcpBridgePromise=this.createWebMcpBridge(e.webmcp))}createWebMcpBridge(e){return Xw().then(n=>{let o=new n.WebMcpBridge(e,{recordToolDisplayTitles:Uw,getToolDisplayTitle:Rp,loadPolyfill:jw});return this.pendingWebMcpConfirmHandler!==void 0&&o.setConfirmHandler(this.pendingWebMcpConfirmHandler),this.webMcpBridge=o,o}).catch(n=>(this.webMcpBridgePromise=null,console.warn("[Persona] Failed to load the WebMCP runtime chunk",n),null))}getWebMcpBridge(){return this.webMcpBridge?Promise.resolve(this.webMcpBridge):this.config.webmcp?.enabled!==!0?Promise.resolve(null):(this.webMcpBridgePromise||(this.webMcpBridgePromise=this.createWebMcpBridge(this.config.webmcp)),this.webMcpBridgePromise)}updateConfig(e){this.config=e}setHistoryInternals(e){this.historyInternals=e}setSSEEventCallback(e){this.onSSEEvent=e}setWebMcpConfirmHandler(e){this.pendingWebMcpConfirmHandler=e,this.webMcpBridge?.setConfirmHandler(e)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(e,n,o){return this.config.webmcp?.enabled!==!0?null:this.getWebMcpBridge().then(r=>r?r.executeToolCall(e,n,o):{isError:!0,content:[{type:"text",text:"WebMCP runtime failed to load."}]})}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:e,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:e,flowId:n};let s=Zw(o,r);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}clientApiBase(){return this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||Wx}getClientApiUrl(e){return`${this.clientApiBase()}/v1/client/${e}`}getClientSession(){return this.clientSession}async reconnectClientTokenStream(e){let n=await this.initSession(),o=!1;for(;;){let r=n.conversationId,s=await this.readVisitorToken();if(n.durableRecovery?.enabled!==!0||!r||!s)throw new it("visitor_token_missing","Durable recovery is not enabled for this client session");let a=`${this.clientApiBase()}/v1/client/conversations/${encodeURIComponent(r)}/executions/${encodeURIComponent(e.executionId)}/events`,l=new URLSearchParams({sessionId:n.sessionId,after:e.after}),c=await fetch(`${a}?${l}`,{method:"GET",headers:{"X-Persona-Version":Ti,"X-Visitor-Token":s},signal:e.signal});if(c.status===401&&!o){o=!0,n=await this.recoverFromUnauthorized(await this.readErrorCode(c),null,!0);continue}if(!c.ok)throw await this.historyErrorFor(c,!0);return c}}async warmSession(){let e=this.clientSession;return!this.isClientTokenMode()||this.sessionInitPromise||e&&new Date<e.expiresAt||this.sessionWarmLatch===e?null:(this.sessionWarmLatch=e,this.initSession().catch(()=>null))}async initSession(){if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;let e=this.sessionInitPromise=this._doInitSession().then(n=>this.sessionInitPromise!==e?this.initSession():(this.clientSession=n,this.sessionWarmLatch=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(n),n)).finally(()=>{this.sessionInitPromise===e&&(this.sessionInitPromise=null)});return e}isHistoryCapable(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()&&!this.historyUnavailable}async readVisitorToken(){let e=this.historyInternals.visitorStore;return e?(await e.ready,await e.get()??null):null}markHistoryUnavailable(){if(!this.historyUnavailable){this.setHistoryIdentityStatus({state:"unavailable",reason:"history_disabled"}),this.historyUnavailable=!0,!this.historyUnavailableWarned&&typeof console<"u"&&(this.historyUnavailableWarned=!0,console.warn("[Persona] Visitor history is disabled for this surface; continuing without it.")),this.historyInternals.onHistoryAvailabilityChanged?.(!1);for(let e of[...this.historyAvailabilitySubscribers])e(!1)}}getHistoryIdentityStatus(){return this.historyIdentityStatus??this.restingIdentityStatus()}subscribeHistoryIdentityStatus(e){return this.historyIdentitySubscribers.add(e),()=>{this.historyIdentitySubscribers.delete(e)}}subscribeHistoryAvailability(e){return this.historyAvailabilitySubscribers.add(e),this.historyUnavailable&&e(!1),()=>{this.historyAvailabilitySubscribers.delete(e)}}restingIdentityStatus(){return this.isClientTokenMode()?this.config.features?.history?.enabled!==!0||this.historyUnavailable?{state:"unavailable",reason:"history_disabled"}:this.browserOnlyStatus():{state:"unavailable",reason:"ineligible_mode"}}browserOnlyStatus(){let e=this.historyIdentityStatus;return e?.state==="browser_only"?e:this.derivedBrowserOnly()}derivedBrowserOnly(){return this.config.features?.history?.scope==="browser"?{state:"browser_only",reason:"configured_browser_scope"}:this.config.getIdentityProof?{state:"browser_only",reason:"proof_unavailable_before_binding"}:{state:"browser_only",reason:"no_identity_provider"}}setHistoryIdentityStatus(e){let n=this.getHistoryIdentityStatus(),o=n.state===e.state&&Ox(n)===Ox(e);if(this.historyIdentityStatus=e,!o){this.historyInternals.onHistoryIdentityStatusChanged?.(e);for(let r of[...this.historyIdentitySubscribers])r(e)}}async createClientSession(e){let n=this.isHistoryCapable()&&!e.omitVisitorFields,o=!e.omitVisitorFields,r=null;(n||o)&&(await this.historyInternals.historyBootstrapReady,r=await this.readVisitorToken());let s=this.routing(),a=s.agentId??s.flowId,l=n||e.durableResume?e.conversationId:void 0,c={token:this.config.clientToken,...a&&{flowId:a},...n&&{visitorHistory:!0},...o&&{durableRecovery:!0},...(n||o)&&r?{visitorToken:r}:{},...n&&e.identityProof?{identityProof:e.identityProof}:{},...l?{conversationId:l}:e.storedSessionId?{sessionId:e.storedSessionId}:{}};e.signal?.throwIfAborted();let p=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Ti},body:JSON.stringify(c),signal:e.signal});if(!p.ok){let m=await p.json().catch(()=>({error:"Session initialization failed"}));if(n&&p.status===403&&m.error==="visitor_history_disabled"){if(this.markHistoryUnavailable(),l)throw new it("history_disabled","Visitor history is disabled for this surface");return this.createClientSession({...e,omitVisitorFields:!0})}throw p.status===403&&m.error==="durable_recovery_disabled"?new it("history_disabled","Durable recovery is disabled for this surface"):(n||e.durableResume)&&p.status===401&&m.error==="visitor_required"?new it("visitor_required","Visitor credential no longer resolves"):l&&p.status===404?new it("not_found","Conversation not found"):p.status===401?new Error(`Invalid client token: ${m.hint||m.error}`):p.status===403?new Error(`Origin not allowed: ${m.hint||m.error}`):new Error(m.error||"Failed to initialize session")}let u=await p.json();return u.visitor?.token&&await this.historyInternals.visitorStore?.set(u.visitor.token),{sessionId:u.sessionId,expiresAt:new Date(u.expiresAt),flow:u.flow,...u.conversationId?{conversationId:u.conversationId}:{},...u.targetId?{targetId:u.targetId}:{},...u.conversationRevision?{conversationRevision:u.conversationRevision}:{},...u.durableRecovery?{durableRecovery:u.durableRecovery}:{},...u.visitor?{visitor:u.visitor}:{},config:{welcomeMessage:u.config.welcomeMessage,placeholder:u.config.placeholder,theme:u.config.theme}}}async _doInitSession(){await this.historyInternals.historyBootstrapReady;let e=this.config.getStoredConversationId?.()||null,n=this.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.isHistoryCapable()&&!n)return this.ordinaryInit(e,!1);let o=await this.readVisitorToken();if(e&&o)try{let r=await this.createClientSession({conversationId:e,durableResume:n});return n&&r.durableRecovery?.enabled!==!0&&this.historyInternals.setStoredResumableHandle?.(null),this.finishInit(r,e,!1)}catch(r){if(!qg(r,"not_found")&&!qg(r,"visitor_required")&&!qg(r,"history_disabled"))throw r;return n&&this.historyInternals.setStoredResumableHandle?.(null),this.ordinaryInit(e,!0)}return this.ordinaryInit(e,!1)}async ordinaryInit(e,n){let o=this.historyInternals.visitorStore;return o&&!await this.readVisitorToken()?o.withFirstInitLock(()=>this.doOrdinaryInit(e,n)):this.doOrdinaryInit(e,n)}async doOrdinaryInit(e,n){let o=this.config.getStoredSessionId?.()||null,r=await this.createClientSession({storedSessionId:o}),s=await this.claimFirstConversation(r);return this.finishInit(s,e,n)}async reinitWithProof(e){let n=this.config.getStoredSessionId?.()||null,o=this.config.getStoredConversationId?.()||null,r=await this.createClientSession({storedSessionId:n,identityProof:e}),s=this.finishInit(r,o,!1);return this.clientSession=s,this.sessionInitPromise=null,this.sessionWarmLatch=!1,this.resetClientToolsFingerprint(),s}async claimFirstConversation(e){if(!e.visitor?.token||this.claimInFlight||!this.isHistoryCapable()&&e.durableRecovery?.enabled!==!0)return e;this.claimInFlight=!0;try{return await this.createClientSession({storedSessionId:e.sessionId})}catch{return e}finally{this.claimInFlight=!1}}finishInit(e,n,o){let r=e.conversationId;return r&&n&&(o||r!==n)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:n,conversationId:r}),this.config.setStoredSessionId?.(e.sessionId),r&&(this.config.setStoredConversationId?.(r),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),e}prepared(e){let n=!1;return{session:e,commit:()=>{n||(n=!0,this.clientSession=e,this.sessionWarmLatch=!1,this.resetClientToolsFingerprint())},discard:()=>{n=!0}}}async prepareConversationSession(e,n){if(!this.isClientTokenMode())throw new Error("prepareConversationSession() only available in client token mode");if(!this.isHistoryCapable())throw new it("history_disabled","Visitor history is disabled for this surface");await this.historyInternals.historyBootstrapReady;let o=n?.proof??null;if(!await this.readVisitorToken()&&!o)throw new it("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let s=await this.createClientSession({conversationId:e,identityProof:o});return this.prepared(s)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw new Error("prepareNewConversationSession() only available in client token mode");await this.historyInternals.historyBootstrapReady;let e=await this.createClientSession({});return this.prepared(e)}handleExternalCredentialChange(){this.clearClientSession(),this.isHistoryCapable()&&this.setHistoryIdentityStatus(this.derivedBrowserOnly())}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.sessionWarmLatch=!1,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.sentNonEmptyClientToolsSessionId=null}getFeedbackApiUrl(){return`${this.clientApiBase()}/v1/client/feedback`}async sendFeedback(e){if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(e.type)&&!e.messageId)throw new Error(`messageId is required for ${e.type} feedback type`);if(e.type==="csat"&&(e.rating===void 0||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(e.type==="nps"&&(e.rating===void 0||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let r={...e,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Ti},body:JSON.stringify(r)});if(!s.ok){let a=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,this.sessionWarmLatch=!1,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(e,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,messageId:e,type:n})}async submitCSATFeedback(e,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:e,comment:n})}async submitNPSFeedback(e,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:e,comment:n})}historyUrl(e,n){let o=new URLSearchParams;for(let[s,a]of Object.entries(n))a===void 0||a===""||o.set(s,String(a));let r=o.toString();return`${this.clientApiBase()}/v1/client/${e}${r?`?${r}`:""}`}resolveHistoryScope(e){if(e)return e;let n=this.config.features?.history?.scope;return n||(this.config.getIdentityProof?"verified-user":"browser")}async resolveChatIdentityProof(e){e?.throwIfAborted();let n=this.config.identityProvider;if(n===void 0)return;let o=this.config.getIdentityProof;if(!n.trim()||!o)throw new Error("Chat identity requires identityProvider and getIdentityProof.");let r,s;try{let a=Promise.resolve().then(()=>o());r=e?await Promise.race([a,new Promise((l,c)=>{s=()=>c(e.reason),e.addEventListener("abort",s,{once:!0}),e.aborted&&s()})]):await a}catch{throw e?.throwIfAborted(),new Error("The identity proof provider failed.")}finally{s&&e?.removeEventListener("abort",s)}if(typeof r!="string"||!r.trim())throw new Error("A fresh identity proof is required to send this message.");return{provider:n,token:r}}async resolveIdentityProof(e,n){let o=this.config.getIdentityProof;if(!o)return n&&this.setHistoryIdentityStatus(this.browserOnlyStatus()),null;n&&this.setHistoryIdentityStatus({state:"verifying"});let r;try{r=await o()??null}catch{throw n&&this.setHistoryIdentityStatus({state:"identity_provider_failed"}),new it("identity_provider_failed","The identity proof provider failed")}if(r)return r;if(e.visitor?.endUserId!=null)throw n&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new it("authentication_required","This browser is bound to a signed-in user and needs a fresh identity proof");return n&&this.setHistoryIdentityStatus({state:"browser_only",reason:"proof_unavailable_before_binding"}),null}async bindIdentity(e,n,o){if(e.visitor?.endUserId!=null)return e;let r=await this.reinitWithProof(n);if(!(r.visitor?.identityStatus==="admitted"&&r.visitor?.endUserId!=null))throw o&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new it("proof_not_admitted",_x);return r}async readErrorCode(e){let n=await e.json().catch(()=>({}));return typeof n.error=="string"?n.error:typeof n.message=="string"?n.message:""}async recoverFromUnauthorized(e,n,o){let r=e.toLowerCase();if(r.includes("invalid_identity_proof"))throw o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new it("invalid_identity_proof",Ug);if(r.includes("visitor token required"))throw new it("visitor_token_missing",Nx);if(r.includes("visitor_identity_mismatch")){if(!n)throw o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new it("visitor_identity_mismatch",Fx);return this.reinitWithProof(n)}if(r.includes("expired")||r.includes("not found"))return this.clearClientSession(),this.initSession();throw new it("unauthorized",e||"History request was not authorized")}async historyErrorFor(e,n){let o=await this.readErrorCode(e);if(e.status===404)return new it("not_found","Conversation not found");if(e.status===429){let r=Number.parseInt(e.headers.get("Retry-After")??"",10);return new it("rate_limited","Too many history requests",{...Number.isFinite(r)?{retryAfterSeconds:r}:{}})}if(e.status===503&&o.includes("identity_proof_not_admitted"))return n&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new it("proof_not_admitted",_x);if(e.status===401){let r=o.toLowerCase();return r.includes("invalid_identity_proof")?(n&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new it("invalid_identity_proof",Ug)):r.includes("visitor token required")?new it("visitor_token_missing",Nx):r.includes("visitor_identity_mismatch")?new it("visitor_identity_mismatch",Fx):new it("unauthorized",o||"History request was not authorized")}return new it("request_failed",o||`History request failed (${e.status})`)}commitIdentityAcknowledgement(e,n,o){let r=e?.toLowerCase()??null;if(n){if(r==="admitted"){o&&this.setHistoryIdentityStatus({state:"verified"});return}throw o&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),r==="ignored"?new it("identity_contract_violation","Server reported an ignored identity proof on a success response"):new it("proof_not_admitted","The response did not acknowledge the identity proof this request sent")}if(r==="admitted")throw new it("identity_contract_violation","Server admitted an identity proof that was never sent");o&&this.setHistoryIdentityStatus(this.browserOnlyStatus())}async historyFetch(e,n){this.assertHistoryUsable();let o=n.trackIdentity!==!1,r=await this.initSession(),s=null;this.resolveHistoryScope(n.scope)==="verified-user"&&(s=await this.resolveIdentityProof(r,o),s&&(r=await this.bindIdentity(r,s,o)));let a=this.historyInternals.visitorStore,l=!1;for(;;){let c=a?.revision()??0,p=await this.readVisitorToken();if(!p&&!n.visitorTokenOptional)throw new it("visitor_token_missing","No visitor credential is stored for this browser");let u=await fetch(this.historyUrl(e,{...n.query,sessionId:r.sessionId}),{method:n.method,headers:{"X-Persona-Version":Ti,...p?{"X-Visitor-Token":p}:{},...s?{"X-Identity-Proof":s}:{},...n.body!==void 0?{"Content-Type":"application/json"}:{}},...n.body!==void 0?{body:JSON.stringify(n.body)}:{},...n.keepalive?{keepalive:!0}:{}});if(u.status===401&&!l){l=!0,r=await this.recoverFromUnauthorized(await this.readErrorCode(u),s,o);continue}if(!u.ok)throw await this.historyErrorFor(u,o);let m=u.headers.get("X-History-Identity-Status"),g=await u.json().catch(()=>{});if(a&&a.revision()!==c)throw new it("credential_changed","The visitor credential changed while the request was in flight");return this.commitIdentityAcknowledgement(m,s!==null,o),g}}assertHistoryUsable(){if(!this.isClientTokenMode())throw new Error("Conversation history is only available in client token mode");if(!this.isHistoryCapable())throw new it("history_disabled","Visitor history is disabled for this surface")}async listConversations(e){let n=await this.historyFetch("conversations",{method:"GET",query:{...e?.cursor?{cursor:e.cursor}:{},...e?.limit!==void 0?{limit:e.limit}:{},...e?.targetId?{targetId:e.targetId}:{}},...e?.scope?{scope:e.scope}:{}});return{data:(Array.isArray(n?.data)?n.data:[]).map(Dx),nextCursor:typeof n?.nextCursor=="string"?n.nextCursor:null}}async getConversation(e,n){let o=await this.historyFetch(`conversations/${encodeURIComponent(e)}`,{method:"GET",query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}});return{summary:Dx(o),messages:Array.isArray(o?.messages)?o.messages:[],nextMessageCursor:typeof o?.nextMessageCursor=="string"?o.nextMessageCursor:null,conversationRevision:typeof o?.conversationRevision=="string"?o.conversationRevision:null}}async finalizeDisplayProjections(e,n){this.assertHistoryUsable();let o=0;for(let c of n){let p=c.displayContent.length;if(p>Bx)throw new it("payload_too_large",`displayContent exceeds the ${Bx} character limit`);o+=p}if(o>zg)throw new it("payload_too_large",`Display projection batch exceeds the ${zg} character limit`);await this.initSession();let r=this.historyInternals.visitorStore,s=r?.revision()??0,a=await this.historyFetch(`conversations/${encodeURIComponent(e)}/display-projections`,{method:"PATCH",body:{messages:n},scope:"browser",keepalive:o<=zg,trackIdentity:!1}),l=typeof a?.conversationRevision=="string"?a.conversationRevision:null;return l&&this.clientSession?.conversationId===e&&(r?.revision()??0)===s&&this.historyInternals.setStoredConversationRevision?.(l),{conversationRevision:l}}async deleteConversation(e,n){let o=await this.historyFetch(`conversations/${encodeURIComponent(e)}`,{method:"DELETE",...n?.scope?{scope:n.scope}:{}});return{deleted:typeof o?.deleted=="number"?o.deleted:0}}async deleteAllConversations(e){let n=await this.historyFetch("conversations",{method:"DELETE",query:{...e?.targetId!==void 0?{targetId:e.targetId}:{}},...e?.scope?{scope:e.scope}:{}});return{deleted:typeof n?.deleted=="number"?n.deleted:0}}async resetVisitor(){this.assertHistoryUsable(),this.setHistoryIdentityStatus({state:"resetting"});try{await this.historyFetch("visitor/reset",{method:"POST",scope:"browser",visitorTokenOptional:!0})}finally{await this.historyInternals.visitorStore?.clear(),this.setHistoryIdentityStatus(this.derivedBrowserOnly())}return{reset:!0}}async dispatch(e,n){return e.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(e,n):this.isAgentMode()?this.dispatchAgent(e,n):this.dispatchProxy(e,n)}async dispatchClientToken(e,n){let o=ex();this.currentClientTurnId=o;let r=()=>this.currentClientTurnId===o,s=a=>{r()&&n(a)};n({type:"status",status:"connecting"});try{let a=()=>{if(e.signal?.throwIfAborted(),!r())throw new DOMException("Turn superseded","AbortError")},l=this.clientSession??await this.initSession();a();let c=async()=>{a();let E=l,T=E.durableRecovery?.enabled===!0;if(T&&(!E.conversationId||!await this.readVisitorToken()))throw new Error("Renewing this conversation requires its visitor credential.");a();let H=await this.createClientSession({...T||this.isHistoryCapable()?{conversationId:E.conversationId,durableResume:T}:{storedSessionId:E.sessionId},signal:e.signal});if(a(),E.conversationId&&H.conversationId!==E.conversationId||T&&H.durableRecovery?.enabled!==!0)throw new Error("Session renewal did not preserve this conversation.");l=this.finishInit(H,E.conversationId??null,!1),this.clientSession=l,this.sessionWarmLatch=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(l)};Date.now()>=l.expiresAt.getTime()-6e4&&await c();let p=await this.buildPayload(e.messages),u=p.metadata?Object.fromEntries(Object.entries(p.metadata).filter(([E])=>E!=="sessionId"&&E!=="session_id")):void 0,m=this.isHistoryCapable(),g={sessionId:l.sessionId,messages:e.messages.filter(jg).map(E=>{let T=m?Yl(E):void 0;return{id:E.id,role:E.role,content:E.contentParts??E.llmContent??E.rawContent??E.content,...T!==void 0&&{displayContent:T}}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...p.inputs&&Object.keys(p.inputs).length>0&&{inputs:p.inputs},...p.context&&{context:p.context},turnId:o,...e.interrupt&&{submitMode:"interrupt"}},h=async()=>{a();let E=l.durableRecovery?.enabled===!0?await this.readVisitorToken():null;return a(),this.sendWithClientToolsDiff(l.sessionId,p.clientTools,async T=>{a();let H=await this.resolveChatIdentityProof(e.signal);a();let A={...g,sessionId:l.sessionId,...T,...H&&{identityProof:H}};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",{...A,...H&&{identityProof:{provider:H.provider,token:"[REDACTED]"}}}),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Ti,...E?{"X-Visitor-Token":E}:{}},body:JSON.stringify(A),signal:e.signal})})},b=await h();if(a(),b.response.status===401){let E=await b.response.clone().json().catch(()=>null);a(),E?.error==="Session not found or expired"&&(await c(),b=await h(),a())}let{response:C,commit:M}=b;if(!C.ok){let E=await C.json().catch(()=>({error:"Chat request failed"}));if(C.status===401&&E.error==="invalid_identity_proof"){let H=new it("invalid_identity_proof",Ug);throw s({type:"error",error:H}),H}if(C.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let H=new Error("Session expired. Please refresh to continue.");throw s({type:"error",error:H}),H}if(C.status===429){let H=new Error(E.hint||"Message limit reached for this session.");throw s({type:"error",error:H}),H}if(C.status===410&&E.error==="conversation_deleted"){let H=new it("conversation_deleted","This conversation was deleted");throw s({type:"error",error:H}),H}let T=new Error(E.error||"Failed to send message");throw s({type:"error",error:T}),T}if(!C.body){let E=new Error("No response body received");throw s({type:"error",error:E}),E}M(),s({type:"status",status:"connected"});try{await this.streamResponse(C.body,s,e.assistantMessageId)}finally{s({type:"status",status:"idle"})}}catch(a){let l=a instanceof Error?a:new Error(String(a));throw!(l instanceof it)&&!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&s({type:"error",error:l}),l}}async dispatchProxy(e,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(e.messages,e.composerOptions);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal},o)}catch(a){let l=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal});if(!s.ok||!s.body){let a=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(e,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(e.messages,e.composerOptions);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal},o)}catch(a){let l=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal});if(!s.ok||!s.body){let a=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n,e.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(e,n,o,r){n({type:"status",status:"connected"});try{await this.streamResponse(e,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(e,n){let o=`${this.clientApiBase()}/v1/agents/${e.agentId}/approve`,r={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(r,await this.getHeaders()),fetch(o,{method:"POST",headers:r,body:JSON.stringify({executionId:e.executionId,approvalId:e.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(e,n,o,r){let s=!!(n&&n.length>0),a=s?qw(n):void 0,l=this.clientToolsFingerprintSessionId===e,c=s&&l&&this.lastSentClientToolsFingerprint===a,p=!s&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===e,u=!1,m;for(let g=0;;g++){if(m=await o({...s&&(u||!c)&&n?{clientTools:n}:{},...p?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),m.status===409&&g===0&&s&&(await m.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){u=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:m,commit:()=>{this.lastSentClientToolsFingerprint=a??null,this.clientToolsFingerprintSessionId=e,s?this.sentNonEmptyClientToolsSessionId=e:p&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(e,n,o){let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||Wx}/resume`,a,l=null;if(r){let u=await this.initSession();a=u.sessionId,u.durableRecovery?.enabled===!0&&(l=await this.readVisitorToken())}let c={"Content-Type":"application/json",...l?{"X-Visitor-Token":l}:{},...this.headers};this.getHeaders&&Object.assign(c,await this.getHeaders());let p={executionId:e,toolOutputs:n,streamResponse:o?.streamResponse??!0,...o?.after?{after:o.after}:{}};if(a&&(p.sessionId=a),r&&a){let u=[...Fp(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:m,commit:g}=await this.sendWithClientToolsDiff(a,u,h=>{let b={...p,...h};return this.debug&&console.debug("[AgentWidgetClient] client token resume",b),fetch(s,{method:"POST",headers:c,body:JSON.stringify(b),signal:o?.signal})},{emptyMeansReplace:!0});return m.ok&&g(),m}return fetch(s,{method:"POST",headers:c,body:JSON.stringify(p),signal:o?.signal})}latestMentionContext(e){for(let n=e.length-1;n>=0;n--){let o=e[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(e){let n={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async r=>{try{let s=await r({messages:e,config:this.config});s&&typeof s=="object"&&Object.assign(n,s)}catch(s){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",s)}}));let o=this.latestMentionContext(e);return o&&Object.assign(n,o),Object.keys(n).length?n:null}normalizeComposerOptions(e){if(!e)return;let n={};return e.selectedModelId&&(n.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(n.activeModeIds=[...e.activeModeIds]),Object.keys(n).length>0?n:void 0}applyInlineAgentModel(e,n){let o=n?.selectedModelId;return!o||!("model"in e)?e:this.config.composer?.models?.some(s=>s.id===o)?{...e,model:o}:e}async buildAgentPayload(e,n){let o=this.routing().agentId;if(!this.config.agent&&!o)throw new Error("Agent configuration required for agent mode");let r=Vg(Vx(e),p=>jg(p)&&(p.role==="user"||p.role==="assistant"||p.role==="system")&&(!p.variant||p.variant==="assistant")?$x(p):null),s=this.normalizeComposerOptions(n),a={agent:this.applyInlineAgentModel(this.config.agent??{agentId:o},s),messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};s&&(a.composerOptions=s);let l=[...Fp(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]];l.length>0&&(a.clientTools=l);let c=await this.buildContextAggregate(e);return c&&(a.context=c),a}async buildPayload(e,n){let o=Vg(Vx(e),p=>jg(p)?$x(p):null),r=this.routing(),s={messages:o,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[p,u]of Object.entries(r.targetPayload))p!=="messages"&&(s[p]=u);let a=[...Fp(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]];a.length>0&&(s.clientTools=a);let l=await this.buildContextAggregate(e);l&&(s.context=l);let c=this.normalizeComposerOptions(n);if(c&&(s.composerOptions=c),this.requestMiddleware)try{let p=await this.requestMiddleware({payload:{...s},config:this.config});if(p&&typeof p=="object"){let u=p;return s.clientTools!==void 0&&!("clientTools"in u)&&(u.clientTools=s.clientTools),u}}catch(p){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",p)}return s}async handleCustomSSEEvent(e,n,o,r,s,a){if(!this.parseSSEEvent)return!1;try{let l=await this.parseSSEEvent(e);if(l===null)return!1;let c=u=>{let m={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...u!==void 0&&{partId:u}};return o.current=m,r(m),m},p=u=>o.current?o.current:c(u);if(l.text!==void 0){l.partId!==void 0&&a.current!==null&&l.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),c(l.partId)),l.partId!==void 0&&(a.current=l.partId);let u=p(l.partId);l.partId!==void 0&&!u.partId&&(u.partId=l.partId),u.content+=l.text,r(u)}return l.done&&(o.current&&(o.current.streaming=!1,r(o.current)),a.current=null,n({type:"status",status:"idle"})),l.error&&(a.current=null,n({type:"error",error:new Error(l.error)})),!0}catch(l){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",l),!1}}async streamResponse(e,n,o,r){let s=e.getReader(),a=new TextDecoder,l="",c=Date.now(),p=0,u=()=>c+p++,m=X=>{let I=X.reasoning?{...X.reasoning,chunks:[...X.reasoning.chunks]}:void 0,j=X.toolCall?{...X.toolCall,chunks:X.toolCall.chunks?[...X.toolCall.chunks]:void 0}:void 0,J=X.tools?X.tools.map(Y=>({...Y,chunks:Y.chunks?[...Y.chunks]:void 0})):void 0;return{...X,reasoning:I,toolCall:j,tools:J}},g=X=>{if(X.role!=="assistant"||X.variant)return!0;let I=Array.isArray(X.contentParts)&&X.contentParts.length>0,j=typeof X.rawContent=="string"&&X.rawContent.trim()!=="";return typeof X.content=="string"&&X.content.trim()!==""||I||j||!!X.stopReason},h=X=>{g(X)&&n({type:"message",message:m(X)})},b=null,C=null,M={current:null},E={current:null},T=null,H="",A=new Map,D=new Map,W=new Map,U=new Map,B=new Map,O=o,R=!1,S=()=>{if(b)return b;let X,I="",j=T;return!R&&O?(X=O,R=!0,I=r??""):O&&j?X=`${O}_${j}`:X=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,b={id:X,role:"assistant",content:I,createdAt:new Date().toISOString(),streaming:!0,sequence:u()},h(b),b},x=X=>{let I=U.get(X);if(I)return I;let j={id:`reason-${X}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:u(),reasoning:{id:X,status:"streaming",chunks:[]}};return U.set(X,j),h(j),j},P=new Set,L=new Map,G=new Set,V=new Map,K=X=>{if(!X)return!1;let I=X.replace(/_+/g,"_").replace(/^_|_$/g,"");return I==="emit_artifact_markdown"||I==="emit_artifact_component"},ee=X=>{let I=B.get(X);if(I)return I;let j={id:`tool-${X}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:u(),toolCall:{id:X,status:"pending"}};return B.set(X,j),h(j),j},oe=X=>{if(typeof X=="number"&&Number.isFinite(X))return X;if(typeof X=="string"){let I=Number(X);if(!Number.isNaN(I)&&Number.isFinite(I))return I;let j=Date.parse(X);if(!Number.isNaN(j))return j}return Date.now()},ne=X=>{if(typeof X=="string")return X;if(X==null)return"";try{return JSON.stringify(X)}catch{return String(X)}},le=new Map,de=new Map,ve=(X,I)=>{let j=ne(I),J=de.get(X.id),Y=bI(J,j);X.rawContent=Y;let ie=le.get(X.id),Me=rt=>{let Ze=X.content??"";rt.trim()!==""&&(Ze.trim().length===0||rt.startsWith(Ze)||rt.trimStart().startsWith(Ze.trim()))&&(X.content=rt)},Ee=()=>{if(ie){let rt=ie.close?.();rt instanceof Promise&&rt.catch(()=>{})}le.delete(X.id),de.delete(X.id),X.streaming=!1,h(X)};if(!ie){Me(j),Ee();return}let Oe=Gl(Y);if(Oe!==null&&Oe.trim()!==""){Me(Oe),Ee();return}let Ct=rt=>{let Ze=typeof rt=="string"?rt:rt?.text??null;if(Ze!==null&&Ze.trim()!=="")return Ze;let ct=ie.getExtractedText();return ct!==null&&ct.trim()!==""?ct:j},Ot;try{Ot=ie.processChunk(Y)}catch{Me(j),Ee();return}if(Ot instanceof Promise){Ot.then(rt=>{Me(Ct(rt)),Ee()}).catch(()=>{Me(j),Ee()});return}Me(Ct(Ot)),Ee()},Le=null,se=(X,I,j,J)=>{X.rawContent=I,le.has(X.id)||le.set(X.id,this.createStreamParser());let Y=le.get(X.id),ie=I.trim().startsWith("{")||I.trim().startsWith("[");if(ie&&de.set(X.id,I),Y.__isPlainTextParser===!0){X.content=J!==void 0?I:X.content+j,de.delete(X.id),le.delete(X.id),X.rawContent=void 0,h(X);return}let Ee=Y.processChunk(I);if(Ee instanceof Promise)Ee.then(Oe=>{let Ct=typeof Oe=="string"?Oe:Oe?.text??null;Ct!==null&&Ct.trim()!==""?(X.content=Ct,h(X)):!ie&&!I.trim().startsWith("<")&&(X.content=J!==void 0?I:X.content+j,de.delete(X.id),le.delete(X.id),X.rawContent=void 0,h(X))}).catch(()=>{X.content=J!==void 0?I:X.content+j,de.delete(X.id),le.delete(X.id),X.rawContent=void 0,h(X)});else{let Oe=typeof Ee=="string"?Ee:Ee?.text??null;Oe!==null&&Oe.trim()!==""?(X.content=Oe,h(X)):!ie&&!I.trim().startsWith("<")&&(X.content=J!==void 0?I:X.content+j,de.delete(X.id),le.delete(X.id),X.rawContent=void 0,h(X))}},_=(X,I)=>{let j=I??X.content;if(j==null||j===""){X.streaming=!1,h(X);return}let Y=de.get(X.id)??ne(j);X.rawContent=Y;let ie=le.get(X.id),Me=null,Ee=!1;if(ie&&(Me=ie.getExtractedText(),Me===null&&(Me=Gl(Y)),Me===null)){let Oe=ie.processChunk(Y);Oe instanceof Promise?(Ee=!0,Oe.then(Ct=>{let Ot=typeof Ct=="string"?Ct:Ct?.text??null;Ot!==null&&(X.content=Ot,X.streaming=!1,le.delete(X.id),de.delete(X.id),h(X))}).catch(()=>{})):Me=typeof Oe=="string"?Oe:Oe?.text??null}if(!Ee){Me!==null&&Me.trim()!==""?X.content=Me:de.has(X.id)||(X.content=ne(j));let Oe=le.get(X.id);if(Oe){let Ct=Oe.close?.();Ct instanceof Promise&&Ct.catch(()=>{}),le.delete(X.id)}de.delete(X.id),X.streaming=!1,h(X)}},Te=(X,I,j)=>{let J=D.get(X);if(J)return J;let Y={id:`nested-${I}-${X}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u(),...j?{variant:j}:{},...j==="reasoning"?{reasoning:{id:X,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:I}};return D.set(X,Y),h(Y),Y},He=[],ut,At=new Map,Wt=0,bt="agent",xe=!1,Ne=null,Ae=null,vt=this.config.iterationDisplay??"separate";for(ut=()=>{for(let X=0;X<He.length;X++){let I=He[X];if(!xe&&bt!=="flow"&&typeof I.stepType=="string"&&(bt="flow"),I.type==="reasoning_start"){let j=typeof I.id=="string"?I.id:null,J=typeof I.parentToolCallId=="string"&&I.parentToolCallId?I.parentToolCallId:null;if(j&&J){A.set(j,J),Te(j,J,"reasoning");continue}let Y=I.id,ie=x(Y);ie.reasoning=ie.reasoning??{id:Y,status:"streaming",chunks:[]},ie.reasoning.startedAt=ie.reasoning.startedAt??Date.now(),ie.reasoning.completedAt=void 0,ie.reasoning.durationMs=void 0,(I.scope==="loop"||I.scope==="turn")&&(ie.reasoning.scope=I.scope),ie.streaming=!0,ie.reasoning.status="streaming",h(ie)}else if(I.type==="reasoning_delta"){let j=typeof I.id=="string"?I.id:null;if(j&&A.has(j)&&D.has(j)){let ie=D.get(j),Me=I.delta;Me&&ie.reasoning&&(ie.reasoning.chunks.push(String(Me)),h(ie));continue}let J=I.id,Y=x(J);Y.reasoning=Y.reasoning??{id:J,status:"streaming",chunks:[]},Y.reasoning.startedAt=Y.reasoning.startedAt??Date.now(),I.delta&&Y.reasoning.chunks.push(I.delta),Y.reasoning.status="streaming",Y.streaming=!0,h(Y)}else if(I.type==="reasoning_complete"){let j=typeof I.id=="string"?I.id:null;if(j&&A.has(j)&&D.has(j)){let Me=D.get(j);if(Me.reasoning){let Ee=typeof I.text=="string"?I.text:"";Ee&&Me.reasoning.chunks.length===0&&Me.reasoning.chunks.push(Ee),Me.reasoning.status="complete",Me.streaming=!1,h(Me)}A.delete(j),D.delete(j);continue}let J=I.id,Y=typeof I.text=="string"?I.text:"";!U.get(J)&&(Y||I.scope==="loop")&&x(J);let ie=U.get(J);if(ie?.reasoning){(I.scope==="loop"||I.scope==="turn")&&(ie.reasoning.scope=I.scope),Y&&ie.reasoning.chunks.length===0&&ie.reasoning.chunks.push(Y),ie.reasoning.status="complete",ie.reasoning.completedAt=Date.now();let Me=ie.reasoning.startedAt??Date.now();ie.reasoning.durationMs=Math.max(0,(ie.reasoning.completedAt??Date.now())-Me),ie.streaming=!1,h(ie)}}else if(I.type==="tool_start"){b&&(b.streaming=!1,h(b),b=null),typeof I.iteration=="number"&&(Wt=I.iteration);let j=I.toolCallId,J=I.toolName;if(K(J)){P.add(j);continue}let Y=ee(j),ie=Y.toolCall??{id:j,status:"pending"};ie.name=J??ie.name,ie.status="running",ie.success=void 0,ie.error=void 0,ie.duration=void 0,I.parameters!==void 0&&(ie.args=I.parameters),ie.startedAt=ie.startedAt??oe(I.startedAt),ie.completedAt=void 0,ie.durationMs=void 0,Y.toolCall=ie,Y.streaming=!0,I.executionId&&(Y.agentMetadata={executionId:I.executionId,iteration:I.iteration}),h(Y)}else if(I.type==="tool_output_delta"){let j=I.toolCallId;if(P.has(j))continue;let J=ee(j),Y=J.toolCall??{id:j,status:"running"};Y.startedAt=Y.startedAt??Date.now();let ie=I.delta;ie&&(Y.chunks=Y.chunks??[],Y.chunks.push(String(ie))),Y.status="running",J.toolCall=Y,J.streaming=!0,I.executionId&&(J.agentMetadata=J.agentMetadata??{executionId:I.executionId,iteration:Wt}),h(J)}else if(I.type==="tool_complete"){let j=I.toolCallId;if(P.has(j)){P.delete(j);continue}let J=ee(j),Y=J.toolCall??{id:j,status:"running"};Y.status="complete",I.result!==void 0&&(Y.result=I.result),Y.name=I.toolName??Y.name,Y.success=I.success,Y.error=I.error,Y.completedAt=Date.now();let ie=I.executionTime;if(typeof ie=="number")Y.durationMs=ie,Y.duration=ie;else{let Me=Y.startedAt??Date.now();Y.durationMs=Math.max(0,(Y.completedAt??Date.now())-Me)}J.toolCall=Y,J.streaming=!1,I.executionId&&(J.agentMetadata=J.agentMetadata??{executionId:I.executionId,iteration:I.iteration??Wt}),h(J)}else if(I.type==="await"&&I.toolName){let j=typeof I.toolCallId=="string"&&I.toolCallId.length>0?I.toolCallId:void 0,J=j??I.toolId??`local-${u()}`,Y=ee(J),ie=I.toolName,Me=I.origin==="webmcp"&&!Sa(ie)?`webmcp:${ie}`:ie,Ee=Sa(Me),Oe=Y.toolCall??{id:J,status:"pending"};Oe.name=Me,Oe.args=I.parameters,Oe.status=Ee?"running":"complete",Oe.chunks=Oe.chunks??[],Oe.startedAt=Oe.startedAt??oe(I.awaitedAt),Ee?(Oe.completedAt=void 0,Oe.duration=void 0,Oe.durationMs=void 0):Oe.completedAt=Oe.completedAt??Oe.startedAt,Y.toolCall=Oe,Y.streaming=!1,Y.agentMetadata={...Y.agentMetadata,executionId:I.executionId??Y.agentMetadata?.executionId,awaitingLocalTool:!0,...j?{webMcpToolCallId:j}:{}},h(Y)}else if(I.type==="text_start"){let j=typeof I.id=="string"?I.id:null,J=typeof I.parentToolCallId=="string"&&I.parentToolCallId?I.parentToolCallId:null;if(j&&J){A.set(j,J);continue}let Y=b;Y&&(bt==="flow"?(_(Y),Le=Y):(Y.streaming=!1,h(Y)),b=null),T=typeof I.id=="string"?I.id:T,H=""}else if(I.type==="text_delta"){let j=typeof I.id=="string"?I.id:null,J=j?A.get(j):void 0;if(j&&J){let Me=typeof I.delta=="string"?I.delta:"",Ee=(W.get(j)??"")+Me;if(W.set(j,Ee),Ee.trim()==="")continue;let Oe=Te(j,J);Oe.agentMetadata={...Oe.agentMetadata,executionId:I.executionId,parentToolId:J},se(Oe,Ee,Me,void 0);continue}if(T=typeof I.id=="string"?I.id:T,bt==="flow"){let Me=typeof I.delta=="string"?I.delta:"";if(H+=Me,H.trim()==="")continue;let Ee=S();Ee.agentMetadata={executionId:I.executionId,iteration:Wt},se(Ee,H,Me,void 0),C=Ee;continue}let Y=typeof I.delta=="string"?I.delta:"";H+=Y;let ie=S();ie.agentMetadata={executionId:I.executionId,iteration:Wt,turnId:Ne??void 0,agentName:Ae?.agentName},se(ie,H,Y,void 0),C=ie}else if(I.type==="text_complete"){let j=typeof I.id=="string"?I.id:null;if(j&&A.has(j)){let Y=D.get(j);Y&&_(Y),A.delete(j),W.delete(j),D.delete(j);continue}let J=b;J&&(bt==="flow"?(_(J),Le=J):((J.content??"")===""&&typeof I.text=="string"&&(J.content=I.text),J.streaming=!1,h(J)),b=null),T=null,H=""}else if(I.type==="step_complete"){if(I.stepType==="tool")continue;if(I.success===!1){let j=I.error||"Step failed";n({type:"error",error:new Error(j)});let J=b;J&&J.streaming&&(J.streaming=!1,h(J)),n({type:"status",status:"idle"});continue}{let j=Le;Le=null;let J=I.stopReason,ie=(I.result&&typeof I.result=="object"?I.result:null)?.response;if(j)J&&(j.stopReason=J),ie!=null?ve(j,ie):j.streaming!==!1&&(le.delete(j.id),de.delete(j.id),j.streaming=!1,h(j));else{let Me=ie!=null&&ie!=="";if(Me||J){let Ee=S();J&&(Ee.stopReason=J),Me?_(Ee,ie):(Ee.streaming=!1,h(Ee))}}continue}}else if(I.type==="execution_start")bt=I.kind==="flow"?"flow":"agent",xe=!0,bt==="agent"&&(Ae={executionId:I.executionId,agentId:I.agentId??"virtual",agentName:I.agentName??""});else if(I.type==="turn_start"){let j=typeof I.iteration=="number"?I.iteration:Wt;if(j!==Wt){if(vt==="separate"&&j>1){let J=b;J&&(J.streaming=!1,h(J),b=null)}Wt=j}Ne=typeof I.id=="string"?I.id:null,C=null}else if(I.type==="tool_input_delta"){let j=I.toolCallId;if(j){let J=B.get(j);J?.toolCall&&(J.toolCall.chunks=J.toolCall.chunks??[],J.toolCall.chunks.push(I.delta??""),h(J))}}else if(I.type==="tool_input_complete"){if(P.has(I.toolCallId))continue;let j=ee(I.toolCallId),J=j.toolCall;J.args=I.parameters,J.name=I.toolName??J.name,h(j)}else if(I.type==="turn_complete"){let j=I.stopReason,J=b??C;if(j&&J!==null){let Y=I.id;(!Y||J.agentMetadata?.turnId===Y)&&(J.stopReason=j,h(J))}Ne===I.id&&(Ne=null)}else if(I.type==="media_start"){let j=String(I.id);At.set(j,{mediaType:typeof I.mediaType=="string"?I.mediaType:void 0,toolCallId:I.toolCallId,parts:[]})}else if(I.type==="media_delta"){let j=At.get(String(I.id));j&&typeof I.delta=="string"&&j.parts.push(I.delta)}else if(I.type==="media_complete"){let j=String(I.id),J=At.get(j);At.delete(j);let Y=(typeof I.mediaType=="string"?I.mediaType:void 0)??J?.mediaType??"application/octet-stream",ie=typeof I.data=="string"?I.data:void 0,Me=typeof I.url=="string"?I.url:J&&J.parts.length>0?J.parts.join(""):void 0,Ee=null;if(ie)Ee={type:"media",data:ie,mediaType:Y};else if(Me){let rt=Y.toLowerCase();Ee={type:rt==="image"||rt.startsWith("image/")?"image-url":"file-url",url:Me,mediaType:Y}}let Oe=I.toolCallId??J?.toolCallId,Ct=Ee?[Ee]:[],Ot=[];for(let rt of Ct){if(!rt||typeof rt!="object")continue;let Ze=rt,ct=typeof Ze.type=="string"?Ze.type:void 0,Rt=typeof Ze.mediaType=="string"?Ze.mediaType.toLowerCase():"",Z=null,Fe="";if(ct==="media"){let Re=typeof Ze.data=="string"?Ze.data:void 0;if(!Re)continue;Fe=Rt.length>0?Rt:"application/octet-stream",Z=`data:${Fe};base64,${Re}`}else if(ct==="image-url"){let Re=typeof Ze.url=="string"?Ze.url:void 0;if(!Re)continue;Fe=Rt,Z=Re}else if(ct==="file-url"){let Re=typeof Ze.url=="string"?Ze.url:void 0;if(!Re)continue;Fe=Rt,Z=Re}else continue;if(Z)if(ct==="image-url"||Fe.startsWith("image/"))Ot.push({type:"image",image:Z,...Fe.includes("/")?{mimeType:Fe}:{}});else if(Fe.startsWith("audio/"))Ot.push({type:"audio",audio:Z,mimeType:Fe});else if(Fe.startsWith("video/"))Ot.push({type:"video",video:Z,mimeType:Fe});else{let Re=Fe||"application/octet-stream";Ot.push({type:"file",data:Z,mimeType:Re,filename:hI(Re)})}}if(Ot.length>0){let rt=u(),Ze=Oe,Rt={id:`agent-media-${typeof Ze=="string"&&Ze.length>0?`${Ze}-${rt}`:String(rt)}`,role:"assistant",content:"",contentParts:Ot,createdAt:new Date().toISOString(),streaming:!1,sequence:rt,agentMetadata:{executionId:I.executionId,iteration:Wt}};h(Rt);let Z=b;Z&&(Z.streaming=!1,h(Z)),b=null,M.current=null}}else if(I.type==="execution_complete"){let j=b;j&&(I.kind==="flow"&&j.streaming!==!1?_(j):(j.streaming=!1,h(j)),b=null),T=null,H="",Le=null,n({type:"status",status:"idle",terminal:!0})}else if(I.type==="execution_error"){let j=typeof I.error=="string"?I.error:I.error?.message??"Execution error";n({type:"error",error:new Error(j)})}else if(I.type!=="ping"){if(I.type==="approval_start"){let j=I.approvalId??`approval-${u()}`,J={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:j,status:"pending",agentId:Ae?.agentId??"virtual",executionId:I.executionId??Ae?.executionId??"",toolName:I.toolName??"",toolType:I.toolType,description:I.description??`Execute ${I.toolName??"tool"}`,...typeof I.reason=="string"&&I.reason?{reason:I.reason}:{},parameters:I.parameters}};h(J)}else if(I.type==="approval_complete"){let j=I.approvalId;if(j){let Y={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:j,status:I.decision??"approved",agentId:Ae?.agentId??"virtual",executionId:I.executionId??Ae?.executionId??"",toolName:"",description:"",resolvedAt:Date.now()}};h(Y)}}else if(I.type==="artifact_start"||I.type==="artifact_delta"||I.type==="artifact_update"||I.type==="artifact_complete"){if(I.type==="artifact_start"){let j=I.artifactType,J=String(I.id),Y=typeof I.title=="string"?I.title:void 0,ie=I.file,Me;if(ie&&typeof ie=="object"&&!Array.isArray(ie)&&typeof ie.path=="string"&&typeof ie.mimeType=="string"&&(Me={path:ie.path,mimeType:ie.mimeType,...typeof ie.language=="string"?{language:ie.language}:{}}),n({type:"artifact_start",id:J,artifactType:j,title:Y,component:typeof I.component=="string"?I.component:void 0,...Me?{file:Me}:{}}),V.set(J,{markdown:"",title:Y,file:Me}),!G.has(J)){G.add(J);let Ee=Cs(this.config.features?.artifacts,{artifactType:j,...Me?{file:Me}:{}}),Oe=typeof I.component=="string"?I.component:void 0,Ct={id:`artifact-ref-${J}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u(),rawContent:$l(Ee,{artifactId:J,title:Y,artifactType:j,status:"streaming",...Me?{file:Me}:{},...Oe?{component:Oe}:{}})};L.set(J,Ct),h(Ct)}}else if(I.type==="artifact_delta"){let j=String(I.id),J=typeof I.delta=="string"?I.delta:String(I.delta??"");n({type:"artifact_delta",id:j,artDelta:J});let Y=V.get(j);Y&&(Y.markdown+=J)}else if(I.type==="artifact_update"){let j=I.props&&typeof I.props=="object"&&!Array.isArray(I.props)?I.props:{};n({type:"artifact_update",id:String(I.id),props:j,component:typeof I.component=="string"?I.component:void 0});let J=V.get(String(I.id));J&&(J.props={...J.props??{},...j})}else if(I.type==="artifact_complete"){let j=String(I.id);n({type:"artifact_complete",id:j});let J=L.get(j);if(J){J.streaming=!1;try{let Y=JSON.parse(J.rawContent??"{}");if(Y.props){Y.props.status="complete";let ie=V.get(j);ie?.markdown&&(Y.props.markdown=ie.markdown),ie?.file&&(Y.props.file=ie.file),Y.component==="PersonaArtifactInline"&&ie?.props&&Object.keys(ie.props).length>0&&(Y.props.componentProps=ie.props)}J.rawContent=JSON.stringify(Y)}catch{}V.delete(j),h(J),L.delete(j)}}}else if(I.type==="error"&&I.recoverable===!1&&I.error!=null&&I.error!==""){let j=typeof I.error=="string"?I.error:I.error?.message!=null?String(I.error.message):"Execution error";n({type:"error",error:new Error(j)});let J=b;J&&J.streaming&&(J.streaming=!1,h(J)),n({type:"status",status:"idle"})}}}He.length=0};;){let{done:X,value:I}=await s.read();if(X)break;l+=a.decode(I,{stream:!0});let j=l.split(`
|
|
1140
|
+
`});function rb(t){if(!t)return wm;let e={...wm};for(let n of O1){let o=t[n];typeof o=="string"&&o.length>0&&(e[n]=o)}return e}var O1,wm,sb=be(()=>{"use strict";O1=["viewTitle","openHistoryLabel","openHistoryBusyLabel","newConversationLabel","expandLabel","collapseLabel","resizeLabel","showEarlierMessagesLabel","openConversationLoadingLabel","openConversationErrorTitle","openConversationRetryLabel","openConversationBackLabel","confirmCancelLabel","deleteConversationConfirmTitle","deleteConversationConfirm","deleteConversationConfirmLabel","clearHistoryConfirmTitle","clearHistoryConfirm","clearHistoryVerifiedConfirm","clearHistoryConfirmLabel","resetIdentityConfirmTitle","resetIdentityConfirm","resetIdentityConfirmLabel","conversationDeletedNotice","identityResetNotice","identityResetUnconfirmedNotice"],wm={viewTitle:"Messages",openHistoryLabel:"Messages",openHistoryBusyLabel:"Messages, available once the reply finishes",newConversationLabel:"New conversation",expandLabel:"Expand conversation list",collapseLabel:"Collapse conversation list",resizeLabel:"Resize conversation list",showEarlierMessagesLabel:"Show earlier messages",openConversationLoadingLabel:"Loading conversation",openConversationErrorTitle:"Could not open the conversation.",openConversationRetryLabel:"Try again",openConversationBackLabel:"Back to messages",confirmCancelLabel:"Cancel",deleteConversationConfirmTitle:"Delete conversation",deleteConversationConfirm:"Delete this conversation? This cannot be undone.",deleteConversationConfirmLabel:"Delete",clearHistoryConfirmTitle:"Delete all conversations",clearHistoryConfirm:"Delete all conversations for this assistant on this browser? This cannot be undone.",clearHistoryVerifiedConfirm:"Delete all conversations for this assistant and signed-in user? This cannot be undone.",clearHistoryConfirmLabel:"Delete all",resetIdentityConfirmTitle:"Forget this device",resetIdentityConfirm:"Forget this device? All Persona data stored in this browser is cleared. Records are not deleted elsewhere.",resetIdentityConfirmLabel:"Forget this device",conversationDeletedNotice:"That conversation was deleted. You are now in a new conversation.",identityResetNotice:"This device was forgotten.",identityResetUnconfirmedNotice:"This device was cleared here, but the server could not confirm it."}});function Gc(t){if(!t)return Kc;let e={...Kc};for(let[n,o]of Object.entries(t))typeof o=="string"&&o.length>0&&(e[n]=o);return e}function wr(t,e){return t.replace(/\{(\w+)\}/g,(n,o)=>o in e?String(e[o]):n)}var Kc,Yc=be(()=>{"use strict";sb();Kc={...wm,emptyTitle:"No conversations yet",emptyDescription:"Start a conversation and it will show up here.",errorTitle:"Could not load conversations",errorDescription:"Something went wrong. Please try again.",retryLabel:"Retry",rateLimitedTitle:"Too many requests",rateLimitedDescription:"Please wait a moment before trying again.",groupStarred:"Starred",groupToday:"Today",groupYesterday:"Yesterday",groupPrevious7Days:"Previous 7 days",groupPrevious30Days:"Previous 30 days",groupMonthYear:"{month} {year}",browserOnlyTitle:"On this device",browserOnlyDescription:"Another browser or device keeps its own separate history.",verifyingTitle:"Checking your account",verifyingDescription:"Looking for messages linked to your account.",verifiedTitle:"Available across signed-in devices",verifiedDescription:"This list refreshes when the chat opens rather than syncing live.",authenticationRequiredTitle:"Sign in to see your messages",authenticationRequiredDescription:"Your session expired. Sign in again to load account history.",identityProviderFailedTitle:"Account history is unavailable",identityProviderFailedDescription:"We could not verify your account, so account history is not shown here.",proofNotAdmittedTitle:"Account history is unavailable",proofNotAdmittedDescription:"This assistant is not set up to accept your account identity.",retryIdentityLabel:"Try again",backLabel:"Back to conversation",closeLabel:"Close conversation list",loadingLabel:"Loading conversations",loadMoreLabel:"Load more",loadingMoreLabel:"Loading more conversations",conversationsTitle:"Conversations",rowActionsLabel:"Conversation options",listOptionsLabel:"Conversation options",deleteConversationLabel:"Delete",clearHistoryLabel:"Delete all conversations",resetIdentityLabel:"Forget this device",messageCountLabel:"{count} messages",messageCountLabelOne:"1 message",conversationRemovedNotice:"Conversation deleted.",historyClearedNotice:"All conversations were deleted.",unavailableTitle:"Conversation history is unavailable",unavailableDescription:"Try again later.",newConversationRequiredTitle:"Start a new conversation",newConversationRequiredDescription:"The previous conversation is gone. Start a new one to keep chatting.",rateLimitedWaitDescription:"You can try again in {seconds} seconds.",openFailedLabel:"Could not open that conversation.",deleteFailedLabel:"Could not delete that conversation.",relativeNow:"now",relativeMinutes:"{value}m",relativeHours:"{value}h",relativeDays:"{value}d",relativeWeeks:"{value}w",relativeYears:"{value}y"}});function _1(t){let e=new Date(t);return e.setHours(0,0,0,0),e.getTime()}function ab(t,e){let n=Date.parse(t);return Number.isFinite(n)?n:e}function N1(t,e){let n=ab(t,e),o=_1(e);if(n>=o)return"today";if(n>=o-ib)return"yesterday";if(n>=o-7*ib)return"previous-7-days";if(n>=o-30*ib)return"previous-30-days";let r=new Date(n);return`month:${r.getFullYear()}-${r.getMonth()}`}function F1(t,e,n,o){if(t==="today")return o.groupToday;if(t==="yesterday")return o.groupYesterday;if(t==="previous-7-days")return o.groupPrevious7Days;if(t==="previous-30-days")return o.groupPrevious30Days;let r=new Date(ab(e,n));return wr(o.groupMonthYear,{month:r.toLocaleString(void 0,{month:"long"}),year:r.getFullYear()})}function $E(t,e,n,o="time"){let r=t.filter(a=>a.starred),s=r.length>0?[{key:"starred",label:n.groupStarred,items:r}]:[];if(o==="none"){let a=t.filter(l=>!l.starred);return a.length>0&&s.push({key:"recent",label:n.conversationsTitle,items:a}),s}for(let a of t){if(a.starred)continue;let l=N1(a.updatedAt,e),c=s[s.length-1];if(c&&c.key===l){c.items.push(a);continue}s.push({key:l,label:F1(l,a.updatedAt,e,n),items:[a]})}return s}function zE(t,e,n){let o=Math.max(0,e-ab(t,e)),r=Math.floor(o/6e4);if(r<1)return n.relativeNow;if(r<60)return wr(n.relativeMinutes,{value:r});let s=Math.floor(r/60);if(s<24)return wr(n.relativeHours,{value:s});let a=Math.floor(s/24);if(a<7)return wr(n.relativeDays,{value:a});let l=Math.floor(a/7);return a<365?wr(n.relativeWeeks,{value:l}):wr(n.relativeYears,{value:Math.floor(a/365)})}function UE(t,e){return t===1?e.messageCountLabelOne:wr(e.messageCountLabel,{count:t})}var ib,lb=be(()=>{"use strict";Yc();ib=864e5});function Os(t,e=20){let n=document.createElementNS(xm,"svg");if(n.setAttribute("width",String(e)),n.setAttribute("height",String(e)),n.setAttribute("viewBox","0 0 24 24"),n.setAttribute("fill","none"),n.setAttribute("stroke","currentColor"),n.setAttribute("stroke-width","2"),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.setAttribute("aria-hidden","true"),n.setAttribute("focusable","false"),t==="ellipsis"){for(let r of[12,19,5]){let s=document.createElementNS(xm,"circle");s.setAttribute("cx",String(r)),s.setAttribute("cy","12"),s.setAttribute("r","1"),n.appendChild(s)}return n}let o=$1[t];if(o){let r=document.createElementNS(xm,"rect");r.setAttribute("x",String(o[0])),r.setAttribute("y",String(o[1])),r.setAttribute("width",String(o[2])),r.setAttribute("height",String(o[3])),r.setAttribute("rx","2"),n.appendChild(r)}for(let r of V1[t]){let s=document.createElementNS(xm,"path");s.setAttribute("d",r),n.appendChild(s)}return n}var xm,V1,$1,cb=be(()=>{"use strict";xm="http://www.w3.org/2000/svg",V1={"arrow-left":["m12 19-7-7 7-7","M19 12H5"],plus:["M5 12h14","M12 5v14"],star:["m12 2 2.9 6.2 6.8.7-5.1 4.5 1.4 6.6-6-3.4-6 3.4 1.4-6.6-5.1-4.5 6.8-.7z"],x:["M18 6 6 18","m6 6 12 12"],"panel-left":["M9 3v18"],monitor:["M8 21h8","M12 17v4"],ellipsis:[]},$1={"panel-left":[3,3,18,18],monitor:[2,3,20,14]}});function U1(t){let e=F("span",{className:"persona-history-row-avatar",attrs:{"aria-hidden":"true"}});return z1.test(t)?e.appendChild(F("img",{attrs:{src:t,alt:"",loading:"lazy"}})):e.textContent=t,e}function qE(t){let{conversation:e,copy:n,busy:o,pending:r}=t,s=o||r!==null,a=e.title.trim().length>0,l=e.starred?(()=>{let h=Os("star",11);return h.setAttribute("fill","currentColor"),h.setAttribute("stroke-width","1"),F("span",{className:"persona-history-row-star"},h,F("span",{className:"persona-history-sr-only",text:n.groupStarred}))})():null,c=F("div",{className:"persona-history-row-head"},F("span",{className:"persona-history-row-title persona-history-truncate",text:a?e.title:e.preview??""}),l,F("time",{className:"persona-history-row-time",attrs:{datetime:e.updatedAt},text:zE(e.updatedAt,t.nowMs,n)})),p=a&&e.preview?F("span",{className:"persona-history-row-preview persona-history-truncate",text:e.preview}):null,u=F("button",{className:Gt("persona-history-row",t.active&&"persona-history-row--active",r&&`persona-history-row--${r}`),attrs:{type:"button","data-persona-history-focus":q1(e.id),"data-persona-history-conversation":e.id,...t.active?{"aria-current":"page"}:{},...s?{"aria-disabled":"true"}:{},...r?{"aria-busy":"true"}:{}}},t.avatar?U1(t.avatar):null,F("div",{className:"persona-history-row-body"},c,p,F("span",{className:"persona-history-row-count persona-history-sr-only",text:UE(e.messageCount,n)})));u.addEventListener("click",()=>{s||t.onOpen()});let m=t.showDelete?db({className:"persona-history-row-menu-button",label:`${n.rowActionsLabel}: ${e.title}`,focusKey:j1(e.id),open:t.menuOpen,inert:s,onToggle:t.onToggleMenu}):null;return F("li",{className:Gt("persona-history-item",!t.showDelete&&"persona-history-item--no-menu"),attrs:{"data-persona-history-item":e.id}},u,m,t.menuOpen&&t.showDelete?K1(t):null,t.error?G1(t.error,n,e.id):null)}function K1(t){let{conversation:e,copy:n}=t;return pb({label:`${n.rowActionsLabel}: ${e.title}`,items:[{label:n.deleteConversationLabel,focusKey:Qc(e.id),danger:!0,onSelect:t.onDelete}],onCloseMenu:t.onCloseMenu})}function db(t){let e=F("button",{className:Gt("persona-history-icon-button",t.className),attrs:{type:"button","aria-label":t.label,"aria-haspopup":"menu","aria-expanded":t.open?"true":"false","data-persona-history-focus":t.focusKey,...t.inert?{"aria-disabled":"true"}:{}}});e.appendChild(Os("ellipsis",t.iconSize));let n=()=>e.getAttribute("aria-disabled")==="true";return e.addEventListener("click",o=>{o.stopPropagation(),!n()&&t.onToggle()}),e.addEventListener("keydown",o=>{o.key!=="ArrowDown"&&o.key!=="ArrowUp"||(o.preventDefault(),!(n()||e.getAttribute("aria-expanded")==="true")&&t.onToggle())}),e}function pb(t){let e=F("div",{className:"persona-history-menu",attrs:{role:"menu","aria-label":t.label}});for(let n of t.items){let o=F("button",{className:Gt("persona-history-menu-item",n.danger&&"persona-history-menu-item--danger"),text:n.label,attrs:{type:"button",role:"menuitem",tabindex:"0","data-persona-history-focus":n.focusKey}});o.addEventListener("click",()=>{t.onCloseMenu(),n.onSelect()}),e.appendChild(o)}return e.addEventListener("keydown",n=>{let o=Array.from(e.querySelectorAll('[role="menuitem"]'));if(o.length===0)return;let r=o.indexOf(document.activeElement);if(n.key==="Tab"){t.onCloseMenu({restoreFocus:!0});return}if(n.key==="ArrowDown"){n.preventDefault(),o[(r+1+o.length)%o.length]?.focus();return}if(n.key==="ArrowUp"){n.preventDefault(),o[(r-1+o.length)%o.length]?.focus();return}if(n.key==="Home"){n.preventDefault(),o[0]?.focus();return}n.key==="End"&&(n.preventDefault(),o[o.length-1]?.focus())}),e}function G1(t,e,n){let o=F("button",{className:"persona-history-secondary persona-history-state-action",text:e.retryLabel,attrs:{type:"button","data-persona-history-focus":`row-retry:${n}`}});return o.addEventListener("click",t.retry),F("div",{className:"persona-history-row-error",attrs:{role:"alert"}},F("span",{text:t.message}),o)}var z1,q1,j1,Qc,jE=be(()=>{"use strict";je();cb();lb();z1=/^(https?:|\/|data:)/i;q1=t=>`row:${t}`,j1=t=>`menu:${t}`,Qc=t=>`menu-item:${t}`});function Y1(t){switch(t){case"authentication_failed":case"authentication_required":case"identity_provider_failed":case"proof_not_admitted":case"unsupported_scope":case"unavailable":return t;default:return"unknown"}}function KE(t){if(Gp(t)){if(t.code==="rate_limited")return{kind:"rate_limited",retryAfterSeconds:t.retryAfterSeconds??0};let e=Y1(t.code);return{kind:"error",reason:e,retryable:e!=="unsupported_scope"}}return{kind:"error",reason:"unknown",retryable:!0}}function Q1(t,e){switch(t.state){case"authentication_required":return{title:e.authenticationRequiredTitle,description:e.authenticationRequiredDescription};case"identity_provider_failed":return{title:e.identityProviderFailedTitle,description:e.identityProviderFailedDescription};case"configuration_error":return{title:e.proofNotAdmittedTitle,description:e.proofNotAdmittedDescription};default:return null}}function X1(t,e){switch(t){case"authentication_required":case"authentication_failed":return{title:e.authenticationRequiredTitle,description:e.authenticationRequiredDescription};case"identity_provider_failed":return{title:e.identityProviderFailedTitle,description:e.identityProviderFailedDescription};case"proof_not_admitted":case"unsupported_scope":return{title:e.proofNotAdmittedTitle,description:e.proofNotAdmittedDescription};case"unavailable":return{title:e.unavailableTitle,description:e.unavailableDescription};default:return{title:e.errorTitle,description:e.errorDescription}}}function Sm(t,e,n,o){let r=F("button",{className:"persona-history-secondary persona-history-state-action",text:t,attrs:{type:"button","data-persona-history-focus":e,...n?{"aria-disabled":"true"}:{}}});return r.addEventListener("click",()=>{n||o()}),r}function Xc(t,e,n,o,r){return F("div",{className:"persona-history-state",attrs:{"data-persona-history-state":t,...r?{role:"alert"}:{role:"status"}}},F("p",{className:"persona-history-state-title",text:e}),F("p",{className:"persona-history-state-description",text:n}),o)}function J1(t){let e=["42%","58%","34%"],n=["94%","78%","88%"],o=[0,1,2].map(r=>F("div",{className:"persona-history-skeleton-row",attrs:{"aria-hidden":"true"}},F("div",{className:"persona-history-skeleton-head"},F("div",{className:"persona-history-skeleton-bar persona-history-skeleton-bar--title",style:{width:e[r]}}),F("div",{className:"persona-history-skeleton-bar persona-history-skeleton-bar--time"})),F("div",{className:"persona-history-skeleton-bar persona-history-skeleton-bar--preview",style:{width:n[r]}})));return F("div",{className:"persona-history-view-loading",attrs:{"data-persona-history-state":"loading",role:"status","aria-label":t.loadingLabel}},...o)}function GE(t){let{state:e,copy:n,busy:o}=t;if(e.kind==="loading")return J1(n);if(e.kind==="empty"){let l=Q1(t.identityStatus,n);return l?Xc("identity",l.title,l.description,t.onRetry?Sm(n.retryIdentityLabel,"state-retry",o,t.onRetry):null,!0):Xc("empty",n.emptyTitle,n.emptyDescription,null,!1)}if(e.kind==="rate_limited"){let l=e.retryAfterSeconds>0?wr(n.rateLimitedWaitDescription,{seconds:e.retryAfterSeconds}):n.rateLimitedDescription;return Xc("rate_limited",n.rateLimitedTitle,l,t.onRetry?Sm(n.retryLabel,"state-retry",o,t.onRetry):null,!1)}if(e.kind==="new_conversation_required")return Xc("new_conversation_required",n.newConversationRequiredTitle,n.newConversationRequiredDescription,t.onStartNew?Sm(n.newConversationLabel,"state-retry",o,t.onStartNew):null,!0);let{title:r,description:s}=X1(e.reason,n),a=e.reason==="authentication_required"||e.reason==="authentication_failed"||e.reason==="identity_provider_failed"?n.retryIdentityLabel:n.retryLabel;return Xc("error",r,s,e.retryable&&t.onRetry?Sm(a,"state-retry",o,t.onRetry):null,!0)}var YE=be(()=>{"use strict";je();Yc();Zl()});function Am(t){return`${t.state}:${"reason"in t?t.reason:""}`}function XE(t,e){switch(t.state){case"verified":return{title:e.verifiedTitle,description:e.verifiedDescription,pending:!1};case"verifying":case"resetting":return{title:e.verifyingTitle,description:e.verifyingDescription,pending:!0};case"authentication_required":return{title:e.authenticationRequiredTitle,description:e.authenticationRequiredDescription,pending:!1};case"identity_provider_failed":return{title:e.identityProviderFailedTitle,description:e.identityProviderFailedDescription,pending:!1};case"configuration_error":return{title:e.proofNotAdmittedTitle,description:e.proofNotAdmittedDescription,pending:!1};case"unavailable":return{title:e.unavailableTitle,description:e.unavailableDescription,pending:!1};default:return{title:e.browserOnlyTitle,description:e.browserOnlyDescription,pending:!1}}}function iD(t){return t.state==="verified"||t.state==="browser_only"}function aD(t){return t.state==="authentication_required"||t.state==="identity_provider_failed"||t.state==="configuration_error"}function ub(t){let e=Gc(t.copy),n=t.now??(()=>Date.now()),o=t.pageSize??Z1,r=`persona-history-title-${Math.random().toString(36).slice(2,8)}`,s=[],a=null,l={kind:"loading",phase:"initial"},c=null,p=t.activeConversationId,u=t.provider.getIdentityStatus(),m=Am(u),g=null,h=!1,b=!1,C=0,M=t.presentation,E=t.collapsible!==!1,T=t.collapsed===!0,R=t.railSide==="right",A=t.renderDom!==!1,D=new Map,W=null,U=_E(),B=z=>{!A&&t.onAnnounce?t.onAnnounce(z):U.announce(z)},O=()=>c!==null,H=`${r}-body`,S=F("button",{className:"persona-history-icon-button persona-history-back",attrs:{type:"button"}}),x=()=>M==="rail"&&E,P,L=()=>{if(t.railBrand){if(!x()){S.classList.remove("persona-history-back--branded");return}if(P===void 0){let z=t.railBrand(!0);P=z?F("span",{className:"persona-history-brand-mark persona-history-toggle-brand",attrs:{"aria-hidden":"true"}},z):null}P&&(S.classList.add("persona-history-back--branded"),S.appendChild(P))}},G=()=>{let z=x(),ge=M==="rail";S.setAttribute("data-persona-history-focus",z?"collapse":"close"),S.setAttribute("aria-label",z?T?e.expandLabel:e.collapseLabel:ge?e.closeLabel:e.backLabel),z?(S.setAttribute("aria-expanded",T?"false":"true"),S.setAttribute("aria-controls",H),t.collapseShortcut?.aria&&S.setAttribute("aria-keyshortcuts",t.collapseShortcut.aria)):(S.removeAttribute("aria-expanded"),S.removeAttribute("aria-controls"),S.removeAttribute("aria-keyshortcuts")),S.replaceChildren(Os(z?"panel-left":ge?"x":"arrow-left")),L()};G(),S.addEventListener("click",()=>{x()?t.onToggleCollapse?.():t.onClose()});let V=F("h2",{className:"persona-history-title",text:e.viewTitle,attrs:{id:r}}),K=F("span",{className:"persona-history-scope-title"}),ee=F("p",{className:"persona-history-scope"},F("span",{className:"persona-history-scope-icon",attrs:{"aria-hidden":"true"}},Os("monitor",14)),K),oe=F("div",{className:"persona-history-heading-group"},V),ne=!1,le,de=()=>{let z=M==="rail",ge=z?t.renderRailHeader:void 0,Ue=null,at=ge!==void 0;if(ge)try{Ue=ge({collapsed:T,defaultTitle:e.viewTitle})}catch(Ce){at=!1,ne||(ne=!0,console.warn("[persona] history rail renderHeader threw",Ce))}if(!at&&z&&t.railBrand){if(le===void 0){let Ce=t.railBrand(!1);le=Ce?F("span",{className:"persona-history-heading-brand",attrs:{"aria-hidden":"true"}},F("span",{className:"persona-history-brand-mark"},Ce),F("span",{className:"persona-history-wordmark",text:e.viewTitle})):null}le&&(at=!0,Ue=le)}V.classList.toggle("persona-history-sr-only",at),oe.replaceChildren(V),Ue&&oe.appendChild(Ue)};de();let ve=F("button",{className:"persona-history-icon-button persona-history-new-icon",attrs:{type:"button","data-persona-history-focus":"new-icon","aria-label":e.newConversationLabel}});ve.appendChild(Os("plus")),ve.addEventListener("click",()=>{we()});let Le=[S,ve].map(z=>t.attachTooltip?.({anchor:z,text:()=>z.getAttribute("aria-label")??"",...z===S&&t.collapseShortcut?{hint:()=>x()?t.collapseShortcut.hint:""}:{}})),se=F("div",{className:"persona-history-topbar"}),_=null,Te=()=>{let z=M==="rail",ge=z?R?"rail-right":"rail":"panel";ge!==_&&(_=ge,ge==="rail"?se.append(oe,S):se.append(S,oe),z?ve.remove():se.appendChild(ve),Y.classList.toggle("persona-history-view--rail-right",ge==="rail-right"))},Re=F("div",{className:"persona-history-scope-alert"}),ut=`${r}-scope`,At=Os("plus",18),Wt=F("button",{className:"persona-history-new",attrs:{type:"button","data-persona-history-focus":"new"}},At,F("span",{text:e.newConversationLabel}));Wt.addEventListener("click",()=>{we()});let bt=F("div",{className:"persona-history-list-region"}),xe=t.showDeleteAll!==!1,Ne=!!t.provider.resetDevice,Ae=t.listActions??[],vt=xe||Ne||Ae.length>0?db({className:"persona-history-list-options",label:e.listOptionsLabel,focusKey:`menu:${Vi}`,open:!1,inert:!0,iconSize:16,onToggle:()=>ot(Vi)}):null,X=F("h3",{className:"persona-history-conversations-title",text:e.conversationsTitle}),I=F("div",{className:"persona-history-caption",attrs:{"data-persona-history-item":Vi}},X,t.showScopeStatus?ee:null,vt),j=F("div",{className:"persona-history-body",attrs:{id:H}},t.showScopeStatus?Re:null,Wt,I,bt),J=t.headerPlacement??"inline";J==="external"&&se.classList.add("persona-history-topbar--shell","persona-history-topbar--shell-enter");let Y=F("div",{className:Gt("persona-history-view",`persona-history-view--${t.presentation}`,"persona-history-view--enter"),attrs:{role:"region","aria-labelledby":r,"data-persona-history-presentation":t.presentation}},U.element,J==="inline"?se:null,j),ie=()=>{Y.classList.toggle("persona-history-view--rail-collapsed",T&&x())};ie(),Te();let Me=(z,ge)=>{let Ue=`${r}-s${ge}`,at=F("div",{className:Gt("persona-history-nav",z.placement==="footer"&&"persona-history-nav--footer"),attrs:{role:"group","data-persona-rail-section":z.id,...z.title?{"aria-labelledby":Ue}:{"aria-label":z.id}}});z.title&&at.appendChild(F("h3",{className:"persona-history-group-heading",text:z.title,attrs:{id:Ue}}));for(let Ce of z.items){let St=Ce.iconNode?.()??null,Bn=F("button",{className:Gt("persona-history-nav-item",St&&"persona-history-nav-item--icon"),attrs:{type:"button","aria-label":Ce.label,"data-persona-rail-item":Ce.id}},St?F("span",{className:"persona-history-nav-icon"},St):null,F("span",{className:"persona-history-nav-label persona-history-truncate",text:Ce.label}),Ce.badge?F("span",{className:"persona-history-nav-badge",text:Ce.badge}):null);Bn.addEventListener("click",()=>Ce.onSelect()),at.appendChild(Bn)}return at},Ee=null,_e=null,Ct=()=>{!Ee||!A||M!=="rail"||T===_e||(_e=T,t.railSections.forEach((z,ge)=>{if(!z.render)return;let Ue=Ee[ge],at=z.title?Ue.firstElementChild:null,Ce=null;try{Ce=z.render(T)}catch(St){z.render=void 0,console.warn("[persona] history rail section threw",z.id,St)}Ue.replaceChildren(...at?[at]:[],...Ce?[Ce]:[]),Ue.hidden=!Ce}))},Ot=()=>{let z=t.railSections;if(Y.classList.toggle("persona-history-view--has-nav",M==="rail"&&!!z?.some(ge=>ge.placement==="above-conversations")),!!z?.length){if(M!=="rail"){Ee?.forEach(ge=>ge.remove());return}Ee??(Ee=z.map(Me));for(let ge of["above-conversations","below-conversations","footer"]){let Ue=ge==="above-conversations"?I.parentNode===j?I:bt:null;z.forEach((at,Ce)=>{at.placement===ge&&j.insertBefore(Ee[Ce],Ue)})}Ct()}};Ot(),mu(Y,"persona-history-view",FE);let rt=(z,ge)=>{let Ue=Y.ownerDocument.defaultView?.getComputedStyle(Y).getPropertyValue(z),at=Number.parseFloat(Ue??"");return Number.isFinite(at)&&at>=0?at:ge},Ze=(z,ge)=>Y.ownerDocument.defaultView?.getComputedStyle(Y).getPropertyValue(z).trim()||ge,ct=null,Ht=()=>{ct!==null&&(clearTimeout(ct),ct=null),Y.removeEventListener("animationend",Ht),Y.classList.remove("persona-history-view--enter")};Y.addEventListener("animationend",Ht),ct=setTimeout(()=>{ct=setTimeout(Ht,rt("--persona-history-enter-ms",eD)+60)},0);let Z=null,Fe=()=>{Z!==null&&(clearTimeout(Z),Z=null),se.classList.remove("persona-history-topbar--shell-enter")},He=()=>{Fe(),se.classList.add("persona-history-topbar--shell-enter"),Z=setTimeout(Fe,QE+60)};J==="external"&&(Z=setTimeout(Fe,QE+60));let nt=[],Bt=null,Ie=()=>{if(Bt)return Bt;if(b||rD()||typeof Y.animate!="function")return Ht(),null;let z=Y.ownerDocument.defaultView?.getComputedStyle(j).opacity||"1";Ht(),Y.style.pointerEvents="none",qe.style.pointerEvents="none";let ge={duration:rt("--persona-history-exit-ms",tD),easing:Ze("--persona-history-exit-easing",nD),fill:"forwards"},Ue=oD[M];return nt=[j.animate([{opacity:z,transform:"none"},{opacity:0,transform:`translateX(${Ue}px)`}],ge)],Bt=Promise.all(nt.map(sD)).then(()=>{}),Bt},Be=(z,ge)=>{z&&(ge?z.setAttribute("aria-disabled","true"):z.removeAttribute("aria-disabled"))},qe=se,Tt=null,mt=()=>{let z=t.slots?.header;if(!z)return;let ge=`${M}|${Am(u)}|${c?`${c.kind}:${"conversationId"in c?c.conversationId:""}`:""}`;if(ge===Tt)return;Tt=ge;let Ue=z({identityStatus:u,pendingAction:c,copy:e,defaultRenderer:()=>se})??se;Ue!==qe&&(qe.replaceWith(Ue),qe=Ue)},xt=null,Mn=()=>{if(!t.showScopeStatus)return;let z=Am(u);if(z===xt)return;xt=z;let ge=XE(u,e);K.textContent=ge.title;let Ue=iD(u);if(ee.hidden=!Ue,Re.replaceChildren(...Ue?[]:[F("span",{className:"persona-history-scope-alert-title",text:ge.title})],F("span",{className:"persona-history-scope-description",text:ge.description,attrs:{id:ut}})),Re.setAttribute("data-persona-history-scope-tone",Ue?"ambient":"attention"),Ue?ee.setAttribute("aria-describedby",ut):ee.removeAttribute("aria-describedby"),ge.pending?Re.setAttribute("role","status"):Re.removeAttribute("role"),Re.setAttribute("data-persona-history-identity",u.state),ee.setAttribute("data-persona-history-identity",u.state),aD(u)){let at=F("button",{className:"persona-history-secondary persona-history-state-action",text:e.retryIdentityLabel,attrs:{type:"button","data-persona-history-focus":"identity-retry"}});at.addEventListener("click",()=>{O()||We("refresh")}),Re.appendChild(at)}},ft=z=>c?c.kind==="open"&&c.conversationId===z?"opening":c.kind==="delete"&&c.conversationId===z?"deleting":null:null,_t=()=>{let z=document.activeElement;return!(z instanceof HTMLElement)||!Y.contains(z)?null:z.getAttribute("data-persona-history-focus")},Vt=z=>{if(h&&g){h=!1;let ge=Y.querySelector(`[data-persona-history-focus="${Qc(g)}"]`);if(ge){ge.focus();return}}z&&Y.querySelector(`[data-persona-history-focus="${z}"]`)?.focus()},pn=()=>{if(!W)return null;let z=F("button",{className:"persona-history-secondary persona-history-state-action",text:e.retryLabel,attrs:{type:"button","data-persona-history-focus":"action-retry"}}),ge=W;return z.addEventListener("click",()=>{O()||ge.retry()}),F("div",{className:"persona-history-row-error",attrs:{role:"alert"}},F("span",{text:ge.message}),z)},ao=()=>$E(s,n(),e,t.grouping).map((z,ge)=>{let Ue=`${r}-g${ge}`,at=F("ul",{className:"persona-history-list",attrs:{"aria-labelledby":Ue}});for(let Ce of z.items){let St=()=>qE({conversation:Ce,active:Ce.id===p,pending:ft(Ce.id),busy:O(),menuOpen:g===Ce.id,error:D.get(Ce.id)??null,avatar:t.rowAvatar,showDelete:t.showDelete!==!1,nowMs:n(),copy:e,onOpen:()=>{Xo(Ce.id)},onToggleMenu:()=>ot(Ce.id),onCloseMenu:$e=>Nt($e),onDelete:()=>{lo(Ce.id)}}),Qn=t.slots?.conversation?.({conversation:Ce,active:Ce.id===p,pending:ft(Ce.id),open:()=>Xo(Ce.id),requestDelete:()=>lo(Ce.id),defaultRenderer:St})??St();at.appendChild(Qn instanceof HTMLLIElement?Qn:F("li",{className:"persona-history-item"},Qn))}return F("div",{className:"persona-history-group",attrs:{"data-persona-history-group":z.key}},F("h3",{className:Gt("persona-history-group-heading",z.key==="recent"&&"persona-history-sr-only"),text:z.label,attrs:{id:Ue}}),at)}),Yn=()=>{if(!a)return null;let z=c?.kind==="load-more"||l.kind==="loading"&&l.phase==="load-more",ge=F("button",{className:"persona-history-secondary persona-history-load-more",text:z?e.loadingMoreLabel:e.loadMoreLabel,attrs:{type:"button","data-persona-history-focus":"load-more",...z?{"aria-busy":"true","aria-disabled":"true"}:{},...O()&&!z?{"aria-disabled":"true"}:{}}});return ge.addEventListener("click",()=>{O()||We("load-more")}),ge},Zc=()=>{let z=_t(),ge=[pn()],Ue=s.length>0;if(Ue&&(ge.push(...ao()),ge.push(Yn())),l.kind!=="ready"&&!(l.kind==="loading"&&l.phase!=="initial"&&Ue)){let Ce=l,St=Ce.kind==="loading"?void 0:()=>We("refresh"),Bn=Ce.kind==="new_conversation_required"?()=>we():void 0,Qn=()=>GE({state:Ce,copy:e,identityStatus:u,busy:O(),...St?{onRetry:()=>{St()}}:{},...Bn?{onStartNew:()=>{Bn()}}:{}}),$e=t.slots?.state?.({state:Ce,identityStatus:u,copy:e,...St?{retry:St}:{},...Bn?{startNewConversation:Bn}:{},defaultRenderer:Qn});ge.push($e??Qn())}bt.replaceChildren(...ge.filter(Ce=>!!Ce)),Vt(z)},_s=()=>{let z=l.kind==="loading"&&s.length===0,ge=[],Ue=()=>ge.length===0?Qc(Vi):`${Qc(Vi)}-${ge.length}`;if(!z)for(let at of Ae)ge.push({label:at.label,focusKey:Ue(),danger:at.danger===!0,onSelect:()=>{at.onSelect({conversations:[...s]})}});return xe&&!(s.length===0&&(l.kind==="empty"||z))&&ge.push({label:e.clearHistoryLabel,focusKey:Ue(),danger:!0,onSelect:()=>{Ve()}}),Ne&&!z&&ge.push({label:e.resetIdentityLabel,focusKey:Ue(),danger:!0,onSelect:()=>{pt()}}),ge},Qo=()=>{if(Be(Wt,O()),Be(ve,O()),vt){let z=_s(),ge=l.kind==="loading"&&s.length===0;vt.hidden=z.length===0&&!ge,Be(vt,O()||z.length===0),vt.setAttribute("aria-expanded",g===Vi?"true":"false");let Ue=I.querySelector(".persona-history-menu");if(g!==Vi||z.length===0)Ue?.remove();else{let at=pb({label:e.listOptionsLabel,items:z,onCloseMenu:Ce=>Nt(Ce)});Ue?Ue.replaceWith(at):I.appendChild(at)}}I.hidden=M!=="rail"&&(!vt||vt.hidden)&&(!t.showScopeStatus||ee.hidden)},Cn,dt=()=>{let z=t.onActiveConversationChange;if(!z)return;let ge=s.find(at=>at.id===p)??null,Ue=ge?`${ge.id}\0${ge.title}\0${ge.starred?1:0}`:"";Ue!==Cn&&(Cn=Ue,z(ge))},Se=()=>{if(!b){if(dt(),!A){t.onModelChange?.();return}mt(),Mn(),Qo(),Zc(),Ct()}},Nt=z=>{if(!g)return;let ge=g;g=null,h=!1,Se(),z?.restoreFocus&&Y.querySelector(`[data-persona-history-focus="menu:${ge}"]`)?.focus()},ot=z=>{if(g===z){Nt({restoreFocus:!0});return}g=z,h=!0,Se()},Pe=z=>{if(!g)return;let ge=z.target;ge instanceof Node&&Y.contains(ge)&&ge.closest?.(`[data-persona-history-item="${g}"]`)||Nt()};document.addEventListener("pointerdown",Pe,!0);let pe=z=>{z.key!=="Escape"||!g||(z.stopPropagation(),Nt({restoreFocus:!0}))};Y.addEventListener("keydown",pe);async function We(z){if(b)return;let ge=++C,Ue=z==="load-more"?a:null;if(!(z==="load-more"&&!Ue)){c={kind:z==="load-more"?"load-more":"refresh"},l={kind:"loading",phase:z},z!=="load-more"&&(D.clear(),W=null),Nt(),Se();try{let at=await t.provider.list({limit:o,context:t.context,...Ue?{cursor:Ue}:{},...t.targetId?{targetId:t.targetId}:{}});if(b||ge!==C)return;s=Ue?[...s,...at.items]:at.items,a=at.nextCursor,l=s.length===0?{kind:"empty"}:{kind:"ready"}}catch(at){if(b||ge!==C)return;l=KE(at)}finally{!b&&ge===C&&(c=null,Se())}}}let Ns=z=>{s=s.filter(ge=>ge.id!==z),D.delete(z),p===z&&(p=null),s.length===0&&!a&&(l={kind:"empty"})};async function Xo(z){if(!(O()||b)){D.delete(z),Nt(),c={kind:"open",conversationId:z},Se();try{if(await t.onSelect(z),b)return;p=z}catch{if(b)return;D.set(z,{message:e.openFailedLabel,retry:()=>{Xo(z)}})}finally{b||(c=null,Se())}}}async function lo(z){if(O()||b)return"cancelled";D.delete(z),c={kind:"delete",conversationId:z},Se();try{let ge=await t.onRequestDeleteConversation(z);return b||ge==="deleted"&&(Ns(z),B(e.conversationRemovedNotice)),ge}catch(ge){return b||(Gp(ge)&&ge.code==="not_found"?Ns(z):D.set(z,{message:e.deleteFailedLabel,retry:()=>{lo(z)}})),"cancelled"}finally{b||(c=null,Se())}}async function we(){if(!(O()||b)){W=null,Nt(),c={kind:"start-new"},Se();try{if(await t.onStartNew(),b)return;l.kind==="new_conversation_required"&&(l=s.length===0?{kind:"empty"}:{kind:"ready"})}catch{if(b)return;W={message:e.errorDescription,retry:()=>{we()}}}finally{b||(c=null,Se())}}}async function Ve(){if(O()||b)return"cancelled";W=null,Nt(),c={kind:"clear"},Se();try{let z=await t.onRequestClearHistory();return b||z==="cleared"&&(s=[],a=null,p=null,l={kind:"empty"},B(e.historyClearedNotice)),z}catch{return b||(W={message:e.errorDescription,retry:()=>{Ve()}}),"cancelled"}finally{b||(c=null,Se())}}let Tn={outcome:"cancelled"};async function pt(){if(O()||b||!t.onRequestResetIdentity)return Tn;W=null,Nt(),c={kind:"reset"},Se();try{let z=await t.onRequestResetIdentity();return b||z.outcome==="reset"&&(B(z.remoteRevocationConfirmed?e.identityResetNotice:e.identityResetUnconfirmedNotice),c=null,await We("refresh")),z}catch{return b||(W={message:e.errorDescription,retry:()=>{pt()}}),Tn}finally{!b&&c?.kind==="reset"&&(c=null,Se())}}let gn=t.provider.subscribeIdentityStatus(z=>{if(b)return;let ge=Am(z),Ue=ge!==m;u=z,m=ge,Se(),Ue&&z.state!=="verifying"&&B(XE(z,e).title)}),km=t.provider.subscribeAvailability?.(z=>{if(!b){if(z){We("refresh");return}s=[],a=null,l={kind:"error",reason:"unavailable",retryable:!1},Se()}});return Se(),We("initial"),{element:Y,copy:e,getModel:()=>({conversations:s,activeConversationId:p,state:l,pendingAction:c,identityStatus:u,nextCursor:a}),operations:{refresh:async()=>{O()||await We("refresh")},loadMore:async()=>{O()||await We("load-more")},openConversation:z=>Xo(z),startNewConversation:()=>we(),requestDeleteConversation:z=>lo(z),requestClearConversationHistory:()=>Ve(),requestResetHistoryIdentity:()=>pt()},setDomRenderEnabled:z=>{z!==A&&(A=z,z&&Se())},refresh:()=>{We("refresh")},setPresentation:z=>{if(z===M)return;Ht(),M=z,Tt=null;let ge=z==="rail";Y.classList.toggle("persona-history-view--panel",!ge),Y.classList.toggle("persona-history-view--rail",ge),Y.setAttribute("data-persona-history-presentation",z),G(),ie(),Te(),de(),Ot(),Se()},setCollapsed:z=>{z!==T&&(T=z,ie(),G(),de(),Ct())},setRailSide:z=>{R=z==="right",Te()},getHeaderElement:()=>qe,setHeaderPlacement:z=>{if(z===J)return;J=z;let ge=z==="external";if(se.classList.toggle("persona-history-topbar--shell",ge),ge){He(),qe.remove();return}Fe(),Y.insertBefore(qe,j)},setActiveConversationId:z=>{p!==z&&(p=z,Se())},applyConversationSummary:z=>{let ge=s.findIndex(Ue=>Ue.id===z.id);ge!==-1&&(s[ge]=z,Se())},removeConversationSummary:z=>{s.some(ge=>ge.id===z)&&(Ns(z),Se())},setNewConversationRequired:z=>{z?l={kind:"new_conversation_required"}:l.kind==="new_conversation_required"&&(l=s.length===0?{kind:"empty"}:{kind:"ready"}),Se()},playExit:Ie,destroy:()=>{b=!0,C+=1,Ht(),Fe(),Le.forEach(z=>z?.destroy()),qe.remove(),nt.forEach(z=>z.cancel()),nt=[],gn(),km?.(),document.removeEventListener("pointerdown",Pe,!0),Y.removeEventListener("keydown",pe),U.destroy(),Y.remove(),Y.replaceChildren()}}}var Z1,Vi,eD,QE,tD,nD,oD,rD,sD,JE=be(()=>{"use strict";Oa();je();NE();VE();Yc();lb();cb();jE();YE();Zl();Z1=25,Vi="persona:list-options",eD=180,QE=120,tD=160,nD="cubic-bezier(0.4, 0, 1, 1)",oD={panel:20,rail:12},rD=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,sD=t=>t.finished?t.finished.then(()=>{},()=>{}):Promise.resolve()});var mb=be(()=>{"use strict";JE();Yc()});var ZE={};$n(ZE,{HISTORY_VIEW_COPY_DEFAULTS:()=>Kc,createHistoryView:()=>ub,resolveHistoryViewCopy:()=>Gc});var e0=be(()=>{"use strict";mb();mb()});var UD={};$n(UD,{createThemePreview:()=>T0});module.exports=UP(UD);var Tp=require("lucide");zn();var ww=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function jo(t,e){if(!t)return e;if(!e)return t;let n={...t};for(let[o,r]of Object.entries(e)){let s=n[o];ww(s)&&ww(r)?n[o]=jo(s,r):n[o]=r}return n}var hg=Symbol("persona.defaultsProvenance"),yg=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function up(t,e=""){return Object.entries(t).flatMap(([n,o])=>{let r=e?`${e}.${n}`:n;return yg(o)?up(o,r):[r]})}function xw(t,e){for(let n of e.split(".")){if(!yg(t)||!Object.prototype.hasOwnProperty.call(t,n))return"absent";if(t=t[n],t===void 0)return"clear"}return"explicit"}function Sw(t,e){return t?.[hg]??e.filter(n=>xw(t,n)==="explicit")}function bg(t,e){return Object.defineProperty(t,hg,{value:e,enumerable:!0,configurable:!0}),t}function vg(t,e,n){return bg(t,Sw(e,up(n)))}function Aw(t,e,n){let o=e[hg];if(o)return o;let r=new Set(Sw(t,n));for(let s of n){let a=xw(e,s);a==="clear"&&r.delete(s),a==="explicit"&&r.add(s)}return[...r]}function Mw(t,e,n){let o={...t};for(let r of e){if(n.includes(r))continue;let s=r.split("."),a=o;for(let l of s.slice(0,-1)){let c=a[l];if(!yg(c)){a=void 0;break}a[l]={...c},a=a[l]}a&&delete a[s[s.length-1]]}return o}var Tw="var(--persona-components-panel-width)",Cg=Symbol("persona.panelAliasProvenance"),vi=(t,e)=>t!=null&&Object.prototype.hasOwnProperty.call(t,e),mp=(t,e)=>vi(t,e)&&t[e]!==void 0,qP=t=>({launcherWidth:mp(t?.launcher,"width"),legacyLauncherWidth:mp(t,"launcherWidth"),sidebarWidth:mp(t?.launcher,"sidebarWidth"),dockWidth:mp(t?.launcher?.dock,"width")}),Nr=t=>{let e=t?.[Cg];return e?{...e}:qP(t)},wg=(t,e)=>(Object.defineProperty(t,Cg,{value:e,enumerable:!0,configurable:!0}),t),xg=(t,e)=>wg(t,Nr(e)),Ew=(t,e)=>{let n=e[Cg];if(n)return{...n};let o=Nr(t);return vi(e,"launcherWidth")&&(o.legacyLauncherWidth=e.launcherWidth!==void 0),vi(e,"launcher")&&e.launcher===void 0?(o.launcherWidth=!1,o.sidebarWidth=!1,o.dockWidth=!1,o):(vi(e.launcher,"width")&&(o.launcherWidth=e.launcher?.width!==void 0),vi(e.launcher,"sidebarWidth")&&(o.sidebarWidth=e.launcher?.sidebarWidth!==void 0),vi(e.launcher,"dock")&&e.launcher?.dock===void 0?o.dockWidth=!1:vi(e.launcher?.dock,"width")&&(o.dockWidth=e.launcher?.dock?.width!==void 0),o)};var Sg="min(440px, calc(100vw - 24px))";var Fl="40px",Ag="How can I help...",Fr={collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",previewMaxLines:3,expandable:!0,loadingAnimation:"none"},wi={activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},jP={enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:Sg,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:Fl,closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},KP={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",tooltip:{delayMs:200,skipDelayMs:300},launcher:jP,copy:{inputPlaceholder:Ag,sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",borderWidth:"0px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"anchor-top",anchorTopOffset:16,showActivityWhilePinned:!0},toolCallDisplay:Fr,reasoningDisplay:wi,streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"},history:{enabled:!1,presentation:"panel",showScopeStatus:!0,showDelete:!0,showDeleteAll:!0}},suggestionChips:["Show me what you can help with","Walk me through getting started","Answer a question about this page"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1},GP={},YP={variant:"circle",width:"min(400px, calc(100vw - 24px))",headerIconSize:"20px"},Ci={launcher:YP,features:{toolCallDisplay:{variant:"row",iconVisibility:"active",autoExpand:!1,grouped:!0,groupedMode:"collapsible",loadingAnimation:"shimmer"},reasoningDisplay:{variant:"row",iconVisibility:"active",autoExpand:!1,loadingAnimation:"shimmer"}},composer:{layout:"single-row",placement:"overlay"},sendButton:{iconName:"arrow-up"},statusIndicator:{mode:"transient"},layout:{contentMaxWidth:"768px",topFade:!0,header:{showSubtitle:!1},messages:{assistant:{width:"full"}}}};function bs(t){return t?.future?.v5Defaults===!0?"v5":"v4"}function fp(t){let e=bs(t)==="v5"?Ci:GP;return jo(KP,e)}var iO=fp();function kw(t,e){if(!(!t&&!e))return t?e?jo(t,e):t:e}function gp(t){let e=fp(t);return t?vg(xg({...e,...t,theme:kw(e.theme,t.theme),darkTheme:kw(e.darkTheme,t.darkTheme),launcher:{...e.launcher,...t.launcher,dock:{...e.launcher?.dock,...t.launcher?.dock},clearChat:{...e.launcher?.clearChat,...t.launcher?.clearChat}},...e.composer||t.composer?{composer:{...e.composer,...t.composer}}:{},tooltip:{...e.tooltip,...t.tooltip},copy:{...e.copy,...t.copy},sendButton:{...e.sendButton,...t.sendButton},statusIndicator:{...e.statusIndicator,...t.statusIndicator},voiceRecognition:{...e.voiceRecognition,...t.voiceRecognition},features:(()=>{let n=e.features?.artifacts,o=t.features?.artifacts,r=e.features?.scrollToBottom,s=t.features?.scrollToBottom,a=e.features?.scrollBehavior,l=t.features?.scrollBehavior,c=e.features?.streamAnimation,p=t.features?.streamAnimation,u=e.features?.askUserQuestion,m=t.features?.askUserQuestion,g=e.features?.history,h=t.features?.history,b=n===void 0&&o===void 0?void 0:{...n,...o,layout:{...n?.layout,...o?.layout}},C=r===void 0&&s===void 0?void 0:{...r,...s},M=a===void 0&&l===void 0?void 0:{...a,...l},E=c===void 0&&p===void 0?void 0:{...c,...p},T=u===void 0&&m===void 0?void 0:{...u,...m,styles:{...u?.styles,...m?.styles}},R=g===void 0&&h===void 0?void 0:{...g,...h,copy:{...g?.copy,...h?.copy}};return{...e.features,...t.features,toolCallDisplay:{...e.features?.toolCallDisplay,...t.features?.toolCallDisplay},reasoningDisplay:{...e.features?.reasoningDisplay,...t.features?.reasoningDisplay},...C!==void 0?{scrollToBottom:C}:{},...M!==void 0?{scrollBehavior:M}:{},...b!==void 0?{artifacts:b}:{},...E!==void 0?{streamAnimation:E}:{},...T!==void 0?{askUserQuestion:T}:{},...R!==void 0?{history:R}:{}}})(),suggestionChips:t.suggestionChips??e.suggestionChips,suggestionChipsConfig:{...e.suggestionChipsConfig,...t.suggestionChipsConfig},layout:{...e.layout,...t.layout,header:{...e.layout?.header,...t.layout?.header},messages:{...e.layout?.messages,...t.layout?.messages,...e.layout?.messages?.user||t.layout?.messages?.user?{user:{...e.layout?.messages?.user,...t.layout?.messages?.user}}:{},...e.layout?.messages?.assistant||t.layout?.messages?.assistant?{assistant:{...e.layout?.messages?.assistant,...t.layout?.messages?.assistant}}:{},avatar:{...e.layout?.messages?.avatar,...t.layout?.messages?.avatar},timestamp:{...e.layout?.messages?.timestamp,...t.layout?.messages?.timestamp}},slots:{...e.layout?.slots,...t.layout?.slots}},markdown:{...e.markdown,...t.markdown,options:{...e.markdown?.options,...t.markdown?.options}},messageActions:{...e.messageActions,...t.messageActions}},t),t,Ci):vg(xg(e),void 0,Ci)}je();Zt();je();var Cp=require("lucide");zn();var sL=["persona-w-full","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"],iL="persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none",aL="persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none",lL=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),wp=(t,e)=>{let n=v("div",["persona-message-bubble",t,...sL].join(" "));return n.id=`bubble-${e}`,n.setAttribute("data-message-id",e),n},xp=t=>{let e=v("button",t.expandable?iL:aL);return e.type="button",t.expandable&&(e.setAttribute("aria-expanded",t.expanded?"true":"false"),e.setAttribute("data-expand-header","true")),e.setAttribute("data-bubble-type",t.bubbleType),e},kg=(t,e,n)=>{t.innerHTML="";let o=Ge(e?Cp.ChevronUp:Cp.ChevronDown,16,n,2);o?t.appendChild(o):t.textContent=e?"Hide":"Show"},wa=(t,e,n)=>{if(!n.expandable)return t.append(e),null;let o=v("div","persona-flex persona-items-center");kg(o,n.expanded,n.iconColor);let r=v("div",n.metaGap?"persona-flex persona-items-center persona-gap-2 persona-ml-auto":"persona-flex persona-items-center persona-ml-auto");return r.append(o),t.append(e,r),o},Sp=t=>{let e=v("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(e.setAttribute("data-persona-collapsed-preview",t.previewKind),e.style.display="none",e.style.whiteSpace="pre-wrap",!t.expanded&&t.isActive&&t.activePreview&&t.previewText){let n=t.renderPreview?.();lL(e,n)||(e.textContent=t.previewText),e.style.display=""}return!t.expanded&&t.isActive&&t.activeMinHeight&&(t.bubble.style.minHeight=t.activeMinHeight),e},Ap=t=>{t.header.setAttribute("aria-expanded",t.expanded?"true":"false"),t.toggleIcon&&kg(t.toggleIcon,t.expanded,t.iconColor),t.content.style.display=t.expanded?"":"none",t.collapsedPreview.style.display=t.expanded?"none":t.collapsedPreview.textContent||t.collapsedPreview.childNodes.length?"":"none"},Mp=(t,e,n)=>{let o=n.stateSet.has(t),r=e.querySelector('button[data-expand-header="true"]'),s=e.querySelector(".persona-border-t"),a=e.querySelector(`[data-persona-collapsed-preview="${n.previewKind}"]`);if(!r||!s)return;r.setAttribute("aria-expanded",o?"true":"false");let c=r.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");c&&kg(c,o,n.iconColor),s.style.display=o?"":"none",a&&(a.style.display=o?"none":a.textContent||a.childNodes.length?"":"none")};function Ep(t,e){let n=e==="tool"?"toolCallDisplay":"reasoningDisplay";return{...t,features:{...t?.features,[n]:{...e==="tool"?Fr:wi,...t?.future?.v5Defaults===!0?Ci.features?.[n]:{},...t?.features?.[n]}}}}function vs(t,e){let n=e==="tool"?"toolCallDisplay":"reasoningDisplay";return t?.features?.[n]?.variant??(t?.future?.v5Defaults?"row":"card")}function Vl(t){let e=Math.max(0,Math.floor((t??0)/1e3));return e<1?"a moment":e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function Vr(t,e,n,o){if(vs(n,o)!=="row")return t;t.className=`persona-message-bubble persona-${o}-bubble persona-activity-row`,t.dataset.activityKind=o,o==="tool"&&n.toolCall?.shadow===void 0&&(t.style.boxShadow="var(--persona-tool-bubble-shadow, none)");let r=t.querySelector(":scope > button");if(!r)return t;r.className="persona-activity-header";let s=o==="tool"?e.toolCall:e.reasoning,a=s?.status!=="complete",l=e.approval?.status??e.toolCall?.approvalStatus,c=l==="denied"?"denied":l==="pending"?"awaiting-approval":e.toolCall?.success===!1?"error":a?s?.status==="pending"?"pending":"running":"done";t.dataset.activityState=c;let p=v("span","persona-activity-icon");p.dataset.activityIcon=c;let u={pending:"circle",running:"loader-circle",done:"check",error:"x",denied:"x","awaiting-approval":"clock"},m=o==="reasoning"?n.features?.reasoningDisplay?.iconName:void 0,g=m?ke(m,16,"currentColor",2):c==="pending"?Ge(Tp.Circle,16,"currentColor",2):c==="awaiting-approval"?Ge(Tp.Clock,16,"currentColor",2):ke(u[c],16,"currentColor",2);g&&p.appendChild(g),r.querySelector(".persona-reasoning-header-icon")?.remove();let h=o==="tool"?"toolCallDisplay":"reasoningDisplay",b=n.features?.[h]?.iconVisibility??(n.future?.v5Defaults?"active":"always");if((b==="always"||b==="active"&&c!=="done")&&r.prepend(p),o==="tool"&&s){let T=v("span","persona-activity-duration");a&&s.startedAt&&T.setAttribute("data-tool-elapsed",String(s.startedAt));let R=(o==="tool"?e.toolCall?.duration:void 0)??s.durationMs??(s.completedAt!==void 0&&s.startedAt!==void 0?s.completedAt-s.startedAt:void 0);T.textContent=R===void 0?"":Vl(R),r.appendChild(T)}r.querySelector(":scope > div:not(.persona-ml-auto)")?.classList.add("persona-activity-label"),r.querySelector(".persona-ml-auto")?.classList.add("persona-activity-chevron");let E=t.querySelector(":scope > .persona-border-t");return E?.classList.add("persona-activity-body"),E&&(E.id=`activity-details-${e.id}`,r.setAttribute("aria-controls",E.id)),t}function Rw(t){let e=new Set,n=new Set,o=new Set,r=new Map,s=a=>{clearTimeout(r.get(a)),r.delete(a)};return{observe(a,l,c,p={}){let u=l==="tool"?a.toolCall:a.reasoning;if(!(!u||n.has(a.id))&&(!e.has(a.id)&&u.status!=="complete"&&u.chunks?.some(Boolean)&&(e.add(a.id),p.autoExpand!==!1&&c.add(a.id)),e.has(a.id)&&u.status==="complete"&&!o.has(a.id))){if(o.add(a.id),p.autoCollapseDelay===!1)return;r.set(a.id,setTimeout(()=>{r.delete(a.id),c.delete(a.id),t(a.id,l)},p.autoCollapseDelay??1e3))}},manual(a){n.add(a),s(a)},prune(a){for(let l of new Set([...e,...n,...o]))a.has(l)||(s(l),e.delete(l),n.delete(l),o.delete(l))},clear(){for(let a of r.keys())s(a);e.clear(),n.clear(),o.clear()}}}function Ww(t,e,n,o){let r=v("div","");r.id=`bubble-${t.id}`,r.dataset.messageId=t.id;let s=v("button","");s.type="button",s.dataset.expandHeader="true",s.dataset.bubbleType="tool",s.setAttribute("aria-expanded",String(n));let a=v("div","");typeof o=="string"?a.textContent=o:a.appendChild(o),wa(s,a,{expandable:!0,expanded:n,iconColor:e.toolCall?.toggleTextColor||e.toolCall?.headerTextColor||"currentColor",metaGap:!0});let l=v("div","persona-border-t");return l.id=`activity-details-${t.id}`,l.style.display=n?"":"none",s.setAttribute("aria-controls",l.id),r.append(s,l),Vr(r,t,{...e,features:{...e.features,toolCallDisplay:{...e.features?.toolCallDisplay,variant:"row"}}},"tool"),r.dataset.personaToolGroup="true",e.features?.toolCallDisplay?.loadingAnimation==="shimmer"&&(r.dataset.activityGroupShimmer="true"),{bubble:r,body:l}}var cL=(t,e)=>t.visible!==!1&&(t.mode!=="transient"||e==="connecting"||e==="paused"||e==="resuming"||e==="error"),xi=(t,e,n)=>{let o=e.mode==="transient",r=t.hasAttribute("data-persona-composer-reason")||t.hasAttribute("data-persona-composer-notice");t.style.display=cL(e,n)||o&&r&&e.visible!==!1?"":"none",t.classList.toggle("persona-mt-2",!o),t.classList.toggle("persona-mb-2",o)},Pg=(t,e,n)=>{!e.parentElement||t.parentElement!==e.parentElement||(n.mode==="transient"?t.nextElementSibling!==e&&e.before(t):e.nextElementSibling!==t&&e.after(t))};function Bw(t,e){let n=t.voiceRecognition,o=e.voiceRecognition;return n?.enabled===!0!=(o?.enabled===!0)||n?.provider?.type!==o?.provider?.type||n?.provider?.custom!==o?.provider?.custom||n?.provider?.runtype?.createPlaybackEngine!==o?.provider?.runtype?.createPlaybackEngine||JSON.stringify(n?.provider?.runtype)!==JSON.stringify(o?.provider?.runtype)||t.agentId!==e.agentId||t.clientToken!==e.clientToken||t.apiUrl!==e.apiUrl}function Un(t){return t?.type==="runtype"||t?.type==="custom"}var dL=()=>typeof window<"u"&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window);function Dw(t){try{if(t?.type==="custom"&&t.custom){let e=t.custom,n=typeof e=="function"?e():e;return!!n&&typeof n.startListening=="function"}return t?.type==="runtype"&&t.runtype?!0:dL()}catch{return!1}}Lp();Rg();var zw=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Uw=t=>t.includes("|"),qw=t=>{let e=t.trim();return e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&(e=e.slice(0,-1)),e.split("|").map(n=>n.trim())},yL=t=>`| ${t.join(" | ")} |`,bL=t=>`| ${Array.from({length:t},()=>"---").join(" | ")} |`,vL=(t,e)=>t.length>=e?t.slice(0,e):t.concat(Array.from({length:e-t.length},()=>"")),jw=t=>{if(!t||!t.includes("|"))return t;let e=t.split(`
|
|
1141
|
+
`),n=!1;for(let o=0;o<e.length-1;o++){let r=e[o],s=e[o+1];if(!Uw(r)||zw.test(r)||!zw.test(s))continue;let a=qw(r).length;if(a<1)continue;let l=bL(a);e[o+1]!==l&&(e[o+1]=l,n=!0);let c=o+2;for(;c<e.length;c++){let p=e[c];if(p.trim()===""||!Uw(p))break;let u=yL(vL(qw(p),a));e[c]!==u&&(e[c]=u,n=!0)}o=c-1}return n?e.join(`
|
|
1142
|
+
`):t};var Kw="var(--persona-md-table-scroll-fade, 24px)",Gw=new WeakSet;function Qw(t){t.querySelectorAll("table").forEach(n=>{if(n.parentElement?.classList.contains("persona-table-scroll"))return;let r=document.createElement("div");r.className="persona-table-scroll",n.replaceWith(r),r.appendChild(n)})}function Yw(t){let e=t.scrollWidth-t.clientWidth;if(e<=1){t.removeAttribute("data-persona-scroll-x");return}t.setAttribute("data-persona-scroll-x","");let o=getComputedStyle(t).direction==="rtl"?e+t.scrollLeft:t.scrollLeft,r=e-o;t.style.setProperty("--persona-fade-l",o<=1?"0px":Kw),t.style.setProperty("--persona-fade-r",r<=1?"0px":Kw)}function Wg(t){Gw.has(t)||(Gw.add(t),t.addEventListener("scroll",e=>{let n=e.target;n?.classList?.contains("persona-table-scroll")&&Yw(n)},!0)),t.querySelectorAll(".persona-table-scroll").forEach(Yw)}Si();Aa();so();var{setLoader:VO,load:IL}=Qt({fallbackImport:()=>Promise.resolve().then(()=>(sx(),rx))});var ix=IL;function Ro(t){return t==="card"?"collapsed":t}function Ma(t){return t.split(";",1)[0].trim().toLowerCase()}function HL(t,e){if(!t)return;let n=Object.entries(t);for(let[r,s]of n)if(Ma(r)===e)return{mode:Ro(s),selector:Ma(r)};let o=`${e.split("/",1)[0]}/*`;for(let[r,s]of n)if(Ma(r)===o)return{mode:Ro(s),selector:o}}function RL(t,e){let n=t?.display,o=typeof n=="string"?{default:n}:n??{};if(e.file&&o.files){if(typeof o.files=="string")return{mode:Ro(o.files),matchedBy:{type:"files"}};let l=e.file.mimeType?Ma(e.file.mimeType):void 0,c=l?HL(o.files.byMediaType,l):void 0;if(l&&c)return{mode:c.mode,matchedBy:{type:"mediaType",mediaType:l,selector:c.selector}};if(o.files.default)return{mode:Ro(o.files.default),matchedBy:{type:"files"}}}let r=o.byKind?.[e.artifactType];if(r)return{mode:Ro(r),matchedBy:{type:"kind",kind:e.artifactType,configuredBy:"byKind"}};let s=o.byType?.[e.artifactType];if(s)return{mode:Ro(s),matchedBy:{type:"kind",kind:e.artifactType,configuredBy:"byType"}};let a=e.presentation?.preferredMode;return a?{mode:Ro(a),matchedBy:{type:"preferredMode"}}:o.default?{mode:Ro(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function Cs(t,e){return RL(t,e).mode}function $l(t,e){return JSON.stringify({component:t==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:e.artifactId,title:e.title,artifactType:e.artifactType,status:e.status,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{},...t==="inline"&&e.component?{component:e.component}:{},...t==="inline"&&e.componentProps?{componentProps:e.componentProps}:{},...e.markdown!==void 0?{markdown:e.markdown}:{}}})}var WL="agent_",BL="flow_";function ax(t){return t.startsWith(WL)?{kind:"agentId",agentId:t}:t.startsWith(BL)?{kind:"flowId",flowId:t}:null}function lx(t,e){let n=t.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let a=n.slice(0,o),l=n.slice(o+1);if(a==="runtype"){let p=ax(l);if(p)return p;throw new Error(`[Persona] target "runtype:${l}" is not a valid Runtype agent_/flow_ id.`)}let c=e?.[a];if(!c)throw new Error(`[Persona] No target provider registered for "${a}". Add a \`targetProviders.${a}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:c(l).payload}}let r=ax(n);if(r)return r;let s=e?.default;if(s)return{kind:"payload",payload:s(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}function Dp(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${t}_${e}`}function Ta(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${t}_${e}`}function cx(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`turn_${t}_${e}`}var ws=require("partial-json");je();var Dg="ask_user_question",zl=8,Ea="data-persona-ask-sheet-for",DL="Other",OL="Other\u2026",px="Type your own answer here",ux="Send",_L="Next",NL="Back",FL="Submit all",VL="Skip",$L=3,Og="data-ask-current-index",_g="data-ask-question-count",mx="data-ask-answers",Ng="data-ask-grouped",fx="data-ask-layout",zL=t=>t.layout==="pills"?"pills":"rows",UL=t=>t.getAttribute(fx)==="pills"?"pills":"rows",dx=!1,gx=t=>t.replace(/["\\]/g,"\\$&"),Ai=t=>t.variant==="tool"&&!!t.toolCall&&t.toolCall.name===Dg,Fg=t=>t?.features?.askUserQuestion??{},ka=t=>{let e=t.toolCall;if(!e)return{payload:null,complete:!1};let n=e.status==="complete";if(e.args&&typeof e.args=="object")return{payload:e.args,complete:n};let o=e.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=(0,ws.parse)(r,ws.STR|ws.OBJ|ws.ARR);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},Ul=t=>{let e=Array.isArray(t?.questions)?t.questions:[];return e.length>zl&&!dx&&(dx=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${zl}.`)),e.slice(0,zl)},qL=t=>Ul(t)[0]??null,jL=(t,e)=>Ul(t)[e]??null,KL=(t,e)=>{let n=e.styles;n&&(n.sheetBackground&&t.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&t.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&t.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&t.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&t.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&t.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&t.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&t.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&t.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},hx=(t,e,n)=>{if(t!=="rows")return null;let o=v("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),e){let r=v("span","persona-ask-row-check");o.appendChild(r)}else{let r=v("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},GL=(t,e,n,o)=>{let s=v("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",o?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(e)),s.setAttribute("data-option-label",t.label),n==="rows"){let a=v("span","persona-ask-row-content"),l=v("span","persona-ask-row-label");if(l.textContent=t.label,a.appendChild(l),t.description){let p=v("span","persona-ask-row-description");p.textContent=t.description,a.appendChild(p)}s.appendChild(a);let c=hx(n,o,e);c&&s.appendChild(c)}else s.textContent=t.label,t.description&&(s.title=t.description);return s},YL=t=>{let n=v("span",t==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},QL=(t,e,n,o)=>{let s=v("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!t?.multiSelect,c=(Array.isArray(t?.options)?t.options:[]).filter(u=>u&&typeof u.label=="string"&&u.label.length>0);if(c.length===0&&!n){for(let u=0;u<$L;u++)s.appendChild(YL(o));return s}if(c.forEach((u,m)=>{s.appendChild(GL(u,m,o,a))}),t?.allowFreeText!==!1){let u=o==="rows"?DL:OL;if(o==="rows"){let m=v("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");m.setAttribute("data-ask-user-action","focus-free-text"),m.setAttribute("data-option-index",String(c.length)),m.setAttribute("data-ask-other-row","true");let g=v("span","persona-ask-row-content"),h=document.createElement("input");h.type="text",h.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",h.placeholder=e.freeTextPlaceholder??px,h.setAttribute("data-ask-free-text-input","true"),h.setAttribute("aria-label",e.freeTextLabel??u),g.appendChild(h),m.appendChild(g);let b=hx(o,a,c.length);b&&m.appendChild(b),s.appendChild(m)}else{let m=v("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");m.type="button",m.setAttribute("data-ask-user-action","open-free-text"),m.textContent=e.freeTextLabel??u,s.appendChild(m)}}return s},yx=(t,e)=>{let o=v("div",e==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");o.setAttribute("data-ask-free-text-row","true");let r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=t.freeTextPlaceholder??px,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),e!=="rows"){let s=v("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=t.submitLabel??ux,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},XL=t=>{let e=v("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");e.setAttribute("data-ask-multi-actions","true");let n=v("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=t.submitLabel??ux,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,e.appendChild(n),e},JL=(t,e,n)=>{let o=v("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let r=v("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??NL,r.setAttribute("data-ask-user-action","back"),r.disabled=t===0,o.appendChild(r);let s=v("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=v("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=n.skipLabel??VL,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let l=v("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let c=t===e-1;return l.textContent=c?n.submitAllLabel??FL:n.nextLabel??_L,l.setAttribute("data-ask-user-action",c?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},Mi=t=>{let e=t.getAttribute(mx);if(!e)return{};try{let n=JSON.parse(e);return n&&typeof n=="object"?n:{}}catch{return{}}},bx=(t,e)=>{t.setAttribute(mx,JSON.stringify(e))},Wo=t=>{let e=Number(t.getAttribute(Og)??"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},ZL=(t,e)=>{t.setAttribute(Og,String(Math.max(0,Math.floor(e))))},Pa=t=>{let e=Number(t.getAttribute(_g)??"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},xs=t=>t.getAttribute(Ng)==="true",eI=(t,e)=>{let n=t.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return e.forEach((r,s)=>{let a=typeof r?.question=="string"?r.question:"";if(a&&Object.prototype.hasOwnProperty.call(n,a)){let l=n[a];(typeof l=="string"||Array.isArray(l))&&(o[s]=l)}}),o},tI=(t,e)=>{let n=t.agentMetadata?.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(e-1,Math.floor(n)))},Op=(t,e)=>{let{payload:n}=ka(e),o=Ul(n),r=Mi(t),s={},a=new Set;return o.forEach((l,c)=>{let p=typeof l?.question=="string"?l.question:"";p&&(a.has(p)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${p}"; later answer wins.`),a.add(p),Object.prototype.hasOwnProperty.call(r,c)&&(s[p]=r[c]))}),s},vx=t=>{let e=Mi(t),n=Wo(t),o=e[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(c=>r.add(c));let s=t.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(c=>{let p=c.getAttribute("data-option-label")??"",u=r.has(p);c.setAttribute("aria-pressed",u?"true":"false"),c.classList.toggle("persona-ask-pill-selected",u)});let a=new Set(Array.from(s).map(c=>c.getAttribute("data-option-label")??"")),l=t.querySelector('[data-ask-free-text-input="true"]');l&&(typeof o=="string"&&o.length>0&&!a.has(o)?(l.value=o,l.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):l.value="")},Cx=t=>{if(!xs(t))return;let e=Mi(t),n=Wo(t),o=e[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=t.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);let a=t.querySelector('[data-ask-user-action="submit-multi"]');if(a){let l=Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=l.length===0}},Vg=(t,e,n)=>{let o=Fg(n),r=UL(t),{payload:s,complete:a}=ka(e),l=xs(t),c=Wo(t),p=Pa(t),u=l?jL(s,c):qL(s),m=!!u?.multiSelect,g=t.querySelector('[data-ask-step-inline="true"]');g&&(g.textContent=l?`${c+1}/${p}`:"");let h=t.querySelector('[data-ask-stepper="true"]');h&&h.remove();let b=t.querySelector('[data-ask-question="true"]');if(b){let T=typeof u?.question=="string"?u.question:"";b.textContent=T,b.classList.toggle("persona-ask-question-skeleton",!T&&!a)}let C=t.querySelector('[data-ask-pill-list="true"]');if(C){let T=QL(u,o,a,r);C.replaceWith(T)}if(r!=="rows"){let T=t.querySelector('[data-ask-free-text-row="true"]');T&&T.replaceWith(yx(o,r))}let M=t.querySelector('[data-ask-multi-actions="true"]');!l&&m&&!M?t.appendChild(XL(o)):(!m||l)&&M&&M.remove(),t.setAttribute("data-multi-select",m?"true":"false");let E=t.querySelector('[data-ask-nav-row="true"]');if(l){let T=JL(c,p,o);E?E.replaceWith(T):t.appendChild(T)}else E&&E.remove();vx(t),Cx(t)},nI=(t,e,n)=>{let o=Fg(e),r=zL(o),s=t.toolCall.id,a=Ul(n),l=Math.max(1,a.length),c=l>1,p=eI(t,a),u=c?tI(t,l):0,m=v("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));m.setAttribute(Ea,s),m.setAttribute("data-tool-call-id",s),m.setAttribute("data-message-id",t.id),m.setAttribute(_g,String(l)),m.setAttribute(Og,String(u)),m.setAttribute(Ng,c?"true":"false"),m.setAttribute(fx,r),bx(m,p),m.setAttribute("role","group"),m.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&m.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),KL(m,o);let g=v("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),h=v("div","persona-ask-sheet-question persona-flex-1");h.setAttribute("data-ask-question","true"),h.textContent="",g.appendChild(h);let b=v("span","persona-ask-sheet-step-inline");b.setAttribute("data-ask-step-inline","true"),b.textContent="",g.appendChild(b),m.appendChild(g);let M=v("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return M.setAttribute("data-ask-pill-list","true"),M.setAttribute("role","group"),m.appendChild(M),r!=="rows"&&m.appendChild(yx(o,r)),Vg(m,t,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},oI=(t,e,n)=>{let{payload:o}=ka(e),r=Math.max(1,Ul(o).length);r>Pa(t)&&(t.setAttribute(_g,String(r)),r>1&&!xs(t)&&t.setAttribute(Ng,"true")),Vg(t,e,n)};var _p=(t,e,n)=>{if(!n||!Ai(t)||Fg(e).enabled===!1)return;let r=t.toolCall.id;n.querySelectorAll(`[${Ea}]`).forEach(p=>{p.getAttribute(Ea)!==r&&p.remove()});let a=n.querySelector(`[${Ea}="${gx(r)}"]`);if(a){oI(a,t,e);return}let{payload:l}=ka(t),c=nI(t,e,l);n.appendChild(c)},La=(t,e)=>{if(!t)return;let n=e?`[${Ea}="${gx(e)}"]`:`[${Ea}]`;t.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(s)?s:180)})},$g=t=>Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(e=>e.getAttribute("data-option-label")).filter(e=>typeof e=="string"&&e.length>0),Ss=(t,e)=>{let n=Mi(t),o=Wo(t);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete n[o]:n[o]=e,bx(t,n),vx(t),Cx(t)},Np=(t,e,n,o)=>{let r=Pa(t),s=Math.max(0,Math.min(r-1,o));ZL(t,s),Vg(t,e,n)};var As="suggest_replies";var rI={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"object",properties:{label:{type:"string",minLength:1,maxLength:80},prompt:{type:"string",minLength:1,maxLength:500},description:{type:"string",minLength:1,maxLength:160}},required:["label"],additionalProperties:!1}}},required:["suggestions"],additionalProperties:!1},xx={name:As,description:"Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the last action after your reply text is complete. Give each suggestion a `label` with the short visible text, an optional `prompt` with the fuller text placed as the user's message (defaults to the label), and an optional `description` with one line of supporting copy. Suggestions are sent as the user's next message, so phrase prompts in the user's voice (e.g. \"Tell me more about pricing\"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.",parametersSchema:rI,origin:"sdk",annotations:{readOnlyHint:!0}},Sx=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),ql=t=>t.variant==="tool"&&t.toolCall?.name===As,sI=t=>{let e=t;if(typeof e=="string")try{e=JSON.parse(e)}catch{return[]}let n=e?.suggestions;if(!Array.isArray(n))return[];let o=n.flatMap(r=>{if(typeof r=="string"){let l=r.trim();return l?[l]:[]}if(!r||typeof r!="object")return[];let s=r;if(typeof s.label!="string"||!s.label.trim())return[];let a={label:s.label.trim()};return typeof s.prompt=="string"&&s.prompt.trim()&&(a.prompt=s.prompt.trim()),typeof s.description=="string"&&s.description.trim()&&(a.description=s.description.trim()),[a]});return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},Ax=t=>{for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role==="user")return null;if(!ql(n))continue;let o=sI(n.toolCall?.args);return o.length>0?o:null}return null},wx=new Set,iI=(t,e,n)=>{let o=`${t}:${e}:${n}`;wx.has(o)||(wx.add(o),console.warn(`[persona] suggestions.followUps.${t} and features.suggestReplies.${t} disagree; suggestions.followUps.${t} wins.`))},Ms=t=>{let e=t?.suggestions?.followUps,n=t?.features?.suggestReplies,o=a=>{let l=e?.[a],c=n?.[a];l===void 0||c===void 0||l!==c&&iI(a,c,l)};t&&(o("enabled"),o("expose"));let r=e?.enabled??n?.enabled??!0,s=r?e?.expose??n?.expose??!1:!1;return{enabled:r,expose:s}};var aI={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:zl,description:"Questions to ask the user. Prefer a single question.",items:{type:"object",properties:{question:{type:"string",description:"The complete question, ending with a question mark."},header:{type:"string",maxLength:12,description:'Short topic label, e.g. "Auth method".'},options:{type:"array",minItems:2,maxItems:4,description:'2-4 distinct choices. Do NOT add an "Other" option: free text is automatic.',items:{type:"object",properties:{label:{type:"string",description:"Concise choice text (1-5 words)."},description:{type:"string",description:"What the option means or implies."}},required:["label"],additionalProperties:!1}},multiSelect:{type:"boolean",description:"Allow selecting multiple options. Default false."},allowFreeText:{type:"boolean",description:"Show a free-text input. Default true."}},required:["question","options"],additionalProperties:!1}}},required:["questions"],additionalProperties:!1},lI={name:Dg,description:"Ask the user multiple-choice questions and wait for their answers. Use only when blocked on a decision that is the user's to make: a preference, a choice between valid approaches, or information you cannot infer. Each question offers 2-4 options plus an automatic free-text input. The result maps each question to its answer (an array when multiSelect); a question absent from the result was skipped.",parametersSchema:aI,origin:"sdk",annotations:{readOnlyHint:!0}},Fp=t=>{let e=[],n=t?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&e.push(lI),Ms(t).expose&&e.push(xx),e};var cI=t=>t.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase().replace(/_+/g,"_").replace(/^_|_$/g,""),dI=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),pI=t=>{if(t.variant!=="tool")return null;let e=t.agentMetadata?.clientToolAnswer;if(!e||!e.toolCallId||e.result===void 0)return null;let n=cI(e.toolName);return n?{call:{toolCallId:e.toolCallId,toolName:n,args:dI(e.args)?e.args:{}},result:{toolCallId:e.toolCallId,toolName:n,result:e.result}}:null},zg=(t,e)=>{let n=[],o=[],r=[],s="",a,l=()=>{o.length!==0&&(n.push({role:"assistant",content:"",createdAt:s,toolCalls:o},{role:"tool",content:"",createdAt:s,toolResults:r}),o=[],r=[])};for(let c of t){let p=pI(c);if(p){let m=c.agentMetadata?.clientToolAnswer?.batch;o.length>0&&(m===void 0||m!==a)&&l(),o.length===0&&(s=c.createdAt,a=m),o.some(g=>g.toolCallId===p.call.toolCallId)||(o.push(p.call),r.push(p.result));continue}let u=e(c);u&&(l(),n.push(u))}return l(),n};Ts();var Rx="4.25.0";var Ti=Rx;var Ha="[Image]";function Wx(t){return typeof t=="string"?t:t.filter(e=>e.type==="text").map(e=>e.text).join("")}function Up(t){return typeof t=="string"?!1:t.some(e=>e.type==="image")}function fr(t){return{type:"text",text:t}}function Bx(t,e){return{type:"image",image:t,...e?.mimeType&&{mimeType:e.mimeType},...e?.alt&&{alt:e.alt}}}var Dx=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],bI=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],Ur=[...Dx,...bI];function vI(t){return Dx.includes(t)||t.startsWith("image/")}function qp(t){return vI(t.type)}function Ox(t,e,n){return{type:"file",data:t,mimeType:e,filename:n}}async function _x(t){return new Promise((e,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;qp(t)?e({type:"image",image:r,mimeType:t.type,alt:t.name}):e({type:"file",data:r,mimeType:t.type,filename:t.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(t)})}function Nx(t,e=Ur,n=10*1024*1024){return e.includes(t.type)?t.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${t.type}". Accepted types: ${e.join(", ")}`}}function CI(t){let e=t.split(".");return e.length>1?e.pop().toLowerCase():""}function Fx(t,e){let n=CI(e).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[t]||n||"FILE"}var wI=["user","assistant","system"],xI=0;function Vx(t){if(typeof t!="string"||t==="")return null;let e=Date.parse(t);return Number.isNaN(e)?null:e}function jp(t){return typeof t=="string"?t:void 0}function SI(t){if(typeof t!="object"||t===null)return null;let e=t;switch(e.type){case"text":return typeof e.text=="string"?fr(e.text):null;case"image":return typeof e.image=="string"?Bx(e.image,{mimeType:jp(e.mimeType),alt:jp(e.alt)}):null;case"file":return typeof e.data=="string"&&typeof e.mimeType=="string"&&typeof e.filename=="string"?Ox(e.data,e.mimeType,e.filename):null;case"audio":return typeof e.audio=="string"?{type:"audio",audio:e.audio,...jp(e.mimeType)!==void 0&&{mimeType:e.mimeType}}:null;case"video":return typeof e.video=="string"?{type:"video",video:e.video,...jp(e.mimeType)!==void 0&&{mimeType:e.mimeType}}:null;default:return null}}function AI(t,e){let n=Vx(e),o=t.map(a=>Vx(a.timestamp)),r=new Array(t.length),s=0;for(;s<o.length;){let a=o[s];if(a!==null){r[s]=a,s+=1;continue}let l=s;for(;l+1<o.length&&o[l+1]===null;)l+=1;let c=l-s+1,p=s>0?r[s-1]:null,u=l+1<o.length?o[l+1]:null,m=u!==null&&n!==null?Math.min(u,n):u??n;for(let g=0;g<c;g+=1)r[s+g]=m!==null?m-(c-g):p!==null?p+g+1:xI+g;s=l+1}return r.map(a=>new Date(a).toISOString())}function $x(t,e){let n=AI(t,e?.beforeCreatedAt),o=[];return t.forEach((r,s)=>{if(typeof r?.id!="string"||r.id===""||!wI.includes(r.role))return;let a=r.role,l=n[s];if(r.displayAvailable===!1){let c={historyDisplayUnavailable:!0};o.push({id:r.id,role:a,content:"",createdAt:l,agentMetadata:c});return}if(typeof r.displayContent=="string"){o.push({id:r.id,role:a,content:r.displayContent,createdAt:l});return}if(typeof r.content=="string"){o.push({id:r.id,role:a,content:r.content,createdAt:l});return}if(Array.isArray(r.content)){let c=r.content.map(SI).filter(u=>u!==null),p=Wx(c);o.push({id:r.id,role:a,content:p||(Up(c)?Ha:""),createdAt:l,...c.length>0&&{contentParts:c}});return}o.push({id:r.id,role:a,content:"",createdAt:l})}),o}function Yl(t){let e=t.content;if(typeof e!="string"||e==="")return;let n=t.contentParts??t.llmContent??t.rawContent??e;if(!(typeof n=="string"&&n===e))return e}function Ql(t,e){let n=new Map;for(let o of t)n.set(o.id,o);for(let o of e)n.set(o.id,o);return[...n.values()].sort((o,r)=>{let s=new Date(o.createdAt).getTime(),a=new Date(r.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(a)&&s!==a)return s-a;let l=o.sequence??0,c=r.sequence??0;return l!==c?l-c:o.id.localeCompare(r.id)})}var MI="https://api.runtype.com/v1/dispatch",zx="https://api.runtype.com",it=class extends Error{constructor(e,n,o){super(n),this.name="HistoryClientError",this.code=e,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}},Ux=32768,qg=49152,qx=t=>{let e=t??{},n=typeof e.targetId=="string"?e.targetId:null;return{id:typeof e.id=="string"?e.id:"",title:typeof e.title=="string"?e.title:"",targetId:n,preview:typeof e.preview=="string"?e.preview:null,messageCount:typeof e.messageCount=="number"?e.messageCount:0,createdAt:typeof e.createdAt=="string"?e.createdAt:"",updatedAt:typeof e.updatedAt=="string"?e.updatedAt:""}},jx=t=>"reason"in t?t.reason:void 0,Kx="The identity proof was not admitted; account history is unavailable",jg="The identity proof was rejected",Gx="The request carried no visitor credential",Yx="The stored visitor belongs to a different signed-in user",Kg=(t,e)=>t instanceof it&&t.code===e;function TI(t){let e=t.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[e];if(o)return`attachment.${o}`;let r=e.indexOf("/");if(r>0){let s=e.slice(r+1).split(";")[0]?.trim()??"";if(s&&s!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(s))return`attachment.${s}`}return"attachment"}var Gg=t=>!!(t.contentParts&&t.contentParts.length>0||t.llmContent&&t.llmContent.trim().length>0||t.rawContent&&t.rawContent.trim().length>0||t.content&&t.content.trim().length>0),Qx=t=>t.slice().sort((e,n)=>new Date(e.createdAt).getTime()-new Date(n.createdAt).getTime()),Xx=t=>({role:t.role,content:t.contentParts??t.llmContent??t.rawContent??t.content,createdAt:t.createdAt});function EI(t){switch(t){case"json":return Ix;case"regex-json":return Lx;case"xml":return Hx;default:return Px}}var Jx=t=>t.startsWith("{")||t.startsWith("[")||t.startsWith("<");function kI(t,e){if(!t)return e;let n=t.trim(),o=e.trim();if(n.length===0)return e;if(o.length===0)return t;let r=Jx(n);if(!Jx(o))return t;if(!r||o===n||o.startsWith(n))return e;let a=Gl(t);return Gl(e)!==null&&a===null?e:t}var Xl=class{constructor(e={},n={}){this.config=e;this.historyInternals=n;this.currentClientTurnId=null;this.clientSession=null;this.sessionInitPromise=null;this.sessionWarmLatch=!1;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;this.historyUnavailable=!1;this.historyUnavailableWarned=!1;this.claimInFlight=!1;this.historyIdentityStatus=null;this.historyIdentitySubscribers=new Set;this.historyAvailabilitySubscribers=new Set;this.webMcpBridge=null;this.webMcpBridgePromise=null;if(e.target&&(e.agentId||e.flowId||e.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=e.apiUrl??MI,this.headers={"Content-Type":"application/json","X-Persona-Version":Ti,...e.headers},this.debug=!!e.debug,this.createStreamParser=e.streamParser??EI(e.parserType),this.contextProviders=e.contextProviders??[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders,e.webmcp?.enabled===!0&&(this.webMcpBridgePromise=this.createWebMcpBridge(e.webmcp))}createWebMcpBridge(e){return ix().then(n=>{let o=new n.WebMcpBridge(e,{recordToolDisplayTitles:Zw,getToolDisplayTitle:Hp,loadPolyfill:tx});return this.pendingWebMcpConfirmHandler!==void 0&&o.setConfirmHandler(this.pendingWebMcpConfirmHandler),this.webMcpBridge=o,o}).catch(n=>(this.webMcpBridgePromise=null,console.warn("[Persona] Failed to load the WebMCP runtime chunk",n),null))}getWebMcpBridge(){return this.webMcpBridge?Promise.resolve(this.webMcpBridge):this.config.webmcp?.enabled!==!0?Promise.resolve(null):(this.webMcpBridgePromise||(this.webMcpBridgePromise=this.createWebMcpBridge(this.config.webmcp)),this.webMcpBridgePromise)}updateConfig(e){this.config=e}setHistoryInternals(e){this.historyInternals=e}setSSEEventCallback(e){this.onSSEEvent=e}setWebMcpConfirmHandler(e){this.pendingWebMcpConfirmHandler=e,this.webMcpBridge?.setConfirmHandler(e)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(e,n,o){return this.config.webmcp?.enabled!==!0?null:this.getWebMcpBridge().then(r=>r?r.executeToolCall(e,n,o):{isError:!0,content:[{type:"text",text:"WebMCP runtime failed to load."}]})}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:e,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:e,flowId:n};let s=lx(o,r);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}clientApiBase(){return this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||zx}getClientApiUrl(e){return`${this.clientApiBase()}/v1/client/${e}`}getClientSession(){return this.clientSession}async reconnectClientTokenStream(e){let n=await this.initSession(),o=!1;for(;;){let r=n.conversationId,s=await this.readVisitorToken();if(n.durableRecovery?.enabled!==!0||!r||!s)throw new it("visitor_token_missing","Durable recovery is not enabled for this client session");let a=`${this.clientApiBase()}/v1/client/conversations/${encodeURIComponent(r)}/executions/${encodeURIComponent(e.executionId)}/events`,l=new URLSearchParams({sessionId:n.sessionId,after:e.after}),c=await fetch(`${a}?${l}`,{method:"GET",headers:{"X-Persona-Version":Ti,"X-Visitor-Token":s},signal:e.signal});if(c.status===401&&!o){o=!0,n=await this.recoverFromUnauthorized(await this.readErrorCode(c),null,!0);continue}if(!c.ok)throw await this.historyErrorFor(c,!0);return c}}async warmSession(){let e=this.clientSession;return!this.isClientTokenMode()||this.sessionInitPromise||e&&new Date<e.expiresAt||this.sessionWarmLatch===e?null:(this.sessionWarmLatch=e,this.initSession().catch(()=>null))}async initSession(){if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;let e=this.sessionInitPromise=this._doInitSession().then(n=>this.sessionInitPromise!==e?this.initSession():(this.clientSession=n,this.sessionWarmLatch=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(n),n)).finally(()=>{this.sessionInitPromise===e&&(this.sessionInitPromise=null)});return e}isHistoryCapable(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()&&!this.historyUnavailable}async readVisitorToken(){let e=this.historyInternals.visitorStore;return e?(await e.ready,await e.get()??null):null}markHistoryUnavailable(){if(!this.historyUnavailable){this.setHistoryIdentityStatus({state:"unavailable",reason:"history_disabled"}),this.historyUnavailable=!0,!this.historyUnavailableWarned&&typeof console<"u"&&(this.historyUnavailableWarned=!0,console.warn("[Persona] Visitor history is disabled for this surface; continuing without it.")),this.historyInternals.onHistoryAvailabilityChanged?.(!1);for(let e of[...this.historyAvailabilitySubscribers])e(!1)}}getHistoryIdentityStatus(){return this.historyIdentityStatus??this.restingIdentityStatus()}subscribeHistoryIdentityStatus(e){return this.historyIdentitySubscribers.add(e),()=>{this.historyIdentitySubscribers.delete(e)}}subscribeHistoryAvailability(e){return this.historyAvailabilitySubscribers.add(e),this.historyUnavailable&&e(!1),()=>{this.historyAvailabilitySubscribers.delete(e)}}restingIdentityStatus(){return this.isClientTokenMode()?this.config.features?.history?.enabled!==!0||this.historyUnavailable?{state:"unavailable",reason:"history_disabled"}:this.browserOnlyStatus():{state:"unavailable",reason:"ineligible_mode"}}browserOnlyStatus(){let e=this.historyIdentityStatus;return e?.state==="browser_only"?e:this.derivedBrowserOnly()}derivedBrowserOnly(){return this.config.features?.history?.scope==="browser"?{state:"browser_only",reason:"configured_browser_scope"}:this.config.getIdentityProof?{state:"browser_only",reason:"proof_unavailable_before_binding"}:{state:"browser_only",reason:"no_identity_provider"}}setHistoryIdentityStatus(e){let n=this.getHistoryIdentityStatus(),o=n.state===e.state&&jx(n)===jx(e);if(this.historyIdentityStatus=e,!o){this.historyInternals.onHistoryIdentityStatusChanged?.(e);for(let r of[...this.historyIdentitySubscribers])r(e)}}async createClientSession(e){let n=this.isHistoryCapable()&&!e.omitVisitorFields,o=!e.omitVisitorFields,r=null;(n||o)&&(await this.historyInternals.historyBootstrapReady,r=await this.readVisitorToken());let s=this.routing(),a=s.agentId??s.flowId,l=n||e.durableResume?e.conversationId:void 0,c={token:this.config.clientToken,...a&&{flowId:a},...n&&{visitorHistory:!0},...o&&{durableRecovery:!0},...(n||o)&&r?{visitorToken:r}:{},...n&&e.identityProof?{identityProof:e.identityProof}:{},...l?{conversationId:l}:e.storedSessionId?{sessionId:e.storedSessionId}:{}};e.signal?.throwIfAborted();let p=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Ti},body:JSON.stringify(c),signal:e.signal});if(!p.ok){let m=await p.json().catch(()=>({error:"Session initialization failed"}));if(n&&p.status===403&&m.error==="visitor_history_disabled"){if(this.markHistoryUnavailable(),l)throw new it("history_disabled","Visitor history is disabled for this surface");return this.createClientSession({...e,omitVisitorFields:!0})}throw p.status===403&&m.error==="durable_recovery_disabled"?new it("history_disabled","Durable recovery is disabled for this surface"):(n||e.durableResume)&&p.status===401&&m.error==="visitor_required"?new it("visitor_required","Visitor credential no longer resolves"):l&&p.status===404?new it("not_found","Conversation not found"):p.status===401?new Error(`Invalid client token: ${m.hint||m.error}`):p.status===403?new Error(`Origin not allowed: ${m.hint||m.error}`):new Error(m.error||"Failed to initialize session")}let u=await p.json();return u.visitor?.token&&await this.historyInternals.visitorStore?.set(u.visitor.token),{sessionId:u.sessionId,expiresAt:new Date(u.expiresAt),flow:u.flow,...u.conversationId?{conversationId:u.conversationId}:{},...u.targetId?{targetId:u.targetId}:{},...u.conversationRevision?{conversationRevision:u.conversationRevision}:{},...u.durableRecovery?{durableRecovery:u.durableRecovery}:{},...u.visitor?{visitor:u.visitor}:{},config:{welcomeMessage:u.config.welcomeMessage,placeholder:u.config.placeholder,theme:u.config.theme}}}async _doInitSession(){await this.historyInternals.historyBootstrapReady;let e=this.config.getStoredConversationId?.()||null,n=this.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.isHistoryCapable()&&!n)return this.ordinaryInit(e,!1);let o=await this.readVisitorToken();if(e&&o)try{let r=await this.createClientSession({conversationId:e,durableResume:n});return n&&r.durableRecovery?.enabled!==!0&&this.historyInternals.setStoredResumableHandle?.(null),this.finishInit(r,e,!1)}catch(r){if(!Kg(r,"not_found")&&!Kg(r,"visitor_required")&&!Kg(r,"history_disabled"))throw r;return n&&this.historyInternals.setStoredResumableHandle?.(null),this.ordinaryInit(e,!0)}return this.ordinaryInit(e,!1)}async ordinaryInit(e,n){let o=this.historyInternals.visitorStore;return o&&!await this.readVisitorToken()?o.withFirstInitLock(()=>this.doOrdinaryInit(e,n)):this.doOrdinaryInit(e,n)}async doOrdinaryInit(e,n){let o=this.config.getStoredSessionId?.()||null,r=await this.createClientSession({storedSessionId:o}),s=await this.claimFirstConversation(r);return this.finishInit(s,e,n)}async reinitWithProof(e){let n=this.config.getStoredSessionId?.()||null,o=this.config.getStoredConversationId?.()||null,r=await this.createClientSession({storedSessionId:n,identityProof:e}),s=this.finishInit(r,o,!1);return this.clientSession=s,this.sessionInitPromise=null,this.sessionWarmLatch=!1,this.resetClientToolsFingerprint(),s}async claimFirstConversation(e){if(!e.visitor?.token||this.claimInFlight||!this.isHistoryCapable()&&e.durableRecovery?.enabled!==!0)return e;this.claimInFlight=!0;try{return await this.createClientSession({storedSessionId:e.sessionId})}catch{return e}finally{this.claimInFlight=!1}}finishInit(e,n,o){let r=e.conversationId;return r&&n&&(o||r!==n)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:n,conversationId:r}),this.config.setStoredSessionId?.(e.sessionId),r&&(this.config.setStoredConversationId?.(r),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),e}prepared(e){let n=!1;return{session:e,commit:()=>{n||(n=!0,this.clientSession=e,this.sessionWarmLatch=!1,this.resetClientToolsFingerprint())},discard:()=>{n=!0}}}async prepareConversationSession(e,n){if(!this.isClientTokenMode())throw new Error("prepareConversationSession() only available in client token mode");if(!this.isHistoryCapable())throw new it("history_disabled","Visitor history is disabled for this surface");await this.historyInternals.historyBootstrapReady;let o=n?.proof??null;if(!await this.readVisitorToken()&&!o)throw new it("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let s=await this.createClientSession({conversationId:e,identityProof:o});return this.prepared(s)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw new Error("prepareNewConversationSession() only available in client token mode");await this.historyInternals.historyBootstrapReady;let e=await this.createClientSession({});return this.prepared(e)}handleExternalCredentialChange(){this.clearClientSession(),this.isHistoryCapable()&&this.setHistoryIdentityStatus(this.derivedBrowserOnly())}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.sessionWarmLatch=!1,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.sentNonEmptyClientToolsSessionId=null}getFeedbackApiUrl(){return`${this.clientApiBase()}/v1/client/feedback`}async sendFeedback(e){if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(e.type)&&!e.messageId)throw new Error(`messageId is required for ${e.type} feedback type`);if(e.type==="csat"&&(e.rating===void 0||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(e.type==="nps"&&(e.rating===void 0||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let r={...e,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Ti},body:JSON.stringify(r)});if(!s.ok){let a=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,this.sessionWarmLatch=!1,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(e,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,messageId:e,type:n})}async submitCSATFeedback(e,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:e,comment:n})}async submitNPSFeedback(e,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:e,comment:n})}historyUrl(e,n){let o=new URLSearchParams;for(let[s,a]of Object.entries(n))a===void 0||a===""||o.set(s,String(a));let r=o.toString();return`${this.clientApiBase()}/v1/client/${e}${r?`?${r}`:""}`}resolveHistoryScope(e){if(e)return e;let n=this.config.features?.history?.scope;return n||(this.config.getIdentityProof?"verified-user":"browser")}async resolveChatIdentityProof(e){e?.throwIfAborted();let n=this.config.identityProvider;if(n===void 0)return;let o=this.config.getIdentityProof;if(!n.trim()||!o)throw new Error("Chat identity requires identityProvider and getIdentityProof.");let r,s;try{let a=Promise.resolve().then(()=>o());r=e?await Promise.race([a,new Promise((l,c)=>{s=()=>c(e.reason),e.addEventListener("abort",s,{once:!0}),e.aborted&&s()})]):await a}catch{throw e?.throwIfAborted(),new Error("The identity proof provider failed.")}finally{s&&e?.removeEventListener("abort",s)}if(typeof r!="string"||!r.trim())throw new Error("A fresh identity proof is required to send this message.");return{provider:n,token:r}}async resolveIdentityProof(e,n){let o=this.config.getIdentityProof;if(!o)return n&&this.setHistoryIdentityStatus(this.browserOnlyStatus()),null;n&&this.setHistoryIdentityStatus({state:"verifying"});let r;try{r=await o()??null}catch{throw n&&this.setHistoryIdentityStatus({state:"identity_provider_failed"}),new it("identity_provider_failed","The identity proof provider failed")}if(r)return r;if(e.visitor?.endUserId!=null)throw n&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new it("authentication_required","This browser is bound to a signed-in user and needs a fresh identity proof");return n&&this.setHistoryIdentityStatus({state:"browser_only",reason:"proof_unavailable_before_binding"}),null}async bindIdentity(e,n,o){if(e.visitor?.endUserId!=null)return e;let r=await this.reinitWithProof(n);if(!(r.visitor?.identityStatus==="admitted"&&r.visitor?.endUserId!=null))throw o&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new it("proof_not_admitted",Kx);return r}async readErrorCode(e){let n=await e.json().catch(()=>({}));return typeof n.error=="string"?n.error:typeof n.message=="string"?n.message:""}async recoverFromUnauthorized(e,n,o){let r=e.toLowerCase();if(r.includes("invalid_identity_proof"))throw o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new it("invalid_identity_proof",jg);if(r.includes("visitor token required"))throw new it("visitor_token_missing",Gx);if(r.includes("visitor_identity_mismatch")){if(!n)throw o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new it("visitor_identity_mismatch",Yx);return this.reinitWithProof(n)}if(r.includes("expired")||r.includes("not found"))return this.clearClientSession(),this.initSession();throw new it("unauthorized",e||"History request was not authorized")}async historyErrorFor(e,n){let o=await this.readErrorCode(e);if(e.status===404)return new it("not_found","Conversation not found");if(e.status===429){let r=Number.parseInt(e.headers.get("Retry-After")??"",10);return new it("rate_limited","Too many history requests",{...Number.isFinite(r)?{retryAfterSeconds:r}:{}})}if(e.status===503&&o.includes("identity_proof_not_admitted"))return n&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new it("proof_not_admitted",Kx);if(e.status===401){let r=o.toLowerCase();return r.includes("invalid_identity_proof")?(n&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new it("invalid_identity_proof",jg)):r.includes("visitor token required")?new it("visitor_token_missing",Gx):r.includes("visitor_identity_mismatch")?new it("visitor_identity_mismatch",Yx):new it("unauthorized",o||"History request was not authorized")}return new it("request_failed",o||`History request failed (${e.status})`)}commitIdentityAcknowledgement(e,n,o){let r=e?.toLowerCase()??null;if(n){if(r==="admitted"){o&&this.setHistoryIdentityStatus({state:"verified"});return}throw o&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),r==="ignored"?new it("identity_contract_violation","Server reported an ignored identity proof on a success response"):new it("proof_not_admitted","The response did not acknowledge the identity proof this request sent")}if(r==="admitted")throw new it("identity_contract_violation","Server admitted an identity proof that was never sent");o&&this.setHistoryIdentityStatus(this.browserOnlyStatus())}async historyFetch(e,n){this.assertHistoryUsable();let o=n.trackIdentity!==!1,r=await this.initSession(),s=null;this.resolveHistoryScope(n.scope)==="verified-user"&&(s=await this.resolveIdentityProof(r,o),s&&(r=await this.bindIdentity(r,s,o)));let a=this.historyInternals.visitorStore,l=!1;for(;;){let c=a?.revision()??0,p=await this.readVisitorToken();if(!p&&!n.visitorTokenOptional)throw new it("visitor_token_missing","No visitor credential is stored for this browser");let u=await fetch(this.historyUrl(e,{...n.query,sessionId:r.sessionId}),{method:n.method,headers:{"X-Persona-Version":Ti,...p?{"X-Visitor-Token":p}:{},...s?{"X-Identity-Proof":s}:{},...n.body!==void 0?{"Content-Type":"application/json"}:{}},...n.body!==void 0?{body:JSON.stringify(n.body)}:{},...n.keepalive?{keepalive:!0}:{}});if(u.status===401&&!l){l=!0,r=await this.recoverFromUnauthorized(await this.readErrorCode(u),s,o);continue}if(!u.ok)throw await this.historyErrorFor(u,o);let m=u.headers.get("X-History-Identity-Status"),g=await u.json().catch(()=>{});if(a&&a.revision()!==c)throw new it("credential_changed","The visitor credential changed while the request was in flight");return this.commitIdentityAcknowledgement(m,s!==null,o),g}}assertHistoryUsable(){if(!this.isClientTokenMode())throw new Error("Conversation history is only available in client token mode");if(!this.isHistoryCapable())throw new it("history_disabled","Visitor history is disabled for this surface")}async listConversations(e){let n=await this.historyFetch("conversations",{method:"GET",query:{...e?.cursor?{cursor:e.cursor}:{},...e?.limit!==void 0?{limit:e.limit}:{},...e?.targetId?{targetId:e.targetId}:{}},...e?.scope?{scope:e.scope}:{}});return{data:(Array.isArray(n?.data)?n.data:[]).map(qx),nextCursor:typeof n?.nextCursor=="string"?n.nextCursor:null}}async getConversation(e,n){let o=await this.historyFetch(`conversations/${encodeURIComponent(e)}`,{method:"GET",query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}});return{summary:qx(o),messages:Array.isArray(o?.messages)?o.messages:[],nextMessageCursor:typeof o?.nextMessageCursor=="string"?o.nextMessageCursor:null,conversationRevision:typeof o?.conversationRevision=="string"?o.conversationRevision:null}}async finalizeDisplayProjections(e,n){this.assertHistoryUsable();let o=0;for(let c of n){let p=c.displayContent.length;if(p>Ux)throw new it("payload_too_large",`displayContent exceeds the ${Ux} character limit`);o+=p}if(o>qg)throw new it("payload_too_large",`Display projection batch exceeds the ${qg} character limit`);await this.initSession();let r=this.historyInternals.visitorStore,s=r?.revision()??0,a=await this.historyFetch(`conversations/${encodeURIComponent(e)}/display-projections`,{method:"PATCH",body:{messages:n},scope:"browser",keepalive:o<=qg,trackIdentity:!1}),l=typeof a?.conversationRevision=="string"?a.conversationRevision:null;return l&&this.clientSession?.conversationId===e&&(r?.revision()??0)===s&&this.historyInternals.setStoredConversationRevision?.(l),{conversationRevision:l}}async deleteConversation(e,n){let o=await this.historyFetch(`conversations/${encodeURIComponent(e)}`,{method:"DELETE",...n?.scope?{scope:n.scope}:{}});return{deleted:typeof o?.deleted=="number"?o.deleted:0}}async deleteAllConversations(e){let n=await this.historyFetch("conversations",{method:"DELETE",query:{...e?.targetId!==void 0?{targetId:e.targetId}:{}},...e?.scope?{scope:e.scope}:{}});return{deleted:typeof n?.deleted=="number"?n.deleted:0}}async resetVisitor(){this.assertHistoryUsable(),this.setHistoryIdentityStatus({state:"resetting"});try{await this.historyFetch("visitor/reset",{method:"POST",scope:"browser",visitorTokenOptional:!0})}finally{await this.historyInternals.visitorStore?.clear(),this.setHistoryIdentityStatus(this.derivedBrowserOnly())}return{reset:!0}}async dispatch(e,n){return e.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(e,n):this.isAgentMode()?this.dispatchAgent(e,n):this.dispatchProxy(e,n)}async dispatchClientToken(e,n){let o=cx();this.currentClientTurnId=o;let r=()=>this.currentClientTurnId===o,s=a=>{r()&&n(a)};n({type:"status",status:"connecting"});try{let a=()=>{if(e.signal?.throwIfAborted(),!r())throw new DOMException("Turn superseded","AbortError")},l=this.clientSession??await this.initSession();a();let c=async()=>{a();let E=l,T=E.durableRecovery?.enabled===!0;if(T&&(!E.conversationId||!await this.readVisitorToken()))throw new Error("Renewing this conversation requires its visitor credential.");a();let R=await this.createClientSession({...T||this.isHistoryCapable()?{conversationId:E.conversationId,durableResume:T}:{storedSessionId:E.sessionId},signal:e.signal});if(a(),E.conversationId&&R.conversationId!==E.conversationId||T&&R.durableRecovery?.enabled!==!0)throw new Error("Session renewal did not preserve this conversation.");l=this.finishInit(R,E.conversationId??null,!1),this.clientSession=l,this.sessionWarmLatch=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(l)};Date.now()>=l.expiresAt.getTime()-6e4&&await c();let p=await this.buildPayload(e.messages),u=p.metadata?Object.fromEntries(Object.entries(p.metadata).filter(([E])=>E!=="sessionId"&&E!=="session_id")):void 0,m=this.isHistoryCapable(),g={sessionId:l.sessionId,messages:e.messages.filter(Gg).map(E=>{let T=m?Yl(E):void 0;return{id:E.id,role:E.role,content:E.contentParts??E.llmContent??E.rawContent??E.content,...T!==void 0&&{displayContent:T}}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...p.inputs&&Object.keys(p.inputs).length>0&&{inputs:p.inputs},...p.context&&{context:p.context},turnId:o,...e.interrupt&&{submitMode:"interrupt"}},h=async()=>{a();let E=l.durableRecovery?.enabled===!0?await this.readVisitorToken():null;return a(),this.sendWithClientToolsDiff(l.sessionId,p.clientTools,async T=>{a();let R=await this.resolveChatIdentityProof(e.signal);a();let A={...g,sessionId:l.sessionId,...T,...R&&{identityProof:R}};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",{...A,...R&&{identityProof:{provider:R.provider,token:"[REDACTED]"}}}),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Ti,...E?{"X-Visitor-Token":E}:{}},body:JSON.stringify(A),signal:e.signal})})},b=await h();if(a(),b.response.status===401){let E=await b.response.clone().json().catch(()=>null);a(),E?.error==="Session not found or expired"&&(await c(),b=await h(),a())}let{response:C,commit:M}=b;if(!C.ok){let E=await C.json().catch(()=>({error:"Chat request failed"}));if(C.status===401&&E.error==="invalid_identity_proof"){let R=new it("invalid_identity_proof",jg);throw s({type:"error",error:R}),R}if(C.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let R=new Error("Session expired. Please refresh to continue.");throw s({type:"error",error:R}),R}if(C.status===429){let R=new Error(E.hint||"Message limit reached for this session.");throw s({type:"error",error:R}),R}if(C.status===410&&E.error==="conversation_deleted"){let R=new it("conversation_deleted","This conversation was deleted");throw s({type:"error",error:R}),R}let T=new Error(E.error||"Failed to send message");throw s({type:"error",error:T}),T}if(!C.body){let E=new Error("No response body received");throw s({type:"error",error:E}),E}M(),s({type:"status",status:"connected"});try{await this.streamResponse(C.body,s,e.assistantMessageId)}finally{s({type:"status",status:"idle"})}}catch(a){let l=a instanceof Error?a:new Error(String(a));throw!(l instanceof it)&&!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&s({type:"error",error:l}),l}}async dispatchProxy(e,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(e.messages,e.composerOptions);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal},o)}catch(a){let l=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal});if(!s.ok||!s.body){let a=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(e,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(e.messages,e.composerOptions);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal},o)}catch(a){let l=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal});if(!s.ok||!s.body){let a=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n,e.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(e,n,o,r){n({type:"status",status:"connected"});try{await this.streamResponse(e,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(e,n){let o=`${this.clientApiBase()}/v1/agents/${e.agentId}/approve`,r={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(r,await this.getHeaders()),fetch(o,{method:"POST",headers:r,body:JSON.stringify({executionId:e.executionId,approvalId:e.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(e,n,o,r){let s=!!(n&&n.length>0),a=s?ex(n):void 0,l=this.clientToolsFingerprintSessionId===e,c=s&&l&&this.lastSentClientToolsFingerprint===a,p=!s&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===e,u=!1,m;for(let g=0;;g++){if(m=await o({...s&&(u||!c)&&n?{clientTools:n}:{},...p?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),m.status===409&&g===0&&s&&(await m.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){u=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:m,commit:()=>{this.lastSentClientToolsFingerprint=a??null,this.clientToolsFingerprintSessionId=e,s?this.sentNonEmptyClientToolsSessionId=e:p&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(e,n,o){let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||zx}/resume`,a,l=null;if(r){let u=await this.initSession();a=u.sessionId,u.durableRecovery?.enabled===!0&&(l=await this.readVisitorToken())}let c={"Content-Type":"application/json",...l?{"X-Visitor-Token":l}:{},...this.headers};this.getHeaders&&Object.assign(c,await this.getHeaders());let p={executionId:e,toolOutputs:n,streamResponse:o?.streamResponse??!0,...o?.after?{after:o.after}:{}};if(a&&(p.sessionId=a),r&&a){let u=[...Fp(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:m,commit:g}=await this.sendWithClientToolsDiff(a,u,h=>{let b={...p,...h};return this.debug&&console.debug("[AgentWidgetClient] client token resume",b),fetch(s,{method:"POST",headers:c,body:JSON.stringify(b),signal:o?.signal})},{emptyMeansReplace:!0});return m.ok&&g(),m}return fetch(s,{method:"POST",headers:c,body:JSON.stringify(p),signal:o?.signal})}latestMentionContext(e){for(let n=e.length-1;n>=0;n--){let o=e[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(e){let n={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async r=>{try{let s=await r({messages:e,config:this.config});s&&typeof s=="object"&&Object.assign(n,s)}catch(s){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",s)}}));let o=this.latestMentionContext(e);return o&&Object.assign(n,o),Object.keys(n).length?n:null}normalizeComposerOptions(e){if(!e)return;let n={};return e.selectedModelId&&(n.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(n.activeModeIds=[...e.activeModeIds]),Object.keys(n).length>0?n:void 0}applyInlineAgentModel(e,n){let o=n?.selectedModelId;return!o||!("model"in e)?e:this.config.composer?.models?.some(s=>s.id===o)?{...e,model:o}:e}async buildAgentPayload(e,n){let o=this.routing().agentId;if(!this.config.agent&&!o)throw new Error("Agent configuration required for agent mode");let r=zg(Qx(e),p=>Gg(p)&&(p.role==="user"||p.role==="assistant"||p.role==="system")&&(!p.variant||p.variant==="assistant")?Xx(p):null),s=this.normalizeComposerOptions(n),a={agent:this.applyInlineAgentModel(this.config.agent??{agentId:o},s),messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};s&&(a.composerOptions=s);let l=[...Fp(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]];l.length>0&&(a.clientTools=l);let c=await this.buildContextAggregate(e);return c&&(a.context=c),a}async buildPayload(e,n){let o=zg(Qx(e),p=>Gg(p)?Xx(p):null),r=this.routing(),s={messages:o,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[p,u]of Object.entries(r.targetPayload))p!=="messages"&&(s[p]=u);let a=[...Fp(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]];a.length>0&&(s.clientTools=a);let l=await this.buildContextAggregate(e);l&&(s.context=l);let c=this.normalizeComposerOptions(n);if(c&&(s.composerOptions=c),this.requestMiddleware)try{let p=await this.requestMiddleware({payload:{...s},config:this.config});if(p&&typeof p=="object"){let u=p;return s.clientTools!==void 0&&!("clientTools"in u)&&(u.clientTools=s.clientTools),u}}catch(p){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",p)}return s}async handleCustomSSEEvent(e,n,o,r,s,a){if(!this.parseSSEEvent)return!1;try{let l=await this.parseSSEEvent(e);if(l===null)return!1;let c=u=>{let m={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...u!==void 0&&{partId:u}};return o.current=m,r(m),m},p=u=>o.current?o.current:c(u);if(l.text!==void 0){l.partId!==void 0&&a.current!==null&&l.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),c(l.partId)),l.partId!==void 0&&(a.current=l.partId);let u=p(l.partId);l.partId!==void 0&&!u.partId&&(u.partId=l.partId),u.content+=l.text,r(u)}return l.done&&(o.current&&(o.current.streaming=!1,r(o.current)),a.current=null,n({type:"status",status:"idle"})),l.error&&(a.current=null,n({type:"error",error:new Error(l.error)})),!0}catch(l){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",l),!1}}async streamResponse(e,n,o,r){let s=e.getReader(),a=new TextDecoder,l="",c=Date.now(),p=0,u=()=>c+p++,m=X=>{let I=X.reasoning?{...X.reasoning,chunks:[...X.reasoning.chunks]}:void 0,j=X.toolCall?{...X.toolCall,chunks:X.toolCall.chunks?[...X.toolCall.chunks]:void 0}:void 0,J=X.tools?X.tools.map(Y=>({...Y,chunks:Y.chunks?[...Y.chunks]:void 0})):void 0;return{...X,reasoning:I,toolCall:j,tools:J}},g=X=>{if(X.role!=="assistant"||X.variant)return!0;let I=Array.isArray(X.contentParts)&&X.contentParts.length>0,j=typeof X.rawContent=="string"&&X.rawContent.trim()!=="";return typeof X.content=="string"&&X.content.trim()!==""||I||j||!!X.stopReason},h=X=>{g(X)&&n({type:"message",message:m(X)})},b=null,C=null,M={current:null},E={current:null},T=null,R="",A=new Map,D=new Map,W=new Map,U=new Map,B=new Map,O=o,H=!1,S=()=>{if(b)return b;let X,I="",j=T;return!H&&O?(X=O,H=!0,I=r??""):O&&j?X=`${O}_${j}`:X=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,b={id:X,role:"assistant",content:I,createdAt:new Date().toISOString(),streaming:!0,sequence:u()},h(b),b},x=X=>{let I=U.get(X);if(I)return I;let j={id:`reason-${X}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:u(),reasoning:{id:X,status:"streaming",chunks:[]}};return U.set(X,j),h(j),j},P=new Set,L=new Map,G=new Set,V=new Map,K=X=>{if(!X)return!1;let I=X.replace(/_+/g,"_").replace(/^_|_$/g,"");return I==="emit_artifact_markdown"||I==="emit_artifact_component"},ee=X=>{let I=B.get(X);if(I)return I;let j={id:`tool-${X}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:u(),toolCall:{id:X,status:"pending"}};return B.set(X,j),h(j),j},oe=X=>{if(typeof X=="number"&&Number.isFinite(X))return X;if(typeof X=="string"){let I=Number(X);if(!Number.isNaN(I)&&Number.isFinite(I))return I;let j=Date.parse(X);if(!Number.isNaN(j))return j}return Date.now()},ne=X=>{if(typeof X=="string")return X;if(X==null)return"";try{return JSON.stringify(X)}catch{return String(X)}},le=new Map,de=new Map,ve=(X,I)=>{let j=ne(I),J=de.get(X.id),Y=kI(J,j);X.rawContent=Y;let ie=le.get(X.id),Me=rt=>{let Ze=X.content??"";rt.trim()!==""&&(Ze.trim().length===0||rt.startsWith(Ze)||rt.trimStart().startsWith(Ze.trim()))&&(X.content=rt)},Ee=()=>{if(ie){let rt=ie.close?.();rt instanceof Promise&&rt.catch(()=>{})}le.delete(X.id),de.delete(X.id),X.streaming=!1,h(X)};if(!ie){Me(j),Ee();return}let _e=Gl(Y);if(_e!==null&&_e.trim()!==""){Me(_e),Ee();return}let Ct=rt=>{let Ze=typeof rt=="string"?rt:rt?.text??null;if(Ze!==null&&Ze.trim()!=="")return Ze;let ct=ie.getExtractedText();return ct!==null&&ct.trim()!==""?ct:j},Ot;try{Ot=ie.processChunk(Y)}catch{Me(j),Ee();return}if(Ot instanceof Promise){Ot.then(rt=>{Me(Ct(rt)),Ee()}).catch(()=>{Me(j),Ee()});return}Me(Ct(Ot)),Ee()},Le=null,se=(X,I,j,J)=>{X.rawContent=I,le.has(X.id)||le.set(X.id,this.createStreamParser());let Y=le.get(X.id),ie=I.trim().startsWith("{")||I.trim().startsWith("[");if(ie&&de.set(X.id,I),Y.__isPlainTextParser===!0){X.content=J!==void 0?I:X.content+j,de.delete(X.id),le.delete(X.id),X.rawContent=void 0,h(X);return}let Ee=Y.processChunk(I);if(Ee instanceof Promise)Ee.then(_e=>{let Ct=typeof _e=="string"?_e:_e?.text??null;Ct!==null&&Ct.trim()!==""?(X.content=Ct,h(X)):!ie&&!I.trim().startsWith("<")&&(X.content=J!==void 0?I:X.content+j,de.delete(X.id),le.delete(X.id),X.rawContent=void 0,h(X))}).catch(()=>{X.content=J!==void 0?I:X.content+j,de.delete(X.id),le.delete(X.id),X.rawContent=void 0,h(X)});else{let _e=typeof Ee=="string"?Ee:Ee?.text??null;_e!==null&&_e.trim()!==""?(X.content=_e,h(X)):!ie&&!I.trim().startsWith("<")&&(X.content=J!==void 0?I:X.content+j,de.delete(X.id),le.delete(X.id),X.rawContent=void 0,h(X))}},_=(X,I)=>{let j=I??X.content;if(j==null||j===""){X.streaming=!1,h(X);return}let Y=de.get(X.id)??ne(j);X.rawContent=Y;let ie=le.get(X.id),Me=null,Ee=!1;if(ie&&(Me=ie.getExtractedText(),Me===null&&(Me=Gl(Y)),Me===null)){let _e=ie.processChunk(Y);_e instanceof Promise?(Ee=!0,_e.then(Ct=>{let Ot=typeof Ct=="string"?Ct:Ct?.text??null;Ot!==null&&(X.content=Ot,X.streaming=!1,le.delete(X.id),de.delete(X.id),h(X))}).catch(()=>{})):Me=typeof _e=="string"?_e:_e?.text??null}if(!Ee){Me!==null&&Me.trim()!==""?X.content=Me:de.has(X.id)||(X.content=ne(j));let _e=le.get(X.id);if(_e){let Ct=_e.close?.();Ct instanceof Promise&&Ct.catch(()=>{}),le.delete(X.id)}de.delete(X.id),X.streaming=!1,h(X)}},Te=(X,I,j)=>{let J=D.get(X);if(J)return J;let Y={id:`nested-${I}-${X}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u(),...j?{variant:j}:{},...j==="reasoning"?{reasoning:{id:X,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:I}};return D.set(X,Y),h(Y),Y},Re=[],ut,At=new Map,Wt=0,bt="agent",xe=!1,Ne=null,Ae=null,vt=this.config.iterationDisplay??"separate";for(ut=()=>{for(let X=0;X<Re.length;X++){let I=Re[X];if(!xe&&bt!=="flow"&&typeof I.stepType=="string"&&(bt="flow"),I.type==="reasoning_start"){let j=typeof I.id=="string"?I.id:null,J=typeof I.parentToolCallId=="string"&&I.parentToolCallId?I.parentToolCallId:null;if(j&&J){A.set(j,J),Te(j,J,"reasoning");continue}let Y=I.id,ie=x(Y);ie.reasoning=ie.reasoning??{id:Y,status:"streaming",chunks:[]},ie.reasoning.startedAt=ie.reasoning.startedAt??Date.now(),ie.reasoning.completedAt=void 0,ie.reasoning.durationMs=void 0,(I.scope==="loop"||I.scope==="turn")&&(ie.reasoning.scope=I.scope),ie.streaming=!0,ie.reasoning.status="streaming",h(ie)}else if(I.type==="reasoning_delta"){let j=typeof I.id=="string"?I.id:null;if(j&&A.has(j)&&D.has(j)){let ie=D.get(j),Me=I.delta;Me&&ie.reasoning&&(ie.reasoning.chunks.push(String(Me)),h(ie));continue}let J=I.id,Y=x(J);Y.reasoning=Y.reasoning??{id:J,status:"streaming",chunks:[]},Y.reasoning.startedAt=Y.reasoning.startedAt??Date.now(),I.delta&&Y.reasoning.chunks.push(I.delta),Y.reasoning.status="streaming",Y.streaming=!0,h(Y)}else if(I.type==="reasoning_complete"){let j=typeof I.id=="string"?I.id:null;if(j&&A.has(j)&&D.has(j)){let Me=D.get(j);if(Me.reasoning){let Ee=typeof I.text=="string"?I.text:"";Ee&&Me.reasoning.chunks.length===0&&Me.reasoning.chunks.push(Ee),Me.reasoning.status="complete",Me.streaming=!1,h(Me)}A.delete(j),D.delete(j);continue}let J=I.id,Y=typeof I.text=="string"?I.text:"";!U.get(J)&&(Y||I.scope==="loop")&&x(J);let ie=U.get(J);if(ie?.reasoning){(I.scope==="loop"||I.scope==="turn")&&(ie.reasoning.scope=I.scope),Y&&ie.reasoning.chunks.length===0&&ie.reasoning.chunks.push(Y),ie.reasoning.status="complete",ie.reasoning.completedAt=Date.now();let Me=ie.reasoning.startedAt??Date.now();ie.reasoning.durationMs=Math.max(0,(ie.reasoning.completedAt??Date.now())-Me),ie.streaming=!1,h(ie)}}else if(I.type==="tool_start"){b&&(b.streaming=!1,h(b),b=null),typeof I.iteration=="number"&&(Wt=I.iteration);let j=I.toolCallId,J=I.toolName;if(K(J)){P.add(j);continue}let Y=ee(j),ie=Y.toolCall??{id:j,status:"pending"};ie.name=J??ie.name,ie.status="running",ie.success=void 0,ie.error=void 0,ie.duration=void 0,I.parameters!==void 0&&(ie.args=I.parameters),ie.startedAt=ie.startedAt??oe(I.startedAt),ie.completedAt=void 0,ie.durationMs=void 0,Y.toolCall=ie,Y.streaming=!0,I.executionId&&(Y.agentMetadata={executionId:I.executionId,iteration:I.iteration}),h(Y)}else if(I.type==="tool_output_delta"){let j=I.toolCallId;if(P.has(j))continue;let J=ee(j),Y=J.toolCall??{id:j,status:"running"};Y.startedAt=Y.startedAt??Date.now();let ie=I.delta;ie&&(Y.chunks=Y.chunks??[],Y.chunks.push(String(ie))),Y.status="running",J.toolCall=Y,J.streaming=!0,I.executionId&&(J.agentMetadata=J.agentMetadata??{executionId:I.executionId,iteration:Wt}),h(J)}else if(I.type==="tool_complete"){let j=I.toolCallId;if(P.has(j)){P.delete(j);continue}let J=ee(j),Y=J.toolCall??{id:j,status:"running"};Y.status="complete",I.result!==void 0&&(Y.result=I.result),Y.name=I.toolName??Y.name,Y.success=I.success,Y.error=I.error,Y.completedAt=Date.now();let ie=I.executionTime;if(typeof ie=="number")Y.durationMs=ie,Y.duration=ie;else{let Me=Y.startedAt??Date.now();Y.durationMs=Math.max(0,(Y.completedAt??Date.now())-Me)}J.toolCall=Y,J.streaming=!1,I.executionId&&(J.agentMetadata=J.agentMetadata??{executionId:I.executionId,iteration:I.iteration??Wt}),h(J)}else if(I.type==="await"&&I.toolName){let j=typeof I.toolCallId=="string"&&I.toolCallId.length>0?I.toolCallId:void 0,J=j??I.toolId??`local-${u()}`,Y=ee(J),ie=I.toolName,Me=I.origin==="webmcp"&&!Sa(ie)?`webmcp:${ie}`:ie,Ee=Sa(Me),_e=Y.toolCall??{id:J,status:"pending"};_e.name=Me,_e.args=I.parameters,_e.status=Ee?"running":"complete",_e.chunks=_e.chunks??[],_e.startedAt=_e.startedAt??oe(I.awaitedAt),Ee?(_e.completedAt=void 0,_e.duration=void 0,_e.durationMs=void 0):_e.completedAt=_e.completedAt??_e.startedAt,Y.toolCall=_e,Y.streaming=!1,Y.agentMetadata={...Y.agentMetadata,executionId:I.executionId??Y.agentMetadata?.executionId,awaitingLocalTool:!0,...j?{webMcpToolCallId:j}:{}},h(Y)}else if(I.type==="text_start"){let j=typeof I.id=="string"?I.id:null,J=typeof I.parentToolCallId=="string"&&I.parentToolCallId?I.parentToolCallId:null;if(j&&J){A.set(j,J);continue}let Y=b;Y&&(bt==="flow"?(_(Y),Le=Y):(Y.streaming=!1,h(Y)),b=null),T=typeof I.id=="string"?I.id:T,R=""}else if(I.type==="text_delta"){let j=typeof I.id=="string"?I.id:null,J=j?A.get(j):void 0;if(j&&J){let Me=typeof I.delta=="string"?I.delta:"",Ee=(W.get(j)??"")+Me;if(W.set(j,Ee),Ee.trim()==="")continue;let _e=Te(j,J);_e.agentMetadata={..._e.agentMetadata,executionId:I.executionId,parentToolId:J},se(_e,Ee,Me,void 0);continue}if(T=typeof I.id=="string"?I.id:T,bt==="flow"){let Me=typeof I.delta=="string"?I.delta:"";if(R+=Me,R.trim()==="")continue;let Ee=S();Ee.agentMetadata={executionId:I.executionId,iteration:Wt},se(Ee,R,Me,void 0),C=Ee;continue}let Y=typeof I.delta=="string"?I.delta:"";R+=Y;let ie=S();ie.agentMetadata={executionId:I.executionId,iteration:Wt,turnId:Ne??void 0,agentName:Ae?.agentName},se(ie,R,Y,void 0),C=ie}else if(I.type==="text_complete"){let j=typeof I.id=="string"?I.id:null;if(j&&A.has(j)){let Y=D.get(j);Y&&_(Y),A.delete(j),W.delete(j),D.delete(j);continue}let J=b;J&&(bt==="flow"?(_(J),Le=J):((J.content??"")===""&&typeof I.text=="string"&&(J.content=I.text),J.streaming=!1,h(J)),b=null),T=null,R=""}else if(I.type==="step_complete"){if(I.stepType==="tool")continue;if(I.success===!1){let j=I.error||"Step failed";n({type:"error",error:new Error(j)});let J=b;J&&J.streaming&&(J.streaming=!1,h(J)),n({type:"status",status:"idle"});continue}{let j=Le;Le=null;let J=I.stopReason,ie=(I.result&&typeof I.result=="object"?I.result:null)?.response;if(j)J&&(j.stopReason=J),ie!=null?ve(j,ie):j.streaming!==!1&&(le.delete(j.id),de.delete(j.id),j.streaming=!1,h(j));else{let Me=ie!=null&&ie!=="";if(Me||J){let Ee=S();J&&(Ee.stopReason=J),Me?_(Ee,ie):(Ee.streaming=!1,h(Ee))}}continue}}else if(I.type==="execution_start")bt=I.kind==="flow"?"flow":"agent",xe=!0,bt==="agent"&&(Ae={executionId:I.executionId,agentId:I.agentId??"virtual",agentName:I.agentName??""});else if(I.type==="turn_start"){let j=typeof I.iteration=="number"?I.iteration:Wt;if(j!==Wt){if(vt==="separate"&&j>1){let J=b;J&&(J.streaming=!1,h(J),b=null)}Wt=j}Ne=typeof I.id=="string"?I.id:null,C=null}else if(I.type==="tool_input_delta"){let j=I.toolCallId;if(j){let J=B.get(j);J?.toolCall&&(J.toolCall.chunks=J.toolCall.chunks??[],J.toolCall.chunks.push(I.delta??""),h(J))}}else if(I.type==="tool_input_complete"){if(P.has(I.toolCallId))continue;let j=ee(I.toolCallId),J=j.toolCall;J.args=I.parameters,J.name=I.toolName??J.name,h(j)}else if(I.type==="turn_complete"){let j=I.stopReason,J=b??C;if(j&&J!==null){let Y=I.id;(!Y||J.agentMetadata?.turnId===Y)&&(J.stopReason=j,h(J))}Ne===I.id&&(Ne=null)}else if(I.type==="media_start"){let j=String(I.id);At.set(j,{mediaType:typeof I.mediaType=="string"?I.mediaType:void 0,toolCallId:I.toolCallId,parts:[]})}else if(I.type==="media_delta"){let j=At.get(String(I.id));j&&typeof I.delta=="string"&&j.parts.push(I.delta)}else if(I.type==="media_complete"){let j=String(I.id),J=At.get(j);At.delete(j);let Y=(typeof I.mediaType=="string"?I.mediaType:void 0)??J?.mediaType??"application/octet-stream",ie=typeof I.data=="string"?I.data:void 0,Me=typeof I.url=="string"?I.url:J&&J.parts.length>0?J.parts.join(""):void 0,Ee=null;if(ie)Ee={type:"media",data:ie,mediaType:Y};else if(Me){let rt=Y.toLowerCase();Ee={type:rt==="image"||rt.startsWith("image/")?"image-url":"file-url",url:Me,mediaType:Y}}let _e=I.toolCallId??J?.toolCallId,Ct=Ee?[Ee]:[],Ot=[];for(let rt of Ct){if(!rt||typeof rt!="object")continue;let Ze=rt,ct=typeof Ze.type=="string"?Ze.type:void 0,Ht=typeof Ze.mediaType=="string"?Ze.mediaType.toLowerCase():"",Z=null,Fe="";if(ct==="media"){let He=typeof Ze.data=="string"?Ze.data:void 0;if(!He)continue;Fe=Ht.length>0?Ht:"application/octet-stream",Z=`data:${Fe};base64,${He}`}else if(ct==="image-url"){let He=typeof Ze.url=="string"?Ze.url:void 0;if(!He)continue;Fe=Ht,Z=He}else if(ct==="file-url"){let He=typeof Ze.url=="string"?Ze.url:void 0;if(!He)continue;Fe=Ht,Z=He}else continue;if(Z)if(ct==="image-url"||Fe.startsWith("image/"))Ot.push({type:"image",image:Z,...Fe.includes("/")?{mimeType:Fe}:{}});else if(Fe.startsWith("audio/"))Ot.push({type:"audio",audio:Z,mimeType:Fe});else if(Fe.startsWith("video/"))Ot.push({type:"video",video:Z,mimeType:Fe});else{let He=Fe||"application/octet-stream";Ot.push({type:"file",data:Z,mimeType:He,filename:TI(He)})}}if(Ot.length>0){let rt=u(),Ze=_e,Ht={id:`agent-media-${typeof Ze=="string"&&Ze.length>0?`${Ze}-${rt}`:String(rt)}`,role:"assistant",content:"",contentParts:Ot,createdAt:new Date().toISOString(),streaming:!1,sequence:rt,agentMetadata:{executionId:I.executionId,iteration:Wt}};h(Ht);let Z=b;Z&&(Z.streaming=!1,h(Z)),b=null,M.current=null}}else if(I.type==="execution_complete"){let j=b;j&&(I.kind==="flow"&&j.streaming!==!1?_(j):(j.streaming=!1,h(j)),b=null),T=null,R="",Le=null,n({type:"status",status:"idle",terminal:!0})}else if(I.type==="execution_error"){let j=typeof I.error=="string"?I.error:I.error?.message??"Execution error";n({type:"error",error:new Error(j)})}else if(I.type!=="ping"){if(I.type==="approval_start"){let j=I.approvalId??`approval-${u()}`,J={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:j,status:"pending",agentId:Ae?.agentId??"virtual",executionId:I.executionId??Ae?.executionId??"",toolName:I.toolName??"",toolType:I.toolType,description:I.description??`Execute ${I.toolName??"tool"}`,...typeof I.reason=="string"&&I.reason?{reason:I.reason}:{},parameters:I.parameters}};h(J)}else if(I.type==="approval_complete"){let j=I.approvalId;if(j){let Y={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:j,status:I.decision??"approved",agentId:Ae?.agentId??"virtual",executionId:I.executionId??Ae?.executionId??"",toolName:"",description:"",resolvedAt:Date.now()}};h(Y)}}else if(I.type==="artifact_start"||I.type==="artifact_delta"||I.type==="artifact_update"||I.type==="artifact_complete"){if(I.type==="artifact_start"){let j=I.artifactType,J=String(I.id),Y=typeof I.title=="string"?I.title:void 0,ie=I.file,Me;if(ie&&typeof ie=="object"&&!Array.isArray(ie)&&typeof ie.path=="string"&&typeof ie.mimeType=="string"&&(Me={path:ie.path,mimeType:ie.mimeType,...typeof ie.language=="string"?{language:ie.language}:{}}),n({type:"artifact_start",id:J,artifactType:j,title:Y,component:typeof I.component=="string"?I.component:void 0,...Me?{file:Me}:{}}),V.set(J,{markdown:"",title:Y,file:Me}),!G.has(J)){G.add(J);let Ee=Cs(this.config.features?.artifacts,{artifactType:j,...Me?{file:Me}:{}}),_e=typeof I.component=="string"?I.component:void 0,Ct={id:`artifact-ref-${J}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u(),rawContent:$l(Ee,{artifactId:J,title:Y,artifactType:j,status:"streaming",...Me?{file:Me}:{},..._e?{component:_e}:{}})};L.set(J,Ct),h(Ct)}}else if(I.type==="artifact_delta"){let j=String(I.id),J=typeof I.delta=="string"?I.delta:String(I.delta??"");n({type:"artifact_delta",id:j,artDelta:J});let Y=V.get(j);Y&&(Y.markdown+=J)}else if(I.type==="artifact_update"){let j=I.props&&typeof I.props=="object"&&!Array.isArray(I.props)?I.props:{};n({type:"artifact_update",id:String(I.id),props:j,component:typeof I.component=="string"?I.component:void 0});let J=V.get(String(I.id));J&&(J.props={...J.props??{},...j})}else if(I.type==="artifact_complete"){let j=String(I.id);n({type:"artifact_complete",id:j});let J=L.get(j);if(J){J.streaming=!1;try{let Y=JSON.parse(J.rawContent??"{}");if(Y.props){Y.props.status="complete";let ie=V.get(j);ie?.markdown&&(Y.props.markdown=ie.markdown),ie?.file&&(Y.props.file=ie.file),Y.component==="PersonaArtifactInline"&&ie?.props&&Object.keys(ie.props).length>0&&(Y.props.componentProps=ie.props)}J.rawContent=JSON.stringify(Y)}catch{}V.delete(j),h(J),L.delete(j)}}}else if(I.type==="error"&&I.recoverable===!1&&I.error!=null&&I.error!==""){let j=typeof I.error=="string"?I.error:I.error?.message!=null?String(I.error.message):"Execution error";n({type:"error",error:new Error(j)});let J=b;J&&J.streaming&&(J.streaming=!1,h(J)),n({type:"status",status:"idle"})}}}Re.length=0};;){let{done:X,value:I}=await s.read();if(X)break;l+=a.decode(I,{stream:!0});let j=l.split(`
|
|
1143
1143
|
|
|
1144
1144
|
`);l=j.pop()??"";for(let J of j){let Y=J.split(`
|
|
1145
|
-
`),ie="message",Me="",Ee=null;for(let Ze of Y)Ze.startsWith("event:")?ie=Ze.replace("event:","").trim():Ze.startsWith("data:")?Me+=Ze.replace("data:","").trim():Ze.startsWith("id:")&&(Ee=Ze.slice(3).trim());let
|
|
1145
|
+
`),ie="message",Me="",Ee=null;for(let Ze of Y)Ze.startsWith("event:")?ie=Ze.replace("event:","").trim():Ze.startsWith("data:")?Me+=Ze.replace("data:","").trim():Ze.startsWith("id:")&&(Ee=Ze.slice(3).trim());let _e=()=>{Ee!==null&&Ee!==""&&n({type:"cursor",id:Ee})};if(!Me){_e();continue}let Ct;try{Ct=JSON.parse(Me)}catch(Ze){n({type:"error",error:Ze instanceof Error?Ze:new Error("Failed to parse chat stream payload")});continue}let Ot=Ct!==null&&typeof Ct=="object"&&!Array.isArray(Ct)?Ct:null,rt=ie!=="message"?ie:typeof Ot?.type=="string"?Ot.type:"message";if(this.onSSEEvent?.(rt,Ct),this.parseSSEEvent){M.current=b;let Ze=await this.handleCustomSSEEvent(Ct,n,M,h,u,E);if(M.current&&M.current!==b&&(b=M.current),Ze){_e();continue}}Ot&&(Re.push({...Ot,type:rt}),ut()),_e()}}ut()}};Aa();Yg();var II=t=>t.sourceLabel?`quoted-text source=${t.sourceLabel}`:"quoted-text";function HI(t){let e=t?.text?.trim()??"";return e?Jl(II(t),e):""}function eS(t){let e=HI(t.quote);return e?t.contentParts&&t.contentParts.length>0?{contentParts:[fr(e),...t.contentParts]}:{llmContent:[e,t.text].filter(Boolean).join(`
|
|
1146
1146
|
|
|
1147
|
-
`)}:{}}function Kp(t,e=140){let n=t.replace(/\s+/g," ").trim();return n.length<=e?n:`${n.slice(0,e-1)}\u2026`}function
|
|
1147
|
+
`)}:{}}function Kp(t,e=140){let n=t.replace(/\s+/g," ").trim();return n.length<=e?n:`${n.slice(0,e-1)}\u2026`}function tS(t,e){let n=t.findIndex(r=>r.id===e);if(n===-1||t[n].role!=="user")return null;let o=n+1;for(;o<t.length&&t[o].role!=="user";)o+=1;return{start:n,end:o}}function Qg(t,e){let n=t.findIndex(o=>o.id===e);if(n<=0)return null;for(let o=n-1;o>=0;o-=1)if(t[o].role==="user")return t[o].id;return null}function nS(t){for(let e=t.length-1;e>=0;e-=1){let n=t[e];if(n.role==="user"||n.streaming)return null;if(!(n.role!=="assistant"||n.variant))return Qg(t,n.id)?n.id:null}return null}function Xg(t){return t.role!=="user"||t.variant||t.streaming||t.contentParts?.length||t.contextMentions?.length||t.contentSegments?.length||t.mentionContext&&Object.keys(t.mentionContext).length>0||t.rawContent!==void 0||t.llmContent!==void 0&&t.llmContent!==t.content||t.quote?!1:typeof t.content=="string"&&t.content.length>0}Zl();function Jg(t){let e=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let n of e){let o=t.find(r=>r.name===n);if(o)return o}return t.find(n=>n.lang.startsWith("en"))??t[0]}var ec=class t{constructor(e={}){this.options=e;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(e,n){if(!t.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(e.text),s=o.getVoices();if(e.voice){let a=s.find(l=>l.name===e.voice);a&&(r.voice=a)}else s.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(s):Jg(s));e.rate!==void 0&&(r.rate=e.rate),e.pitch!==void 0&&(r.pitch=e.pitch),r.onend=()=>n.onEnd?.(),r.onerror=a=>{let l=a.error;l==="canceled"||l==="interrupted"?n.onEnd?.():n.onError?.(new Error(l||"Speech synthesis failed"))},setTimeout(()=>{o.speak(r),n.onStart?.()},50)}pause(){t.isSupported()&&window.speechSynthesis.pause()}resume(){t.isSupported()&&window.speechSynthesis.resume()}stop(){t.isSupported()&&window.speechSynthesis.cancel()}};var Yp=class{constructor(e){this.resolveEngine=e;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){return this.engine?.supportsPause??!0}stateFor(e){return this.activeId===e?this.state:"idle"}activeMessageId(){return this.activeId}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}toggle(e,n){if(this.activeId===e){if(this.state==="playing"){this.engine?.supportsPause?(this.engine.pause(),this.set(e,"paused")):this.stop();return}if(this.state==="paused"){this.engine?.resume(),this.set(e,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(e,n)}async play(e,n){let o=++this.generation;this.engine?.stop(),this.set(e,"loading");try{if(!this.engine){let r=await this.resolveEngine();if(o!==this.generation)return;if(!r){this.set(null,"idle");return}this.engine=r}this.engine.speak(n,{onStart:()=>{o===this.generation&&this.set(e,"playing")},onEnd:()=>{o===this.generation&&this.set(null,"idle")},onError:()=>{o===this.generation&&this.set(null,"idle")}})}catch{o===this.generation&&this.set(null,"idle")}}stop(){this.generation++,this.engine?.stop(),this.set(null,"idle")}destroy(){this.stop(),this.engine?.destroy?.(),this.engine=null,this.listeners.clear()}set(e,n){this.activeId=n==="idle"?null:e,this.state=n;for(let o of this.listeners)o(this.activeId,this.state)}};var tc=class{constructor(){this.cancelled=!1}start(e){this.turnId=e,this.cancelled=!1}cancel(){this.cancelled=!0}accepts(e){return!this.cancelled&&(!e||!this.turnId||e===this.turnId)}};so();var{setLoader:O_,load:qI}=Qt({fallbackImport:()=>Promise.resolve().then(()=>(lS(),aS))});var oh=qI;function rh(t){if(!t)return"";let e=jI(t);return cS(e!==null?e:t)}function jI(t){let e=t.trim(),n=e.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(e=n[1].trim()),!e.startsWith("{"))return null;try{let o=JSON.parse(e);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function cS(t){if(!t)return"";let e=t;return e=e.replace(/```[\s\S]*?```/g," "),e=e.replace(/~~~[\s\S]*?~~~/g," "),e=e.replace(/`([^`]+)`/g,"$1"),e=e.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),e=e.replace(/<\/?[a-zA-Z][^>]*>/g," "),e=e.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),e=e.replace(/^[ \t]*>[ \t]?/gm,""),e=e.replace(/^[ \t]*[-*+][ \t]+/gm,""),e=e.replace(/^[ \t]*\d+\.[ \t]+/gm,""),e=e.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),e=e.replace(/(\*\*|__)(.*?)\1/g,"$2"),e=e.replace(/(\*|_)(.*?)\1/g,"$2"),e=e.replace(/~~(.*?)~~/g,"$1"),e=e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," "),e=e.replace(/[ \t]+/g," "),e=e.replace(/[ \t]*\n[ \t]*/g,`
|
|
1148
1148
|
`),e=e.replace(/\n{2,}/g,`
|
|
1149
|
-
`),e.trim()}var
|
|
1149
|
+
`),e.trim()}var fS=null;var sh=()=>fS?fS():Promise.resolve().then(()=>(mS(),uS));so();var{setLoader:K_,load:XI}=Qt({fallbackImport:()=>Promise.resolve().then(()=>(hS(),gS))});var yS=XI;var JI=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId","getIdentityProof","identityProvider","getStoredConversationId","setStoredConversationId","clearStoredConversationId","clearStoredSessionId"];function ZI(t,e){return JI.some(n=>t[n]!==e[n])}var hr=class extends Error{constructor(e,n){super(n),this.name="SessionHistoryError",this.code=e}};function ih(t,e){let n=t instanceof Error?t:new Error(String(t));if(typeof e=="string")return e;if(typeof e=="function")return e(n);let o="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${o}
|
|
1150
1150
|
|
|
1151
|
-
_Details: ${n.message}_`:o}var sh=t=>({isError:!0,content:[{type:"text",text:t}]}),_I=(t,e="WebMCP tool execution failed.")=>t instanceof Error&&t.message?t.message:typeof t=="string"&&t?t:e,lS=t=>Sa(t)||t===As,Jp=class t{constructor(e={},n,o={}){this.config=e;this.callbacks=n;this.historyInternals=o;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.resumable=null;this.activeAssistantMessageId=null;this.reconnecting=!1;this.reconnectController=null;this.reconnectControllerPromise=null;this.executionStateTimer=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceSetupPromise=null;this.voiceSetupGeneration=0;this.voiceLevel=0;this.voiceActive=!1;this.voiceStatus="disconnected";this.activeConversationId=null;this.activeConversationRevision=null;this.historyNextMessageCursor=null;this.historyOpenEpoch=0;this.suppressWelcomeInjection=!1;this.historyRecovery=null;this.historySendBlocked=!1;this.historyGate=null;this.olderPageRequests=new Map;this.projectionFinalizationPromise=null;this.acknowledgedProjections=new Map;this.pendingProjections=null;this.bootConversationRevision=null;this.bootRevisionCaptured=!1;this.visitorStoreUnsubscribe=null;this.subscribedVisitorStore=null;this.credentialReinitPending=!1;this.credentialReinitPromise=null;this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.voiceTurns=new tc;this.voiceDisconnectPromise=Promise.resolve();this.ttsSpokenMessageIds=new Set;this.readAloud=new Yp(()=>this.createSpeechEngine());this.handleEvent=e=>{if(e.type==="message"){this.upsertMessage(e.message),e.message.role==="assistant"&&!e.message.variant&&e.message.streaming&&(this.activeAssistantMessageId=e.message.id);let n=e.message.toolCall,o=!!n?.name&&(Sa(n.name)||n.name===As&&Ms(this.config).enabled);e.message.agentMetadata?.awaitingLocalTool===!0&&o&&this.enqueueWebMcpAwait(e.message),e.message.agentMetadata?.executionId&&(this.agentExecution?e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration):this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:"",agentName:e.message.agentMetadata.agentName??"",status:"running",currentIteration:e.message.agentMetadata.iteration??0,maxTurns:0})}else if(e.type==="cursor")this.trackCursor(e.id);else if(e.type==="status"){if(e.status==="idle"&&!e.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(e.status),e.status==="connecting")this.setStreaming(!0);else if(e.status==="idle"||e.status==="error"){this.isAwaitPending()||this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null,this.invalidateConversationRevision(),this.scheduleProjectionFinalization());let n=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(e.status==="error"?this.agentExecution.status="error":n||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else e.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.agentExecution?.status==="running"&&(this.agentExecution.status="error"),this.callbacks.onError?.(e.error)):(e.type==="artifact_start"||e.type==="artifact_delta"||e.type==="artifact_update"||e.type==="artifact_complete")&&this.applyArtifactStreamEvent(e)};this.historyInternals=this.composeHistoryInternals(o),this.messages=[...e.initialMessages??[]].map(r=>({...r,sequence:r.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new Xl(e,this.historyInternals),this.syncVisitorStoreSubscription(),this.wireDefaultWebMcpConfirm();for(let r of e.initialArtifacts??[])this.artifacts.set(r.id,{...r,status:"complete"});e.initialSelectedArtifactId!=null&&(this.selectedArtifactId=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts(),this.prefetchVoiceRuntime()}prefetchVoiceRuntime(){this.config.voiceRecognition?.provider&&th().catch(()=>{})}prefetchRuntypeTts(){let e=this.config.textToSpeech;if(e?.provider!=="runtype"||e.createEngine)return;let n=e.host??this.config.apiUrl,o=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!n||!o||!this.config.clientToken||oh().catch(()=>{})}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return Ew(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceLevel(){return this.voiceProvider?.onLevel?this.voiceLevel:null}getVoiceInterruptionMode(){return this.voiceProvider?.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){this.voiceProvider?.stopPlayback&&(this.voiceTurns.cancel(),this.voiceProvider.stopPlayback())}isBargeInActive(){return this.voiceProvider?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.voiceProvider?.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){let e=this.config.textToSpeech;if(e?.createEngine)return e.createEngine();let n=ec.isSupported()?new ec({pickVoice:e?.pickVoice}):null;if(e?.provider==="runtype"){let o=e.host??this.config.apiUrl,r=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,s=this.config.clientToken,a=e.browserFallback!==!1;if(o&&r&&s)return oh().then(({RuntypeSpeechEngine:l,FallbackSpeechEngine:c})=>{let p=new l({host:o,agentId:r,clientToken:s,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return a&&n?new c(p,n,{onFallback:u=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${u.message}`)}):p});if(a&&n)return s&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(e){try{let n=e||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.cleanupVoice();let o=this.voiceDisconnectPromise,r=++this.voiceSetupGeneration;this.voiceSetupPromise=th().then(async s=>{await o,r===this.voiceSetupGeneration&&this.wireVoiceProvider(s.createVoiceProvider(n))}).catch(s=>{console.error("Failed to setup voice:",s)}).finally(()=>{r===this.voiceSetupGeneration&&(this.voiceSetupPromise=null)})}catch(n){console.error("Failed to setup voice:",n)}}wireVoiceProvider(e){try{this.voiceProvider=e;let n=this.voiceSetupGeneration,o=()=>this.voiceProvider===e&&n===this.voiceSetupGeneration,s=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(a=>{o()&&a.provider!=="runtype"&&a.text&&a.text.trim()&&this.sendMessage(a.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((a,l,c,p)=>{if(o())if(a==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:l,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!c});else{let u=this.injectMessage({role:"user",content:l,streaming:!1,voiceProcessing:!c});this.pendingVoiceUserMessageId=u.id}if(c){this.voiceTurns.start(p?.turnId),this.pendingVoiceUserMessageId=null;let u=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=u.id,this.setStreaming(!0)}}else{if(!this.voiceTurns.accepts(p?.turnId))return;if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:l,createdAt:new Date().toISOString(),streaming:!c,voiceProcessing:!c});else{let u=this.injectMessage({role:"assistant",content:l,streaming:!c,voiceProcessing:!c});this.pendingVoiceAssistantMessageId=u.id}c&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onLevel&&this.voiceProvider.onLevel(a=>{o()&&(this.voiceLevel=Number.isFinite(a)?Math.max(0,Math.min(1,a)):0)}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(a=>{o()&&this.config.voiceRecognition?.onMetrics?.(a)}),this.voiceProvider.onError(a=>{o()&&(console.error("Voice error:",a),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:s,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null))}),this.voiceProvider.onStatusChange(a=>{o()&&(this.voiceStatus=a,this.voiceActive=a==="listening",(a==="listening"||a==="idle"||a==="disconnected")&&this.settlePendingVoiceTurn(a!=="listening"),this.callbacks.onVoiceStatusChanged?.(a))}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}async toggleVoice(){if(!this.voiceProvider&&this.voiceSetupPromise&&await this.voiceSetupPromise,!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(e){console.error("Failed to start voice:",e)}}}cleanupVoice(){let e=this.voiceProvider!==null;if(this.voiceSetupGeneration++,this.voiceSetupPromise=null,this.voiceProvider){let n=this.voiceProvider;this.voiceProvider=null,this.voiceDisconnectPromise=this.disconnectVoice(n)}this.voiceActive=!1,this.voiceStatus="disconnected",this.settlePendingVoiceTurn(!0),this.voiceTurns=new tc,e&&this.callbacks.onVoiceStatusChanged?.("disconnected")}async disconnectVoice(e){try{await e.disconnect()}catch(n){console.error("Failed to disconnect voice:",n)}}settlePendingVoiceTurn(e){let n=e?this.pendingVoiceUserMessageId:null,o=this.pendingVoiceAssistantMessageId;!n&&!o||(o&&this.voiceTurns.cancel(),e&&(this.pendingVoiceUserMessageId=null),this.pendingVoiceAssistantMessageId=null,o&&this.ttsSpokenMessageIds.add(o),this.messages=this.messages.flatMap(r=>r.id!==n&&r.id!==o?[r]:r.id===o&&!r.content.trim()?[]:[{...r,streaming:!1,voiceProcessing:!1}]),this.callbacks.onMessagesChanged([...this.messages]),o&&this.setStreaming(!1))}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let e=this.config.voiceRecognition.provider;switch(e.type){case"runtype":return{type:"runtype",runtype:{agentId:e.runtype?.agentId??this.config.agentId??"",clientToken:e.runtype?.clientToken??this.config.clientToken,host:e.runtype?.host??this.config.apiUrl,voiceId:e.runtype?.voiceId,createPlaybackEngine:e.runtype?.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:e.browser?.language||"en-US",continuous:e.browser?.continuous}};case"custom":return{type:"custom",custom:e.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;this.config.features?.history?.enabled&&(await this.historyInternals.historyBootstrapReady,this.bootConversationRevision=this.historyInternals.getStoredConversationRevision?.()??null,this.bootRevisionCaptured=!0);try{let e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return this.callbacks.onError?.(e instanceof Error?e:new Error(String(e))),null}}warmClientSession(){let e=!this.messages.length;this.client.warmSession().then(n=>{n&&this.client.getClientSession()===n&&this.setClientSession(n,e)})}setClientSession(e,n){this.clientSession=e,this.injectWelcomeMessage(e,n)}injectWelcomeMessage(e,n=!this.messages.length){if(this.suppressWelcomeInjection||!e.config.welcomeMessage||!n)return;let o=this.messages[0],r={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:o?.createdAt??new Date().toISOString(),sequence:o?(o.sequence??0)-1:this.nextSequence()};this.appendMessage(r)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,n){return this.client.submitMessageFeedback(e,n)}async submitCSATFeedback(e,n){return this.client.submitCSATFeedback(e,n)}async submitNPSFeedback(e,n){return this.client.submitNPSFeedback(e,n)}setHistoryInternals(e){this.historyInternals=this.composeHistoryInternals(e),this.client.setHistoryInternals(this.historyInternals),this.syncVisitorStoreSubscription()}destroy(){this.cleanupVoice(),this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=null}composeHistoryInternals(e){let n=e.onHistoryContinuityChanged;return{...e,onHistoryContinuityChanged:o=>{this.handleHistoryContinuityChanged(o),n?.(o)}}}get historyProvider(){return this.historyInternals.historyProvider??null}requireHistoryProvider(){let e=this.historyProvider;if(!e)throw new hr("history_unavailable","No conversation history provider is installed");return e}historyContext(e){let n=this.requireHistoryProvider(),o=e??this.config.features?.history?.scope,r=this.config.getIdentityProof?"verified-user":"browser",s=o??(n.capabilities.scopes.includes(r)?r:n.capabilities.scopes[0]??r);if(!n.capabilities.scopes.includes(s))throw new gr("unsupported_scope","This history scope is not supported.");return{scope:s}}getHistoryState(){return{activeConversationId:this.activeConversationId,conversationRevision:this.activeConversationRevision,nextMessageCursor:this.historyNextMessageCursor,recovery:this.historyRecovery,sendBlocked:this.historySendBlocked}}getActiveConversationId(){return this.activeConversationId}emitHistoryState(){this.callbacks.onHistoryStateChanged?.(this.getHistoryState())}notifyHistory(e,n){this.callbacks.onHistoryNotice?.({code:e,message:n})}async awaitHistorySettled(){let e=this.historyGate;e&&await e.catch(()=>{});let n=this.projectionFinalizationPromise;n&&await n.catch(()=>{})}assertHistoryIdle(){if(this.streaming||this.status==="paused"||this.status==="resuming")throw new hr("conversation_busy","Finish or stop the current turn before switching conversations")}listConversations(e){return this.requireHistoryProvider().list({...e?.cursor?{cursor:e.cursor}:{},...e?.limit!==void 0?{limit:e.limit}:{},...e?.targetId!==void 0?{targetId:e.targetId}:{},context:this.historyContext(e?.scope)})}async openConversation(e,n){let o=this.requireHistoryProvider();this.assertHistoryIdle();let r=this.historyContext(n?.scope);await this.awaitHistorySettled();let s=++this.historyOpenEpoch,a=await o.getPage(e,{context:r});if(s!==this.historyOpenEpoch)throw new hr("superseded","A later selection won");let l=await o.prepareOpen(e,{context:r});if(s!==this.historyOpenEpoch)throw l.discard(),new hr("superseded","A later selection won");this.suppressWelcomeInjection=!0;try{await this.commitActivation(l)}finally{this.suppressWelcomeInjection=!1}this.activeConversationId=l.conversationId||e,this.activeConversationRevision=l.conversationRevision||a.conversationRevision||null,this.historyNextMessageCursor=a.nextCursor,this.historyRecovery=null,this.historySendBlocked=!1,this.resetConversationScopedState();for(let c of a.messages)this.acknowledgedProjections.set(c.id,c.content);return this.persistConversationMetadata(),this.hydrateMessages(a.messages),this.emitHistoryState(),{summary:a.summary,nextMessageCursor:a.nextCursor}}loadOlderMessages(e,n,o){let r=this.requireHistoryProvider(),s=this.historyContext(o?.scope),a=n??this.historyNextMessageCursor;if(!a)return Promise.resolve({messages:[],nextMessageCursor:null});let l=`${e} ${a}`,c=this.olderPageRequests.get(l);if(c)return c;let p=this.fetchOlderPage(r,e,a,s).finally(()=>{this.olderPageRequests.delete(l)});return this.olderPageRequests.set(l,p),p}async fetchOlderPage(e,n,o,r){let s=this.messages[0]?.createdAt,a=await e.getPage(n,{cursor:o,...s?{beforeCreatedAt:s}:{},context:r});if(this.activeConversationId&&this.activeConversationId!==n)return{messages:[],nextMessageCursor:a.nextCursor};let l=Ql(this.messages,a.messages);this.messages=this.sortMessages(l.map(c=>this.ensureSequence(c))),this.historyNextMessageCursor=a.nextCursor;for(let c of a.messages)this.acknowledgedProjections.set(c.id,c.content);return this.historyInternals.setStoredMessageCursor?.(a.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.emitHistoryState(),{messages:a.messages,nextMessageCursor:a.nextCursor}}async startNewConversation(e){let n=this.requireHistoryProvider(),o=this.historyContext(e?.scope);await this.awaitHistorySettled();let r=++this.historyOpenEpoch,s=await n.prepareStartNew({context:o});if(r!==this.historyOpenEpoch)throw s.discard(),new hr("superseded","A later action won");await this.installFreshConversation(s)}async installFreshConversation(e){this.discardConversationState(),await this.commitActivation(e),this.activeConversationId=e.conversationId||null,this.activeConversationRevision=e.conversationRevision||null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.historySendBlocked=!1,this.persistConversationMetadata(),this.emitHistoryState()}async deleteConversation(e,n){let o=this.requireHistoryProvider(),r=this.historyContext(n?.scope);await this.awaitHistorySettled(),await o.delete(e,{context:r}),e===this.activeConversationId&&await this.recoverFromDestroyedConversation(r)}async updateConversation(e,n,o){let r=this.requireHistoryProvider();if(!r.update)throw new hr("history_unavailable","This history provider cannot update conversations");let s=this.historyContext(o?.scope);return await this.awaitHistorySettled(),r.update(e,n,{context:s})}canUpdateConversations(){return typeof this.historyProvider?.update=="function"}async clearConversationHistory(e){let n=this.requireHistoryProvider(),o=this.historyContext(e?.scope);await this.awaitHistorySettled();let r=await n.deleteAll({...e?.targetId!==void 0?{targetId:e.targetId}:{},context:o});return await this.recoverFromDestroyedConversation(o),r}async resetHistoryDevice(){let e=this.requireHistoryProvider();if(!e.resetDevice)throw new hr("history_unavailable","This history provider cannot reset the device");this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null;try{return await e.resetDevice()}finally{this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.historySendBlocked=!1,this.emitHistoryState()}}async recoverFromDestroyedConversation(e){this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historySendBlocked=!0,this.historyRecovery=null,this.emitHistoryState(),await this.prepareReplacementConversation(e)}async prepareReplacementConversation(e){let n=this.historyProvider;if(!n){this.historySendBlocked=!1,this.emitHistoryState();return}try{let o=await n.prepareStartNew({context:e});await this.installFreshConversation(o)}catch{this.historySendBlocked=!0,this.historyRecovery="new_conversation_required",this.emitHistoryState(),this.notifyHistory("new_conversation_required","That conversation was deleted. Start a new conversation to continue.")}}async retryRequiredConversation(){if(!(this.historyRecovery!=="new_conversation_required"||!this.historyProvider)&&(this.historyRecovery=null,await this.prepareReplacementConversation(this.historyContext()),this.historyRecovery==="new_conversation_required"))throw new hr("new_conversation_required","A new conversation is required before sending")}async commitActivation(e){await e.commit();let n=this.client.getClientSession();n&&n.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(n)}bindActivatedSession(e){this.clientSession=e,this.config.setStoredSessionId?.(e.sessionId),e.conversationId&&(this.activeConversationId=e.conversationId,this.activeConversationRevision=e.conversationRevision??null,this.config.setStoredConversationId?.(e.conversationId),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),this.suppressWelcomeInjection||this.injectWelcomeMessage(e)}persistConversationMetadata(){this.activeConversationId?this.config.setStoredConversationId?.(this.activeConversationId):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.activeConversationRevision),this.historyInternals.setStoredMessageCursor?.(this.historyNextMessageCursor)}resetConversationScopedState(){this.historyInternals.setStoredResumableHandle?.(null),this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.acknowledgedProjections.clear(),this.setPendingProjections(null)}discardConversationState(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.resetConversationScopedState(),this.olderPageRequests.clear(),this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}handleHistoryContinuityChanged(e){this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.historySendBlocked=!0,this.discardConversationState(),this.activeConversationId=e.conversationId,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.emitHistoryState(),this.notifyHistory("history_continuity_reset","This browser was reconnected to a different conversation, so the previous messages were cleared."),this.historyGate=Promise.resolve().then(()=>{this.historySendBlocked=!1,this.historyGate=null,this.emitHistoryState()})}syncVisitorStoreSubscription(){let e=this.historyInternals.visitorStore??null;e!==this.subscribedVisitorStore&&(this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=e,e&&(this.visitorStoreUnsubscribe=e.subscribe(n=>this.handleExternalCredentialChange(n))))}handleExternalCredentialChange(e){if(e.source!=="external"||e.previousToken===null)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.credentialReinitPending=!0,this.credentialReinitPromise=null;let n=this.messages.length>0;n||this.activeConversationId!==null||(this.config.getStoredConversationId?.()??null)!==null?this.discardConversationState():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.olderPageRequests.clear(),this.setPendingProjections(null)),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.emitHistoryState(),n&&this.notifyHistory("history_continuity_reset","This browser's conversation history was reset in another tab, so the previous messages were cleared.")}completeCredentialReinit(){return this.credentialReinitPending?(this.credentialReinitPromise||(this.credentialReinitPromise=this.runCredentialReinit().finally(()=>{this.credentialReinitPromise=null})),this.credentialReinitPromise):Promise.resolve()}async runCredentialReinit(){if(!this.isClientTokenMode()){this.credentialReinitPending=!1;return}try{this.bindActivatedSession(await this.client.initSession()),this.credentialReinitPending=!1}catch{}}reconcileBootConversation(e){let n=this.historyProvider,o=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.activeConversationId;if(!n||!o)return Promise.resolve();let r=this.historyContext(e?.scope);this.historySendBlocked=!0,this.emitHistoryState();let s=this.runBootReconciliation(n,o,r).finally(()=>{this.historySendBlocked=this.historyRecovery!==null,this.historyGate===s&&(this.historyGate=null),this.emitHistoryState()});return this.historyGate=s,s}async runBootReconciliation(e,n,o){this.activeConversationId=n;let r=this.clientSession?.conversationRevision??this.activeConversationRevision??null,s=this.bootRevisionCaptured?this.bootConversationRevision:this.historyInternals.getStoredConversationRevision?.()??null;if(this.bootRevisionCaptured=!1,this.historyNextMessageCursor=this.historyInternals.getStoredMessageCursor?.()??this.historyNextMessageCursor,await this.replayPendingProjections(),r&&s&&r===s){this.activeConversationRevision=r;return}let a=await e.getPage(n,{context:o}),l=new Set(a.messages.map(m=>m.id)),c=this.messages.some(m=>l.has(m.id)),p=a.messages[0]?.createdAt,u;if(!c)u=a.messages.map(m=>this.ensureSequence(m));else{let m=this.resumable?this.activeAssistantMessageId:null,g=this.messages.filter(h=>l.has(h.id)||h.id===m?!0:p!==void 0&&h.createdAt<p);u=Ql(g,a.messages).map(h=>this.ensureSequence(h))}this.historyNextMessageCursor=a.nextCursor,this.activeConversationRevision=a.conversationRevision||r||null,this.acknowledgedProjections.clear();for(let m of a.messages)this.acknowledgedProjections.set(m.id,m.content);this.persistConversationMetadata(),this.messages=this.sortMessages(u),this.callbacks.onMessagesChanged([...this.messages])}projectionFinalizationEnabled(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}setPendingProjections(e){this.pendingProjections=e,this.historyInternals.setPendingDisplayProjections?.(e)}readPendingProjections(){return this.historyInternals.getPendingDisplayProjections?.()??this.pendingProjections}recordDispatchedProjections(e){if(this.projectionFinalizationEnabled())for(let n of e){let o=Yl(n);o!==void 0&&this.acknowledgedProjections.set(n.id,o)}}scheduleProjectionFinalization(){if(!this.projectionFinalizationEnabled())return;let e=this.activeConversationId;if(!e)return;let n=[];for(let o of this.messages){if(o.role!=="assistant"||o.streaming)continue;let r=Yl(o);r!==void 0&&this.acknowledgedProjections.get(o.id)!==r&&n.push({id:o.id,displayContent:r})}n.length!==0&&(this.setPendingProjections({conversationId:e,messageIds:n.map(o=>o.id)}),this.enqueueProjectionFinalization(e,n))}enqueueProjectionFinalization(e,n){let r=(this.projectionFinalizationPromise??Promise.resolve()).catch(()=>{}).then(()=>this.finalizeProjections(e,n,!1)).finally(()=>{this.projectionFinalizationPromise===r&&(this.projectionFinalizationPromise=null)});this.projectionFinalizationPromise=r}async finalizeProjections(e,n,o){if(this.activeConversationId!==e)return;let r=n.filter(s=>this.acknowledgedProjections.get(s.id)!==s.displayContent);if(r.length===0){this.clearFinalizedMarker(e,n);return}try{let{conversationRevision:s}=await this.client.finalizeDisplayProjections(e,r);for(let a of r)this.acknowledgedProjections.set(a.id,a.displayContent);this.activeConversationId===e&&s&&(this.activeConversationRevision=s),this.clearFinalizedMarker(e,n)}catch(s){if(!o&&this.isTransientProjectionError(s)){await this.finalizeProjections(e,r,!0);return}if(s instanceof it&&(s.code==="not_found"||s.code==="conversation_deleted")){this.clearFinalizedMarker(e,n);return}this.notifyHistory("projection_finalization_failed","Some message formatting could not be saved for history; it will be retried.")}}isTransientProjectionError(e){return e instanceof it?e.code==="request_failed":e instanceof Error}clearFinalizedMarker(e,n){let o=this.readPendingProjections();if(!o||o.conversationId!==e)return;let r=new Set(n.map(a=>a.id)),s=o.messageIds.filter(a=>!r.has(a));this.setPendingProjections(s.length?{conversationId:e,messageIds:s}:null)}async replayPendingProjections(){if(!this.projectionFinalizationEnabled())return;let e=this.readPendingProjections();if(!e)return;if(this.activeConversationId&&e.conversationId!==this.activeConversationId){this.setPendingProjections(null);return}let n=[];for(let o of e.messageIds){let r=this.messages.find(s=>s.id===o);!r||typeof r.content!="string"||n.push({id:o,displayContent:r.content})}if(n.length===0){this.setPendingProjections(null);return}this.enqueueProjectionFinalization(e.conversationId,n),await this.projectionFinalizationPromise?.catch(()=>{})}invalidateConversationRevision(){this.activeConversationId&&(this.activeConversationRevision=null,this.historyInternals.setStoredConversationRevision?.(null))}async awaitHistorySendable(){await this.awaitHistorySettled(),await this.completeCredentialReinit(),this.historyRecovery==="new_conversation_required"&&await this.retryRequiredConversation()}static isConversationDeleted(e){return e instanceof it&&e.code==="conversation_deleted"}async dispatchWithDeletedRecovery(e,n,o,r,s){this.recordDispatchedProjections(e);try{await this.client.dispatch({messages:e,signal:n.signal,assistantMessageId:o,composerOptions:s?.composerOptions,interrupt:s?.interrupt},this.handleEvent);return}catch(a){if(!t.isConversationDeleted(a))throw a;let l=await this.recoverFromDeletedConversation(r);if(!l)throw a;this.recordDispatchedProjections([l]),await this.client.dispatch({messages:[l],signal:n.signal,assistantMessageId:o,composerOptions:s?.composerOptions},this.handleEvent)}}async recoverFromDeletedConversation(e){let n=this.messages.find(r=>r.id===e);if(!n)return null;let o={...n};this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.suppressWelcomeInjection=!0;try{let r=this.historyProvider;if(r){let s=await r.prepareStartNew({context:this.historyContext()});await this.installFreshConversation(s)}else{this.client.clearClientSession();let s=await this.client.initSession();this.bindActivatedSession(s)}}catch{return this.historySendBlocked=!0,this.historyRecovery="new_conversation_required",this.emitHistoryState(),this.notifyHistory("new_conversation_required","That conversation was deleted. Start a new conversation to continue."),null}finally{this.suppressWelcomeInjection=!1}return this.appendMessage(o),this.setStreaming(!0),this.notifyHistory("conversation_deleted_recovered","That conversation was deleted. Started a new conversation."),this.messages.find(r=>r.id===o.id)??o}updateConfig(e){let n=this.config.features?.artifacts?.display,o={...this.config,...e},r=Tw(this.config,o),s=OI(this.config,o);this.config=o,r&&(this.cleanupVoice(),o.voiceRecognition?.enabled===!0&&so(o.voiceRecognition.provider)&&this.setupVoice());let a=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!s){this.client.updateConfig(o),a&&this.refreshArtifactReferenceBlocks();return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let l=this.client.getSSEEventCallback();this.client=new Xl(this.config,this.historyInternals),a&&this.refreshArtifactReferenceBlocks(),this.wireDefaultWebMcpConfirm(),l&&this.client.setSSEEventCallback(l)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:n,content:o,llmContent:r,contentParts:s,id:a,createdAt:l,sequence:c,streaming:p=!1,voiceProcessing:u,rawContent:m}=e,h={id:a??(n==="user"?Dp():n==="assistant"?Ta():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:l??new Date().toISOString(),sequence:c??this.nextSequence(),streaming:p,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...u!==void 0&&{voiceProcessing:u},...m!==void 0&&{rawContent:m}};return this.upsertMessage(h),h}injectAssistantMessage(e){return this.injectMessage({...e,role:"assistant"})}injectUserMessage(e){return this.injectMessage({...e,role:"user"})}injectSystemMessage(e){return this.injectMessage({...e,role:"system"})}injectMessageBatch(e){let n=[];for(let o of e){let{role:r,content:s,llmContent:a,contentParts:l,id:c,createdAt:p,sequence:u,streaming:m=!1,voiceProcessing:g,rawContent:h}=o,C={id:c??(r==="user"?Dp():r==="assistant"?Ta():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:s,createdAt:p??new Date().toISOString(),sequence:u??this.nextSequence(),streaming:m,...a!==void 0&&{llmContent:a},...l!==void 0&&{contentParts:l},...g!==void 0&&{voiceProcessing:g},...h!==void 0&&{rawContent:h}};n.push(C)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(e){let{component:n,props:o={},text:r="",llmContent:s,id:a,createdAt:l,sequence:c}=e,p={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(p),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...l!==void 0&&{createdAt:l},...c!==void 0&&{sequence:c}})}async applyMentionBundle(e,n,o){let r;try{r=await o()}catch{return}let s=r.blocks.join(`
|
|
1151
|
+
_Details: ${n.message}_`:o}var ah=t=>({isError:!0,content:[{type:"text",text:t}]}),eH=(t,e="WebMCP tool execution failed.")=>t instanceof Error&&t.message?t.message:typeof t=="string"&&t?t:e,bS=t=>Sa(t)||t===As,Jp=class t{constructor(e={},n,o={}){this.config=e;this.callbacks=n;this.historyInternals=o;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.resumable=null;this.activeAssistantMessageId=null;this.reconnecting=!1;this.reconnectController=null;this.reconnectControllerPromise=null;this.executionStateTimer=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceSetupPromise=null;this.voiceSetupGeneration=0;this.voiceLevel=0;this.voiceActive=!1;this.voiceStatus="disconnected";this.activeConversationId=null;this.activeConversationRevision=null;this.historyNextMessageCursor=null;this.historyOpenEpoch=0;this.suppressWelcomeInjection=!1;this.historyRecovery=null;this.historySendBlocked=!1;this.historyGate=null;this.olderPageRequests=new Map;this.projectionFinalizationPromise=null;this.acknowledgedProjections=new Map;this.pendingProjections=null;this.bootConversationRevision=null;this.bootRevisionCaptured=!1;this.visitorStoreUnsubscribe=null;this.subscribedVisitorStore=null;this.credentialReinitPending=!1;this.credentialReinitPromise=null;this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.voiceTurns=new tc;this.voiceDisconnectPromise=Promise.resolve();this.ttsSpokenMessageIds=new Set;this.readAloud=new Yp(()=>this.createSpeechEngine());this.handleEvent=e=>{if(e.type==="message"){this.upsertMessage(e.message),e.message.role==="assistant"&&!e.message.variant&&e.message.streaming&&(this.activeAssistantMessageId=e.message.id);let n=e.message.toolCall,o=!!n?.name&&(Sa(n.name)||n.name===As&&Ms(this.config).enabled);e.message.agentMetadata?.awaitingLocalTool===!0&&o&&this.enqueueWebMcpAwait(e.message),e.message.agentMetadata?.executionId&&(this.agentExecution?e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration):this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:"",agentName:e.message.agentMetadata.agentName??"",status:"running",currentIteration:e.message.agentMetadata.iteration??0,maxTurns:0})}else if(e.type==="cursor")this.trackCursor(e.id);else if(e.type==="status"){if(e.status==="idle"&&!e.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(e.status),e.status==="connecting")this.setStreaming(!0);else if(e.status==="idle"||e.status==="error"){this.isAwaitPending()||this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null,this.invalidateConversationRevision(),this.scheduleProjectionFinalization());let n=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(e.status==="error"?this.agentExecution.status="error":n||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else e.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.agentExecution?.status==="running"&&(this.agentExecution.status="error"),this.callbacks.onError?.(e.error)):(e.type==="artifact_start"||e.type==="artifact_delta"||e.type==="artifact_update"||e.type==="artifact_complete")&&this.applyArtifactStreamEvent(e)};this.historyInternals=this.composeHistoryInternals(o),this.messages=[...e.initialMessages??[]].map(r=>({...r,sequence:r.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new Xl(e,this.historyInternals),this.syncVisitorStoreSubscription(),this.wireDefaultWebMcpConfirm();for(let r of e.initialArtifacts??[])this.artifacts.set(r.id,{...r,status:"complete"});e.initialSelectedArtifactId!=null&&(this.selectedArtifactId=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts(),this.prefetchVoiceRuntime()}prefetchVoiceRuntime(){this.config.voiceRecognition?.provider&&oh().catch(()=>{})}prefetchRuntypeTts(){let e=this.config.textToSpeech;if(e?.provider!=="runtype"||e.createEngine)return;let n=e.host??this.config.apiUrl,o=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!n||!o||!this.config.clientToken||sh().catch(()=>{})}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return Dw(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceLevel(){return this.voiceProvider?.onLevel?this.voiceLevel:null}getVoiceInterruptionMode(){return this.voiceProvider?.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){this.voiceProvider?.stopPlayback&&(this.voiceTurns.cancel(),this.voiceProvider.stopPlayback())}isBargeInActive(){return this.voiceProvider?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.voiceProvider?.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){let e=this.config.textToSpeech;if(e?.createEngine)return e.createEngine();let n=ec.isSupported()?new ec({pickVoice:e?.pickVoice}):null;if(e?.provider==="runtype"){let o=e.host??this.config.apiUrl,r=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,s=this.config.clientToken,a=e.browserFallback!==!1;if(o&&r&&s)return sh().then(({RuntypeSpeechEngine:l,FallbackSpeechEngine:c})=>{let p=new l({host:o,agentId:r,clientToken:s,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return a&&n?new c(p,n,{onFallback:u=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${u.message}`)}):p});if(a&&n)return s&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(e){try{let n=e||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.cleanupVoice();let o=this.voiceDisconnectPromise,r=++this.voiceSetupGeneration;this.voiceSetupPromise=oh().then(async s=>{await o,r===this.voiceSetupGeneration&&this.wireVoiceProvider(s.createVoiceProvider(n))}).catch(s=>{console.error("Failed to setup voice:",s)}).finally(()=>{r===this.voiceSetupGeneration&&(this.voiceSetupPromise=null)})}catch(n){console.error("Failed to setup voice:",n)}}wireVoiceProvider(e){try{this.voiceProvider=e;let n=this.voiceSetupGeneration,o=()=>this.voiceProvider===e&&n===this.voiceSetupGeneration,s=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(a=>{o()&&a.provider!=="runtype"&&a.text&&a.text.trim()&&this.sendMessage(a.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((a,l,c,p)=>{if(o())if(a==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:l,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!c});else{let u=this.injectMessage({role:"user",content:l,streaming:!1,voiceProcessing:!c});this.pendingVoiceUserMessageId=u.id}if(c){this.voiceTurns.start(p?.turnId),this.pendingVoiceUserMessageId=null;let u=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=u.id,this.setStreaming(!0)}}else{if(!this.voiceTurns.accepts(p?.turnId))return;if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:l,createdAt:new Date().toISOString(),streaming:!c,voiceProcessing:!c});else{let u=this.injectMessage({role:"assistant",content:l,streaming:!c,voiceProcessing:!c});this.pendingVoiceAssistantMessageId=u.id}c&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onLevel&&this.voiceProvider.onLevel(a=>{o()&&(this.voiceLevel=Number.isFinite(a)?Math.max(0,Math.min(1,a)):0)}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(a=>{o()&&this.config.voiceRecognition?.onMetrics?.(a)}),this.voiceProvider.onError(a=>{o()&&(console.error("Voice error:",a),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:s,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null))}),this.voiceProvider.onStatusChange(a=>{o()&&(this.voiceStatus=a,this.voiceActive=a==="listening",(a==="listening"||a==="idle"||a==="disconnected")&&this.settlePendingVoiceTurn(a!=="listening"),this.callbacks.onVoiceStatusChanged?.(a))}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}async toggleVoice(){if(!this.voiceProvider&&this.voiceSetupPromise&&await this.voiceSetupPromise,!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(e){console.error("Failed to start voice:",e)}}}prewarmVoice(){if(!Un(this.config.voiceRecognition?.provider)){this.warmClientSession();return}let e=this.voiceSetupGeneration,n=()=>{let o=this.voiceProvider;!o?.prewarm||e!==this.voiceSetupGeneration||this.voiceActive||this.isBargeInActive()||Promise.resolve().then(()=>o.prewarm?.()).catch(()=>{})};if(!this.voiceProvider&&this.voiceSetupPromise){this.voiceSetupPromise.then(n,()=>{});return}n()}cleanupVoice(){let e=this.voiceProvider!==null;if(this.voiceSetupGeneration++,this.voiceSetupPromise=null,this.voiceProvider){let n=this.voiceProvider;this.voiceProvider=null,this.voiceDisconnectPromise=this.disconnectVoice(n)}this.voiceActive=!1,this.voiceStatus="disconnected",this.settlePendingVoiceTurn(!0),this.voiceTurns=new tc,e&&this.callbacks.onVoiceStatusChanged?.("disconnected")}async disconnectVoice(e){try{await e.disconnect()}catch(n){console.error("Failed to disconnect voice:",n)}}settlePendingVoiceTurn(e){let n=e?this.pendingVoiceUserMessageId:null,o=this.pendingVoiceAssistantMessageId;!n&&!o||(o&&this.voiceTurns.cancel(),e&&(this.pendingVoiceUserMessageId=null),this.pendingVoiceAssistantMessageId=null,o&&this.ttsSpokenMessageIds.add(o),this.messages=this.messages.flatMap(r=>r.id!==n&&r.id!==o?[r]:r.id===o&&!r.content.trim()?[]:[{...r,streaming:!1,voiceProcessing:!1}]),this.callbacks.onMessagesChanged([...this.messages]),o&&this.setStreaming(!1))}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let e=this.config.voiceRecognition.provider;switch(e.type){case"runtype":return{type:"runtype",runtype:{agentId:e.runtype?.agentId??this.config.agentId??"",clientToken:e.runtype?.clientToken??this.config.clientToken,host:e.runtype?.host??this.config.apiUrl,voiceId:e.runtype?.voiceId,createPlaybackEngine:e.runtype?.createPlaybackEngine,prewarmMode:e.runtype?.prewarmMode,attachIdleMs:e.runtype?.attachIdleMs}};case"browser":return{type:"browser",browser:{language:e.browser?.language||"en-US",continuous:e.browser?.continuous}};case"custom":return{type:"custom",custom:e.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;this.config.features?.history?.enabled&&(await this.historyInternals.historyBootstrapReady,this.bootConversationRevision=this.historyInternals.getStoredConversationRevision?.()??null,this.bootRevisionCaptured=!0);try{let e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return this.callbacks.onError?.(e instanceof Error?e:new Error(String(e))),null}}warmClientSession(){let e=!this.messages.length;this.client.warmSession().then(n=>{n&&this.client.getClientSession()===n&&this.setClientSession(n,e)})}setClientSession(e,n){this.clientSession=e,this.injectWelcomeMessage(e,n)}injectWelcomeMessage(e,n=!this.messages.length){if(this.suppressWelcomeInjection||!e.config.welcomeMessage||!n)return;let o=this.messages[0],r={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:o?.createdAt??new Date().toISOString(),sequence:o?(o.sequence??0)-1:this.nextSequence()};this.appendMessage(r)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,n){return this.client.submitMessageFeedback(e,n)}async submitCSATFeedback(e,n){return this.client.submitCSATFeedback(e,n)}async submitNPSFeedback(e,n){return this.client.submitNPSFeedback(e,n)}setHistoryInternals(e){this.historyInternals=this.composeHistoryInternals(e),this.client.setHistoryInternals(this.historyInternals),this.syncVisitorStoreSubscription()}destroy(){this.cleanupVoice(),this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=null}composeHistoryInternals(e){let n=e.onHistoryContinuityChanged;return{...e,onHistoryContinuityChanged:o=>{this.handleHistoryContinuityChanged(o),n?.(o)}}}get historyProvider(){return this.historyInternals.historyProvider??null}requireHistoryProvider(){let e=this.historyProvider;if(!e)throw new hr("history_unavailable","No conversation history provider is installed");return e}historyContext(e){let n=this.requireHistoryProvider(),o=e??this.config.features?.history?.scope,r=this.config.getIdentityProof?"verified-user":"browser",s=o??(n.capabilities.scopes.includes(r)?r:n.capabilities.scopes[0]??r);if(!n.capabilities.scopes.includes(s))throw new gr("unsupported_scope","This history scope is not supported.");return{scope:s}}getHistoryState(){return{activeConversationId:this.activeConversationId,conversationRevision:this.activeConversationRevision,nextMessageCursor:this.historyNextMessageCursor,recovery:this.historyRecovery,sendBlocked:this.historySendBlocked}}getActiveConversationId(){return this.activeConversationId}emitHistoryState(){this.callbacks.onHistoryStateChanged?.(this.getHistoryState())}notifyHistory(e,n){this.callbacks.onHistoryNotice?.({code:e,message:n})}async awaitHistorySettled(){let e=this.historyGate;e&&await e.catch(()=>{});let n=this.projectionFinalizationPromise;n&&await n.catch(()=>{})}assertHistoryIdle(){if(this.streaming||this.status==="paused"||this.status==="resuming")throw new hr("conversation_busy","Finish or stop the current turn before switching conversations")}listConversations(e){return this.requireHistoryProvider().list({...e?.cursor?{cursor:e.cursor}:{},...e?.limit!==void 0?{limit:e.limit}:{},...e?.targetId!==void 0?{targetId:e.targetId}:{},context:this.historyContext(e?.scope)})}async openConversation(e,n){let o=this.requireHistoryProvider();this.assertHistoryIdle();let r=this.historyContext(n?.scope);await this.awaitHistorySettled();let s=++this.historyOpenEpoch,a=await o.getPage(e,{context:r});if(s!==this.historyOpenEpoch)throw new hr("superseded","A later selection won");let l=await o.prepareOpen(e,{context:r});if(s!==this.historyOpenEpoch)throw l.discard(),new hr("superseded","A later selection won");this.suppressWelcomeInjection=!0;try{await this.commitActivation(l)}finally{this.suppressWelcomeInjection=!1}this.activeConversationId=l.conversationId||e,this.activeConversationRevision=l.conversationRevision||a.conversationRevision||null,this.historyNextMessageCursor=a.nextCursor,this.historyRecovery=null,this.historySendBlocked=!1,this.resetConversationScopedState();for(let c of a.messages)this.acknowledgedProjections.set(c.id,c.content);return this.persistConversationMetadata(),this.hydrateMessages(a.messages),this.emitHistoryState(),{summary:a.summary,nextMessageCursor:a.nextCursor}}loadOlderMessages(e,n,o){let r=this.requireHistoryProvider(),s=this.historyContext(o?.scope),a=n??this.historyNextMessageCursor;if(!a)return Promise.resolve({messages:[],nextMessageCursor:null});let l=`${e} ${a}`,c=this.olderPageRequests.get(l);if(c)return c;let p=this.fetchOlderPage(r,e,a,s).finally(()=>{this.olderPageRequests.delete(l)});return this.olderPageRequests.set(l,p),p}async fetchOlderPage(e,n,o,r){let s=this.messages[0]?.createdAt,a=await e.getPage(n,{cursor:o,...s?{beforeCreatedAt:s}:{},context:r});if(this.activeConversationId&&this.activeConversationId!==n)return{messages:[],nextMessageCursor:a.nextCursor};let l=Ql(this.messages,a.messages);this.messages=this.sortMessages(l.map(c=>this.ensureSequence(c))),this.historyNextMessageCursor=a.nextCursor;for(let c of a.messages)this.acknowledgedProjections.set(c.id,c.content);return this.historyInternals.setStoredMessageCursor?.(a.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.emitHistoryState(),{messages:a.messages,nextMessageCursor:a.nextCursor}}async startNewConversation(e){let n=this.requireHistoryProvider(),o=this.historyContext(e?.scope);await this.awaitHistorySettled();let r=++this.historyOpenEpoch,s=await n.prepareStartNew({context:o});if(r!==this.historyOpenEpoch)throw s.discard(),new hr("superseded","A later action won");await this.installFreshConversation(s)}async installFreshConversation(e){this.discardConversationState(),await this.commitActivation(e),this.activeConversationId=e.conversationId||null,this.activeConversationRevision=e.conversationRevision||null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.historySendBlocked=!1,this.persistConversationMetadata(),this.emitHistoryState()}async deleteConversation(e,n){let o=this.requireHistoryProvider(),r=this.historyContext(n?.scope);await this.awaitHistorySettled(),await o.delete(e,{context:r}),e===this.activeConversationId&&await this.recoverFromDestroyedConversation(r)}async updateConversation(e,n,o){let r=this.requireHistoryProvider();if(!r.update)throw new hr("history_unavailable","This history provider cannot update conversations");let s=this.historyContext(o?.scope);return await this.awaitHistorySettled(),r.update(e,n,{context:s})}canUpdateConversations(){return typeof this.historyProvider?.update=="function"}async clearConversationHistory(e){let n=this.requireHistoryProvider(),o=this.historyContext(e?.scope);await this.awaitHistorySettled();let r=await n.deleteAll({...e?.targetId!==void 0?{targetId:e.targetId}:{},context:o});return await this.recoverFromDestroyedConversation(o),r}async resetHistoryDevice(){let e=this.requireHistoryProvider();if(!e.resetDevice)throw new hr("history_unavailable","This history provider cannot reset the device");this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null;try{return await e.resetDevice()}finally{this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.historySendBlocked=!1,this.emitHistoryState()}}async recoverFromDestroyedConversation(e){this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historySendBlocked=!0,this.historyRecovery=null,this.emitHistoryState(),await this.prepareReplacementConversation(e)}async prepareReplacementConversation(e){let n=this.historyProvider;if(!n){this.historySendBlocked=!1,this.emitHistoryState();return}try{let o=await n.prepareStartNew({context:e});await this.installFreshConversation(o)}catch{this.historySendBlocked=!0,this.historyRecovery="new_conversation_required",this.emitHistoryState(),this.notifyHistory("new_conversation_required","That conversation was deleted. Start a new conversation to continue.")}}async retryRequiredConversation(){if(!(this.historyRecovery!=="new_conversation_required"||!this.historyProvider)&&(this.historyRecovery=null,await this.prepareReplacementConversation(this.historyContext()),this.historyRecovery==="new_conversation_required"))throw new hr("new_conversation_required","A new conversation is required before sending")}async commitActivation(e){await e.commit();let n=this.client.getClientSession();n&&n.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(n)}bindActivatedSession(e){this.clientSession=e,this.config.setStoredSessionId?.(e.sessionId),e.conversationId&&(this.activeConversationId=e.conversationId,this.activeConversationRevision=e.conversationRevision??null,this.config.setStoredConversationId?.(e.conversationId),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),this.suppressWelcomeInjection||this.injectWelcomeMessage(e)}persistConversationMetadata(){this.activeConversationId?this.config.setStoredConversationId?.(this.activeConversationId):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.activeConversationRevision),this.historyInternals.setStoredMessageCursor?.(this.historyNextMessageCursor)}resetConversationScopedState(){this.historyInternals.setStoredResumableHandle?.(null),this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.acknowledgedProjections.clear(),this.setPendingProjections(null)}discardConversationState(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.resetConversationScopedState(),this.olderPageRequests.clear(),this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}handleHistoryContinuityChanged(e){this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.historySendBlocked=!0,this.discardConversationState(),this.activeConversationId=e.conversationId,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.emitHistoryState(),this.notifyHistory("history_continuity_reset","This browser was reconnected to a different conversation, so the previous messages were cleared."),this.historyGate=Promise.resolve().then(()=>{this.historySendBlocked=!1,this.historyGate=null,this.emitHistoryState()})}syncVisitorStoreSubscription(){let e=this.historyInternals.visitorStore??null;e!==this.subscribedVisitorStore&&(this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=e,e&&(this.visitorStoreUnsubscribe=e.subscribe(n=>this.handleExternalCredentialChange(n))))}handleExternalCredentialChange(e){if(e.source!=="external"||e.previousToken===null)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.credentialReinitPending=!0,this.credentialReinitPromise=null;let n=this.messages.length>0;n||this.activeConversationId!==null||(this.config.getStoredConversationId?.()??null)!==null?this.discardConversationState():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.olderPageRequests.clear(),this.setPendingProjections(null)),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.emitHistoryState(),n&&this.notifyHistory("history_continuity_reset","This browser's conversation history was reset in another tab, so the previous messages were cleared.")}completeCredentialReinit(){return this.credentialReinitPending?(this.credentialReinitPromise||(this.credentialReinitPromise=this.runCredentialReinit().finally(()=>{this.credentialReinitPromise=null})),this.credentialReinitPromise):Promise.resolve()}async runCredentialReinit(){if(!this.isClientTokenMode()){this.credentialReinitPending=!1;return}try{this.bindActivatedSession(await this.client.initSession()),this.credentialReinitPending=!1}catch{}}reconcileBootConversation(e){let n=this.historyProvider,o=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.activeConversationId;if(!n||!o)return Promise.resolve();let r=this.historyContext(e?.scope);this.historySendBlocked=!0,this.emitHistoryState();let s=this.runBootReconciliation(n,o,r).finally(()=>{this.historySendBlocked=this.historyRecovery!==null,this.historyGate===s&&(this.historyGate=null),this.emitHistoryState()});return this.historyGate=s,s}async runBootReconciliation(e,n,o){this.activeConversationId=n;let r=this.clientSession?.conversationRevision??this.activeConversationRevision??null,s=this.bootRevisionCaptured?this.bootConversationRevision:this.historyInternals.getStoredConversationRevision?.()??null;if(this.bootRevisionCaptured=!1,this.historyNextMessageCursor=this.historyInternals.getStoredMessageCursor?.()??this.historyNextMessageCursor,await this.replayPendingProjections(),r&&s&&r===s){this.activeConversationRevision=r;return}let a=await e.getPage(n,{context:o}),l=new Set(a.messages.map(m=>m.id)),c=this.messages.some(m=>l.has(m.id)),p=a.messages[0]?.createdAt,u;if(!c)u=a.messages.map(m=>this.ensureSequence(m));else{let m=this.resumable?this.activeAssistantMessageId:null,g=this.messages.filter(h=>l.has(h.id)||h.id===m?!0:p!==void 0&&h.createdAt<p);u=Ql(g,a.messages).map(h=>this.ensureSequence(h))}this.historyNextMessageCursor=a.nextCursor,this.activeConversationRevision=a.conversationRevision||r||null,this.acknowledgedProjections.clear();for(let m of a.messages)this.acknowledgedProjections.set(m.id,m.content);this.persistConversationMetadata(),this.messages=this.sortMessages(u),this.callbacks.onMessagesChanged([...this.messages])}projectionFinalizationEnabled(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}setPendingProjections(e){this.pendingProjections=e,this.historyInternals.setPendingDisplayProjections?.(e)}readPendingProjections(){return this.historyInternals.getPendingDisplayProjections?.()??this.pendingProjections}recordDispatchedProjections(e){if(this.projectionFinalizationEnabled())for(let n of e){let o=Yl(n);o!==void 0&&this.acknowledgedProjections.set(n.id,o)}}scheduleProjectionFinalization(){if(!this.projectionFinalizationEnabled())return;let e=this.activeConversationId;if(!e)return;let n=[];for(let o of this.messages){if(o.role!=="assistant"||o.streaming)continue;let r=Yl(o);r!==void 0&&this.acknowledgedProjections.get(o.id)!==r&&n.push({id:o.id,displayContent:r})}n.length!==0&&(this.setPendingProjections({conversationId:e,messageIds:n.map(o=>o.id)}),this.enqueueProjectionFinalization(e,n))}enqueueProjectionFinalization(e,n){let r=(this.projectionFinalizationPromise??Promise.resolve()).catch(()=>{}).then(()=>this.finalizeProjections(e,n,!1)).finally(()=>{this.projectionFinalizationPromise===r&&(this.projectionFinalizationPromise=null)});this.projectionFinalizationPromise=r}async finalizeProjections(e,n,o){if(this.activeConversationId!==e)return;let r=n.filter(s=>this.acknowledgedProjections.get(s.id)!==s.displayContent);if(r.length===0){this.clearFinalizedMarker(e,n);return}try{let{conversationRevision:s}=await this.client.finalizeDisplayProjections(e,r);for(let a of r)this.acknowledgedProjections.set(a.id,a.displayContent);this.activeConversationId===e&&s&&(this.activeConversationRevision=s),this.clearFinalizedMarker(e,n)}catch(s){if(!o&&this.isTransientProjectionError(s)){await this.finalizeProjections(e,r,!0);return}if(s instanceof it&&(s.code==="not_found"||s.code==="conversation_deleted")){this.clearFinalizedMarker(e,n);return}this.notifyHistory("projection_finalization_failed","Some message formatting could not be saved for history; it will be retried.")}}isTransientProjectionError(e){return e instanceof it?e.code==="request_failed":e instanceof Error}clearFinalizedMarker(e,n){let o=this.readPendingProjections();if(!o||o.conversationId!==e)return;let r=new Set(n.map(a=>a.id)),s=o.messageIds.filter(a=>!r.has(a));this.setPendingProjections(s.length?{conversationId:e,messageIds:s}:null)}async replayPendingProjections(){if(!this.projectionFinalizationEnabled())return;let e=this.readPendingProjections();if(!e)return;if(this.activeConversationId&&e.conversationId!==this.activeConversationId){this.setPendingProjections(null);return}let n=[];for(let o of e.messageIds){let r=this.messages.find(s=>s.id===o);!r||typeof r.content!="string"||n.push({id:o,displayContent:r.content})}if(n.length===0){this.setPendingProjections(null);return}this.enqueueProjectionFinalization(e.conversationId,n),await this.projectionFinalizationPromise?.catch(()=>{})}invalidateConversationRevision(){this.activeConversationId&&(this.activeConversationRevision=null,this.historyInternals.setStoredConversationRevision?.(null))}async awaitHistorySendable(){await this.awaitHistorySettled(),await this.completeCredentialReinit(),this.historyRecovery==="new_conversation_required"&&await this.retryRequiredConversation()}static isConversationDeleted(e){return e instanceof it&&e.code==="conversation_deleted"}async dispatchWithDeletedRecovery(e,n,o,r,s){this.recordDispatchedProjections(e);try{await this.client.dispatch({messages:e,signal:n.signal,assistantMessageId:o,composerOptions:s?.composerOptions,interrupt:s?.interrupt},this.handleEvent);return}catch(a){if(!t.isConversationDeleted(a))throw a;let l=await this.recoverFromDeletedConversation(r);if(!l)throw a;this.recordDispatchedProjections([l]),await this.client.dispatch({messages:[l],signal:n.signal,assistantMessageId:o,composerOptions:s?.composerOptions},this.handleEvent)}}async recoverFromDeletedConversation(e){let n=this.messages.find(r=>r.id===e);if(!n)return null;let o={...n};this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.suppressWelcomeInjection=!0;try{let r=this.historyProvider;if(r){let s=await r.prepareStartNew({context:this.historyContext()});await this.installFreshConversation(s)}else{this.client.clearClientSession();let s=await this.client.initSession();this.bindActivatedSession(s)}}catch{return this.historySendBlocked=!0,this.historyRecovery="new_conversation_required",this.emitHistoryState(),this.notifyHistory("new_conversation_required","That conversation was deleted. Start a new conversation to continue."),null}finally{this.suppressWelcomeInjection=!1}return this.appendMessage(o),this.setStreaming(!0),this.notifyHistory("conversation_deleted_recovered","That conversation was deleted. Started a new conversation."),this.messages.find(r=>r.id===o.id)??o}updateConfig(e){let n=this.config.features?.artifacts?.display,o={...this.config,...e},r=Bw(this.config,o),s=ZI(this.config,o);this.config=o,r&&(this.cleanupVoice(),o.voiceRecognition?.enabled===!0&&Un(o.voiceRecognition.provider)&&this.setupVoice());let a=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!s){this.client.updateConfig(o),a&&this.refreshArtifactReferenceBlocks();return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let l=this.client.getSSEEventCallback();this.client=new Xl(this.config,this.historyInternals),a&&this.refreshArtifactReferenceBlocks(),this.wireDefaultWebMcpConfirm(),l&&this.client.setSSEEventCallback(l)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:n,content:o,llmContent:r,contentParts:s,id:a,createdAt:l,sequence:c,streaming:p=!1,voiceProcessing:u,rawContent:m}=e,h={id:a??(n==="user"?Dp():n==="assistant"?Ta():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:l??new Date().toISOString(),sequence:c??this.nextSequence(),streaming:p,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...u!==void 0&&{voiceProcessing:u},...m!==void 0&&{rawContent:m}};return this.upsertMessage(h),h}injectAssistantMessage(e){return this.injectMessage({...e,role:"assistant"})}injectUserMessage(e){return this.injectMessage({...e,role:"user"})}injectSystemMessage(e){return this.injectMessage({...e,role:"system"})}injectMessageBatch(e){let n=[];for(let o of e){let{role:r,content:s,llmContent:a,contentParts:l,id:c,createdAt:p,sequence:u,streaming:m=!1,voiceProcessing:g,rawContent:h}=o,C={id:c??(r==="user"?Dp():r==="assistant"?Ta():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:s,createdAt:p??new Date().toISOString(),sequence:u??this.nextSequence(),streaming:m,...a!==void 0&&{llmContent:a},...l!==void 0&&{contentParts:l},...g!==void 0&&{voiceProcessing:g},...h!==void 0&&{rawContent:h}};n.push(C)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(e){let{component:n,props:o={},text:r="",llmContent:s,id:a,createdAt:l,sequence:c}=e,p={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(p),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...l!==void 0&&{createdAt:l},...c!==void 0&&{sequence:c}})}async applyMentionBundle(e,n,o){let r;try{r=await o()}catch{return}let s=r.blocks.join(`
|
|
1152
1152
|
|
|
1153
1153
|
`),a=[s,n].filter(Boolean).join(`
|
|
1154
1154
|
|
|
1155
|
-
`),l=Array.isArray(e.contentParts)&&e.contentParts.length>0,c=r.contentParts.length>0;if(l){let p=[];s&&p.push(fr(s)),p.push(...r.contentParts),p.push(...e.contentParts),e.contentParts=p}else if(c){let p=[];a&&p.push(fr(a)),p.push(...r.contentParts),e.contentParts=p}else s&&(e.llmContent=a);Object.keys(r.context).length>0&&(e.mentionContext=r.context)}async sendMessage(e,n){let o=e.trim(),r=!!n?.replayFields&&(n.replayFields.llmContent!==void 0||n.replayFields.rawContent!==void 0||(n.replayFields.contextMentions?.length??0)>0);if(!o&&(!n?.contentParts||n.contentParts.length===0)&&(!n?.mentions||n.mentions.refs.length===0)&&!r)return;(this.historyGate||this.projectionFinalizationPromise||this.historySendBlocked||this.credentialReinitPending)&&await this.awaitHistorySendable(),this.stopSpeaking(),this.abortController?.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let s=Dp(),a=Ta();this.activeAssistantMessageId=null;let l=n?.contentParts&&Up(n.contentParts)?Ra:"",c={id:s,role:"user",content:o||l,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:n?.viaVoice||!1,...n?.contentParts&&n.contentParts.length>0&&{contentParts:n.contentParts},...n?.mentions&&n.mentions.refs.length>0&&{contextMentions:n.mentions.refs},...n?.contentSegments&&n.contentSegments.length>0&&{contentSegments:n.contentSegments},...n?.composerOptions&&{composerOptions:n.composerOptions},...n?.replayFields??{}};this.appendMessage(c),this.setStreaming(!0);let p=new AbortController;if(this.abortController=p,n?.mentions){let m=this.messages.find(g=>g.id===s)??c;if(await this.applyMentionBundle(m,o,n.mentions.finalize),p.signal.aborted||this.abortController!==p)return;this.callbacks.onMessagesChanged([...this.messages])}if(n?.quote&&!n.replayFields){let m=this.messages.find(h=>h.id===s)??c,g=qx({quote:n.quote,text:m.llmContent??m.content,contentParts:m.contentParts});g.contentParts&&(m.contentParts=g.contentParts),g.llmContent!==void 0&&(m.llmContent=g.llmContent),(g.contentParts||g.llmContent!==void 0)&&(m.quote={...n.quote},this.callbacks.onMessagesChanged([...this.messages]))}let u=[...this.messages];try{await this.dispatchWithDeletedRecovery(u,p,a,s,{composerOptions:n?.composerOptions,interrupt:n?.interrupt})}catch(m){if(this.status==="resuming"||this.reconnecting)return;let g=m instanceof Error&&(m.name==="AbortError"||m.message.includes("aborted")||m.message.includes("abort"));if(!g){let h=rh(m,this.config.errorMessage);if(h){let b={id:a,role:"assistant",createdAt:new Date().toISOString(),content:h,sequence:this.nextSequence()};this.appendMessage(b)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,g||(m instanceof Error?this.callbacks.onError?.(m):this.callbacks.onError?.(new Error(String(m))))}}resubmitFrom(e,n){let o=jx(this.messages,e);if(!o)return!1;let r=this.messages[o.start],s=n.replacement,a=s?s.text:r.content,l=s?s.contentParts:r.contentParts;if(!(!!a?.trim()||(l?.length??0)>0||!s&&(r.llmContent?.trim()?.length??0)>0))return!1;let p=s?void 0:{...r.llmContent!==void 0&&{llmContent:r.llmContent},...r.rawContent!==void 0&&{rawContent:r.rawContent},...r.mentionContext&&{mentionContext:r.mentionContext},...r.contextMentions&&{contextMentions:r.contextMentions},...r.quote&&{quote:r.quote}},u=s?this.toComposerOptionsPayload(s.options):r.composerOptions,m=s?s.contentSegments:r.contentSegments,g=s?s.options?.quote:void 0,h=s?s.viaVoice:r.viaVoice;return this.cancel(),this.messages=this.messages.slice(0,o.start),this.sendMessage(a??"",{...l?.length?{contentParts:[...l]}:{},...m?.length?{contentSegments:[...m]}:{},...u?{composerOptions:u}:{},...g?{quote:g}:{},...p&&Object.keys(p).length>0?{replayFields:p}:{},viaVoice:h===!0}),!0}toComposerOptionsPayload(e){if(!e)return;let n={};return e.selectedModelId&&(n.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(n.activeModeIds=[...e.activeModeIds]),Object.keys(n).length>0?n:void 0}async continueConversation(){if(this.streaming)return;(this.historyGate||this.projectionFinalizationPromise||this.historySendBlocked||this.credentialReinitPending)&&await this.awaitHistorySendable(),this.abortController?.abort(),this.teardownReconnect();let e=Ta();this.activeAssistantMessageId=null,this.setStreaming(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:e},this.handleEvent)}catch(r){if(this.status==="resuming"||this.reconnecting)return;let s=r instanceof Error&&(r.name==="AbortError"||r.message.includes("aborted")||r.message.includes("abort"));if(!s){let a=rh(r,this.config.errorMessage);if(a){let l={id:e,role:"assistant",createdAt:new Date().toISOString(),content:a,sequence:this.nextSequence()};this.appendMessage(l)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,s||(r instanceof Error?this.callbacks.onError?.(r):this.callbacks.onError?.(new Error(String(r))))}}async connectStream(e,n){if(this.streaming&&!n?.allowReentry)return;n?.allowReentry||this.abortController?.abort(),n?.preserveAssistantId&&n.assistantMessageId&&(this.activeAssistantMessageId=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,r=!1;for(let s of this.messages)s.streaming&&s.id!==o&&(s.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(e,this.handleEvent,n?.assistantMessageId,n?.seedContent)}catch(s){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.callbacks.onError?.(s instanceof Error?s:new Error(String(s)))}}wireDefaultWebMcpConfirm(){let e=this.config.webmcp;e?.enabled===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(e){try{if(this.config.webmcp?.autoApprove?.(e)===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:e.toolName,toolType:"webmcp",description:e.description??`Allow the assistant to run ${e.toolName}?`,parameters:e.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(r=>{this.webMcpApprovalResolvers.set(o,r)})}resolveWebMcpApproval(e,n){let o=this.webMcpApprovalResolvers.get(e);if(!o)return;this.webMcpApprovalResolvers.delete(e);let r=this.messages.find(s=>s.id===e);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(e,n,o){let r=`approval-${e.id}`,s={...e,status:n,resolvedAt:Date.now()},a=this.messages.find(u=>u.id===r),l={id:r,role:"assistant",content:"",createdAt:a?.createdAt??new Date().toISOString(),...a?.sequence!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(l),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let c=this.config.approval,p=c&&typeof c=="object"?c.onDecision:void 0;try{let u;if(p?u=await p({approvalId:e.id,executionId:e.executionId,agentId:e.agentId,toolName:e.toolName},n,o):u=await this.client.resolveApproval({agentId:e.agentId,executionId:e.executionId,approvalId:e.id},n),u){let m=null;if(u instanceof Response){if(!u.ok){let g=await u.json().catch(()=>null);throw new Error(g?.error??`Approval request failed: ${u.status}`)}m=u.body}else u instanceof ReadableStream&&(m=u);m?await this.connectStream(m,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${e.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(u){let m=u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||this.callbacks.onError?.(u instanceof Error?u:new Error(String(u)))}}persistAskUserQuestionProgress(e,n){let o=this.messages.find(r=>r.id===e.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(e,n){let o=this.messages.find(r=>r.id===e.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(e,n){if(this.messages.find(u=>u.id===e.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=e.agentMetadata?.executionId,s=e.toolCall?.name;if(!r||!s){this.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let u=e.toolCall?.args,m=Array.isArray(u?.questions)?u.questions:[];if(m.length===1){let g=typeof m[0]?.question=="string"?m[0].question:"";g&&(a={[g]:n})}}this.markAskUserQuestionResolved(e,a),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let l=e.toolCall.id,c=e.toolCall?.args,p=Array.isArray(c?.questions)?c.questions:[];if(p.length===0){let u=typeof n=="string"?n:Object.entries(n).map(([m,g])=>`${m}: ${Array.isArray(g)?g.join(", "):g}`).join(" | ");this.appendMessage({id:`ask-user-answer-${l}`,role:"user",content:u,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let u=a??{};p.forEach((m,g)=>{let h=typeof m?.question=="string"?m.question:"";if(!h)return;let b=u[h],C=Array.isArray(b)?b.join(", "):typeof b=="string"?b:"";this.appendMessage({id:`ask-user-q-${l}-${g}`,role:"assistant",content:h,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${l}-${g}`,role:"user",content:C||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let u=await this.client.resumeFlow(r,{[s]:n},{after:this.resumable?.executionId===r?this.resumable.lastEventId:void 0});if(!u.ok){let m=await u.json().catch(()=>null);throw new Error(m?.error??`Resume failed: ${u.status}`)}u.body?await this.connectStream(u.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(u){let m=u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||this.callbacks.onError?.(u instanceof Error?u:new Error(String(u)))}}enqueueWebMcpAwait(e){let n=e.agentMetadata?.executionId,o=e.toolCall?.id;if(!n||!o){let s=this.webMcpEpoch;queueMicrotask(()=>{s===this.webMcpEpoch&&this.resolveWebMcpToolCall(e)});return}let r=this.webMcpAwaitBatches.get(n);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,r)),!r.seen.has(o)&&(r.seen.add(o),r.snapshots.push(e))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let e=this.webMcpEpoch;queueMicrotask(()=>{if(e===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(e){let n=this.webMcpAwaitBatches.get(e);if(!n)return;this.webMcpAwaitBatches.delete(e);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(e,o)}resolveWebMcpToolStartedAt(e){let o=[this.messages.find(r=>r.id===e.id)?.toolCall?.startedAt,e.toolCall?.startedAt];for(let r of o)if(typeof r=="number"&&Number.isFinite(r))return r;return Date.now()}isSuggestRepliesAlreadyResolved(e){return e.toolCall?.name!==As?!1:(this.messages.find(o=>o.id===e.id)??e).agentMetadata?.suggestRepliesResolved===!0}markWebMcpToolRunning(e){let n=this.resolveWebMcpToolStartedAt(e);return this.upsertMessage({...e,streaming:!0,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1},toolCall:e.toolCall?{...e.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:e.toolCall}),n}markWebMcpToolComplete(e,n,o,r=Date.now(),s){this.messages.some(a=>a.id===e.id)&&this.upsertMessage({...e,streaming:!1,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1,...s},toolCall:e.toolCall?{...e.toolCall,status:"complete",result:n,startedAt:o,completedAt:r,duration:void 0,durationMs:Math.max(0,r-o)}:e.toolCall})}async resolveWebMcpToolCallBatch(e,n){let o=[],r=new AbortController;this.webMcpResolveControllers.add(r),this.setStreaming(!0);let s=async c=>{let p=c.toolCall?.name,u=c.toolCall?.id;if(!p||!u)return null;let m=`${e}:${u}`;if(this.webMcpInflightKeys.has(m)||this.webMcpResolvedKeys.has(m)||this.isSuggestRepliesAlreadyResolved(c))return null;this.webMcpInflightKeys.add(m),o.push(m);let g=this.markWebMcpToolRunning(c),h=c.agentMetadata?.webMcpToolCallId??p;if(p===As)return{dedupeKey:m,resumeKey:h,output:fx(),toolMessage:c,startedAt:g,completedAt:Date.now()};let b=this.client.executeWebMcpToolCall(p,c.toolCall?.args,r.signal),C;if(!b)C={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{C=await b}catch(M){let E=M instanceof Error&&(M.name==="AbortError"||M.message.includes("aborted")||M.message.includes("abort"));return E||this.callbacks.onError?.(M instanceof Error?M:new Error(String(M))),this.markWebMcpToolComplete(c,sh(E?"Aborted by cancel()":_I(M)),g),this.webMcpInflightKeys.delete(m),null}return r.signal.aborted?(this.markWebMcpToolComplete(c,sh("Aborted by cancel()"),g),this.webMcpInflightKeys.delete(m),null):{dedupeKey:m,resumeKey:h,output:C,toolMessage:c,startedAt:g,completedAt:Date.now()}},a;if(this.config.webmcp?.execution==="sequential"){a=[];for(let c of n)a.push(await s(c))}else a=await Promise.all(n.map(s));let l=[];try{if(l=a.filter(m=>m!==null),l.length===0)return;let c={};for(let m of l)c[m.resumeKey]=m.output;let p=await this.client.resumeFlow(e,c,{signal:r.signal,after:this.resumable?.executionId===e?this.resumable.lastEventId:void 0});if(!p.ok){let m=await p.json().catch(()=>null);throw new Error(m?.error??`Resume failed: ${p.status}`)}let u=l[0].dedupeKey;for(let m of l){this.webMcpResolvedKeys.add(m.dedupeKey);let g=m.toolMessage.toolCall?.name,h=m.toolMessage.agentMetadata?.webMcpToolCallId;this.markWebMcpToolComplete(m.toolMessage,m.output,m.startedAt,m.completedAt,{...g===As?{suggestRepliesResolved:!0}:{},...g&&h?{clientToolAnswer:{toolCallId:h,toolName:g,args:m.toolMessage.toolCall?.args,result:m.output,batch:u}}:{}})}p.body&&await this.connectStream(p.body,{allowReentry:!0})}catch(c){if(!(c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"))))this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)));else for(let u of l)this.markWebMcpToolComplete(u.toolMessage,sh("Aborted by cancel()"),u.startedAt)}finally{for(let c of o)this.webMcpInflightKeys.delete(c);this.webMcpResolveControllers.delete(r),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(e){let n=e.agentMetadata?.executionId,o=e.toolCall?.name,r=e.toolCall?.id;if(!n){this.callbacks.onError?.(new Error("WebMCP await missing executionId: dispatch left paused."));return}if(!o)return;if(!r){let a=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(a)||this.webMcpResolvedKeys.has(a))return;this.webMcpInflightKeys.add(a);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(a)}catch(l){this.callbacks.onError?.(l instanceof Error?l:new Error(String(l)))}finally{this.webMcpInflightKeys.delete(a)}return}let s=`${n}:${r}`;if(!(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(e)))return this.resolveWebMcpToolCallBatch(n,[e])}async resumeWithToolOutput(e,n,o,r){let s=await this.client.resumeFlow(e,{[n]:o},{signal:r?.signal,after:this.resumable?.executionId===e?this.resumable.lastEventId:void 0});if(!s.ok){let a=await s.json().catch(()=>null);throw new Error(a?.error??`Resume failed: ${s.status}`)}r?.onHttpOk?.(),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let e of this.webMcpResolveControllers)e.abort();this.webMcpResolveControllers.clear();for(let e of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(e,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(e){this.selectedArtifactId=e,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(e){let n=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=e.artifactType==="markdown"?{id:n,artifactType:"markdown",title:e.title,status:"complete",markdown:e.content,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{}}:{id:n,artifactType:"component",title:e.title,status:"complete",component:e.component,props:e.props??{},...e.presentation?{presentation:e.presentation}:{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),e.transcript!==!1&&this.injectArtifactRefBlock(o),o}injectArtifactRefBlock(e){let n=`artifact-ref-${e.id}`,o=Cs(this.config.features?.artifacts,e),r=$l(o,{artifactId:e.id,title:e.title,artifactType:e.artifactType,status:"complete",...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{},...e.component?{component:e.component}:{},...e.props?{componentProps:e.props}:{},...e.markdown!==void 0?{markdown:e.markdown}:{}}),s=this.messages.find(a=>a.id===n);if(s){s.rawContent=r,s.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:n,content:"",rawContent:r})}refreshArtifactReferenceBlocks(){let e=!1;for(let n of this.artifacts.values()){let o=this.messages.find(a=>a.id===`artifact-ref-${n.id}`);if(!o)continue;let r=Cs(this.config.features?.artifacts,n),s=$l(r,{artifactId:n.id,title:n.title,artifactType:n.artifactType,status:n.status,...n.file?{file:n.file}:{},...n.presentation?{presentation:n.presentation}:{},...n.component?{component:n.component}:{},...n.props?{componentProps:n.props}:{},...n.markdown!==void 0?{markdown:n.markdown}:{}});o.rawContent!==s&&(o.rawContent=s,o.streaming=n.status==="streaming",e=!0)}e&&this.callbacks.onMessagesChanged([...this.messages])}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(e){switch(e.type){case"artifact_start":{e.artifactType==="markdown"?this.artifacts.set(e.id,{id:e.id,artifactType:"markdown",title:e.title,status:"streaming",markdown:"",...e.file?{file:e.file}:{}}):this.artifacts.set(e.id,{id:e.id,artifactType:"component",title:e.title,status:"streaming",component:e.component??"",props:{}}),this.selectedArtifactId=e.id;break}case"artifact_delta":{let n=this.artifacts.get(e.id);n?.artifactType==="markdown"&&(n.markdown=(n.markdown??"")+e.artDelta);break}case"artifact_update":{let n=this.artifacts.get(e.id);n?.artifactType==="component"&&(n.props={...n.props,...e.props},e.component&&(n.component=e.component));break}case"artifact_complete":{let n=this.artifacts.get(e.id);n&&(n.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(e){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(e.map(n=>({...n,streaming:!1,sequence:n.sequence??this.nextSequence()}))),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(e,n=null){this.artifacts.clear();for(let o of e)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}trackCursor(e){let n=this.agentExecution?.executionId;if(!n||!this.activeAssistantMessageId||this.agentExecution?.status!=="running")return;let o=this.resumable===null;this.resumable={executionId:n,lastEventId:e,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(o)}isDurableDrop(){return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(e=>e.agentMetadata?.awaitingLocalTool===!0&&e.agentMetadata?.askUserQuestionAnswered!==!0||e.variant==="approval"&&e.approval?.status==="pending")}beginReconnect(){this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.resumable}),this.setStreaming(!0),this.setStatus("resuming"),this.loadReconnectController().then(e=>{this.reconnecting&&this.resumable&&e.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=aS().then(({createReconnectController:e})=>{let n=e(this.buildReconnectHost());return this.reconnectController=n,n}),this.reconnectControllerPromise.catch(()=>{this.reconnectControllerPromise=null})),this.reconnectControllerPromise)}buildReconnectHost(){let e=this;return{get config(){return e.config},getResumable:()=>e.resumable,clearResumable:()=>e.clearResumable(),getStatus:()=>e.status,setStatus:n=>e.setStatus(n),setStreaming:n=>e.setStreaming(n),setReconnecting:n=>{e.reconnecting=n},setAbortController:n=>{e.abortController=n},getMessages:()=>e.messages,notifyMessagesChanged:()=>e.callbacks.onMessagesChanged([...e.messages]),resumeConnect:(n,o,r)=>e.connectStream(n,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:n=>e.appendMessage(n),nextSequence:()=>e.nextSequence(),emitReconnect:n=>e.callbacks.onReconnect?.(n),buildErrorContent:n=>rh(new Error(n),e.config.errorMessage),onError:n=>e.callbacks.onError?.(n)}}reconnectNow(){if(this.reconnecting){this.reconnectController?.wake();return}this.beginReconnect()}resumeFromHandle(e){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let n=this.reopenTrailingAssistant();n||(n=Ta(),this.appendMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=n,this.agentExecution||(this.agentExecution={executionId:e.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:e.executionId,lastEventId:e.after,assistantMessageId:n,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let e=this.messages.length-1;e>=0;e--){let n=this.messages[e];if(n.role==="assistant"&&!n.variant)return n.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),n.id;if(n.role==="user")break}return null}teardownReconnect(){this.reconnecting=!1,this.reconnectController?.teardown(),this.clearResumable()}clearResumable(){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let e=this.resumable!==null;this.resumable=null,e&&this.config.onExecutionState?.(null)}notifyExecutionState(e){let n=this.config.onExecutionState;if(n){if(e){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),n(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{this.executionStateTimer=null,this.config.onExecutionState?.(this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}setStreaming(e){if(this.streaming===e)return;let n=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),n&&!e&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let e=this.config.textToSpeech;if(!e?.enabled||!(!e.provider||e.provider==="browser"||e.provider==="runtype"&&e.browserFallback))return;let o=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let r=nh(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:e.voice,rate:e.rate,pitch:e.pitch})}static pickBestVoice(e){return Qg(e)}toggleReadAloud(e){let n=this.messages.find(s=>s.id===e);if(!n||n.role!=="assistant")return;let o=nh(n.content||"");if(!o.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(e,{text:o,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(e){return this.readAloud.stateFor(e)}onReadAloudChange(e){return this.readAloud.onChange(e)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(e){let n=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let n=this.ensureSequence(e),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((r,s)=>{if(s!==o)return r;let a={...r,...n};r.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(a.agentMetadata={...a.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1});let l=r.agentMetadata?.clientToolAnswer;if(l&&a.agentMetadata&&!a.agentMetadata.clientToolAnswer&&(a.agentMetadata={...a.agentMetadata,clientToolAnswer:l}),r.approval&&n.approval&&r.approval.id===n.approval.id){let m=r.approval,g=n.approval;a.approval={...m,...g,executionId:g.executionId||m.executionId,toolName:g.toolName||m.toolName,description:g.description||m.description,toolType:g.toolType??m.toolType,reason:g.reason??m.reason,parameters:g.parameters??m.parameters}}let c=n.toolCall?.name,p=n.agentMetadata?.executionId,u=n.toolCall?.id;if(c&&lS(c)&&p&&u&&n.agentMetadata?.awaitingLocalTool===!0){let m=`${p}:${u}`,g=this.webMcpInflightKeys.has(m),h=this.webMcpResolvedKeys.has(m),b=r.toolCall?.name,C=r.agentMetadata?.executionId===p&&r.toolCall?.id===u&&b!==void 0&&lS(b)&&r.toolCall?.status==="complete";(g||h||C)&&(a.agentMetadata={...a.agentMetadata??{},awaitingLocalTool:!1},a.toolCall=r.toolCall,a.streaming=r.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(e){return[...e].sort((n,o)=>{let r=new Date(n.createdAt).getTime(),s=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let a=n.sequence??0,l=o.sequence??0;return a!==l?a-l:n.id.localeCompare(o.id)})}};je();var Bo=require("lucide");zn();Zt();var NI={add:t=>Px(t)},FI=t=>Number.isFinite(t)?Math.min(1,Math.max(0,t)):0,Zp={allowedTypes:Ur,maxFileSize:10*1024*1024,maxFiles:4};function VI(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function $I(t){return t==="application/pdf"?Bo.FileText:t.startsWith("text/")?Bo.FileText:t.includes("word")?Bo.FileText:t.includes("excel")||t.includes("spreadsheet")?Bo.FileSpreadsheet:t==="application/json"?Bo.FileCode:Bo.File}var oc=class t{constructor(e={}){this.attachments=[];this.previewsContainer=null;this.pendingAdds=new Map;this.destroyed=!1;this.config={allowedTypes:e.allowedTypes??Zp.allowedTypes,maxFileSize:e.maxFileSize??Zp.maxFileSize,maxFiles:e.maxFiles??Zp.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange,adapter:e.adapter}}hasCustomAdapter(){return typeof this.config.adapter?.add=="function"}adapter(){return this.hasCustomAdapter()?this.config.adapter:NI}setPreviewsContainer(e){this.previewsContainer=e}remountPreviews(e){if(this.previewsContainer=e,e){e.innerHTML="";for(let n of this.attachments)this.renderPreview(n)}this.updatePreviewsVisibility()}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:Zp.allowedTypes),e.maxFileSize!==void 0&&(this.config.maxFileSize=e.maxFileSize),e.maxFiles!==void 0&&(this.config.maxFiles=e.maxFiles),e.onFileRejected!==void 0&&(this.config.onFileRejected=e.onFileRejected),e.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=e.onAttachmentsChange),e.adapter!==void 0&&(this.config.adapter=e.adapter)}isReady(){return this.attachments.every(e=>e.status==="ready")}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(e=>e.contentPart).filter(e=>e!==null)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(e){!e||e.length===0||await this.handleFiles(Array.from(e))}async handleFiles(e){if(!e.length||this.destroyed)return;let n=[];for(let o of e){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(o,"count");continue}let r=Lx(o,this.config.allowedTypes,this.config.maxFileSize);if(!r.valid){let a=r.error?.includes("type")?"type":"size";this.config.onFileRejected?.(o,a);continue}let s={id:VI(),file:o,previewUrl:qp(o)?URL.createObjectURL(o):null,contentPart:null,status:this.hasCustomAdapter()?"uploading":"processing",progress:this.hasCustomAdapter()?0:void 0};this.attachments.push(s),this.renderPreview(s),n.push(s)}this.updatePreviewsVisibility(),this.notify(),await Promise.all(n.map(o=>this.runAdd(o)))}async runAdd(e){let n=new AbortController;this.pendingAdds.set(e.id,n);let o=()=>this.destroyed||n.signal.aborted||this.pendingAdds.get(e.id)!==n||!this.attachments.includes(e);try{let r=await this.adapter().add(e.file,{signal:n.signal,onProgress:s=>{o()||e.status!=="uploading"||(e.progress=FI(s),this.updatePreview(e),this.notify())}});if(o())return;e.contentPart=r,e.status="ready",e.progress=void 0,e.error=void 0}catch(r){if(o())return;e.status="error",e.progress=void 0,e.error=r instanceof Error?r.message:String(r??"Upload failed")}finally{this.pendingAdds.get(e.id)===n&&this.pendingAdds.delete(e.id)}this.updatePreview(e),this.notify()}retryAttachment(e){let n=this.attachments.find(o=>o.id===e);!n||n.status!=="error"||this.destroyed||(n.status=this.hasCustomAdapter()?"uploading":"processing",n.progress=this.hasCustomAdapter()?0:void 0,n.error=void 0,this.updatePreview(n),this.notify(),this.runAdd(n))}abortAdd(e){let n=this.pendingAdds.get(e);n&&(this.pendingAdds.delete(e),n.abort())}removeAttachment(e){let n=this.attachments.findIndex(s=>s.id===e);if(n===-1)return;let o=this.attachments[n];this.abortAdd(e),o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let r=this.previewsContainer?.querySelector(`[data-attachment-id="${e}"]`);r&&r.remove(),o.status==="ready"&&o.contentPart&&this.releasePart(o.contentPart),this.updatePreviewsVisibility(),this.notify()}releasePart(e){let n=this.config.adapter?.remove;if(n)try{let o=n(e,{signal:new AbortController().signal});o&&typeof o.catch=="function"&&o.catch(r=>{console.error("[AttachmentManager] adapter.remove failed:",r)})}catch(o){console.error("[AttachmentManager] adapter.remove failed:",o)}}clearAttachments(){for(let e of this.attachments)this.abortAdd(e.id),e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.pendingAdds.clear(),this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),this.notify()}destroy(){if(!this.destroyed){this.destroyed=!0;for(let e of this.pendingAdds.values())e.abort();this.pendingAdds.clear();for(let e of this.attachments)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.previewsContainer=null}}notify(){this.destroyed||this.config.onAttachmentsChange?.(this.getAttachments())}renderPreview(e){if(!this.previewsContainer)return;let n=qp(e.file),o=v("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",e.id),o.style.width="48px",o.style.height="48px",n&&e.previewUrl){let u=v("img");u.src=e.previewUrl,u.alt=e.file.name,u.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",u.style.width="48px",u.style.height="48px",u.style.objectFit="cover",u.style.borderRadius="8px",o.appendChild(u)}else{let u=v("div");u.style.width="48px",u.style.height="48px",u.style.borderRadius="8px",u.style.backgroundColor="var(--persona-container, #f3f4f6)",u.style.border="1px solid var(--persona-border, #e5e7eb)",u.style.display="flex",u.style.flexDirection="column",u.style.alignItems="center",u.style.justifyContent="center",u.style.gap="2px",u.style.overflow="hidden";let m=$I(e.file.type),g=Ge(m,20,"var(--persona-muted, #6b7280)",1.5);g&&u.appendChild(g);let h=v("span");h.textContent=Ix(e.file.type,e.file.name),h.style.fontSize="8px",h.style.fontWeight="600",h.style.color="var(--persona-muted, #6b7280)",h.style.textTransform="uppercase",h.style.lineHeight="1",u.appendChild(h),o.appendChild(u)}let r=F("div",{className:"persona-attachment-status",attrs:{"data-persona-attachment-status":""}}),s=v("div","persona-attachment-progress");s.appendChild(v("div","persona-attachment-progress__bar"));let a=F("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),l=ke("rotate-cw",12,"var(--persona-text-inverse, #ffffff)",2);l?a.appendChild(l):a.textContent="\u21BB",a.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),this.retryAttachment(e.id)}),r.append(s,a),o.appendChild(r);let c=v("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");c.type="button",c.setAttribute("aria-label","Remove attachment"),c.style.position="absolute",c.style.top="-4px",c.style.insetInlineEnd="-4px",c.style.width="18px",c.style.height="18px",c.style.borderRadius="50%",c.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",c.style.border="none",c.style.cursor="pointer",c.style.display="flex",c.style.alignItems="center",c.style.justifyContent="center",c.style.padding="0";let p=Ge(Bo.X,10,"var(--persona-text-inverse, #ffffff)",2);p?c.appendChild(p):(c.textContent="\xD7",c.style.color="var(--persona-text-inverse, #ffffff)",c.style.fontSize="14px",c.style.lineHeight="1"),c.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),this.removeAttachment(e.id)}),o.appendChild(c),this.previewsContainer.appendChild(o),this.applyPreviewState(o,e)}updatePreview(e){let n=this.previewsContainer?.querySelector(`[data-attachment-id="${e.id}"]`);n&&this.applyPreviewState(n,e)}applyPreviewState(e,n){e.dataset.status=n.status;let o=n.status!=="ready"&&n.status!=="error";e.setAttribute("aria-busy",o?"true":"false"),e.title=n.status==="error"?`${n.file.name}: ${n.error??"Upload failed"}`:n.file.name;let r=e.querySelector(".persona-attachment-progress__bar");if(r){let s=n.progress;r.style.width=typeof s=="number"?`${Math.round(s*100)}%`:""}}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(e,n){return new t({allowedTypes:e?.allowedTypes,maxFileSize:e?.maxFileSize,maxFiles:e?.maxFiles,onFileRejected:e?.onFileRejected,onAttachmentsChange:n,adapter:e?.adapter})}};var cS=(t,e)=>t.length===e.length&&t.every((n,o)=>n===e[o]),zI=(t,e)=>t.length===e.length&&t.every((n,o)=>{let r=e[o];return n.id===r.id&&n.name===r.name&&n.mimeType===r.mimeType&&n.size===r.size&&n.status===r.status&&n.progress===r.progress&&n.error===r.error});function dS(){let t={text:"",attachments:[],mentionRefs:[],selectedModelId:void 0,activeModeIds:[],quote:void 0,pendingSubmission:void 0,preparing:!1,streaming:!1,inputDisabled:!1,sendDisabled:!1},e=new Set,n=null,o=!1,r=!1,s=()=>t.preparing?"preparing":t.streaming?"streaming":"idle",a=()=>{let u=s();return Object.freeze({text:t.text,attachments:Object.freeze(t.attachments.map(m=>Object.freeze({...m}))),mentionRefs:Object.freeze([...t.mentionRefs]),selectedModelId:t.selectedModelId,activeModeIds:Object.freeze([...t.activeModeIds]),quote:t.quote?Object.freeze({...t.quote}):void 0,pendingSubmission:t.pendingSubmission,phase:u,inputDisabled:t.inputDisabled,sendDisabled:u!=="idle"||t.sendDisabled||t.inputDisabled})},l=()=>(n||(n=a()),n),c=()=>{if(o=!1,r||e.size===0)return;let u=l();for(let m of[...e])try{m(u)}catch(g){typeof console<"u"&&console.error("[AgentWidget] composer state listener failed:",g)}},p=()=>{n=null,!(r||o)&&(o=!0,queueMicrotask(c))};return{getState:l,subscribe:u=>(e.add(u),()=>e.delete(u)),setText:u=>{t.text!==u&&(t.text=u,p())},setAttachments:u=>{zI(t.attachments,u)||(t.attachments=[...u],p())},setMentionRefs:u=>{cS(t.mentionRefs,u)||(t.mentionRefs=[...u],p())},setSelectedModelId:u=>{t.selectedModelId!==u&&(t.selectedModelId=u,p())},setActiveModeIds:u=>{cS(t.activeModeIds,u)||(t.activeModeIds=[...u],p())},setQuote:u=>{let m=t.quote;m?.text===u?.text&&m?.messageId===u?.messageId&&m?.sourceLabel===u?.sourceLabel||(t.quote=u?{...u}:void 0,p())},setPendingSubmission:u=>{t.pendingSubmission!==u&&(t.pendingSubmission=u,p())},setPreparing:u=>{t.preparing!==u&&(t.preparing=u,p())},setStreaming:u=>{t.streaming!==u&&(t.streaming=u,p())},setInputDisabled:u=>{t.inputDisabled!==u&&(t.inputDisabled=u,p())},setSendDisabled:u=>{t.sendDisabled!==u&&(t.sendDisabled=u,p())},flush:()=>{o&&c()},destroy:()=>{r=!0,o=!1,e.clear()}}}je();var io=(t,...e)=>{for(let n of e){let o=t.querySelector(n);if(o)return o}return null},pS=(t,e)=>{let n=v("div",t);return n.setAttribute(e,""),n.setAttribute("data-persona-composer-synthesized",""),n.style.display="contents",n};function uS(t,e={}){let n=io(t,"[data-persona-composer-form]"),o=io(t,"[data-persona-composer-input]");if(!n||!o){let E=`[Persona] composer surface is missing required element(s): ${[!n&&"form",!o&&"input"].filter(Boolean).join(", ")}. Mark them with data-persona-composer-form / data-persona-composer-input.`;if(e.debug&&(n||o))throw new Error(E);return typeof console<"u"&&console.warn(E),null}let r={header:io(t,"[data-persona-composer-header]"),body:io(t,"[data-persona-composer-body]"),actionsStart:io(t,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:io(t,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:io(t,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:io(t,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:io(t,"[data-persona-composer-status]")},s=new Set,a=r.header;a||(s.add("header"),a=pS("persona-widget-composer__header","data-persona-composer-header"),n.parentNode?n.parentNode.insertBefore(a,n):t.appendChild(a));let l=r.body??o.parentElement??n,c=(M,E,T,H,A)=>{if(E)return E;s.add(M);let D=pS(T,H);return A.appendChild(D),D},p=c("actionsStart",r.actionsStart,"persona-widget-composer__left-actions","data-persona-composer-actions-start",n),u=c("actionsEnd",r.actionsEnd,"persona-widget-composer__right-actions","data-persona-composer-actions-end",n),m=c("suggestions",r.suggestions,"persona-widget-composer__suggestions","data-persona-composer-suggestions",t),g=c("status",r.status,"persona-widget-composer__status","data-persona-composer-status",t),h=[],b=(M,E)=>M.target===E.target&&M.type===E.type&&M.handler===E.handler,C=io(t,"[data-persona-composer-attachment-input]",'input[type="file"]')??void 0;return{footer:t,form:n,input:o,header:a,body:l,actionsStart:p,actionsEnd:u,suggestions:m,status:g,attachmentInput:C,attachmentPreviews:io(t,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:io(t,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:io(t,"[data-persona-composer-submit]")??void 0,micButton:io(t,"[data-persona-composer-mic]")??void 0,synthesized:s,found:r,addListener:(M,E,T,H)=>{M.addEventListener(E,T,H),h.push({target:M,type:E,handler:T,options:H})},removeListener:(M,E,T,H)=>{M.removeEventListener(E,T,H),h=h.filter(A=>!b(A,{target:M,type:E,handler:T}))},destroy:()=>{for(let M of h)M.target.removeEventListener(M.type,M.handler,M.options);h=[]}}}je();Zt();ks();var UI=8,qI=8,ih=10,mS=200,fS=300,gS=0,tu=t=>Math.max(0,t);function hS(t){t.delayMs!==void 0&&(mS=tu(t.delayMs)),t.skipDelayMs!==void 0&&(fS=tu(t.skipDelayMs))}var jI=()=>Date.now()<gS,KI=t=>{gS=t>0?Date.now()+t:0},eu=new WeakMap,lh="data-persona-tooltip-suppressed",GI=t=>typeof t.closest=="function"&&t.closest(`[${lh}]`)!==null;function yS(t){eu.get(t)?.hide()}var bS=t=>t.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in t,YI=t=>{let e=t.getRootNode?.();return bS(e)?e:t.ownerDocument.body},ah=(t,e,n)=>Math.min(Math.max(t,e),Math.max(e,n)),QI=[...["background","foreground","hint-fg","radius","font-size","padding","max-width","shadow","arrow-display"].map(t=>`--persona-tooltip-${t}`),"--persona-font-family","--persona-radius-sm"];function In(t){eu.get(t.anchor)?.destroy();let{anchor:e,trigger:n=e,text:o,hint:r,enabled:s=!0,gap:a=UI,viewportPadding:l=qI}=t,c=()=>e.ownerDocument,p=()=>c().defaultView??window,u=null,m=null,g=null,h=null,b,C=!1,M=!1,E=!1,T=()=>(typeof o=="function"?o():o).trim(),H=()=>(typeof r=="function"?r():r??"").trim(),A=()=>tu(t.delayMs??mS),D=()=>tu(t.skipDelayMs??fS),W=()=>{b!==void 0&&(p().clearTimeout(b),b=void 0)},U=()=>{W();let oe=u!==null;h?.(),h=null,u?.remove(),u=null,m=null,g=null,oe&&KI(D())},B=()=>{if(!u)return;let oe=c(),ne=p(),le=e.getBoundingClientRect(),de=u.getBoundingClientRect(),ve=oe.documentElement.clientWidth||ne.innerWidth,Le=oe.documentElement.clientHeight||ne.innerHeight,se=ve-l-de.width,_=le.left+le.width/2-de.width/2,Te=ah(_,l,se),He=le.top-l,ut=Le-l-le.bottom,At=de.height+a,Wt=He>=At||He>=ut?"top":"bottom",bt=Wt==="top"?le.top-a-de.height:le.bottom+a,xe=Le-l-de.height,Ne=ah(bt,l,xe),Ae=le.left+le.width/2,vt=Math.max(ih,de.width-ih),X=ah(Ae-Te,ih,vt);u.dataset.placement=Wt,u.style.left=`${Te}px`,u.style.top=`${Ne}px`,u.style.setProperty("--persona-tooltip-arrow-x",`${X}px`)},O=()=>{if(E||!s||u||!e.isConnected||GI(e))return;let oe=T(),ne=YI(e);if(!oe||!ne)return;let le=c(),de=p();u=le.createElement("div"),u.className="persona-control-tooltip",u.setAttribute("role","tooltip"),u.dataset.state="measuring",u.style.zIndex=String(Ba);let ve=de.getComputedStyle?.(e);if(ve){for(let At of QI){let Wt=ve.getPropertyValue(At).trim();Wt&&u.style.setProperty(At,Wt)}ve.fontFamily&&(u.style.fontFamily=ve.fontFamily)}m=le.createElement("span"),m.className="persona-control-tooltip__label",m.textContent=oe,u.appendChild(m);let Le=H();Le&&(g=le.createElement("span"),g.className="persona-control-tooltip__hint",g.textContent=Le,u.appendChild(g));let se=le.createElement("span");se.className="persona-control-tooltip__arrow",u.appendChild(se),ne.appendChild(u),B(),u.dataset.state="open";let _=()=>{if(!e.isConnected){U();return}m&&(m.textContent=T()),g&&(g.textContent=H()),B()};de.addEventListener("scroll",_,!0),de.addEventListener("resize",_);let Te=e.getRootNode(),He=bS(Te)?Te:le.documentElement,ut=typeof MutationObserver>"u"?null:new MutationObserver(()=>{e.isConnected||U()});ut?.observe(He,{childList:!0,subtree:!0}),h=()=>{de.removeEventListener("scroll",_,!0),de.removeEventListener("resize",_),ut?.disconnect()}},R=oe=>{if(!(E||u)){if(W(),oe||A()<=0||jI()){O();return}b=p().setTimeout(()=>{b=void 0,O()},A())}},S=()=>{C||M?R(M):U()},x=()=>{let oe=p();(!oe.matchMedia||!oe.matchMedia("(hover: none)").matches)&&(C=!0,S())},P=()=>{C=!1,S()},L=()=>{try{M=e.matches(":focus-visible")}catch{M=!0}S()},G=()=>{M=!1,S()},V=()=>{C=!1,M=!1,U()},K=oe=>{oe.key==="Escape"&&V()};n.addEventListener("mouseenter",x),n.addEventListener("mouseleave",P),e.addEventListener("focus",L),e.addEventListener("blur",G),e.addEventListener("keydown",K),e.addEventListener("click",V);let ee={get isOpen(){return u!==null},show:O,hide:U,reposition:B,destroy:()=>{E||(E=!0,U(),n.removeEventListener("mouseenter",x),n.removeEventListener("mouseleave",P),e.removeEventListener("focus",L),e.removeEventListener("blur",G),e.removeEventListener("keydown",K),e.removeEventListener("click",V),eu.delete(e))}};return eu.set(e,ee),ee}je();Zt();function ch(t){let e=t.ownerDocument?.defaultView;if(!e?.getComputedStyle)return 20;let n=e.getComputedStyle(t).lineHeight;if(!n||!n.trim().endsWith("px"))return 20;let o=parseFloat(n);return Number.isFinite(o)&&o>0?o:20}function nu(t,e){return typeof t!="number"||!Number.isFinite(t)?e:t>0?t:e}function vS(t,e){t.style.maxHeight=`${e*ch(t)}px`,t.style.overflowY="auto"}function rc(t){let e=t?.ownerDocument?.defaultView??(typeof window<"u"?window:null);if(!e||typeof e.matchMedia!="function")return!1;try{return e.matchMedia("(pointer: coarse)").matches===!0}catch{return!1}}function CS(t){return t.insertNewlineOnTouchEnter===!0&&t.coarsePointer===!0}function wS(t,e){if(t.key!=="Enter"||t.shiftKey||t.isComposing)return!1;let n=t.metaKey===!0||t.ctrlKey===!0,o=e.submitKey??"enter";return o==="none"?!1:o==="mod-enter"?n:n||!CS(e)}function XI(t){return(t.submitKey??"enter")!=="enter"||CS(t)?"enter":"send"}function ou(t,e){t.setAttribute("enterkeyhint",XI(e))}function ru(t,e){let n=e?.autocomplete;t.setAttribute("autocomplete",typeof n=="string"&&n?n:"off");let o=(r,s)=>{s===void 0?t.removeAttribute(r):t.setAttribute(r,s)};o("autocapitalize",typeof e?.autocapitalize=="string"?e.autocapitalize:void 0),o("spellcheck",typeof e?.spellcheck=="boolean"?String(e.spellcheck):void 0),o("inputmode",typeof e?.inputmode=="string"&&e.inputmode?e.inputmode:void 0),o("aria-label",typeof e?.ariaLabel=="string"&&e.ariaLabel?e.ariaLabel:void 0)}function dh(t){return t===!0?{disabled:!0}:!t||typeof t!="object"?{disabled:!1}:{disabled:!0,reason:typeof t.reason=="string"&&t.reason?t.reason:void 0}}var yo="persona-composer-control",Go="persona-composer-control--glyph",uh=40,Un=24,su=(t,e,n)=>{let o=t.ownerDocument?.defaultView;if(!o)return;let r=o.getComputedStyle(t);for(let s of n){let a=r.getPropertyValue(s).trim();a?e.style.setProperty(s,a):e.style.removeProperty(s)}},iu=(t,e)=>{let n=v("textarea");n.setAttribute("data-persona-composer-input",""),n.placeholder=t?.copy?.inputPlaceholder??xg,n.dir="auto",ou(n,{submitKey:t?.composer?.submitKey,insertNewlineOnTouchEnter:t?.composer?.insertNewlineOnTouchEnter,coarsePointer:rc(n)}),ru(n,t?.composer?.inputAttributes),n.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-text focus:persona-outline-none focus:persona-border-none persona-composer-textarea",n.rows=1,n.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',n.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let o=nu(t?.composer?.maxLines,e?.defaultMaxLines??3),r=`${o*20}px`;n.style.maxHeight=r,n.style.overflowY="auto";let s=()=>{let l=n.style.maxHeight;if(l!==r){let p=parseFloat(l);if(Number.isFinite(p)&&p>0)return p}let c=o*ch(n);return r=`${c}px`,n.style.maxHeight=r,c},a=()=>{n.addEventListener("input",()=>{n.style.height="auto";let l=Math.min(n.scrollHeight,s());n.style.height=`${l}px`})};return n.style.border="none",n.style.outline="none",n.style.borderWidth="0",n.style.borderStyle="none",n.style.borderColor="transparent",n.addEventListener("focus",()=>{n.style.border="none",n.style.outline="none",n.style.borderWidth="0",n.style.borderStyle="none",n.style.borderColor="transparent",n.style.boxShadow="none"}),n.addEventListener("blur",()=>{n.style.border="none",n.style.outline="none"}),{textarea:n,attachAutoResize:a}},ZI="[data-persona-glyph-stack]",mh=(t,e,n="send")=>{let o=F("span",{className:"persona-composer-glyph-stack",attrs:{"data-mode":n,"data-persona-glyph-stack":""}});return t.setAttribute("data-glyph","send"),e.setAttribute("data-glyph","stop"),o.append(t,e),o},au=t=>{let e=t?.sendButton??{},n=e.useIcon??!1,o=e.iconText??"\u2191",r=e.iconName,s=e.stopIconName??"square",a=e.tooltipText??"Send message",l=e.stopTooltipText??"Stop generating",c=t?.copy?.sendButtonLabel??"Send",p=t?.copy?.stopButtonLabel??"Stop",u=e.showTooltip??!1,m=e.size,g=parseFloat(m??"")||uh,h=e.backgroundColor,b=e.textColor,C=v("div","persona-send-button-wrapper"),M=F("button",{className:Gt("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?`persona-flex persona-items-center persona-justify-center ${yo}`:"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!h&&"persona-bg-persona-primary",!n&&!b&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":"","data-persona-send-mode":"send"},style:{width:n?m:void 0,height:n?m:void 0,minWidth:n?m:void 0,minHeight:n?m:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?b||"var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))":b||void 0,backgroundColor:n&&h||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:n?"0":e.paddingX||void 0,paddingRight:n?"0":e.paddingX||void 0,paddingTop:n?"0":e.paddingY||void 0,paddingBottom:n?"0":e.paddingY||void 0}}),E=null,T=null,H=null;if(n){let W=parseFloat(e.iconSize??"")||Math.round(g*.5),U=e.iconStrokeWidth??2,B=b?.trim()||"currentColor";if(r&&(E=ke(r,W,B,U)),T=ke(s,W,B,U),!e.iconSize)for(let O of[E,T])O&&(O.style.width=`var(--persona-components-composer-sendIconSize, ${W}px)`,O.style.height=`var(--persona-components-composer-sendIconSize, ${W}px)`);E&&T?(H=mh(E,T),M.appendChild(H)):E?M.appendChild(E):(M.textContent=o,T=null)}else M.textContent=c;M.setAttribute("aria-label",a),C.appendChild(M),In({anchor:M,trigger:C,text:()=>M.getAttribute("aria-label")??"",enabled:u});let A="send";return{button:M,wrapper:C,setMode:W=>{if(W===A)return;A=W;let U=W==="stop"?l:a;M.setAttribute("aria-label",U),M.setAttribute("data-persona-send-mode",W),n?(M.querySelector(ZI)??H)?.setAttribute("data-mode",W):M.textContent=W==="stop"?p:c},glyphStack:H}},Da=t=>{let e=t?.voiceRecognition??{};if(!(e.enabled===!0))return null;let o=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),r=e.provider?.type==="runtype",s=e.provider?.type==="custom";if(!(o||r||s))return null;let l=e.iconName??"mic",c=e.iconSize,p=parseFloat(c??"")||Un,u=e.backgroundColor??t?.sendButton?.backgroundColor,m=e.iconColor??t?.sendButton?.textColor,g=v("div","persona-send-button-wrapper"),h=F("button",{className:Gt("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",yo,!c&&Go),attrs:{type:"button","data-persona-composer-mic":"","data-state":"idle","aria-label":e.tooltipText??"Start voice recognition"},style:{width:c,height:c,minWidth:c,minHeight:c,fontSize:"18px",lineHeight:"1",color:m||"var(--persona-text, #111827)",backgroundColor:u||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:e.paddingX||void 0,paddingRight:e.paddingX||void 0,paddingTop:e.paddingY||void 0,paddingBottom:e.paddingY||void 0}}),C=ke(l,p,m||"currentColor",1.5);C?h.appendChild(C):h.textContent="\u{1F3A4}",g.appendChild(h);let M=e.tooltipText??"Start voice recognition",E=e.showTooltip??!1;return In({anchor:h,trigger:g,text:()=>h.getAttribute("aria-label")??M,enabled:E}),{button:h,wrapper:g}},lu=t=>{let e=t?.attachments??{};if(e.enabled!==!0)return null;let n=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");n.setAttribute("data-persona-composer-attachment-previews",""),n.style.display="none";let o=v("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=(e.allowedTypes??Ur).join(","),o.multiple=(e.maxFiles??4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let r=e.buttonIconName??"paperclip",s=v("div","persona-send-button-wrapper"),a=F("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${yo} ${Go}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":e.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),l=ke(r,Un,"currentColor",1.5);l?a.appendChild(l):a.textContent="\u{1F4CE}",a.addEventListener("click",p=>{p.preventDefault(),o.click()}),s.appendChild(a);let c=e.buttonTooltipText??"Attach file";return In({anchor:a,trigger:s,text:()=>a.getAttribute("aria-label")??c}),{button:a,wrapper:s,input:o,previewsContainer:n}},cu=t=>{let e=t?.statusIndicator??{},n=e.align==="left"?"persona-text-left":e.align==="center"?"persona-text-center":"persona-text-right",o=v("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status",""),xi(o,e,"idle");let r=e.idleText??"Online";if(e.idleLink){let s=v("a");s.href=e.idleLink,s.target="_blank",s.rel="noopener noreferrer",s.textContent=r,s.style.color="inherit",s.style.textDecoration="none",o.appendChild(s)}else o.textContent=r;return o},du=()=>F("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});Oa();je();Zt();var tR='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',nR=["--persona-components-composer-overflowMenu-background","--persona-components-composer-overflowMenu-borderColor","--persona-components-composer-overflowMenu-borderRadius","--persona-components-composer-overflowMenu-foreground","--persona-components-composer-overflowMenu-shadow"],fh="data-persona-menu-focus",oR=new Set(["ArrowDown","ArrowUp","Home","End"]);function MS(t){return t.getAttribute("role")==="menuitem"?t:t.querySelector(tR)??t}var rR=t=>t.disabled===!0||t.getAttribute("aria-disabled")==="true";function TS(t){let e=t.label,n=!1,o=v("div","persona-send-button-wrapper"),r=F("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${yo} ${Go}`,attrs:{type:"button","aria-haspopup":"menu","aria-expanded":"false","data-persona-composer-overflow-trigger":""}});o.appendChild(r);let s=F("div",{className:"persona-composer-overflow-menu",attrs:{role:"menu",tabindex:"-1","data-persona-composer-overflow-menu":""}}),a=()=>{let L=t.getButtonSize?.()??"";r.style.width=L,r.style.height=L,r.style.minWidth=L,r.style.minHeight=L,r.style.lineHeight="1",r.replaceChildren();let G=ke("plus",Un,"currentColor",1.5);G?r.appendChild(G):r.textContent="+"},l=()=>{r.setAttribute("aria-label",e),r.setAttribute("title",e),s.setAttribute("aria-label",e)};l(),a();let c=[],p=-1,u=!1,m=()=>{let G=s.getRootNode().activeElement;return G instanceof HTMLElement?G:null},g=()=>{let L=m();for(let G of c){let V=!!L&&MS(G)===L;G.toggleAttribute(fh,V&&u)}},h=()=>c.filter(L=>L.isConnected||s.contains(L)).map(MS).filter(L=>!rR(L)),b=(L,G)=>{L.forEach((V,K)=>{V.setAttribute("tabindex",K===G?"0":"-1")})},C=L=>{let G=h();if(G.length===0)return;let V=(L%G.length+G.length)%G.length;p=V,b(G,V),G[V].focus(),g()},M=()=>o.ownerDocument??document,E=null,T=null,H=null,A=()=>{E&&(M().removeEventListener("focusin",E,!0),E=null)},D=()=>{T&&(s.removeEventListener("focusin",T),T=null),H&&(s.removeEventListener("pointerdown",H,!0),H=null)},W=null,U=()=>(W||(W=Ps({anchor:r,content:s,placement:"top-start",offset:6,onDismiss:()=>{r.setAttribute("aria-expanded","false"),A()}})),W),B=()=>W?.isOpen===!0,O=(L=!1)=>{if(B()){W?.close(),r.setAttribute("aria-expanded","false"),A(),D(),p=-1,u=!1;for(let G of c)G.removeAttribute(fh);L&&r.focus()}},R=(L=0,G=!1)=>{if(n||B())return;u=G,su(r,s,nR),U().open(),r.setAttribute("aria-expanded","true");let V=h();b(V,-1),C(L<0?V.length-1:L),E=K=>{let ee=typeof K.composedPath=="function"?K.composedPath():[];ee.includes(s)||ee.includes(o)||O()},M().addEventListener("focusin",E,!0),T=()=>g(),s.addEventListener("focusin",T),H=()=>{u=!1},s.addEventListener("pointerdown",H,!0)},S=L=>{L.preventDefault(),L.stopPropagation(),B()?O(!0):R(0)},x=L=>{if(L.key==="ArrowDown"||L.key==="Enter"||L.key===" "){L.preventDefault(),u=!0,B()?C(0):R(0,!0);return}L.key==="ArrowUp"&&(L.preventDefault(),u=!0,B()?C(-1):R(-1,!0))},P=L=>{switch(oR.has(L.key)&&(u=!0),L.key){case"ArrowDown":L.preventDefault(),C(p+1);return;case"ArrowUp":L.preventDefault(),C(p-1);return;case"Home":L.preventDefault(),C(0);return;case"End":L.preventDefault(),C(h().length-1);return;case"Escape":L.preventDefault(),L.stopPropagation(),O(!0);return;case"Tab":O(!0);return;default:}};return r.addEventListener("click",S),r.addEventListener("keydown",x),s.addEventListener("keydown",P),{trigger:o,triggerButton:r,panel:s,setItems:L=>{for(let V of c)L.includes(V)||V.removeAttribute(fh);if(c=[...L],!B())return;let G=h();b(G,Math.min(p,G.length-1)),g()},isOpen:B,open:()=>R(0),close:O,setLabel:L=>{L!==e&&(e=L,l())},applyButtonSize:a,destroy:()=>{n=!0,A(),D(),r.removeEventListener("click",S),r.removeEventListener("keydown",x),s.removeEventListener("keydown",P),W?.destroy(),W=null,o.remove(),s.remove(),c=[]}}}var yr={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},ES="data-persona-composer-action",gh="data-persona-composer-disable-when-streaming",sR="core:overflow",iR=t=>t==="core:attachment"?"attachments":t.startsWith("core:mention")?"mentions":null;function aR(t,e){if(t===void 0)return null;if(typeof t=="number")return Number.isFinite(t)?t:null;let n=Number.parseFloat(t);if(/^\s*-?\d*\.?\d+(px)?\s*$/.test(t)&&Number.isFinite(n))return n;let o=v("div");o.style.position="absolute",o.style.visibility="hidden",o.style.pointerEvents="none",o.style.height="0",o.style.width=t,e.appendChild(o);let r=o.getBoundingClientRect().width;return o.remove(),Number.isFinite(r)&&r>0?r:Number.isFinite(n)?n:null}function hh(t){let e=t.clientWidth;if(!e)return 0;let n=t.ownerDocument?.defaultView;if(!n?.getComputedStyle)return e;let o=n.getComputedStyle(t),r=(Number.parseFloat(o.paddingLeft)||0)+(Number.parseFloat(o.paddingRight)||0);return Math.max(0,e-r)}var kS=(t,e)=>{!t||typeof console>"u"||console.warn(e)},lR=(t,e)=>e.includes(":")?e:`${t}:${e}`;function cR(t){let{debug:e}=t,n=[],o=new Map,r=0,s=l=>{let c=o.get(l.id);if(c){kS(e,`[Persona] composer action "${l.id}" is already contributed by ${PS(c)}; the ${PS(l)} copy is ignored.`);return}o.set(l.id,l),n.push(l)};for(let l of t.builtIns)s({id:l.id,placement:l.placement,presentation:"bar",order:l.order,sequence:r++,source:"core",builtIn:l});let a=(l,c,p)=>{let u=p?lR(p,l.id):l.id,m=l.order??yr.custom;l.placement==="end"&&m>=yr.send&&(kS(e,`[Persona] composer action "${u}" ordered at ${m} would render after send; clamped to ${yr.send-1}.`),m=yr.send-1),s({id:u,placement:l.placement,presentation:l.presentation??"bar",order:m,sequence:r++,source:c,pluginId:p,action:l})};for(let l of t.configActions??[])a(l,"config");for(let l of t.plugins){if(!l.contributeComposerActions)continue;let c;try{c=l.contributeComposerActions(t.contributionContext)}catch(p){typeof console<"u"&&console.error(`[Persona] plugin "${l.id}" contributeComposerActions failed:`,p);continue}for(let p of c??[])a(p,"plugin",l.id)}return n.sort((l,c)=>l.order===c.order?l.sequence-c.sequence:l.order-c.order)}var PS=t=>t.source==="plugin"?`plugin "${t.pluginId}"`:t.source==="config"?"composer.actions":"a core built-in",LS=(t,e,n)=>t===void 0?n:typeof t=="function"?t(e)===!0:t===!0,dR=t=>t.phase==="streaming"||t.text.trim().length>0||t.attachments.length>0;function pR(t,e){if(!t||t==="always")return!0;let n=dR(e);return t==="when-text"?n:!n}var Ls=t=>t.kind==="custom",yh=t=>t instanceof HTMLButtonElement?t:t.querySelector("button")??t,uR=t=>{let e=yh(t);return e.getAttribute("aria-label")?.trim()||e.getAttribute("title")?.trim()||""},mR='.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]';function fR(t){let e="",n=o=>{if(o.nodeType===Node.TEXT_NODE){e+=o.nodeValue??"";return}if(o.nodeType!==Node.ELEMENT_NODE)return;let r=o;typeof r.matches=="function"&&r.matches(mR)||o.childNodes.forEach(n)};return n(t),e.trim()}var gR=t=>fR(t).length===0;function IS(t){let e=new Map,n=[],o=!1,r=()=>t.getButtonSize?.(),s=(S,x)=>{let P=S.button;if(!P)return;P.setAttribute("role","menuitem"),P.setAttribute("tabindex","-1"),P.className="persona-composer-overflow-menu__item";for(let V of["width","height","minWidth","minHeight","fontSize","color","backgroundColor"])P.style[V]="";P.style.lineHeight="1",x.tooltipText?P.setAttribute("title",x.tooltipText):P.removeAttribute("title"),P.replaceChildren();let L=v("span","persona-composer-overflow-menu__icon");if(x.iconName){let V=ke(x.iconName,16,"currentColor",1.5);V&&L.appendChild(V)}let G=v("span","persona-composer-overflow-menu__label");G.textContent=x.shortLabel??x.label,P.append(L,G)},a=(S,x)=>{let P=S.button;if(!P)return;if(P.setAttribute("aria-label",x.label),x.pressed===void 0?P.removeAttribute("aria-pressed"):P.setAttribute("aria-pressed",x.pressed?"true":"false"),P.toggleAttribute(gh,x.disableWhenStreaming===!0),S.mode==="menu"){S.tooltip?.destroy(),S.tooltip=void 0,s(S,x);return}P.removeAttribute("role"),P.removeAttribute("tabindex"),P.removeAttribute("title");let L=r(),G=!!x.shortLabel;if(P.className=Gt("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",yo,Go,G&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),P.style.width=L&&!G?L:"",P.style.height=L??"",P.style.minWidth=L&&!G?L:"",P.style.minHeight=L??"",P.style.fontSize=G?"":"18px",P.style.lineHeight="1",P.style.color=x.iconColor??"",P.style.backgroundColor=x.backgroundColor??"",P.replaceChildren(),x.iconName){let V=ke(x.iconName,Un,"currentColor",1.5);V&&P.appendChild(V)}if(G){let V=v("span","persona-composer-action-button__label");V.textContent=x.shortLabel,P.appendChild(V)}else P.firstChild||(P.textContent=x.label);S.tooltip?.destroy(),S.tooltip=In({anchor:P,trigger:S.element,text:()=>x.tooltipText??x.label,enabled:!!x.tooltipText})},l=(S,x)=>{let P=S.action,L=F("button",{attrs:{type:"button"}}),G=L;if(x==="bar"){let ee=v("div","persona-send-button-wrapper");ee.appendChild(L),G=ee}G.setAttribute(ES,S.id);let V={resolved:S,element:G,button:L,owned:!0,managed:!0,busy:!1,visible:!0,mode:x},K=ee=>{if(ee.preventDefault(),ee.stopPropagation(),V.busy||L.disabled)return;let oe=V.resolved.action;V.mode==="menu"&&h?.close(!0);let ne;try{ne=oe.onSelect(t.actionContext,ee)}catch(le){t.reportError(le,{actionId:V.resolved.id});return}!ne||typeof ne.then!="function"||(V.busy=!0,L.setAttribute("aria-busy","true"),ne.catch(le=>{t.reportError(le,{actionId:V.resolved.id})}).finally(()=>{V.busy=!1,L.removeAttribute("aria-busy")}))};return L.addEventListener("click",K),V.detach=()=>L.removeEventListener("click",K),a(V,P),V},c=S=>{let x=S.action,P;try{P=x.render({...t.actionContext,id:S.id,action:x})}catch(L){return t.reportError(L,{actionId:S.id}),null}return P?.element?(P.element.setAttribute(ES,S.id),P.element.toggleAttribute(gh,x.disableWhenStreaming===!0),{resolved:S,element:P.element,owned:!0,managed:!0,destroy:P.destroy,busy:!1,visible:!0,mode:"bar"}):null},p=(S,x)=>{if(S.builtIn){let L=S.builtIn.element;return L?{resolved:S,element:L,owned:!1,managed:S.builtIn.managed===!0,busy:!1,visible:!0,mode:"bar"}:null}let P=S.action;return P?Ls(P)?c(S):l(S,x):null},u=S=>{if(S.detach?.(),S.tooltip?.destroy(),S.detachMenuSlot?.(),S.detachMenuSlot=void 0,S.menuLabel?.remove(),S.menuLabel=void 0,S.menuSlot?.remove(),S.menuSlot=void 0,S.owned){try{S.destroy?.()}catch(x){t.reportError(x,{actionId:S.resolved.id})}S.element.remove()}},m=(S,x)=>{for(let P=0;P<x.length;P++){let L=x[P];if(!L.managed)continue;let G=null;for(let V=P+1;V<x.length;V++){let K=x[V];if(!K.managed&&K.element.parentElement===S){G=K.element;break}}G?(L.element.parentElement!==S||L.element.nextSibling!==G)&&S.insertBefore(L.element,G):S.lastChild!==L.element&&S.appendChild(L.element)}},g=(S,x)=>{if(S.button){S.button.disabled=x;return}if(!S.owned)return;let P=S.element;P.toggleAttribute("data-disabled",x),P.setAttribute("aria-disabled",x?"true":"false");let L=P instanceof HTMLButtonElement||P instanceof HTMLSelectElement||P instanceof HTMLInputElement||P instanceof HTMLTextAreaElement?P:P.querySelector("button, select, input, textarea");L&&(L.disabled=x)},h=null,b=null,C=null,M=0,E=()=>{let S=t.getOverflow?.();return S?.enabled===!0?S:void 0},T=()=>(h?h.setLabel(t.getOverflowLabel?.()??"More actions"):h=TS({label:t.getOverflowLabel?.()??"More actions",getButtonSize:r}),h),H=S=>{b!==S&&(C?.disconnect(),b=S,M=hh(S),!(typeof ResizeObserver>"u")&&(C=new ResizeObserver(x=>{let L=x[x.length-1]?.contentRect?.width??hh(S);L!==M&&(M=L,O())}),C.observe(S)))},A=(S,x)=>{let P=aR(S.collapseAutoActionsBelow,x);if(P===null)return!1;let L=M||hh(x);return L>0&&L<P},D=(S,x,P)=>{if(!x)return"bar";if(S.resolved.builtIn){let G=iR(S.resolved.id);return G&&x.includeBuiltIns?.includes(G)?"menu":"bar"}let L=S.resolved.presentation;return L==="overflow"||L==="auto"&&P?"menu":"bar"},W=S=>{let x=S.menuSlot;if(!x)return;if(!gR(S.element)){S.menuLabel?.remove(),S.menuLabel=void 0;return}let P=uR(S.element);if(!P){S.menuLabel?.remove(),S.menuLabel=void 0;return}S.menuLabel||(S.menuLabel=v("span","persona-composer-overflow-menu__label")),S.menuLabel.textContent!==P&&(S.menuLabel.textContent=P),S.menuLabel.parentElement!==x&&x.appendChild(S.menuLabel)},U=(S,x)=>{if(S.mode===x)return S;let P=S.resolved.action;if(P&&!Ls(P)){u(S),e.delete(S.resolved.id);let L=l(S.resolved,x);return e.set(S.resolved.id,L),L}if(x==="menu"){let L=F("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none",[lh]:""}});L.appendChild(S.element),yS(yh(S.element)),S.menuSlot=L;let G=V=>{let K=yh(S.element);if(K.disabled)return;let ee=V.target===K||K.contains(V.target);h?.close(!0),ee||K.click()};L.addEventListener("click",G,!0),S.detachMenuSlot=()=>L.removeEventListener("click",G,!0),S.managed=!0,W(S)}else S.detachMenuSlot?.(),S.detachMenuSlot=void 0,S.menuLabel?.remove(),S.menuLabel=void 0,S.menuSlot?.remove(),S.menuSlot=void 0;return S.mode=x,S},B=(S,x)=>{let P=x.map(L=>L.menuSlot??L.element);for(P.forEach((L,G)=>{let V=S.children[G];V!==L&&(V?S.insertBefore(L,V):S.appendChild(L))});S.children.length>P.length;)S.lastElementChild?.remove()},O=()=>{if(o)return;let S=t.getBindings();if(!S)return;let x=t.getState(),P=x.phase==="streaming",L=E();L&&H(S.footer);let G=L?A(L,S.footer):!1,V={start:[],end:[]},K=[];for(let ee of n){let oe=e.get(ee.id);if(!oe)continue;let ne=ee.action,le=ne?LS(ne.visible,x,!0)&&pR(ne.visibility,x):!0;if(oe.visible!==le&&(oe.visible=le,!le&&oe.managed&&(oe.menuSlot??oe.element).remove()),!!le){if(oe=U(oe,D(oe,L,G)),ne){let de=LS(ne.disabled,x,!1)||ne.disableWhenStreaming===!0&&P;g(oe,de),!Ls(ne)&&ne.pressed!==void 0&&oe.button?.setAttribute("aria-pressed",ne.pressed?"true":"false")}oe.mode==="menu"?(W(oe),K.push(oe)):V[ee.placement].push(oe)}}if(K.length>0){let ee=T();B(ee.panel,K),ee.setItems(K.map(de=>de.menuSlot??de.element)),ee.applyButtonSize();let oe=Number.isFinite(L?.order)?L?.order:yr.overflow,ne=V.start.findIndex(de=>de.resolved.order>oe),le={resolved:{id:sR,placement:"start",presentation:"bar",order:oe,sequence:-1,source:"core"},element:ee.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};V.start.splice(ne<0?V.start.length:ne,0,le)}else h&&(h.close(),h.trigger.remove(),h.setItems([]));m(S.actionsStart,V.start),m(S.actionsEnd,V.end)};return{resolve:()=>{if(o)return;let S=cR(t.collect()),x=new Set(S.map(P=>P.id));for(let[P,L]of e)x.has(P)||(u(L),e.delete(P));for(let P of S){let L=e.get(P.id);if(!L){let ee=p(P,"bar");ee&&e.set(P.id,ee);continue}let G=L.resolved.action,V=P.action;if(!!G!=!!V||G&&V&&Ls(G)!==Ls(V)||G&&V&&Ls(G)&&Ls(V)&&G.render!==V.render){u(L),e.delete(P.id);let ee=p(P,L.mode);ee&&e.set(P.id,ee);continue}L.resolved=P,P.builtIn?(L.managed=P.builtIn.managed===!0||L.mode==="menu",P.builtIn.element&&L.mode==="bar"&&(L.element=P.builtIn.element)):V&&!Ls(V)?a(L,V):V&&L.element.toggleAttribute(gh,V.disableWhenStreaming===!0)}n=S,O()},sync:O,getResolved:()=>n,getOverflowMenu:()=>h,destroy:()=>{if(!o){o=!0,C?.disconnect(),C=null,b=null;for(let S of e.values())u(S);e.clear(),h?.destroy(),h=null,n=[]}}}}Oa();je();Zt();var hR="core:model",yR=700,RS=16,bR=["--persona-components-composer-modelPicker-menuBackground","--persona-components-composer-modelPicker-menuBorderRadius","--persona-components-composer-modelPicker-rowHoverBackground","--persona-components-composer-modelPicker-labelColor","--persona-components-composer-modelPicker-descriptionColor"],HS=()=>{let t=F("span",{className:"persona-composer-model-picker-wrapper",attrs:{"data-persona-composer-model-picker-wrapper":""}}),e=F("span",{className:"persona-composer-model-picker-chevron",attrs:{"aria-hidden":"true"}});return{wrapper:t,chevron:e}};function WS(t){let e=t.label??"Model",n=t.presentation??"native",o=null,r=c=>{let p=t.getSelectedModelId();return c.find(u=>u.id===p)??c[0]},s=()=>{let c=F("select",{className:"persona-composer-model-picker",attrs:{"aria-label":e,"data-persona-composer-model-picker":""}}),p="",u=()=>{let C=t.getModels(),M=C.map(E=>`${E.id}:${E.label}`).join("|");M!==p&&(p=M,c.replaceChildren(...C.map(E=>{let T=F("option",{attrs:{value:E.id}});return T.textContent=E.label,T}))),c.value=r(C)?.id??""};u(),o=u;let m=()=>{c.value&&t.onSelect(c.value)};c.addEventListener("change",m);let g=C=>C.stopPropagation();c.addEventListener("click",g);let{wrapper:h,chevron:b}=HS();return h.append(c,b),{element:h,destroy:()=>{o===u&&(o=null),c.removeEventListener("change",m),c.removeEventListener("click",g)}}},a=()=>{let c=F("button",{className:"persona-composer-model-picker persona-composer-model-picker-trigger",attrs:{type:"button","aria-haspopup":"listbox","aria-expanded":"false","data-persona-composer-model-picker":"popover"}}),p=v("span","persona-composer-model-picker-label"),u=v("span","persona-composer-model-picker-suffix");c.append(p,u);let m=F("div",{className:"persona-composer-model-menu",attrs:{role:"listbox",tabindex:"-1","aria-label":e,"data-persona-composer-model-menu":""}}),g=new Map,h="",b=null,C=()=>b?.isOpen===!0,M=(x=!1)=>{C()&&(b?.close(),c.setAttribute("aria-expanded","false"),x&&c.focus())},E=x=>{let P=[...g.values()];if(P.length===0)return;let L=(x%P.length+P.length)%P.length;P[L].focus()},T=x=>{if(C())return;b||(b=Ps({anchor:c,content:m,placement:"top-start",offset:6,onDismiss:()=>c.setAttribute("aria-expanded","false")})),su(c,m,bR),b.open(),c.setAttribute("aria-expanded","true");let L=[...g.keys()].indexOf(r(t.getModels())?.id??"");E(x??(L>=0?L:0))},H=x=>{M(!0),t.onSelect(x)},A=x=>{x.preventDefault(),x.stopPropagation();let P=x.currentTarget.getAttribute("data-persona-model-option");P&&H(P)},D=x=>{let P=F("button",{className:"persona-composer-model-option",attrs:{type:"button",role:"option",tabindex:"-1","aria-selected":"false","data-persona-model-option":x.id}});if(x.icon){let ee=ke(x.icon,RS,"currentColor",1.5);if(ee){let oe=v("span","persona-composer-model-option-icon");oe.appendChild(ee),P.appendChild(oe)}}let L=v("span","persona-composer-model-option-body"),G=v("span","persona-composer-model-option-label");if(G.textContent=x.label,L.appendChild(G),x.description){let ee=v("span","persona-composer-model-option-description");ee.textContent=x.description,L.appendChild(ee)}P.appendChild(L);let V=v("span","persona-composer-model-option-check");V.setAttribute("aria-hidden","true");let K=ke("check",RS,"currentColor",2);return K&&V.appendChild(K),P.appendChild(V),P.addEventListener("click",A),P},W=()=>{let x=t.getModels(),P=x.map(V=>`${V.id}:${V.label}:${V.icon??""}:${V.description??""}`).join("|");if(P!==h){h=P;for(let V of g.values())V.removeEventListener("click",A);g.clear(),m.replaceChildren(...x.map(V=>{let K=D(V);return g.set(V.id,K),K}))}let L=r(x);for(let[V,K]of g)K.setAttribute("aria-selected",String(V===L?.id));p.textContent=L?.label??"";let G=t.getSuffix?.()??"";u.textContent=G,c.setAttribute("aria-label",[e,[L?.label,G].filter(Boolean).join(" ")].filter(Boolean).join(": "))};W(),o=W;let U=x=>{x.preventDefault(),x.stopPropagation(),C()?M(!0):T()},B=x=>{if(x.key==="ArrowDown"){x.preventDefault(),C()?E(0):T(0);return}x.key==="ArrowUp"&&(x.preventDefault(),C()?E(-1):T(-1))},O=x=>{let P=[...g.values()],L=P.indexOf(x.target?.closest?.(".persona-composer-model-option"));switch(x.key){case"ArrowDown":x.preventDefault(),E(L+1);return;case"ArrowUp":x.preventDefault(),E(L-1);return;case"Home":x.preventDefault(),E(0);return;case"End":x.preventDefault(),E(P.length-1);return;case"Escape":x.preventDefault(),x.stopPropagation(),M(!0);return;case"Tab":M(!0);return;default:}};c.addEventListener("click",U),c.addEventListener("keydown",B),m.addEventListener("keydown",O);let{wrapper:R,chevron:S}=HS();return R.append(c,S),{element:R,destroy:()=>{o===W&&(o=null),c.removeEventListener("click",U),c.removeEventListener("keydown",B),m.removeEventListener("keydown",O);for(let x of g.values())x.removeEventListener("click",A);g.clear(),b?.destroy(),b=null,m.remove()}}};return{action:{id:hR,kind:"custom",placement:"end",order:yR,presentation:n==="popover"?"bar":"auto",label:e,render:()=>n==="popover"?a():s()},repaint:()=>o?.()}}je();Zt();fu();var vR=":scope > [data-persona-composer-mode]";function BS(t){let e=t.row,n="",o=!1,r=new Set(t.initialIds??[]),s=p=>{let u=F("span",{className:"persona-mention-chip persona-composer-mode-chip",attrs:{"data-persona-composer-mode":p.id}});if(p.iconName){let b=v("span","persona-mention-chip-icon"),C=ke(p.iconName,12,"currentColor",1.5);C&&b.appendChild(C),u.appendChild(b)}let m=v("span","persona-mention-chip-label");m.textContent=p.shortLabel??p.label,u.appendChild(m);let g=F("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${p.label}`}}),h=ke("x",12,"currentColor",2);return h?g.appendChild(h):g.textContent="\xD7",g.addEventListener("click",b=>{b.preventDefault(),b.stopPropagation(),t.onRemove(p.id)}),u.appendChild(g),u},a=()=>Array.from(e.querySelectorAll(vR)),l=p=>{p.setAttribute("data-persona-chip-exit",""),p.setAttribute("aria-hidden","true"),p.style.pointerEvents="none";let u=()=>{p.remove(),_a(e)},m=e.ownerDocument.defaultView,g=typeof m?.getComputedStyle=="function"?m.getComputedStyle(p).animationName:"";if(!g||g==="none"){u();return}p.addEventListener("animationend",u,{once:!0}),p.addEventListener("animationcancel",u,{once:!0})},c=()=>{for(let p of a())p.remove()};return{element:e,render:(p,u)=>{if(o)return;let m=u.filter(C=>p.includes(C.id)),g=m.map(C=>`${C.id}:${C.shortLabel??C.label}`).join("|");if(g===n)return;n=g;let h=new Map;for(let C of a()){let M=C.getAttribute("data-persona-composer-mode");M&&m.some(T=>T.id===M)&&!C.hasAttribute("data-persona-chip-exit")?h.set(M,C):C.hasAttribute("data-persona-chip-exit")||l(C)}let b=e.firstChild;for(let C of m){let M=h.get(C.id);M||(M=s(C),r.has(C.id)||(M.setAttribute("data-persona-chip-enter",""),M.addEventListener("animationend",()=>M?.removeAttribute("data-persona-chip-enter"),{once:!0}))),r.delete(C.id),M!==b&&e.insertBefore(M,b),b=M.nextSibling}_a(e)},destroy:()=>{o=!0,c(),_a(e)}}}je();Zt();var DS=t=>`core:mode:${t}`;var Ch=t=>Math.min(300+t,499),OS=t=>`core:mode-group:${t}`;function gu(t,e){return t?e?.find(n=>n.id===t)?.presentation==="segmented":!1}function CR(t,e){return t?e?.find(n=>n.id===t)?.chipVisibility==="hidden":!1}function _S(t,e){return t?.length?t.filter(n=>!gu(n.groupId,e)&&!CR(n.groupId,e)):[]}var wR=(t,e)=>t.groupId?e?.find(n=>n.id===t.groupId)?.selection??null:null;function NS(t,e,n,o){let r=n.find(l=>l.id===e);if(!r)return[...t];let s=t.includes(e),a=new Set(t);if(s)a.delete(e);else{if(wR(r,o)==="single"){let l=n.filter(c=>c.groupId===r.groupId).map(c=>c.id);a=new Set([...a].filter(c=>!l.includes(c)))}a.add(e)}return n.filter(l=>a.has(l.id)).map(l=>l.id)}function hu(t,e){return e?.length?e.filter(n=>t.includes(n.id)).map(n=>n.id):[]}function FS(t,e){return e?.length?e.filter(n=>t.includes(n.id)&&(n.persistence??"sticky")!=="once").map(n=>n.id):[]}function VS(t,e){if(!(!e?.length||t.length===0))return e.find(n=>t.includes(n.id)&&n.placeholder)?.placeholder}var xR=16;function $S(t){let e=null;return{action:{id:OS(t.groupId),kind:"custom",placement:"start",presentation:"bar",label:t.getGroup()?.label??t.groupId,render:()=>{let o=F("div",{className:"persona-composer-segmented",attrs:{"data-persona-composer-mode-group":t.groupId}}),r=new Map,s="",a=p=>{p.preventDefault(),p.stopPropagation();let m=p.currentTarget.getAttribute("data-persona-composer-mode");!m||t.getActiveIds().includes(m)&&t.getGroup()?.selection==="single"||t.onSelect(m)},l=p=>{let u=F("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":p.id,"aria-label":p.label}});if(p.iconName){let g=ke(p.iconName,xR,"currentColor",1.5);g&&u.appendChild(g)}let m=v("span","persona-composer-segmented-label");return m.textContent=p.shortLabel??p.label,u.appendChild(m),u.addEventListener("click",a),u},c=()=>{let p=t.getGroup();p?.label?(o.setAttribute("role","group"),o.setAttribute("aria-label",p.label)):(o.removeAttribute("role"),o.removeAttribute("aria-label"));let u=t.getModes(),m=u.map(h=>`${h.id}:${h.shortLabel??h.label}:${h.iconName??""}`).join("|");if(m!==s){s=m;for(let b of r.values())b.removeEventListener("click",a);r.clear();let h=u.map(b=>{let C=l(b);return r.set(b.id,C),C});o.replaceChildren(...h)}let g=t.getActiveIds();for(let[h,b]of r)b.setAttribute("aria-pressed",String(g.includes(h)))};return c(),e=c,{element:o,destroy:()=>{e===c&&(e=null);for(let p of r.values())p.removeEventListener("click",a);r.clear()}}}},repaint:()=>e?.()}}fu();je();Zt();function zS(t){let e=F("div",{className:"persona-composer-quote",attrs:{"data-persona-composer-quote":""}});e.style.display="none";let n="",o=!1,r=s=>{let a=v("span","persona-composer-quote-bar"),l=v("div","persona-composer-quote-content");if(s.sourceLabel){let m=v("div","persona-composer-quote-source");m.textContent=s.sourceLabel,l.appendChild(m)}let c=F("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});c.textContent=Kp(s.text),l.appendChild(c);let p=F("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":t.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),u=ke("x",12,"currentColor",2);u?p.appendChild(u):p.textContent="\xD7",p.addEventListener("click",m=>{m.preventDefault(),m.stopPropagation(),t.onDismiss()}),e.replaceChildren(a,l,p)};return{element:e,render:s=>{if(o)return;let a=s?`${s.sourceLabel??""}\0${s.text}`:"";if(a!==n){if(n=a,!s){e.replaceChildren(),e.style.display="none";return}r(s),e.style.display="flex"}},destroy:()=>{o=!0,e.replaceChildren(),e.remove()}}}je();Zt();function US(t){let e=F("div",{className:"persona-composer-pending",attrs:{"data-persona-composer-pending":""}});e.style.display="none";let n,o=!1,r=(a,l,c,p)=>{let u=F("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":l,[c]:""}}),m=ke(a,12,"currentColor",2);return m?u.appendChild(m):u.textContent=l,u.addEventListener("click",g=>{g.preventDefault(),g.stopPropagation(),p()}),u},s=a=>{let l=Kp(a.text??"",90);if(l)return l;let c=a.contentParts?.length??0;return c>0?c===1?"1 attachment":`${c} attachments`:(a.mentionRefs?.length??0)>0?a.mentionRefs.map(u=>u.label).join(", "):"Queued message"};return{element:e,render:a=>{if(o||a===n)return;if(n=a,!a){e.replaceChildren(),e.style.display="none";return}let l=v("span","persona-composer-pending-badge");l.textContent=t.label??"Sends next";let c=F("div",{className:"persona-composer-pending-text",attrs:{"data-persona-composer-pending-text":""}});c.textContent=s(a),e.replaceChildren(l,c,r("pencil",t.editLabel??"Edit queued message","data-persona-composer-pending-edit",t.onEdit),r("x",t.removeLabel??"Remove queued message","data-persona-composer-pending-remove",t.onRemove)),e.style.display="flex"},destroy:()=>{o=!0,e.replaceChildren(),e.remove()}}}je();function qS(t){let e=F("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":t.messageId,"data-preserve-runtime":""}}),n=F("textarea",{className:"persona-message-edit-input",attrs:{rows:"1",dir:"auto","aria-label":"Edit message","data-persona-message-edit-input":""}});n.value=t.initialText;let o=()=>{n.style.height="auto",n.style.height=`${n.scrollHeight}px`};n.addEventListener("input",o);let r=v("div","persona-message-edit-actions"),s=(l,c,p,u)=>{let m=F("button",{className:`persona-message-edit-button ${c}`,attrs:{type:"button",[p]:""},text:l});return m.addEventListener("click",g=>{g.preventDefault(),g.stopPropagation(),u()}),m},a=()=>{let l=n.value.trim();l&&t.onSave(l)};return r.append(s(t.cancelLabel??"Cancel","persona-message-edit-cancel","data-persona-message-edit-cancel",t.onCancel),s(t.saveLabel??"Send","persona-message-edit-save","data-persona-message-edit-save",a)),n.addEventListener("keydown",l=>{if(l.key==="Escape"){l.preventDefault(),l.stopPropagation(),t.onCancel();return}l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),a())}),e.append(n,r),{element:e,getValue:()=>n.value,focus:()=>{n.focus();let l=n.value.length;n.setSelectionRange(l,l),o()},destroy:()=>{e.replaceChildren(),e.remove()}}}function jS(t){let e=t.text??"";if(e.trim().length>0||(t.mentionRefs?.length??0)>0||(t.activeModeIds?.length??0)>0||t.quote||t.selectedModelId)return{text:e,...t.mentionRefs?.length?{mentionRefs:[...t.mentionRefs]}:{},...t.contentSegments?.length?{contentSegments:[...t.contentSegments]}:{},...t.selectedModelId?{selectedModelId:t.selectedModelId}:{},...t.activeModeIds?.length?{activeModeIds:[...t.activeModeIds]}:{},...t.quote?{quote:{...t.quote}}:{}}}function KS(t,e){if(!t||typeof t.text!="string")return;let n=new Set(e.mentionSourceIds),o=(t.mentionRefs??[]).filter(c=>n.has(c.sourceId)),r=o.length===(t.mentionRefs?.length??0)&&o.length>0,s=new Set(e.modes.map(c=>c.id)),a=(t.activeModeIds??[]).filter(c=>s.has(c)),l=t.selectedModelId&&e.modelIds.includes(t.selectedModelId)?t.selectedModelId:void 0;return{text:t.text,...r?{mentionRefs:o}:{},...r&&t.contentSegments?.length?{contentSegments:t.contentSegments}:{},...l?{selectedModelId:l}:{},...a.length?{activeModeIds:a}:{},...t.quote?.text?{quote:t.quote}:{}}}function GS(t){let e=t.delay??500,n=null,o=!1,r=()=>{n!==null&&(clearTimeout(n),n=null)};return{schedule:()=>{o||(r(),n=setTimeout(()=>{n=null,t.write()},e))},flush:()=>{o||n===null||(r(),t.write())},cancel:r,destroy:()=>{o=!0,r()}}}function YS(t){return t.wrapped||t.text.includes(`
|
|
1156
|
-
`)?!1:!(t.hasAttachments||t.hasChips||t.hasQuote||t.hasPendingSubmission)}function
|
|
1155
|
+
`),l=Array.isArray(e.contentParts)&&e.contentParts.length>0,c=r.contentParts.length>0;if(l){let p=[];s&&p.push(fr(s)),p.push(...r.contentParts),p.push(...e.contentParts),e.contentParts=p}else if(c){let p=[];a&&p.push(fr(a)),p.push(...r.contentParts),e.contentParts=p}else s&&(e.llmContent=a);Object.keys(r.context).length>0&&(e.mentionContext=r.context)}async sendMessage(e,n){let o=e.trim(),r=!!n?.replayFields&&(n.replayFields.llmContent!==void 0||n.replayFields.rawContent!==void 0||(n.replayFields.contextMentions?.length??0)>0);if(!o&&(!n?.contentParts||n.contentParts.length===0)&&(!n?.mentions||n.mentions.refs.length===0)&&!r)return;(this.historyGate||this.projectionFinalizationPromise||this.historySendBlocked||this.credentialReinitPending)&&await this.awaitHistorySendable(),this.stopSpeaking(),this.abortController?.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let s=Dp(),a=Ta();this.activeAssistantMessageId=null;let l=n?.contentParts&&Up(n.contentParts)?Ha:"",c={id:s,role:"user",content:o||l,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:n?.viaVoice||!1,...n?.contentParts&&n.contentParts.length>0&&{contentParts:n.contentParts},...n?.mentions&&n.mentions.refs.length>0&&{contextMentions:n.mentions.refs},...n?.contentSegments&&n.contentSegments.length>0&&{contentSegments:n.contentSegments},...n?.composerOptions&&{composerOptions:n.composerOptions},...n?.replayFields??{}};this.appendMessage(c),this.setStreaming(!0);let p=new AbortController;if(this.abortController=p,n?.mentions){let m=this.messages.find(g=>g.id===s)??c;if(await this.applyMentionBundle(m,o,n.mentions.finalize),p.signal.aborted||this.abortController!==p)return;this.callbacks.onMessagesChanged([...this.messages])}if(n?.quote&&!n.replayFields){let m=this.messages.find(h=>h.id===s)??c,g=eS({quote:n.quote,text:m.llmContent??m.content,contentParts:m.contentParts});g.contentParts&&(m.contentParts=g.contentParts),g.llmContent!==void 0&&(m.llmContent=g.llmContent),(g.contentParts||g.llmContent!==void 0)&&(m.quote={...n.quote},this.callbacks.onMessagesChanged([...this.messages]))}let u=[...this.messages];try{await this.dispatchWithDeletedRecovery(u,p,a,s,{composerOptions:n?.composerOptions,interrupt:n?.interrupt})}catch(m){if(this.status==="resuming"||this.reconnecting)return;let g=m instanceof Error&&(m.name==="AbortError"||m.message.includes("aborted")||m.message.includes("abort"));if(!g){let h=ih(m,this.config.errorMessage);if(h){let b={id:a,role:"assistant",createdAt:new Date().toISOString(),content:h,sequence:this.nextSequence()};this.appendMessage(b)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,g||(m instanceof Error?this.callbacks.onError?.(m):this.callbacks.onError?.(new Error(String(m))))}}resubmitFrom(e,n){let o=tS(this.messages,e);if(!o)return!1;let r=this.messages[o.start],s=n.replacement,a=s?s.text:r.content,l=s?s.contentParts:r.contentParts;if(!(!!a?.trim()||(l?.length??0)>0||!s&&(r.llmContent?.trim()?.length??0)>0))return!1;let p=s?void 0:{...r.llmContent!==void 0&&{llmContent:r.llmContent},...r.rawContent!==void 0&&{rawContent:r.rawContent},...r.mentionContext&&{mentionContext:r.mentionContext},...r.contextMentions&&{contextMentions:r.contextMentions},...r.quote&&{quote:r.quote}},u=s?this.toComposerOptionsPayload(s.options):r.composerOptions,m=s?s.contentSegments:r.contentSegments,g=s?s.options?.quote:void 0,h=s?s.viaVoice:r.viaVoice;return this.cancel(),this.messages=this.messages.slice(0,o.start),this.sendMessage(a??"",{...l?.length?{contentParts:[...l]}:{},...m?.length?{contentSegments:[...m]}:{},...u?{composerOptions:u}:{},...g?{quote:g}:{},...p&&Object.keys(p).length>0?{replayFields:p}:{},viaVoice:h===!0}),!0}toComposerOptionsPayload(e){if(!e)return;let n={};return e.selectedModelId&&(n.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(n.activeModeIds=[...e.activeModeIds]),Object.keys(n).length>0?n:void 0}async continueConversation(){if(this.streaming)return;(this.historyGate||this.projectionFinalizationPromise||this.historySendBlocked||this.credentialReinitPending)&&await this.awaitHistorySendable(),this.abortController?.abort(),this.teardownReconnect();let e=Ta();this.activeAssistantMessageId=null,this.setStreaming(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:e},this.handleEvent)}catch(r){if(this.status==="resuming"||this.reconnecting)return;let s=r instanceof Error&&(r.name==="AbortError"||r.message.includes("aborted")||r.message.includes("abort"));if(!s){let a=ih(r,this.config.errorMessage);if(a){let l={id:e,role:"assistant",createdAt:new Date().toISOString(),content:a,sequence:this.nextSequence()};this.appendMessage(l)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,s||(r instanceof Error?this.callbacks.onError?.(r):this.callbacks.onError?.(new Error(String(r))))}}async connectStream(e,n){if(this.streaming&&!n?.allowReentry)return;n?.allowReentry||this.abortController?.abort(),n?.preserveAssistantId&&n.assistantMessageId&&(this.activeAssistantMessageId=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,r=!1;for(let s of this.messages)s.streaming&&s.id!==o&&(s.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(e,this.handleEvent,n?.assistantMessageId,n?.seedContent)}catch(s){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.callbacks.onError?.(s instanceof Error?s:new Error(String(s)))}}wireDefaultWebMcpConfirm(){let e=this.config.webmcp;e?.enabled===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(e){try{if(this.config.webmcp?.autoApprove?.(e)===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:e.toolName,toolType:"webmcp",description:e.description??`Allow the assistant to run ${e.toolName}?`,parameters:e.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(r=>{this.webMcpApprovalResolvers.set(o,r)})}resolveWebMcpApproval(e,n){let o=this.webMcpApprovalResolvers.get(e);if(!o)return;this.webMcpApprovalResolvers.delete(e);let r=this.messages.find(s=>s.id===e);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(e,n,o){let r=`approval-${e.id}`,s={...e,status:n,resolvedAt:Date.now()},a=this.messages.find(u=>u.id===r),l={id:r,role:"assistant",content:"",createdAt:a?.createdAt??new Date().toISOString(),...a?.sequence!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(l),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let c=this.config.approval,p=c&&typeof c=="object"?c.onDecision:void 0;try{let u;if(p?u=await p({approvalId:e.id,executionId:e.executionId,agentId:e.agentId,toolName:e.toolName},n,o):u=await this.client.resolveApproval({agentId:e.agentId,executionId:e.executionId,approvalId:e.id},n),u){let m=null;if(u instanceof Response){if(!u.ok){let g=await u.json().catch(()=>null);throw new Error(g?.error??`Approval request failed: ${u.status}`)}m=u.body}else u instanceof ReadableStream&&(m=u);m?await this.connectStream(m,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${e.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(u){let m=u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||this.callbacks.onError?.(u instanceof Error?u:new Error(String(u)))}}persistAskUserQuestionProgress(e,n){let o=this.messages.find(r=>r.id===e.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(e,n){let o=this.messages.find(r=>r.id===e.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(e,n){if(this.messages.find(u=>u.id===e.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=e.agentMetadata?.executionId,s=e.toolCall?.name;if(!r||!s){this.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let u=e.toolCall?.args,m=Array.isArray(u?.questions)?u.questions:[];if(m.length===1){let g=typeof m[0]?.question=="string"?m[0].question:"";g&&(a={[g]:n})}}this.markAskUserQuestionResolved(e,a),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let l=e.toolCall.id,c=e.toolCall?.args,p=Array.isArray(c?.questions)?c.questions:[];if(p.length===0){let u=typeof n=="string"?n:Object.entries(n).map(([m,g])=>`${m}: ${Array.isArray(g)?g.join(", "):g}`).join(" | ");this.appendMessage({id:`ask-user-answer-${l}`,role:"user",content:u,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let u=a??{};p.forEach((m,g)=>{let h=typeof m?.question=="string"?m.question:"";if(!h)return;let b=u[h],C=Array.isArray(b)?b.join(", "):typeof b=="string"?b:"";this.appendMessage({id:`ask-user-q-${l}-${g}`,role:"assistant",content:h,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${l}-${g}`,role:"user",content:C||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let u=await this.client.resumeFlow(r,{[s]:n},{after:this.resumable?.executionId===r?this.resumable.lastEventId:void 0});if(!u.ok){let m=await u.json().catch(()=>null);throw new Error(m?.error??`Resume failed: ${u.status}`)}u.body?await this.connectStream(u.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(u){let m=u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||this.callbacks.onError?.(u instanceof Error?u:new Error(String(u)))}}enqueueWebMcpAwait(e){let n=e.agentMetadata?.executionId,o=e.toolCall?.id;if(!n||!o){let s=this.webMcpEpoch;queueMicrotask(()=>{s===this.webMcpEpoch&&this.resolveWebMcpToolCall(e)});return}let r=this.webMcpAwaitBatches.get(n);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,r)),!r.seen.has(o)&&(r.seen.add(o),r.snapshots.push(e))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let e=this.webMcpEpoch;queueMicrotask(()=>{if(e===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(e){let n=this.webMcpAwaitBatches.get(e);if(!n)return;this.webMcpAwaitBatches.delete(e);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(e,o)}resolveWebMcpToolStartedAt(e){let o=[this.messages.find(r=>r.id===e.id)?.toolCall?.startedAt,e.toolCall?.startedAt];for(let r of o)if(typeof r=="number"&&Number.isFinite(r))return r;return Date.now()}isSuggestRepliesAlreadyResolved(e){return e.toolCall?.name!==As?!1:(this.messages.find(o=>o.id===e.id)??e).agentMetadata?.suggestRepliesResolved===!0}markWebMcpToolRunning(e){let n=this.resolveWebMcpToolStartedAt(e);return this.upsertMessage({...e,streaming:!0,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1},toolCall:e.toolCall?{...e.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:e.toolCall}),n}markWebMcpToolComplete(e,n,o,r=Date.now(),s){this.messages.some(a=>a.id===e.id)&&this.upsertMessage({...e,streaming:!1,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1,...s},toolCall:e.toolCall?{...e.toolCall,status:"complete",result:n,startedAt:o,completedAt:r,duration:void 0,durationMs:Math.max(0,r-o)}:e.toolCall})}async resolveWebMcpToolCallBatch(e,n){let o=[],r=new AbortController;this.webMcpResolveControllers.add(r),this.setStreaming(!0);let s=async c=>{let p=c.toolCall?.name,u=c.toolCall?.id;if(!p||!u)return null;let m=`${e}:${u}`;if(this.webMcpInflightKeys.has(m)||this.webMcpResolvedKeys.has(m)||this.isSuggestRepliesAlreadyResolved(c))return null;this.webMcpInflightKeys.add(m),o.push(m);let g=this.markWebMcpToolRunning(c),h=c.agentMetadata?.webMcpToolCallId??p;if(p===As)return{dedupeKey:m,resumeKey:h,output:Sx(),toolMessage:c,startedAt:g,completedAt:Date.now()};let b=this.client.executeWebMcpToolCall(p,c.toolCall?.args,r.signal),C;if(!b)C={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{C=await b}catch(M){let E=M instanceof Error&&(M.name==="AbortError"||M.message.includes("aborted")||M.message.includes("abort"));return E||this.callbacks.onError?.(M instanceof Error?M:new Error(String(M))),this.markWebMcpToolComplete(c,ah(E?"Aborted by cancel()":eH(M)),g),this.webMcpInflightKeys.delete(m),null}return r.signal.aborted?(this.markWebMcpToolComplete(c,ah("Aborted by cancel()"),g),this.webMcpInflightKeys.delete(m),null):{dedupeKey:m,resumeKey:h,output:C,toolMessage:c,startedAt:g,completedAt:Date.now()}},a;if(this.config.webmcp?.execution==="sequential"){a=[];for(let c of n)a.push(await s(c))}else a=await Promise.all(n.map(s));let l=[];try{if(l=a.filter(m=>m!==null),l.length===0)return;let c={};for(let m of l)c[m.resumeKey]=m.output;let p=await this.client.resumeFlow(e,c,{signal:r.signal,after:this.resumable?.executionId===e?this.resumable.lastEventId:void 0});if(!p.ok){let m=await p.json().catch(()=>null);throw new Error(m?.error??`Resume failed: ${p.status}`)}let u=l[0].dedupeKey;for(let m of l){this.webMcpResolvedKeys.add(m.dedupeKey);let g=m.toolMessage.toolCall?.name,h=m.toolMessage.agentMetadata?.webMcpToolCallId;this.markWebMcpToolComplete(m.toolMessage,m.output,m.startedAt,m.completedAt,{...g===As?{suggestRepliesResolved:!0}:{},...g&&h?{clientToolAnswer:{toolCallId:h,toolName:g,args:m.toolMessage.toolCall?.args,result:m.output,batch:u}}:{}})}p.body&&await this.connectStream(p.body,{allowReentry:!0})}catch(c){if(!(c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"))))this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)));else for(let u of l)this.markWebMcpToolComplete(u.toolMessage,ah("Aborted by cancel()"),u.startedAt)}finally{for(let c of o)this.webMcpInflightKeys.delete(c);this.webMcpResolveControllers.delete(r),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(e){let n=e.agentMetadata?.executionId,o=e.toolCall?.name,r=e.toolCall?.id;if(!n){this.callbacks.onError?.(new Error("WebMCP await missing executionId: dispatch left paused."));return}if(!o)return;if(!r){let a=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(a)||this.webMcpResolvedKeys.has(a))return;this.webMcpInflightKeys.add(a);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(a)}catch(l){this.callbacks.onError?.(l instanceof Error?l:new Error(String(l)))}finally{this.webMcpInflightKeys.delete(a)}return}let s=`${n}:${r}`;if(!(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(e)))return this.resolveWebMcpToolCallBatch(n,[e])}async resumeWithToolOutput(e,n,o,r){let s=await this.client.resumeFlow(e,{[n]:o},{signal:r?.signal,after:this.resumable?.executionId===e?this.resumable.lastEventId:void 0});if(!s.ok){let a=await s.json().catch(()=>null);throw new Error(a?.error??`Resume failed: ${s.status}`)}r?.onHttpOk?.(),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let e of this.webMcpResolveControllers)e.abort();this.webMcpResolveControllers.clear();for(let e of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(e,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(e){this.selectedArtifactId=e,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(e){let n=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=e.artifactType==="markdown"?{id:n,artifactType:"markdown",title:e.title,status:"complete",markdown:e.content,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{}}:{id:n,artifactType:"component",title:e.title,status:"complete",component:e.component,props:e.props??{},...e.presentation?{presentation:e.presentation}:{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),e.transcript!==!1&&this.injectArtifactRefBlock(o),o}injectArtifactRefBlock(e){let n=`artifact-ref-${e.id}`,o=Cs(this.config.features?.artifacts,e),r=$l(o,{artifactId:e.id,title:e.title,artifactType:e.artifactType,status:"complete",...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{},...e.component?{component:e.component}:{},...e.props?{componentProps:e.props}:{},...e.markdown!==void 0?{markdown:e.markdown}:{}}),s=this.messages.find(a=>a.id===n);if(s){s.rawContent=r,s.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:n,content:"",rawContent:r})}refreshArtifactReferenceBlocks(){let e=!1;for(let n of this.artifacts.values()){let o=this.messages.find(a=>a.id===`artifact-ref-${n.id}`);if(!o)continue;let r=Cs(this.config.features?.artifacts,n),s=$l(r,{artifactId:n.id,title:n.title,artifactType:n.artifactType,status:n.status,...n.file?{file:n.file}:{},...n.presentation?{presentation:n.presentation}:{},...n.component?{component:n.component}:{},...n.props?{componentProps:n.props}:{},...n.markdown!==void 0?{markdown:n.markdown}:{}});o.rawContent!==s&&(o.rawContent=s,o.streaming=n.status==="streaming",e=!0)}e&&this.callbacks.onMessagesChanged([...this.messages])}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(e){switch(e.type){case"artifact_start":{e.artifactType==="markdown"?this.artifacts.set(e.id,{id:e.id,artifactType:"markdown",title:e.title,status:"streaming",markdown:"",...e.file?{file:e.file}:{}}):this.artifacts.set(e.id,{id:e.id,artifactType:"component",title:e.title,status:"streaming",component:e.component??"",props:{}}),this.selectedArtifactId=e.id;break}case"artifact_delta":{let n=this.artifacts.get(e.id);n?.artifactType==="markdown"&&(n.markdown=(n.markdown??"")+e.artDelta);break}case"artifact_update":{let n=this.artifacts.get(e.id);n?.artifactType==="component"&&(n.props={...n.props,...e.props},e.component&&(n.component=e.component));break}case"artifact_complete":{let n=this.artifacts.get(e.id);n&&(n.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(e){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(e.map(n=>({...n,streaming:!1,sequence:n.sequence??this.nextSequence()}))),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(e,n=null){this.artifacts.clear();for(let o of e)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}trackCursor(e){let n=this.agentExecution?.executionId;if(!n||!this.activeAssistantMessageId||this.agentExecution?.status!=="running")return;let o=this.resumable===null;this.resumable={executionId:n,lastEventId:e,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(o)}isDurableDrop(){return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(e=>e.agentMetadata?.awaitingLocalTool===!0&&e.agentMetadata?.askUserQuestionAnswered!==!0||e.variant==="approval"&&e.approval?.status==="pending")}beginReconnect(){this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.resumable}),this.setStreaming(!0),this.setStatus("resuming"),this.loadReconnectController().then(e=>{this.reconnecting&&this.resumable&&e.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=yS().then(({createReconnectController:e})=>{let n=e(this.buildReconnectHost());return this.reconnectController=n,n}),this.reconnectControllerPromise.catch(()=>{this.reconnectControllerPromise=null})),this.reconnectControllerPromise)}buildReconnectHost(){let e=this;return{get config(){return e.config},getResumable:()=>e.resumable,clearResumable:()=>e.clearResumable(),getStatus:()=>e.status,setStatus:n=>e.setStatus(n),setStreaming:n=>e.setStreaming(n),setReconnecting:n=>{e.reconnecting=n},setAbortController:n=>{e.abortController=n},getMessages:()=>e.messages,notifyMessagesChanged:()=>e.callbacks.onMessagesChanged([...e.messages]),resumeConnect:(n,o,r)=>e.connectStream(n,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:n=>e.appendMessage(n),nextSequence:()=>e.nextSequence(),emitReconnect:n=>e.callbacks.onReconnect?.(n),buildErrorContent:n=>ih(new Error(n),e.config.errorMessage),onError:n=>e.callbacks.onError?.(n)}}reconnectNow(){if(this.reconnecting){this.reconnectController?.wake();return}this.beginReconnect()}resumeFromHandle(e){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let n=this.reopenTrailingAssistant();n||(n=Ta(),this.appendMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=n,this.agentExecution||(this.agentExecution={executionId:e.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:e.executionId,lastEventId:e.after,assistantMessageId:n,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let e=this.messages.length-1;e>=0;e--){let n=this.messages[e];if(n.role==="assistant"&&!n.variant)return n.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),n.id;if(n.role==="user")break}return null}teardownReconnect(){this.reconnecting=!1,this.reconnectController?.teardown(),this.clearResumable()}clearResumable(){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let e=this.resumable!==null;this.resumable=null,e&&this.config.onExecutionState?.(null)}notifyExecutionState(e){let n=this.config.onExecutionState;if(n){if(e){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),n(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{this.executionStateTimer=null,this.config.onExecutionState?.(this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}setStreaming(e){if(this.streaming===e)return;let n=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),n&&!e&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let e=this.config.textToSpeech;if(!e?.enabled||!(!e.provider||e.provider==="browser"||e.provider==="runtype"&&e.browserFallback))return;let o=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let r=rh(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:e.voice,rate:e.rate,pitch:e.pitch})}static pickBestVoice(e){return Jg(e)}toggleReadAloud(e){let n=this.messages.find(s=>s.id===e);if(!n||n.role!=="assistant")return;let o=rh(n.content||"");if(!o.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(e,{text:o,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(e){return this.readAloud.stateFor(e)}onReadAloudChange(e){return this.readAloud.onChange(e)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(e){let n=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let n=this.ensureSequence(e),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((r,s)=>{if(s!==o)return r;let a={...r,...n};r.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(a.agentMetadata={...a.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1});let l=r.agentMetadata?.clientToolAnswer;if(l&&a.agentMetadata&&!a.agentMetadata.clientToolAnswer&&(a.agentMetadata={...a.agentMetadata,clientToolAnswer:l}),r.approval&&n.approval&&r.approval.id===n.approval.id){let m=r.approval,g=n.approval;a.approval={...m,...g,executionId:g.executionId||m.executionId,toolName:g.toolName||m.toolName,description:g.description||m.description,toolType:g.toolType??m.toolType,reason:g.reason??m.reason,parameters:g.parameters??m.parameters}}let c=n.toolCall?.name,p=n.agentMetadata?.executionId,u=n.toolCall?.id;if(c&&bS(c)&&p&&u&&n.agentMetadata?.awaitingLocalTool===!0){let m=`${p}:${u}`,g=this.webMcpInflightKeys.has(m),h=this.webMcpResolvedKeys.has(m),b=r.toolCall?.name,C=r.agentMetadata?.executionId===p&&r.toolCall?.id===u&&b!==void 0&&bS(b)&&r.toolCall?.status==="complete";(g||h||C)&&(a.agentMetadata={...a.agentMetadata??{},awaitingLocalTool:!1},a.toolCall=r.toolCall,a.streaming=r.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(e){return[...e].sort((n,o)=>{let r=new Date(n.createdAt).getTime(),s=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let a=n.sequence??0,l=o.sequence??0;return a!==l?a-l:n.id.localeCompare(o.id)})}};je();var Bo=require("lucide");zn();Zt();var tH={add:t=>_x(t)},nH=t=>Number.isFinite(t)?Math.min(1,Math.max(0,t)):0,Zp={allowedTypes:Ur,maxFileSize:10*1024*1024,maxFiles:4};function oH(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function rH(t){return t==="application/pdf"?Bo.FileText:t.startsWith("text/")?Bo.FileText:t.includes("word")?Bo.FileText:t.includes("excel")||t.includes("spreadsheet")?Bo.FileSpreadsheet:t==="application/json"?Bo.FileCode:Bo.File}var oc=class t{constructor(e={}){this.attachments=[];this.previewsContainer=null;this.pendingAdds=new Map;this.destroyed=!1;this.config={allowedTypes:e.allowedTypes??Zp.allowedTypes,maxFileSize:e.maxFileSize??Zp.maxFileSize,maxFiles:e.maxFiles??Zp.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange,adapter:e.adapter}}hasCustomAdapter(){return typeof this.config.adapter?.add=="function"}adapter(){return this.hasCustomAdapter()?this.config.adapter:tH}setPreviewsContainer(e){this.previewsContainer=e}remountPreviews(e){if(this.previewsContainer=e,e){e.innerHTML="";for(let n of this.attachments)this.renderPreview(n)}this.updatePreviewsVisibility()}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:Zp.allowedTypes),e.maxFileSize!==void 0&&(this.config.maxFileSize=e.maxFileSize),e.maxFiles!==void 0&&(this.config.maxFiles=e.maxFiles),e.onFileRejected!==void 0&&(this.config.onFileRejected=e.onFileRejected),e.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=e.onAttachmentsChange),e.adapter!==void 0&&(this.config.adapter=e.adapter)}isReady(){return this.attachments.every(e=>e.status==="ready")}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(e=>e.contentPart).filter(e=>e!==null)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(e){!e||e.length===0||await this.handleFiles(Array.from(e))}async handleFiles(e){if(!e.length||this.destroyed)return;let n=[];for(let o of e){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(o,"count");continue}let r=Nx(o,this.config.allowedTypes,this.config.maxFileSize);if(!r.valid){let a=r.error?.includes("type")?"type":"size";this.config.onFileRejected?.(o,a);continue}let s={id:oH(),file:o,previewUrl:qp(o)?URL.createObjectURL(o):null,contentPart:null,status:this.hasCustomAdapter()?"uploading":"processing",progress:this.hasCustomAdapter()?0:void 0};this.attachments.push(s),this.renderPreview(s),n.push(s)}this.updatePreviewsVisibility(),this.notify(),await Promise.all(n.map(o=>this.runAdd(o)))}async runAdd(e){let n=new AbortController;this.pendingAdds.set(e.id,n);let o=()=>this.destroyed||n.signal.aborted||this.pendingAdds.get(e.id)!==n||!this.attachments.includes(e);try{let r=await this.adapter().add(e.file,{signal:n.signal,onProgress:s=>{o()||e.status!=="uploading"||(e.progress=nH(s),this.updatePreview(e),this.notify())}});if(o())return;e.contentPart=r,e.status="ready",e.progress=void 0,e.error=void 0}catch(r){if(o())return;e.status="error",e.progress=void 0,e.error=r instanceof Error?r.message:String(r??"Upload failed")}finally{this.pendingAdds.get(e.id)===n&&this.pendingAdds.delete(e.id)}this.updatePreview(e),this.notify()}retryAttachment(e){let n=this.attachments.find(o=>o.id===e);!n||n.status!=="error"||this.destroyed||(n.status=this.hasCustomAdapter()?"uploading":"processing",n.progress=this.hasCustomAdapter()?0:void 0,n.error=void 0,this.updatePreview(n),this.notify(),this.runAdd(n))}abortAdd(e){let n=this.pendingAdds.get(e);n&&(this.pendingAdds.delete(e),n.abort())}removeAttachment(e){let n=this.attachments.findIndex(s=>s.id===e);if(n===-1)return;let o=this.attachments[n];this.abortAdd(e),o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let r=this.previewsContainer?.querySelector(`[data-attachment-id="${e}"]`);r&&r.remove(),o.status==="ready"&&o.contentPart&&this.releasePart(o.contentPart),this.updatePreviewsVisibility(),this.notify()}releasePart(e){let n=this.config.adapter?.remove;if(n)try{let o=n(e,{signal:new AbortController().signal});o&&typeof o.catch=="function"&&o.catch(r=>{console.error("[AttachmentManager] adapter.remove failed:",r)})}catch(o){console.error("[AttachmentManager] adapter.remove failed:",o)}}clearAttachments(){for(let e of this.attachments)this.abortAdd(e.id),e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.pendingAdds.clear(),this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),this.notify()}destroy(){if(!this.destroyed){this.destroyed=!0;for(let e of this.pendingAdds.values())e.abort();this.pendingAdds.clear();for(let e of this.attachments)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.previewsContainer=null}}notify(){this.destroyed||this.config.onAttachmentsChange?.(this.getAttachments())}renderPreview(e){if(!this.previewsContainer)return;let n=qp(e.file),o=v("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",e.id),o.style.width="48px",o.style.height="48px",n&&e.previewUrl){let u=v("img");u.src=e.previewUrl,u.alt=e.file.name,u.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",u.style.width="48px",u.style.height="48px",u.style.objectFit="cover",u.style.borderRadius="8px",o.appendChild(u)}else{let u=v("div");u.style.width="48px",u.style.height="48px",u.style.borderRadius="8px",u.style.backgroundColor="var(--persona-container, #f3f4f6)",u.style.border="1px solid var(--persona-border, #e5e7eb)",u.style.display="flex",u.style.flexDirection="column",u.style.alignItems="center",u.style.justifyContent="center",u.style.gap="2px",u.style.overflow="hidden";let m=rH(e.file.type),g=Ge(m,20,"var(--persona-muted, #6b7280)",1.5);g&&u.appendChild(g);let h=v("span");h.textContent=Fx(e.file.type,e.file.name),h.style.fontSize="8px",h.style.fontWeight="600",h.style.color="var(--persona-muted, #6b7280)",h.style.textTransform="uppercase",h.style.lineHeight="1",u.appendChild(h),o.appendChild(u)}let r=F("div",{className:"persona-attachment-status",attrs:{"data-persona-attachment-status":""}}),s=v("div","persona-attachment-progress");s.appendChild(v("div","persona-attachment-progress__bar"));let a=F("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),l=ke("rotate-cw",12,"var(--persona-text-inverse, #ffffff)",2);l?a.appendChild(l):a.textContent="\u21BB",a.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),this.retryAttachment(e.id)}),r.append(s,a),o.appendChild(r);let c=v("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");c.type="button",c.setAttribute("aria-label","Remove attachment"),c.style.position="absolute",c.style.top="-4px",c.style.insetInlineEnd="-4px",c.style.width="18px",c.style.height="18px",c.style.borderRadius="50%",c.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",c.style.border="none",c.style.cursor="pointer",c.style.display="flex",c.style.alignItems="center",c.style.justifyContent="center",c.style.padding="0";let p=Ge(Bo.X,10,"var(--persona-text-inverse, #ffffff)",2);p?c.appendChild(p):(c.textContent="\xD7",c.style.color="var(--persona-text-inverse, #ffffff)",c.style.fontSize="14px",c.style.lineHeight="1"),c.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),this.removeAttachment(e.id)}),o.appendChild(c),this.previewsContainer.appendChild(o),this.applyPreviewState(o,e)}updatePreview(e){let n=this.previewsContainer?.querySelector(`[data-attachment-id="${e.id}"]`);n&&this.applyPreviewState(n,e)}applyPreviewState(e,n){e.dataset.status=n.status;let o=n.status!=="ready"&&n.status!=="error";e.setAttribute("aria-busy",o?"true":"false"),e.title=n.status==="error"?`${n.file.name}: ${n.error??"Upload failed"}`:n.file.name;let r=e.querySelector(".persona-attachment-progress__bar");if(r){let s=n.progress;r.style.width=typeof s=="number"?`${Math.round(s*100)}%`:""}}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(e,n){return new t({allowedTypes:e?.allowedTypes,maxFileSize:e?.maxFileSize,maxFiles:e?.maxFiles,onFileRejected:e?.onFileRejected,onAttachmentsChange:n,adapter:e?.adapter})}};var vS=(t,e)=>t.length===e.length&&t.every((n,o)=>n===e[o]),sH=(t,e)=>t.length===e.length&&t.every((n,o)=>{let r=e[o];return n.id===r.id&&n.name===r.name&&n.mimeType===r.mimeType&&n.size===r.size&&n.status===r.status&&n.progress===r.progress&&n.error===r.error});function CS(){let t={text:"",attachments:[],mentionRefs:[],selectedModelId:void 0,activeModeIds:[],quote:void 0,pendingSubmission:void 0,preparing:!1,streaming:!1,inputDisabled:!1,sendDisabled:!1},e=new Set,n=null,o=!1,r=!1,s=()=>t.preparing?"preparing":t.streaming?"streaming":"idle",a=()=>{let u=s();return Object.freeze({text:t.text,attachments:Object.freeze(t.attachments.map(m=>Object.freeze({...m}))),mentionRefs:Object.freeze([...t.mentionRefs]),selectedModelId:t.selectedModelId,activeModeIds:Object.freeze([...t.activeModeIds]),quote:t.quote?Object.freeze({...t.quote}):void 0,pendingSubmission:t.pendingSubmission,phase:u,inputDisabled:t.inputDisabled,sendDisabled:u!=="idle"||t.sendDisabled||t.inputDisabled})},l=()=>(n||(n=a()),n),c=()=>{if(o=!1,r||e.size===0)return;let u=l();for(let m of[...e])try{m(u)}catch(g){typeof console<"u"&&console.error("[AgentWidget] composer state listener failed:",g)}},p=()=>{n=null,!(r||o)&&(o=!0,queueMicrotask(c))};return{getState:l,subscribe:u=>(e.add(u),()=>e.delete(u)),setText:u=>{t.text!==u&&(t.text=u,p())},setAttachments:u=>{sH(t.attachments,u)||(t.attachments=[...u],p())},setMentionRefs:u=>{vS(t.mentionRefs,u)||(t.mentionRefs=[...u],p())},setSelectedModelId:u=>{t.selectedModelId!==u&&(t.selectedModelId=u,p())},setActiveModeIds:u=>{vS(t.activeModeIds,u)||(t.activeModeIds=[...u],p())},setQuote:u=>{let m=t.quote;m?.text===u?.text&&m?.messageId===u?.messageId&&m?.sourceLabel===u?.sourceLabel||(t.quote=u?{...u}:void 0,p())},setPendingSubmission:u=>{t.pendingSubmission!==u&&(t.pendingSubmission=u,p())},setPreparing:u=>{t.preparing!==u&&(t.preparing=u,p())},setStreaming:u=>{t.streaming!==u&&(t.streaming=u,p())},setInputDisabled:u=>{t.inputDisabled!==u&&(t.inputDisabled=u,p())},setSendDisabled:u=>{t.sendDisabled!==u&&(t.sendDisabled=u,p())},flush:()=>{o&&c()},destroy:()=>{r=!0,o=!1,e.clear()}}}je();var io=(t,...e)=>{for(let n of e){let o=t.querySelector(n);if(o)return o}return null},wS=(t,e)=>{let n=v("div",t);return n.setAttribute(e,""),n.setAttribute("data-persona-composer-synthesized",""),n.style.display="contents",n};function xS(t,e={}){let n=io(t,"[data-persona-composer-form]"),o=io(t,"[data-persona-composer-input]");if(!n||!o){let E=`[Persona] composer surface is missing required element(s): ${[!n&&"form",!o&&"input"].filter(Boolean).join(", ")}. Mark them with data-persona-composer-form / data-persona-composer-input.`;if(e.debug&&(n||o))throw new Error(E);return typeof console<"u"&&console.warn(E),null}let r={header:io(t,"[data-persona-composer-header]"),body:io(t,"[data-persona-composer-body]"),actionsStart:io(t,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:io(t,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:io(t,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:io(t,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:io(t,"[data-persona-composer-status]")},s=new Set,a=r.header;a||(s.add("header"),a=wS("persona-widget-composer__header","data-persona-composer-header"),n.parentNode?n.parentNode.insertBefore(a,n):t.appendChild(a));let l=r.body??o.parentElement??n,c=(M,E,T,R,A)=>{if(E)return E;s.add(M);let D=wS(T,R);return A.appendChild(D),D},p=c("actionsStart",r.actionsStart,"persona-widget-composer__left-actions","data-persona-composer-actions-start",n),u=c("actionsEnd",r.actionsEnd,"persona-widget-composer__right-actions","data-persona-composer-actions-end",n),m=c("suggestions",r.suggestions,"persona-widget-composer__suggestions","data-persona-composer-suggestions",t),g=c("status",r.status,"persona-widget-composer__status","data-persona-composer-status",t),h=[],b=(M,E)=>M.target===E.target&&M.type===E.type&&M.handler===E.handler,C=io(t,"[data-persona-composer-attachment-input]",'input[type="file"]')??void 0;return{footer:t,form:n,input:o,header:a,body:l,actionsStart:p,actionsEnd:u,suggestions:m,status:g,attachmentInput:C,attachmentPreviews:io(t,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:io(t,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:io(t,"[data-persona-composer-submit]")??void 0,micButton:io(t,"[data-persona-composer-mic]")??void 0,synthesized:s,found:r,addListener:(M,E,T,R)=>{M.addEventListener(E,T,R),h.push({target:M,type:E,handler:T,options:R})},removeListener:(M,E,T,R)=>{M.removeEventListener(E,T,R),h=h.filter(A=>!b(A,{target:M,type:E,handler:T}))},destroy:()=>{for(let M of h)M.target.removeEventListener(M.type,M.handler,M.options);h=[]}}}je();Zt();ks();var iH=8,aH=8,lh=10,SS=200,AS=300,MS=0,tu=t=>Math.max(0,t);function TS(t){t.delayMs!==void 0&&(SS=tu(t.delayMs)),t.skipDelayMs!==void 0&&(AS=tu(t.skipDelayMs))}var lH=()=>Date.now()<MS,cH=t=>{MS=t>0?Date.now()+t:0},eu=new WeakMap,dh="data-persona-tooltip-suppressed",dH=t=>typeof t.closest=="function"&&t.closest(`[${dh}]`)!==null;function ES(t){eu.get(t)?.hide()}var kS=t=>t.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in t,pH=t=>{let e=t.getRootNode?.();return kS(e)?e:t.ownerDocument.body},ch=(t,e,n)=>Math.min(Math.max(t,e),Math.max(e,n)),uH=[...["background","foreground","hint-fg","radius","font-size","padding","max-width","shadow","arrow-display"].map(t=>`--persona-tooltip-${t}`),"--persona-font-family","--persona-radius-sm"];function In(t){eu.get(t.anchor)?.destroy();let{anchor:e,trigger:n=e,text:o,hint:r,enabled:s=!0,gap:a=iH,viewportPadding:l=aH}=t,c=()=>e.ownerDocument,p=()=>c().defaultView??window,u=null,m=null,g=null,h=null,b,C=!1,M=!1,E=!1,T=()=>(typeof o=="function"?o():o).trim(),R=()=>(typeof r=="function"?r():r??"").trim(),A=()=>tu(t.delayMs??SS),D=()=>tu(t.skipDelayMs??AS),W=()=>{b!==void 0&&(p().clearTimeout(b),b=void 0)},U=()=>{W();let oe=u!==null;h?.(),h=null,u?.remove(),u=null,m=null,g=null,oe&&cH(D())},B=()=>{if(!u)return;let oe=c(),ne=p(),le=e.getBoundingClientRect(),de=u.getBoundingClientRect(),ve=oe.documentElement.clientWidth||ne.innerWidth,Le=oe.documentElement.clientHeight||ne.innerHeight,se=ve-l-de.width,_=le.left+le.width/2-de.width/2,Te=ch(_,l,se),Re=le.top-l,ut=Le-l-le.bottom,At=de.height+a,Wt=Re>=At||Re>=ut?"top":"bottom",bt=Wt==="top"?le.top-a-de.height:le.bottom+a,xe=Le-l-de.height,Ne=ch(bt,l,xe),Ae=le.left+le.width/2,vt=Math.max(lh,de.width-lh),X=ch(Ae-Te,lh,vt);u.dataset.placement=Wt,u.style.left=`${Te}px`,u.style.top=`${Ne}px`,u.style.setProperty("--persona-tooltip-arrow-x",`${X}px`)},O=()=>{if(E||!s||u||!e.isConnected||dH(e))return;let oe=T(),ne=pH(e);if(!oe||!ne)return;let le=c(),de=p();u=le.createElement("div"),u.className="persona-control-tooltip",u.setAttribute("role","tooltip"),u.dataset.state="measuring",u.style.zIndex=String(Ba);let ve=de.getComputedStyle?.(e);if(ve){for(let At of uH){let Wt=ve.getPropertyValue(At).trim();Wt&&u.style.setProperty(At,Wt)}ve.fontFamily&&(u.style.fontFamily=ve.fontFamily)}m=le.createElement("span"),m.className="persona-control-tooltip__label",m.textContent=oe,u.appendChild(m);let Le=R();Le&&(g=le.createElement("span"),g.className="persona-control-tooltip__hint",g.textContent=Le,u.appendChild(g));let se=le.createElement("span");se.className="persona-control-tooltip__arrow",u.appendChild(se),ne.appendChild(u),B(),u.dataset.state="open";let _=()=>{if(!e.isConnected){U();return}m&&(m.textContent=T()),g&&(g.textContent=R()),B()};de.addEventListener("scroll",_,!0),de.addEventListener("resize",_);let Te=e.getRootNode(),Re=kS(Te)?Te:le.documentElement,ut=typeof MutationObserver>"u"?null:new MutationObserver(()=>{e.isConnected||U()});ut?.observe(Re,{childList:!0,subtree:!0}),h=()=>{de.removeEventListener("scroll",_,!0),de.removeEventListener("resize",_),ut?.disconnect()}},H=oe=>{if(!(E||u)){if(W(),oe||A()<=0||lH()){O();return}b=p().setTimeout(()=>{b=void 0,O()},A())}},S=()=>{C||M?H(M):U()},x=()=>{let oe=p();(!oe.matchMedia||!oe.matchMedia("(hover: none)").matches)&&(C=!0,S())},P=()=>{C=!1,S()},L=()=>{try{M=e.matches(":focus-visible")}catch{M=!0}S()},G=()=>{M=!1,S()},V=()=>{C=!1,M=!1,U()},K=oe=>{oe.key==="Escape"&&V()};n.addEventListener("mouseenter",x),n.addEventListener("mouseleave",P),e.addEventListener("focus",L),e.addEventListener("blur",G),e.addEventListener("keydown",K),e.addEventListener("click",V);let ee={get isOpen(){return u!==null},show:O,hide:U,reposition:B,destroy:()=>{E||(E=!0,U(),n.removeEventListener("mouseenter",x),n.removeEventListener("mouseleave",P),e.removeEventListener("focus",L),e.removeEventListener("blur",G),e.removeEventListener("keydown",K),e.removeEventListener("click",V),eu.delete(e))}};return eu.set(e,ee),ee}je();Zt();function ph(t){let e=t.ownerDocument?.defaultView;if(!e?.getComputedStyle)return 20;let n=e.getComputedStyle(t).lineHeight;if(!n||!n.trim().endsWith("px"))return 20;let o=parseFloat(n);return Number.isFinite(o)&&o>0?o:20}function nu(t,e){return typeof t!="number"||!Number.isFinite(t)?e:t>0?t:e}function PS(t,e){t.style.maxHeight=`${e*ph(t)}px`,t.style.overflowY="auto"}function rc(t){let e=t?.ownerDocument?.defaultView??(typeof window<"u"?window:null);if(!e||typeof e.matchMedia!="function")return!1;try{return e.matchMedia("(pointer: coarse)").matches===!0}catch{return!1}}function LS(t){return t.insertNewlineOnTouchEnter===!0&&t.coarsePointer===!0}function IS(t,e){if(t.key!=="Enter"||t.shiftKey||t.isComposing)return!1;let n=t.metaKey===!0||t.ctrlKey===!0,o=e.submitKey??"enter";return o==="none"?!1:o==="mod-enter"?n:n||!LS(e)}function mH(t){return(t.submitKey??"enter")!=="enter"||LS(t)?"enter":"send"}function ou(t,e){t.setAttribute("enterkeyhint",mH(e))}function ru(t,e){let n=e?.autocomplete;t.setAttribute("autocomplete",typeof n=="string"&&n?n:"off");let o=(r,s)=>{s===void 0?t.removeAttribute(r):t.setAttribute(r,s)};o("autocapitalize",typeof e?.autocapitalize=="string"?e.autocapitalize:void 0),o("spellcheck",typeof e?.spellcheck=="boolean"?String(e.spellcheck):void 0),o("inputmode",typeof e?.inputmode=="string"&&e.inputmode?e.inputmode:void 0),o("aria-label",typeof e?.ariaLabel=="string"&&e.ariaLabel?e.ariaLabel:void 0)}function uh(t){return t===!0?{disabled:!0}:!t||typeof t!="object"?{disabled:!1}:{disabled:!0,reason:typeof t.reason=="string"&&t.reason?t.reason:void 0}}var yo="persona-composer-control",Go="persona-composer-control--glyph",fh=40,qn=24,su=(t,e,n)=>{let o=t.ownerDocument?.defaultView;if(!o)return;let r=o.getComputedStyle(t);for(let s of n){let a=r.getPropertyValue(s).trim();a?e.style.setProperty(s,a):e.style.removeProperty(s)}},iu=(t,e)=>{let n=v("textarea");n.setAttribute("data-persona-composer-input",""),n.placeholder=t?.copy?.inputPlaceholder??Ag,n.dir="auto",ou(n,{submitKey:t?.composer?.submitKey,insertNewlineOnTouchEnter:t?.composer?.insertNewlineOnTouchEnter,coarsePointer:rc(n)}),ru(n,t?.composer?.inputAttributes),n.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-text focus:persona-outline-none focus:persona-border-none persona-composer-textarea",n.rows=1,n.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',n.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let o=nu(t?.composer?.maxLines,e?.defaultMaxLines??3),r=`${o*20}px`;n.style.maxHeight=r,n.style.overflowY="auto";let s=()=>{let l=n.style.maxHeight;if(l!==r){let p=parseFloat(l);if(Number.isFinite(p)&&p>0)return p}let c=o*ph(n);return r=`${c}px`,n.style.maxHeight=r,c},a=()=>{n.addEventListener("input",()=>{n.style.height="auto";let l=Math.min(n.scrollHeight,s());n.style.height=`${l}px`})};return n.style.border="none",n.style.outline="none",n.style.borderWidth="0",n.style.borderStyle="none",n.style.borderColor="transparent",n.addEventListener("focus",()=>{n.style.border="none",n.style.outline="none",n.style.borderWidth="0",n.style.borderStyle="none",n.style.borderColor="transparent",n.style.boxShadow="none"}),n.addEventListener("blur",()=>{n.style.border="none",n.style.outline="none"}),{textarea:n,attachAutoResize:a}},gH="[data-persona-glyph-stack]",gh=(t,e,n="send")=>{let o=F("span",{className:"persona-composer-glyph-stack",attrs:{"data-mode":n,"data-persona-glyph-stack":""}});return t.setAttribute("data-glyph","send"),e.setAttribute("data-glyph","stop"),o.append(t,e),o},au=t=>{let e=t?.sendButton??{},n=e.useIcon??!1,o=e.iconText??"\u2191",r=e.iconName,s=e.stopIconName??"square",a=e.tooltipText??"Send message",l=e.stopTooltipText??"Stop generating",c=t?.copy?.sendButtonLabel??"Send",p=t?.copy?.stopButtonLabel??"Stop",u=e.showTooltip??!1,m=e.size,g=parseFloat(m??"")||fh,h=e.backgroundColor,b=e.textColor,C=v("div","persona-send-button-wrapper"),M=F("button",{className:Gt("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?`persona-flex persona-items-center persona-justify-center ${yo}`:"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!h&&"persona-bg-persona-primary",!n&&!b&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":"","data-persona-send-mode":"send"},style:{width:n?m:void 0,height:n?m:void 0,minWidth:n?m:void 0,minHeight:n?m:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?b||"var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))":b||void 0,backgroundColor:n&&h||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:n?"0":e.paddingX||void 0,paddingRight:n?"0":e.paddingX||void 0,paddingTop:n?"0":e.paddingY||void 0,paddingBottom:n?"0":e.paddingY||void 0}}),E=null,T=null,R=null;if(n){let W=parseFloat(e.iconSize??"")||Math.round(g*.5),U=e.iconStrokeWidth??2,B=b?.trim()||"currentColor";if(r&&(E=ke(r,W,B,U)),T=ke(s,W,B,U),!e.iconSize)for(let O of[E,T])O&&(O.style.width=`var(--persona-components-composer-sendIconSize, ${W}px)`,O.style.height=`var(--persona-components-composer-sendIconSize, ${W}px)`);E&&T?(R=gh(E,T),M.appendChild(R)):E?M.appendChild(E):(M.textContent=o,T=null)}else M.textContent=c;M.setAttribute("aria-label",a),C.appendChild(M),In({anchor:M,trigger:C,text:()=>M.getAttribute("aria-label")??"",enabled:u});let A="send";return{button:M,wrapper:C,setMode:W=>{if(W===A)return;A=W;let U=W==="stop"?l:a;M.setAttribute("aria-label",U),M.setAttribute("data-persona-send-mode",W),n?(M.querySelector(gH)??R)?.setAttribute("data-mode",W):M.textContent=W==="stop"?p:c},glyphStack:R}},Da=t=>{let e=t?.voiceRecognition??{};if(!(e.enabled===!0))return null;let o=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),r=e.provider?.type==="runtype",s=e.provider?.type==="custom";if(!(o||r||s))return null;let l=e.iconName??"mic",c=e.iconSize,p=parseFloat(c??"")||qn,u=e.backgroundColor??t?.sendButton?.backgroundColor,m=e.iconColor??t?.sendButton?.textColor,g=v("div","persona-send-button-wrapper"),h=F("button",{className:Gt("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",yo,!c&&Go),attrs:{type:"button","data-persona-composer-mic":"","data-state":"idle","aria-label":e.tooltipText??"Start voice recognition"},style:{width:c,height:c,minWidth:c,minHeight:c,fontSize:"18px",lineHeight:"1",color:m||"var(--persona-text, #111827)",backgroundColor:u||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:e.paddingX||void 0,paddingRight:e.paddingX||void 0,paddingTop:e.paddingY||void 0,paddingBottom:e.paddingY||void 0}}),C=ke(l,p,m||"currentColor",1.5);C?h.appendChild(C):h.textContent="\u{1F3A4}",g.appendChild(h);let M=e.tooltipText??"Start voice recognition",E=e.showTooltip??!1;return In({anchor:h,trigger:g,text:()=>h.getAttribute("aria-label")??M,enabled:E}),{button:h,wrapper:g}},lu=t=>{let e=t?.attachments??{};if(e.enabled!==!0)return null;let n=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");n.setAttribute("data-persona-composer-attachment-previews",""),n.style.display="none";let o=v("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=(e.allowedTypes??Ur).join(","),o.multiple=(e.maxFiles??4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let r=e.buttonIconName??"paperclip",s=v("div","persona-send-button-wrapper"),a=F("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${yo} ${Go}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":e.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),l=ke(r,qn,"currentColor",1.5);l?a.appendChild(l):a.textContent="\u{1F4CE}",a.addEventListener("click",p=>{p.preventDefault(),o.click()}),s.appendChild(a);let c=e.buttonTooltipText??"Attach file";return In({anchor:a,trigger:s,text:()=>a.getAttribute("aria-label")??c}),{button:a,wrapper:s,input:o,previewsContainer:n}},cu=t=>{let e=t?.statusIndicator??{},n=e.align==="left"?"persona-text-left":e.align==="center"?"persona-text-center":"persona-text-right",o=v("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status",""),xi(o,e,"idle");let r=e.idleText??"Online";if(e.idleLink){let s=v("a");s.href=e.idleLink,s.target="_blank",s.rel="noopener noreferrer",s.textContent=r,s.style.color="inherit",s.style.textDecoration="none",o.appendChild(s)}else o.textContent=r;return o},du=()=>F("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});Oa();je();Zt();var yH='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',bH=["--persona-components-composer-overflowMenu-background","--persona-components-composer-overflowMenu-borderColor","--persona-components-composer-overflowMenu-borderRadius","--persona-components-composer-overflowMenu-foreground","--persona-components-composer-overflowMenu-shadow"],hh="data-persona-menu-focus",vH=new Set(["ArrowDown","ArrowUp","Home","End"]);function BS(t){return t.getAttribute("role")==="menuitem"?t:t.querySelector(yH)??t}var CH=t=>t.disabled===!0||t.getAttribute("aria-disabled")==="true";function DS(t){let e=t.label,n=!1,o=v("div","persona-send-button-wrapper"),r=F("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${yo} ${Go}`,attrs:{type:"button","aria-haspopup":"menu","aria-expanded":"false","data-persona-composer-overflow-trigger":""}});o.appendChild(r);let s=F("div",{className:"persona-composer-overflow-menu",attrs:{role:"menu",tabindex:"-1","data-persona-composer-overflow-menu":""}}),a=()=>{let L=t.getButtonSize?.()??"";r.style.width=L,r.style.height=L,r.style.minWidth=L,r.style.minHeight=L,r.style.lineHeight="1",r.replaceChildren();let G=ke("plus",qn,"currentColor",1.5);G?r.appendChild(G):r.textContent="+"},l=()=>{r.setAttribute("aria-label",e),r.setAttribute("title",e),s.setAttribute("aria-label",e)};l(),a();let c=[],p=-1,u=!1,m=()=>{let G=s.getRootNode().activeElement;return G instanceof HTMLElement?G:null},g=()=>{let L=m();for(let G of c){let V=!!L&&BS(G)===L;G.toggleAttribute(hh,V&&u)}},h=()=>c.filter(L=>L.isConnected||s.contains(L)).map(BS).filter(L=>!CH(L)),b=(L,G)=>{L.forEach((V,K)=>{V.setAttribute("tabindex",K===G?"0":"-1")})},C=L=>{let G=h();if(G.length===0)return;let V=(L%G.length+G.length)%G.length;p=V,b(G,V),G[V].focus(),g()},M=()=>o.ownerDocument??document,E=null,T=null,R=null,A=()=>{E&&(M().removeEventListener("focusin",E,!0),E=null)},D=()=>{T&&(s.removeEventListener("focusin",T),T=null),R&&(s.removeEventListener("pointerdown",R,!0),R=null)},W=null,U=()=>(W||(W=Ps({anchor:r,content:s,placement:"top-start",offset:6,onDismiss:()=>{r.setAttribute("aria-expanded","false"),A()}})),W),B=()=>W?.isOpen===!0,O=(L=!1)=>{if(B()){W?.close(),r.setAttribute("aria-expanded","false"),A(),D(),p=-1,u=!1;for(let G of c)G.removeAttribute(hh);L&&r.focus()}},H=(L=0,G=!1)=>{if(n||B())return;u=G,su(r,s,bH),U().open(),r.setAttribute("aria-expanded","true");let V=h();b(V,-1),C(L<0?V.length-1:L),E=K=>{let ee=typeof K.composedPath=="function"?K.composedPath():[];ee.includes(s)||ee.includes(o)||O()},M().addEventListener("focusin",E,!0),T=()=>g(),s.addEventListener("focusin",T),R=()=>{u=!1},s.addEventListener("pointerdown",R,!0)},S=L=>{L.preventDefault(),L.stopPropagation(),B()?O(!0):H(0)},x=L=>{if(L.key==="ArrowDown"||L.key==="Enter"||L.key===" "){L.preventDefault(),u=!0,B()?C(0):H(0,!0);return}L.key==="ArrowUp"&&(L.preventDefault(),u=!0,B()?C(-1):H(-1,!0))},P=L=>{switch(vH.has(L.key)&&(u=!0),L.key){case"ArrowDown":L.preventDefault(),C(p+1);return;case"ArrowUp":L.preventDefault(),C(p-1);return;case"Home":L.preventDefault(),C(0);return;case"End":L.preventDefault(),C(h().length-1);return;case"Escape":L.preventDefault(),L.stopPropagation(),O(!0);return;case"Tab":O(!0);return;default:}};return r.addEventListener("click",S),r.addEventListener("keydown",x),s.addEventListener("keydown",P),{trigger:o,triggerButton:r,panel:s,setItems:L=>{for(let V of c)L.includes(V)||V.removeAttribute(hh);if(c=[...L],!B())return;let G=h();b(G,Math.min(p,G.length-1)),g()},isOpen:B,open:()=>H(0),close:O,setLabel:L=>{L!==e&&(e=L,l())},applyButtonSize:a,destroy:()=>{n=!0,A(),D(),r.removeEventListener("click",S),r.removeEventListener("keydown",x),s.removeEventListener("keydown",P),W?.destroy(),W=null,o.remove(),s.remove(),c=[]}}}var yr={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},OS="data-persona-composer-action",yh="data-persona-composer-disable-when-streaming",wH="core:overflow",xH=t=>t==="core:attachment"?"attachments":t.startsWith("core:mention")?"mentions":null;function SH(t,e){if(t===void 0)return null;if(typeof t=="number")return Number.isFinite(t)?t:null;let n=Number.parseFloat(t);if(/^\s*-?\d*\.?\d+(px)?\s*$/.test(t)&&Number.isFinite(n))return n;let o=v("div");o.style.position="absolute",o.style.visibility="hidden",o.style.pointerEvents="none",o.style.height="0",o.style.width=t,e.appendChild(o);let r=o.getBoundingClientRect().width;return o.remove(),Number.isFinite(r)&&r>0?r:Number.isFinite(n)?n:null}function bh(t){let e=t.clientWidth;if(!e)return 0;let n=t.ownerDocument?.defaultView;if(!n?.getComputedStyle)return e;let o=n.getComputedStyle(t),r=(Number.parseFloat(o.paddingLeft)||0)+(Number.parseFloat(o.paddingRight)||0);return Math.max(0,e-r)}var _S=(t,e)=>{!t||typeof console>"u"||console.warn(e)},AH=(t,e)=>e.includes(":")?e:`${t}:${e}`;function MH(t){let{debug:e}=t,n=[],o=new Map,r=0,s=l=>{let c=o.get(l.id);if(c){_S(e,`[Persona] composer action "${l.id}" is already contributed by ${NS(c)}; the ${NS(l)} copy is ignored.`);return}o.set(l.id,l),n.push(l)};for(let l of t.builtIns)s({id:l.id,placement:l.placement,presentation:"bar",order:l.order,sequence:r++,source:"core",builtIn:l});let a=(l,c,p)=>{let u=p?AH(p,l.id):l.id,m=l.order??yr.custom;l.placement==="end"&&m>=yr.send&&(_S(e,`[Persona] composer action "${u}" ordered at ${m} would render after send; clamped to ${yr.send-1}.`),m=yr.send-1),s({id:u,placement:l.placement,presentation:l.presentation??"bar",order:m,sequence:r++,source:c,pluginId:p,action:l})};for(let l of t.configActions??[])a(l,"config");for(let l of t.plugins){if(!l.contributeComposerActions)continue;let c;try{c=l.contributeComposerActions(t.contributionContext)}catch(p){typeof console<"u"&&console.error(`[Persona] plugin "${l.id}" contributeComposerActions failed:`,p);continue}for(let p of c??[])a(p,"plugin",l.id)}return n.sort((l,c)=>l.order===c.order?l.sequence-c.sequence:l.order-c.order)}var NS=t=>t.source==="plugin"?`plugin "${t.pluginId}"`:t.source==="config"?"composer.actions":"a core built-in",FS=(t,e,n)=>t===void 0?n:typeof t=="function"?t(e)===!0:t===!0,TH=t=>t.phase==="streaming"||t.text.trim().length>0||t.attachments.length>0;function EH(t,e){if(!t||t==="always")return!0;let n=TH(e);return t==="when-text"?n:!n}var Ls=t=>t.kind==="custom",vh=t=>t instanceof HTMLButtonElement?t:t.querySelector("button")??t,kH=t=>{let e=vh(t);return e.getAttribute("aria-label")?.trim()||e.getAttribute("title")?.trim()||""},PH='.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]';function LH(t){let e="",n=o=>{if(o.nodeType===Node.TEXT_NODE){e+=o.nodeValue??"";return}if(o.nodeType!==Node.ELEMENT_NODE)return;let r=o;typeof r.matches=="function"&&r.matches(PH)||o.childNodes.forEach(n)};return n(t),e.trim()}var IH=t=>LH(t).length===0;function VS(t){let e=new Map,n=[],o=!1,r=()=>t.getButtonSize?.(),s=(S,x)=>{let P=S.button;if(!P)return;P.setAttribute("role","menuitem"),P.setAttribute("tabindex","-1"),P.className="persona-composer-overflow-menu__item";for(let V of["width","height","minWidth","minHeight","fontSize","color","backgroundColor"])P.style[V]="";P.style.lineHeight="1",x.tooltipText?P.setAttribute("title",x.tooltipText):P.removeAttribute("title"),P.replaceChildren();let L=v("span","persona-composer-overflow-menu__icon");if(x.iconName){let V=ke(x.iconName,16,"currentColor",1.5);V&&L.appendChild(V)}let G=v("span","persona-composer-overflow-menu__label");G.textContent=x.shortLabel??x.label,P.append(L,G)},a=(S,x)=>{let P=S.button;if(!P)return;if(P.setAttribute("aria-label",x.label),x.pressed===void 0?P.removeAttribute("aria-pressed"):P.setAttribute("aria-pressed",x.pressed?"true":"false"),P.toggleAttribute(yh,x.disableWhenStreaming===!0),S.mode==="menu"){S.tooltip?.destroy(),S.tooltip=void 0,s(S,x);return}P.removeAttribute("role"),P.removeAttribute("tabindex"),P.removeAttribute("title");let L=r(),G=!!x.shortLabel;if(P.className=Gt("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",yo,Go,G&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),P.style.width=L&&!G?L:"",P.style.height=L??"",P.style.minWidth=L&&!G?L:"",P.style.minHeight=L??"",P.style.fontSize=G?"":"18px",P.style.lineHeight="1",P.style.color=x.iconColor??"",P.style.backgroundColor=x.backgroundColor??"",P.replaceChildren(),x.iconName){let V=ke(x.iconName,qn,"currentColor",1.5);V&&P.appendChild(V)}if(G){let V=v("span","persona-composer-action-button__label");V.textContent=x.shortLabel,P.appendChild(V)}else P.firstChild||(P.textContent=x.label);S.tooltip?.destroy(),S.tooltip=In({anchor:P,trigger:S.element,text:()=>x.tooltipText??x.label,enabled:!!x.tooltipText})},l=(S,x)=>{let P=S.action,L=F("button",{attrs:{type:"button"}}),G=L;if(x==="bar"){let ee=v("div","persona-send-button-wrapper");ee.appendChild(L),G=ee}G.setAttribute(OS,S.id);let V={resolved:S,element:G,button:L,owned:!0,managed:!0,busy:!1,visible:!0,mode:x},K=ee=>{if(ee.preventDefault(),ee.stopPropagation(),V.busy||L.disabled)return;let oe=V.resolved.action;V.mode==="menu"&&h?.close(!0);let ne;try{ne=oe.onSelect(t.actionContext,ee)}catch(le){t.reportError(le,{actionId:V.resolved.id});return}!ne||typeof ne.then!="function"||(V.busy=!0,L.setAttribute("aria-busy","true"),ne.catch(le=>{t.reportError(le,{actionId:V.resolved.id})}).finally(()=>{V.busy=!1,L.removeAttribute("aria-busy")}))};return L.addEventListener("click",K),V.detach=()=>L.removeEventListener("click",K),a(V,P),V},c=S=>{let x=S.action,P;try{P=x.render({...t.actionContext,id:S.id,action:x})}catch(L){return t.reportError(L,{actionId:S.id}),null}return P?.element?(P.element.setAttribute(OS,S.id),P.element.toggleAttribute(yh,x.disableWhenStreaming===!0),{resolved:S,element:P.element,owned:!0,managed:!0,destroy:P.destroy,busy:!1,visible:!0,mode:"bar"}):null},p=(S,x)=>{if(S.builtIn){let L=S.builtIn.element;return L?{resolved:S,element:L,owned:!1,managed:S.builtIn.managed===!0,busy:!1,visible:!0,mode:"bar"}:null}let P=S.action;return P?Ls(P)?c(S):l(S,x):null},u=S=>{if(S.detach?.(),S.tooltip?.destroy(),S.detachMenuSlot?.(),S.detachMenuSlot=void 0,S.menuLabel?.remove(),S.menuLabel=void 0,S.menuSlot?.remove(),S.menuSlot=void 0,S.owned){try{S.destroy?.()}catch(x){t.reportError(x,{actionId:S.resolved.id})}S.element.remove()}},m=(S,x)=>{for(let P=0;P<x.length;P++){let L=x[P];if(!L.managed)continue;let G=null;for(let V=P+1;V<x.length;V++){let K=x[V];if(!K.managed&&K.element.parentElement===S){G=K.element;break}}G?(L.element.parentElement!==S||L.element.nextSibling!==G)&&S.insertBefore(L.element,G):S.lastChild!==L.element&&S.appendChild(L.element)}},g=(S,x)=>{if(S.button){S.button.disabled=x;return}if(!S.owned)return;let P=S.element;P.toggleAttribute("data-disabled",x),P.setAttribute("aria-disabled",x?"true":"false");let L=P instanceof HTMLButtonElement||P instanceof HTMLSelectElement||P instanceof HTMLInputElement||P instanceof HTMLTextAreaElement?P:P.querySelector("button, select, input, textarea");L&&(L.disabled=x)},h=null,b=null,C=null,M=0,E=()=>{let S=t.getOverflow?.();return S?.enabled===!0?S:void 0},T=()=>(h?h.setLabel(t.getOverflowLabel?.()??"More actions"):h=DS({label:t.getOverflowLabel?.()??"More actions",getButtonSize:r}),h),R=S=>{b!==S&&(C?.disconnect(),b=S,M=bh(S),!(typeof ResizeObserver>"u")&&(C=new ResizeObserver(x=>{let L=x[x.length-1]?.contentRect?.width??bh(S);L!==M&&(M=L,O())}),C.observe(S)))},A=(S,x)=>{let P=SH(S.collapseAutoActionsBelow,x);if(P===null)return!1;let L=M||bh(x);return L>0&&L<P},D=(S,x,P)=>{if(!x)return"bar";if(S.resolved.builtIn){let G=xH(S.resolved.id);return G&&x.includeBuiltIns?.includes(G)?"menu":"bar"}let L=S.resolved.presentation;return L==="overflow"||L==="auto"&&P?"menu":"bar"},W=S=>{let x=S.menuSlot;if(!x)return;if(!IH(S.element)){S.menuLabel?.remove(),S.menuLabel=void 0;return}let P=kH(S.element);if(!P){S.menuLabel?.remove(),S.menuLabel=void 0;return}S.menuLabel||(S.menuLabel=v("span","persona-composer-overflow-menu__label")),S.menuLabel.textContent!==P&&(S.menuLabel.textContent=P),S.menuLabel.parentElement!==x&&x.appendChild(S.menuLabel)},U=(S,x)=>{if(S.mode===x)return S;let P=S.resolved.action;if(P&&!Ls(P)){u(S),e.delete(S.resolved.id);let L=l(S.resolved,x);return e.set(S.resolved.id,L),L}if(x==="menu"){let L=F("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none",[dh]:""}});L.appendChild(S.element),ES(vh(S.element)),S.menuSlot=L;let G=V=>{let K=vh(S.element);if(K.disabled)return;let ee=V.target===K||K.contains(V.target);h?.close(!0),ee||K.click()};L.addEventListener("click",G,!0),S.detachMenuSlot=()=>L.removeEventListener("click",G,!0),S.managed=!0,W(S)}else S.detachMenuSlot?.(),S.detachMenuSlot=void 0,S.menuLabel?.remove(),S.menuLabel=void 0,S.menuSlot?.remove(),S.menuSlot=void 0;return S.mode=x,S},B=(S,x)=>{let P=x.map(L=>L.menuSlot??L.element);for(P.forEach((L,G)=>{let V=S.children[G];V!==L&&(V?S.insertBefore(L,V):S.appendChild(L))});S.children.length>P.length;)S.lastElementChild?.remove()},O=()=>{if(o)return;let S=t.getBindings();if(!S)return;let x=t.getState(),P=x.phase==="streaming",L=E();L&&R(S.footer);let G=L?A(L,S.footer):!1,V={start:[],end:[]},K=[];for(let ee of n){let oe=e.get(ee.id);if(!oe)continue;let ne=ee.action,le=ne?FS(ne.visible,x,!0)&&EH(ne.visibility,x):!0;if(oe.visible!==le&&(oe.visible=le,!le&&oe.managed&&(oe.menuSlot??oe.element).remove()),!!le){if(oe=U(oe,D(oe,L,G)),ne){let de=FS(ne.disabled,x,!1)||ne.disableWhenStreaming===!0&&P;g(oe,de),!Ls(ne)&&ne.pressed!==void 0&&oe.button?.setAttribute("aria-pressed",ne.pressed?"true":"false")}oe.mode==="menu"?(W(oe),K.push(oe)):V[ee.placement].push(oe)}}if(K.length>0){let ee=T();B(ee.panel,K),ee.setItems(K.map(de=>de.menuSlot??de.element)),ee.applyButtonSize();let oe=Number.isFinite(L?.order)?L?.order:yr.overflow,ne=V.start.findIndex(de=>de.resolved.order>oe),le={resolved:{id:wH,placement:"start",presentation:"bar",order:oe,sequence:-1,source:"core"},element:ee.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};V.start.splice(ne<0?V.start.length:ne,0,le)}else h&&(h.close(),h.trigger.remove(),h.setItems([]));m(S.actionsStart,V.start),m(S.actionsEnd,V.end)};return{resolve:()=>{if(o)return;let S=MH(t.collect()),x=new Set(S.map(P=>P.id));for(let[P,L]of e)x.has(P)||(u(L),e.delete(P));for(let P of S){let L=e.get(P.id);if(!L){let ee=p(P,"bar");ee&&e.set(P.id,ee);continue}let G=L.resolved.action,V=P.action;if(!!G!=!!V||G&&V&&Ls(G)!==Ls(V)||G&&V&&Ls(G)&&Ls(V)&&G.render!==V.render){u(L),e.delete(P.id);let ee=p(P,L.mode);ee&&e.set(P.id,ee);continue}L.resolved=P,P.builtIn?(L.managed=P.builtIn.managed===!0||L.mode==="menu",P.builtIn.element&&L.mode==="bar"&&(L.element=P.builtIn.element)):V&&!Ls(V)?a(L,V):V&&L.element.toggleAttribute(yh,V.disableWhenStreaming===!0)}n=S,O()},sync:O,getResolved:()=>n,getOverflowMenu:()=>h,destroy:()=>{if(!o){o=!0,C?.disconnect(),C=null,b=null;for(let S of e.values())u(S);e.clear(),h?.destroy(),h=null,n=[]}}}}Oa();je();Zt();var HH="core:model",RH=700,$S=16,WH=["--persona-components-composer-modelPicker-menuBackground","--persona-components-composer-modelPicker-menuBorderRadius","--persona-components-composer-modelPicker-rowHoverBackground","--persona-components-composer-modelPicker-labelColor","--persona-components-composer-modelPicker-descriptionColor"],zS=()=>{let t=F("span",{className:"persona-composer-model-picker-wrapper",attrs:{"data-persona-composer-model-picker-wrapper":""}}),e=F("span",{className:"persona-composer-model-picker-chevron",attrs:{"aria-hidden":"true"}});return{wrapper:t,chevron:e}};function US(t){let e=t.label??"Model",n=t.presentation??"native",o=null,r=c=>{let p=t.getSelectedModelId();return c.find(u=>u.id===p)??c[0]},s=()=>{let c=F("select",{className:"persona-composer-model-picker",attrs:{"aria-label":e,"data-persona-composer-model-picker":""}}),p="",u=()=>{let C=t.getModels(),M=C.map(E=>`${E.id}:${E.label}`).join("|");M!==p&&(p=M,c.replaceChildren(...C.map(E=>{let T=F("option",{attrs:{value:E.id}});return T.textContent=E.label,T}))),c.value=r(C)?.id??""};u(),o=u;let m=()=>{c.value&&t.onSelect(c.value)};c.addEventListener("change",m);let g=C=>C.stopPropagation();c.addEventListener("click",g);let{wrapper:h,chevron:b}=zS();return h.append(c,b),{element:h,destroy:()=>{o===u&&(o=null),c.removeEventListener("change",m),c.removeEventListener("click",g)}}},a=()=>{let c=F("button",{className:"persona-composer-model-picker persona-composer-model-picker-trigger",attrs:{type:"button","aria-haspopup":"listbox","aria-expanded":"false","data-persona-composer-model-picker":"popover"}}),p=v("span","persona-composer-model-picker-label"),u=v("span","persona-composer-model-picker-suffix");c.append(p,u);let m=F("div",{className:"persona-composer-model-menu",attrs:{role:"listbox",tabindex:"-1","aria-label":e,"data-persona-composer-model-menu":""}}),g=new Map,h="",b=null,C=()=>b?.isOpen===!0,M=(x=!1)=>{C()&&(b?.close(),c.setAttribute("aria-expanded","false"),x&&c.focus())},E=x=>{let P=[...g.values()];if(P.length===0)return;let L=(x%P.length+P.length)%P.length;P[L].focus()},T=x=>{if(C())return;b||(b=Ps({anchor:c,content:m,placement:"top-start",offset:6,onDismiss:()=>c.setAttribute("aria-expanded","false")})),su(c,m,WH),b.open(),c.setAttribute("aria-expanded","true");let L=[...g.keys()].indexOf(r(t.getModels())?.id??"");E(x??(L>=0?L:0))},R=x=>{M(!0),t.onSelect(x)},A=x=>{x.preventDefault(),x.stopPropagation();let P=x.currentTarget.getAttribute("data-persona-model-option");P&&R(P)},D=x=>{let P=F("button",{className:"persona-composer-model-option",attrs:{type:"button",role:"option",tabindex:"-1","aria-selected":"false","data-persona-model-option":x.id}});if(x.icon){let ee=ke(x.icon,$S,"currentColor",1.5);if(ee){let oe=v("span","persona-composer-model-option-icon");oe.appendChild(ee),P.appendChild(oe)}}let L=v("span","persona-composer-model-option-body"),G=v("span","persona-composer-model-option-label");if(G.textContent=x.label,L.appendChild(G),x.description){let ee=v("span","persona-composer-model-option-description");ee.textContent=x.description,L.appendChild(ee)}P.appendChild(L);let V=v("span","persona-composer-model-option-check");V.setAttribute("aria-hidden","true");let K=ke("check",$S,"currentColor",2);return K&&V.appendChild(K),P.appendChild(V),P.addEventListener("click",A),P},W=()=>{let x=t.getModels(),P=x.map(V=>`${V.id}:${V.label}:${V.icon??""}:${V.description??""}`).join("|");if(P!==h){h=P;for(let V of g.values())V.removeEventListener("click",A);g.clear(),m.replaceChildren(...x.map(V=>{let K=D(V);return g.set(V.id,K),K}))}let L=r(x);for(let[V,K]of g)K.setAttribute("aria-selected",String(V===L?.id));p.textContent=L?.label??"";let G=t.getSuffix?.()??"";u.textContent=G,c.setAttribute("aria-label",[e,[L?.label,G].filter(Boolean).join(" ")].filter(Boolean).join(": "))};W(),o=W;let U=x=>{x.preventDefault(),x.stopPropagation(),C()?M(!0):T()},B=x=>{if(x.key==="ArrowDown"){x.preventDefault(),C()?E(0):T(0);return}x.key==="ArrowUp"&&(x.preventDefault(),C()?E(-1):T(-1))},O=x=>{let P=[...g.values()],L=P.indexOf(x.target?.closest?.(".persona-composer-model-option"));switch(x.key){case"ArrowDown":x.preventDefault(),E(L+1);return;case"ArrowUp":x.preventDefault(),E(L-1);return;case"Home":x.preventDefault(),E(0);return;case"End":x.preventDefault(),E(P.length-1);return;case"Escape":x.preventDefault(),x.stopPropagation(),M(!0);return;case"Tab":M(!0);return;default:}};c.addEventListener("click",U),c.addEventListener("keydown",B),m.addEventListener("keydown",O);let{wrapper:H,chevron:S}=zS();return H.append(c,S),{element:H,destroy:()=>{o===W&&(o=null),c.removeEventListener("click",U),c.removeEventListener("keydown",B),m.removeEventListener("keydown",O);for(let x of g.values())x.removeEventListener("click",A);g.clear(),b?.destroy(),b=null,m.remove()}}};return{action:{id:HH,kind:"custom",placement:"end",order:RH,presentation:n==="popover"?"bar":"auto",label:e,render:()=>n==="popover"?a():s()},repaint:()=>o?.()}}je();Zt();fu();var BH=":scope > [data-persona-composer-mode]";function qS(t){let e=t.row,n="",o=!1,r=new Set(t.initialIds??[]),s=p=>{let u=F("span",{className:"persona-mention-chip persona-composer-mode-chip",attrs:{"data-persona-composer-mode":p.id}});if(p.iconName){let b=v("span","persona-mention-chip-icon"),C=ke(p.iconName,12,"currentColor",1.5);C&&b.appendChild(C),u.appendChild(b)}let m=v("span","persona-mention-chip-label");m.textContent=p.shortLabel??p.label,u.appendChild(m);let g=F("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${p.label}`}}),h=ke("x",12,"currentColor",2);return h?g.appendChild(h):g.textContent="\xD7",g.addEventListener("click",b=>{b.preventDefault(),b.stopPropagation(),t.onRemove(p.id)}),u.appendChild(g),u},a=()=>Array.from(e.querySelectorAll(BH)),l=p=>{p.setAttribute("data-persona-chip-exit",""),p.setAttribute("aria-hidden","true"),p.style.pointerEvents="none";let u=()=>{p.remove(),_a(e)},m=e.ownerDocument.defaultView,g=typeof m?.getComputedStyle=="function"?m.getComputedStyle(p).animationName:"";if(!g||g==="none"){u();return}p.addEventListener("animationend",u,{once:!0}),p.addEventListener("animationcancel",u,{once:!0})},c=()=>{for(let p of a())p.remove()};return{element:e,render:(p,u)=>{if(o)return;let m=u.filter(C=>p.includes(C.id)),g=m.map(C=>`${C.id}:${C.shortLabel??C.label}`).join("|");if(g===n)return;n=g;let h=new Map;for(let C of a()){let M=C.getAttribute("data-persona-composer-mode");M&&m.some(T=>T.id===M)&&!C.hasAttribute("data-persona-chip-exit")?h.set(M,C):C.hasAttribute("data-persona-chip-exit")||l(C)}let b=e.firstChild;for(let C of m){let M=h.get(C.id);M||(M=s(C),r.has(C.id)||(M.setAttribute("data-persona-chip-enter",""),M.addEventListener("animationend",()=>M?.removeAttribute("data-persona-chip-enter"),{once:!0}))),r.delete(C.id),M!==b&&e.insertBefore(M,b),b=M.nextSibling}_a(e)},destroy:()=>{o=!0,c(),_a(e)}}}je();Zt();var jS=t=>`core:mode:${t}`;var xh=t=>Math.min(300+t,499),KS=t=>`core:mode-group:${t}`;function gu(t,e){return t?e?.find(n=>n.id===t)?.presentation==="segmented":!1}function DH(t,e){return t?e?.find(n=>n.id===t)?.chipVisibility==="hidden":!1}function GS(t,e){return t?.length?t.filter(n=>!gu(n.groupId,e)&&!DH(n.groupId,e)):[]}var OH=(t,e)=>t.groupId?e?.find(n=>n.id===t.groupId)?.selection??null:null;function YS(t,e,n,o){let r=n.find(l=>l.id===e);if(!r)return[...t];let s=t.includes(e),a=new Set(t);if(s)a.delete(e);else{if(OH(r,o)==="single"){let l=n.filter(c=>c.groupId===r.groupId).map(c=>c.id);a=new Set([...a].filter(c=>!l.includes(c)))}a.add(e)}return n.filter(l=>a.has(l.id)).map(l=>l.id)}function hu(t,e){return e?.length?e.filter(n=>t.includes(n.id)).map(n=>n.id):[]}function QS(t,e){return e?.length?e.filter(n=>t.includes(n.id)&&(n.persistence??"sticky")!=="once").map(n=>n.id):[]}function XS(t,e){if(!(!e?.length||t.length===0))return e.find(n=>t.includes(n.id)&&n.placeholder)?.placeholder}var _H=16;function JS(t){let e=null;return{action:{id:KS(t.groupId),kind:"custom",placement:"start",presentation:"bar",label:t.getGroup()?.label??t.groupId,render:()=>{let o=F("div",{className:"persona-composer-segmented",attrs:{"data-persona-composer-mode-group":t.groupId}}),r=new Map,s="",a=p=>{p.preventDefault(),p.stopPropagation();let m=p.currentTarget.getAttribute("data-persona-composer-mode");!m||t.getActiveIds().includes(m)&&t.getGroup()?.selection==="single"||t.onSelect(m)},l=p=>{let u=F("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":p.id,"aria-label":p.label}});if(p.iconName){let g=ke(p.iconName,_H,"currentColor",1.5);g&&u.appendChild(g)}let m=v("span","persona-composer-segmented-label");return m.textContent=p.shortLabel??p.label,u.appendChild(m),u.addEventListener("click",a),u},c=()=>{let p=t.getGroup();p?.label?(o.setAttribute("role","group"),o.setAttribute("aria-label",p.label)):(o.removeAttribute("role"),o.removeAttribute("aria-label"));let u=t.getModes(),m=u.map(h=>`${h.id}:${h.shortLabel??h.label}:${h.iconName??""}`).join("|");if(m!==s){s=m;for(let b of r.values())b.removeEventListener("click",a);r.clear();let h=u.map(b=>{let C=l(b);return r.set(b.id,C),C});o.replaceChildren(...h)}let g=t.getActiveIds();for(let[h,b]of r)b.setAttribute("aria-pressed",String(g.includes(h)))};return c(),e=c,{element:o,destroy:()=>{e===c&&(e=null);for(let p of r.values())p.removeEventListener("click",a);r.clear()}}}},repaint:()=>e?.()}}fu();je();Zt();function ZS(t){let e=F("div",{className:"persona-composer-quote",attrs:{"data-persona-composer-quote":""}});e.style.display="none";let n="",o=!1,r=s=>{let a=v("span","persona-composer-quote-bar"),l=v("div","persona-composer-quote-content");if(s.sourceLabel){let m=v("div","persona-composer-quote-source");m.textContent=s.sourceLabel,l.appendChild(m)}let c=F("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});c.textContent=Kp(s.text),l.appendChild(c);let p=F("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":t.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),u=ke("x",12,"currentColor",2);u?p.appendChild(u):p.textContent="\xD7",p.addEventListener("click",m=>{m.preventDefault(),m.stopPropagation(),t.onDismiss()}),e.replaceChildren(a,l,p)};return{element:e,render:s=>{if(o)return;let a=s?`${s.sourceLabel??""}\0${s.text}`:"";if(a!==n){if(n=a,!s){e.replaceChildren(),e.style.display="none";return}r(s),e.style.display="flex"}},destroy:()=>{o=!0,e.replaceChildren(),e.remove()}}}je();Zt();function eA(t){let e=F("div",{className:"persona-composer-pending",attrs:{"data-persona-composer-pending":""}});e.style.display="none";let n,o=!1,r=(a,l,c,p)=>{let u=F("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":l,[c]:""}}),m=ke(a,12,"currentColor",2);return m?u.appendChild(m):u.textContent=l,u.addEventListener("click",g=>{g.preventDefault(),g.stopPropagation(),p()}),u},s=a=>{let l=Kp(a.text??"",90);if(l)return l;let c=a.contentParts?.length??0;return c>0?c===1?"1 attachment":`${c} attachments`:(a.mentionRefs?.length??0)>0?a.mentionRefs.map(u=>u.label).join(", "):"Queued message"};return{element:e,render:a=>{if(o||a===n)return;if(n=a,!a){e.replaceChildren(),e.style.display="none";return}let l=v("span","persona-composer-pending-badge");l.textContent=t.label??"Sends next";let c=F("div",{className:"persona-composer-pending-text",attrs:{"data-persona-composer-pending-text":""}});c.textContent=s(a),e.replaceChildren(l,c,r("pencil",t.editLabel??"Edit queued message","data-persona-composer-pending-edit",t.onEdit),r("x",t.removeLabel??"Remove queued message","data-persona-composer-pending-remove",t.onRemove)),e.style.display="flex"},destroy:()=>{o=!0,e.replaceChildren(),e.remove()}}}je();function tA(t){let e=F("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":t.messageId,"data-preserve-runtime":""}}),n=F("textarea",{className:"persona-message-edit-input",attrs:{rows:"1",dir:"auto","aria-label":"Edit message","data-persona-message-edit-input":""}});n.value=t.initialText;let o=()=>{n.style.height="auto",n.style.height=`${n.scrollHeight}px`};n.addEventListener("input",o);let r=v("div","persona-message-edit-actions"),s=(l,c,p,u)=>{let m=F("button",{className:`persona-message-edit-button ${c}`,attrs:{type:"button",[p]:""},text:l});return m.addEventListener("click",g=>{g.preventDefault(),g.stopPropagation(),u()}),m},a=()=>{let l=n.value.trim();l&&t.onSave(l)};return r.append(s(t.cancelLabel??"Cancel","persona-message-edit-cancel","data-persona-message-edit-cancel",t.onCancel),s(t.saveLabel??"Send","persona-message-edit-save","data-persona-message-edit-save",a)),n.addEventListener("keydown",l=>{if(l.key==="Escape"){l.preventDefault(),l.stopPropagation(),t.onCancel();return}l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),a())}),e.append(n,r),{element:e,getValue:()=>n.value,focus:()=>{n.focus();let l=n.value.length;n.setSelectionRange(l,l),o()},destroy:()=>{e.replaceChildren(),e.remove()}}}function nA(t){let e=t.text??"";if(e.trim().length>0||(t.mentionRefs?.length??0)>0||(t.activeModeIds?.length??0)>0||t.quote||t.selectedModelId)return{text:e,...t.mentionRefs?.length?{mentionRefs:[...t.mentionRefs]}:{},...t.contentSegments?.length?{contentSegments:[...t.contentSegments]}:{},...t.selectedModelId?{selectedModelId:t.selectedModelId}:{},...t.activeModeIds?.length?{activeModeIds:[...t.activeModeIds]}:{},...t.quote?{quote:{...t.quote}}:{}}}function oA(t,e){if(!t||typeof t.text!="string")return;let n=new Set(e.mentionSourceIds),o=(t.mentionRefs??[]).filter(c=>n.has(c.sourceId)),r=o.length===(t.mentionRefs?.length??0)&&o.length>0,s=new Set(e.modes.map(c=>c.id)),a=(t.activeModeIds??[]).filter(c=>s.has(c)),l=t.selectedModelId&&e.modelIds.includes(t.selectedModelId)?t.selectedModelId:void 0;return{text:t.text,...r?{mentionRefs:o}:{},...r&&t.contentSegments?.length?{contentSegments:t.contentSegments}:{},...l?{selectedModelId:l}:{},...a.length?{activeModeIds:a}:{},...t.quote?.text?{quote:t.quote}:{}}}function rA(t){let e=t.delay??500,n=null,o=!1,r=()=>{n!==null&&(clearTimeout(n),n=null)};return{schedule:()=>{o||(r(),n=setTimeout(()=>{n=null,t.write()},e))},flush:()=>{o||n===null||(r(),t.write())},cancel:r,destroy:()=>{o=!0,r()}}}function sA(t){return t.wrapped||t.text.includes(`
|
|
1156
|
+
`)?!1:!(t.hasAttachments||t.hasChips||t.hasQuote||t.hasPendingSubmission)}function iA(){let t=!1;return{observe:(e,n)=>n?(e&&(t=!0),t):(t=!1,!1),release:()=>{t=!1}}}function aA(t){if(!t)return!1;let e=t.ownerDocument?.defaultView;if(!e?.getComputedStyle)return!1;let n=e.getComputedStyle(t),o=Number.parseFloat(n.lineHeight),r=Number.parseFloat(n.fontSize),s=Number.isFinite(o)&&o>0?o:Number.isFinite(r)&&r>0?r*1.4:0;if(!s)return!1;let a=(Number.parseFloat(n.paddingTop)||0)+(Number.parseFloat(n.paddingBottom)||0);return t.scrollHeight-a>s*1.5}yu();function Sh(t){return Object.freeze({text:t.text,contentParts:t.contentParts?Object.freeze([...t.contentParts]):void 0,mentionRefs:Object.freeze([...t.mentionRefs]),contentSegments:t.contentSegments?Object.freeze([...t.contentSegments]):void 0,options:Object.freeze({...t.options}),viaVoice:t.viaVoice})}function dA(t){return t.inputDisabled===!0||t.sendDisabled===!0||t.hasAttachments&&!t.attachmentsReady?!1:!!t.text||t.hasAttachments||t.hasMentions||t.hasServerMentions}var NH=t=>typeof t?.then=="function";function cA(t,e){return e===!1?{status:"canceled"}:!e||typeof e!="object"?{status:"proceed"}:(typeof e.text=="string"&&(t.text=e.text),e.options&&(t.options={...t.options,...e.options}),{status:"proceed"})}function pA(t,e,n){let o;try{o=t(Sh(e),{signal:n})}catch(r){return{status:"error",error:r}}return NH(o)?Promise.resolve(o).then(r=>n.aborted?{status:"aborted"}:cA(e,r),r=>n.aborted?{status:"aborted"}:{status:"error",error:r}):cA(e,o)}je();bu();Ah();je();Zt();function gA(t){let{config:e,onOpen:n}=t,o=e.buttonIconName??"plus",r=e.buttonTooltipText??"Add context",s=v("div","persona-send-button-wrapper"),a=F("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${yo} ${Go}`,attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":r,"aria-haspopup":"listbox","aria-expanded":"false"},style:{fontSize:"18px",lineHeight:"1"}}),l=ke(o,qn,"currentColor",1.5);return l?a.appendChild(l):a.textContent="+",a.addEventListener("click",c=>{c.preventDefault(),c.stopPropagation(),n()}),s.appendChild(a),In({anchor:a,trigger:s,text:()=>a.getAttribute("aria-label")??r}),{button:a,wrapper:s}}so();var{setLoader:l2,load:jH}=Qt({fallbackImport:()=>Promise.resolve().then(()=>(RA(),HA))});var kh=jH;Zt();so();var{setLoader:C2,load:nR}=Qt({fallbackImport:()=>Promise.resolve().then(()=>(qA(),UA)),resetOnSetLoader:!0});var jA=nR;je();Zt();function pc(t,e={}){if(e.render)return e.render({ref:t,readonly:!!e.readonly});let n=F("span",{className:Gt("persona-mention-token",e.readonly&&"persona-mention-token-readonly"),attrs:{"data-mention-source":t.sourceId,title:t.label,role:"img","aria-label":`${t.label} mention`}});t.color&&n.style.setProperty("--persona-mention-token-accent",t.color);let o=ke(t.iconName??"at-sign",13,"currentColor",2);if(o){let r=v("span","persona-mention-token-icon");r.appendChild(o),n.appendChild(r)}return n.appendChild(F("span",{className:"persona-mention-token-label",text:`@${t.label}`})),n}function KA(t){let e=t.config.contextMentions;if(!e?.enabled)return null;let n=vu(e).filter(A=>A.sources.length>0);if(n.length===0)return typeof console<"u"&&console.warn("[Persona] contextMentions.enabled is true but no sources were provided; mentions are disabled."),null;let o=n.filter(A=>A.sources.some(D=>typeof D.matchCommand=="function")),r=A=>o.some(D=>D.trigger?D.position==="line-start"?A.split(`
|
|
1157
1157
|
`).some(U=>U.startsWith(D.trigger)):(D.position==="anywhere"?A:A.split(`
|
|
1158
|
-
`)[0]).startsWith(D.trigger):!1),s=(A,D)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${A}`,{detail:D}))}catch{}},a=!t.chipRow,l=t.chipRow??F("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),c=null,p=null,u=t.textarea,m=null,g=null,h=null,b=null,C=()=>{if(c)return Promise.resolve(c);if(p)return p;let A=Th().then(D=>(D.setMentionIconRenderer(ke),c=D.mountContextMentions({mentionConfig:e,textarea:t.textarea,composerInput:m??void 0,anchor:t.anchor,contextRow:l,getMessages:t.getMessages,getConfig:()=>t.config,liveRegionHost:t.liveRegionHost,popoverContainer:t.popoverContainer,onPickerOpenChange:H,emit:s}),c)).catch(D=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",D),p===A&&(p=null),null));return p=A,A},M=()=>{DA().then(A=>{let D=A.mountInlineComposer({textarea:t.textarea,renderToken:U=>pc(U,{render:e.renderMentionToken}),onMentionRemoved:U=>c?.untrackMention(U)});m=D.input,g=D.destroy;let W=u;W.replaceWith(D.element),u=D.element,b={next:D.element,prev:W},h?.(D.element,W),c?c.rebindComposer(D.input):p&&p.then(U=>U?.rebindComposer(D.input))}).catch(A=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",A)})};e.display==="inline"&&M();let E=[],T=new Map;for(let A of n){if(!A.showButton)continue;let D=sA({config:{...e,buttonIconName:A.buttonIconName,buttonTooltipText:A.buttonTooltipText},onOpen:()=>{C().then(W=>W?.openMenu(A.trigger))}});E.push(D),T.set(A.trigger,D.button)}let H=(A,D,W)=>{let U=T.get(D);U&&(U.setAttribute("aria-expanded",A?"true":"false"),A?U.setAttribute("aria-controls",W):U.removeAttribute("aria-controls"))};return{affordanceButtons:E.map(A=>A.wrapper),contextRow:l,handleInput:A=>{if(c){c.handleInput();return}if(!oA(A))return;let D=u,W=D.selectionStart??0;ic(D.value,W,n)&&C().then(U=>U?.handleInput())},handleKeydown:A=>{if(c?.isMenuOpen())return c.handleKeydown(A);if(A.key==="Backspace"&&c?.hasMentions()&&!b){let D=u,W=D.selectionStart===0&&D.selectionEnd===0;if((D.value.length===0||W)&&c.removeLastChip())return A.preventDefault(),!0}return!1},isMenuOpen:()=>c?.isMenuOpen()??!1,hasMentions:()=>c?.hasMentions()??!1,getMentionRefs:()=>c?.getMentionRefs()??[],collectForSubmit:()=>c?.collectForSubmit()??null,takeInlineCommand:async A=>r(A)?(c??await C())?.dispatchInlineCommand(A)??null:null,clear:()=>c?.clear(),prefetch:()=>{Th().catch(()=>{})},onComposerSwap:A=>{h=A,b&&A(b.next,b.prev)},destroy:()=>{c?.destroy(),g?.();for(let A of E)A.wrapper.remove();a&&l.remove()}}}var Iu=t=>t?.launcher?.variant??(t?.future?.v5Defaults===!0?"circle":"pill"),Ru={background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",border:"transparent",size:"48px",iconSize:"24px",borderRadius:"palette.radius.full",shadow:"0 8px 24px rgba(0,0,0,.16)",offset:"20px"};var Wu="16px",Bu="transparent",VR=(()=>{let t={};for(let e of[0,1,2,3,4,5,6,8,10,12,16,20,24,32,40,48,56,64])t[e]=e===0?"0px":`${e/4}rem`;return t})(),uc={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"},purple:{50:"#faf5ff",100:"#f3e8ff",200:"#e9d5ff",300:"#d8b4fe",400:"#c084fc",500:"#a855f7",600:"#9333ea",700:"#7e22ce",800:"#6b21a8",900:"#581c87",950:"#3b0764"},teal:{50:"#f0fdfa",100:"#ccfbf1",200:"#99f6e4",300:"#5eead4",400:"#2dd4bf",500:"#14b8a6",600:"#0d9488",700:"#0f766e",800:"#115e59",900:"#134e4a",950:"#042f2e"}},spacing:VR,typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},Hu={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.50",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.info.500"}},spacing:{xs:"palette.spacing.1",sm:"palette.spacing.2",md:"palette.spacing.4",lg:"palette.spacing.6",xl:"palette.spacing.8","2xl":"palette.spacing.10"},typography:{fontFamily:"palette.typography.fontFamily.sans",fontSize:"palette.typography.fontSize.base",fontWeight:"palette.typography.fontWeight.normal",lineHeight:"palette.typography.lineHeight.normal"}},bo={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm",hoverBackground:"rgba(0, 0, 0, 0.05)"}},input:{background:"semantic.colors.surface",placeholder:"semantic.colors.textMuted",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"semantic.colors.surface",foreground:"semantic.colors.primary",border:"semantic.colors.border",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:wg,maxWidth:"none",height:"min(640px, max(200px, calc(100vh - 64px)))",maxHeight:"none",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:Wu,canvasBackground:Bu,modes:{floating:{border:"1px solid var(--persona-border)",shadow:"palette.shadows.xl",borderRadius:"palette.radius.xl"},inline:{border:"1px solid var(--persona-border)",shadow:"none",borderRadius:"palette.radius.xl"},docked:{border:"none",shadow:"none",borderRadius:"palette.radius.xl"},sidebar:{border:"none",borderRadius:"0"},mobile:{border:"none",shadow:"none",borderRadius:"0"}}},header:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"20px 24px",minimalPadding:"16px 24px",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50"},message:{gap:"12px",user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"semantic.colors.container",text:"semantic.colors.text",borderRadius:"palette.radius.lg",border:"semantic.colors.border",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"transparent",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"palette.shadows.none"},suggestion:{chip:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.full",padding:"0.5rem 0.875rem",gap:"0.5rem",itemGap:"8px",minHeight:"36px",fontSize:"0.8125rem",lineHeight:"1.25",iconSize:"16px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},card:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.xl",padding:"1rem",shadow:"palette.shadows.sm",gap:"0.625rem",itemGap:"8px",minHeight:"72px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"18px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},list:{background:"transparent",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.md",padding:"0.75rem",gap:"0.625rem",itemGap:"8px",minHeight:"44px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"17px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"}},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},scrollbar:{thumb:"semantic.colors.border",track:"transparent"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit",borderRadius:"palette.radius.md"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},eventStream:{badge:{flow:{background:"palette.colors.success.100",foreground:"palette.colors.success.700"},step:{background:"palette.colors.primary.100",foreground:"palette.colors.primary.700"},reasoning:{background:"palette.colors.warning.100",foreground:"palette.colors.warning.700"},tool:{background:"palette.colors.purple.100",foreground:"palette.colors.purple.800"},agent:{background:"palette.colors.teal.100",foreground:"palette.colors.teal.800"},error:{background:"palette.colors.error.100",foreground:"palette.colors.error.700"},default:{background:"palette.colors.gray.100",foreground:"palette.colors.gray.600"}}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}},$R=uc.colors.gray,zR={50:"#fafafa",100:"#f5f5f5",200:"#e5e5e5",300:"#d4d4d4",400:"#a3a3a3",500:"#737373",600:"#525252",700:"#404040",800:"#262626",900:"#171717",950:"#0a0a0a"},UR={...uc,colors:{...uc.colors,gray:$R}},qR={...uc,colors:{...uc.colors,gray:zR},radius:{none:"0px",sm:"4px",md:"8px",lg:"12px",xl:"16px","2xl":"24px",full:"9999px"}};var jR=Hu,KR={...Hu,colors:{...Hu.colors,surface:"#ffffff",background:"#ffffff",container:"semantic.colors.surface",textInverse:"#ffffff"},typography:{...Hu.typography,fontSize:"14px",lineHeight:"1.5"}};var Dh=bo,GR={...bo,launcher:Ru,activity:{rowHeight:"32px",labelSize:"13px",iconSize:"16px",indent:"0px",groupIndent:"0px",groupGap:"0px",groupPadding:"0px",transcriptGap:"0px",responseGap:"12px",bodyPadding:"4px 0",bodySize:"13px",bodyLineHeight:"1.5",bodyFontWeight:"400",sectionGap:"8px",bodySurface:"transparent"},toolBubble:{shadow:"none"},reasoningBubble:{shadow:"none"},input:{...bo.input,borderRadius:"palette.radius.full"},introCard:{...bo.introCard,title:{fontSize:"22px",fontWeight:"500"}},suggestion:{chip:{...bo.suggestion.chip,fontWeight:"400"},card:{...bo.suggestion.card,fontWeight:"400"},list:{...bo.suggestion.list,fontWeight:"400"}},panel:{...bo.panel,width:"min(400px, calc(100vw - 24px))",height:"min(704px, calc(100dvh - 104px))",borderRadius:"palette.radius.xl"},header:{...bo.header,background:"semantic.colors.container",foreground:"semantic.colors.text",padding:"8px 8px 8px 16px",minimalPadding:"8px 8px 8px 16px",minHeight:"48px",borderBottom:"none",iconBackground:"transparent",iconForeground:"semantic.colors.text",iconScale:"1",controlSize:"28px",controlIconSize:"18px",controlStrokeWidth:"1.5",actionIconForeground:"semantic.colors.textMuted",controlBorderRadius:"8px",controlHoverBackground:"color-mix(in srgb, var(--persona-text) 8%, transparent)",controlHoverForeground:"semantic.colors.text",controlFocusOutline:"2px solid color-mix(in srgb, var(--persona-text) 50%, transparent)",title:{fontSize:"14px",fontWeight:"500",lineHeight:"1.5"}},message:{...bo.message,gap:"20px",fullscreenGap:"28px",topFadeHeight:"18px",user:{...bo.message.user,background:"palette.colors.gray.100",text:"semantic.colors.text",borderRadius:"palette.radius.xl",shadow:"none",padding:"8px 14px",fontSize:"14px",lineHeight:"1.5"},assistant:{...bo.message.assistant,background:"transparent",border:"transparent",borderWidth:"0px",borderRadius:"0px",shadow:"none",padding:"0px",fontSize:"14px",lineHeight:"1.55"}},composer:{...bo.composer,padding:"8px",fontSize:"15px",lineHeight:"1.5",controlSize:"32px",controlIconSize:"20px",sendIconSize:"18px",sendButtonRadius:"9999px",footerBorder:"none",overlayBand:"linear-gradient(to bottom, transparent, var(--persona-container) 24px)",focusBorderColor:"color-mix(in srgb, var(--persona-text) 28%, var(--persona-border))",focusRing:"1px solid color-mix(in srgb, var(--persona-text) 12%, transparent)"}};var YR=t=>bs({future:t}),Oh=t=>YR(t)==="v5"?{palette:qR,semantic:KR,components:GR}:{palette:UR,semantic:jR,components:Dh};function Hn(t,e){if(!e.startsWith("palette.")&&!e.startsWith("semantic.")&&!e.startsWith("components."))return e;let n=e.split("."),o=t;for(let r of n){if(o==null)return;o=o[r]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?Hn(t,o):o}function NA(t){let e={};function n(o,r){for(let[s,a]of Object.entries(o)){let l=`${r}.${s}`;if(typeof a=="string"){let c=Hn(t,a);c!==void 0&&(e[l]={path:l,value:c,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,l)}}return n(t.palette,"palette"),n(t.semantic,"semantic"),n(t.components,"components"),e}function QR(t){let e=[],n=[];return t.palette||e.push({path:"palette",message:"Theme must include a palette",severity:"error"}),t.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),t.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:e.length===0,errors:e,warnings:n}}function FA(t,e){let n={...t};for(let[o,r]of Object.entries(e)){let s=n[o];s&&typeof s=="object"&&!Array.isArray(s)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=FA(s,r):n[o]=r}return n}function XR(t,e){return e?FA(t,e):t}function Na(t,e={}){let n=Oh(e.future),o={palette:n.palette,semantic:n.semantic,components:n.components},r={palette:{...o.palette,...t?.palette,colors:{...o.palette.colors,...t?.palette?.colors},spacing:{...o.palette.spacing,...t?.palette?.spacing},typography:{...o.palette.typography,...t?.palette?.typography},shadows:{...o.palette.shadows,...t?.palette?.shadows},borders:{...o.palette.borders,...t?.palette?.borders},radius:{...o.palette.radius,...t?.palette?.radius}},semantic:{...o.semantic,...t?.semantic,colors:{...o.semantic.colors,...t?.semantic?.colors,interactive:{...o.semantic.colors.interactive,...t?.semantic?.colors?.interactive},feedback:{...o.semantic.colors.feedback,...t?.semantic?.colors?.feedback}},spacing:{...o.semantic.spacing,...t?.semantic?.spacing},typography:{...o.semantic.typography,...t?.semantic?.typography}},components:XR(o.components,t?.components)},s=t?.components?.activity;for(let p of["toolBubble","reasoningBubble"])for(let u of["rowHeight","labelSize","iconSize","indent","bodySurface"])s?.[u]!==void 0&&(r.components[p][u]=s[u]);let a=t?.components?.collapsibleWidget?.surface;a!==void 0&&s?.bodySurface===void 0&&(r.components.activity={...r.components.activity,bodySurface:a});let l=t?.components?.header;l?.padding!==void 0&&l.minimalPadding===void 0&&(r.components.header.minimalPadding=r.components.header.padding);let c=t?.components?.message;if(c?.gap!==void 0&&c.fullscreenGap===void 0&&(r.components.message.fullscreenGap=r.components.message.gap),e.validate!==!1){let p=QR(r);if(!p.valid)throw new Error(`Theme validation failed: ${p.errors.map(u=>u.message).join(", ")}`)}if(e.plugins)for(let p of e.plugins)r=p.transform(r);return r}var Bh=t=>t.trim()==="0"?"0px":t,_A="--persona-",JR=t=>{if(!t)return;let e=t.trim().toLowerCase(),n;if(e.charCodeAt(0)===35){let a=e.slice(1);if(!/^[0-9a-f]+$/.test(a))return;a.length===3||a.length===4?n=[0,1,2].map(l=>parseInt(a[l]+a[l],16)):(a.length===6||a.length===8)&&(n=[0,2,4].map(l=>parseInt(a.slice(l,l+2),16)))}else{let a=e.match(/^rgba?\(([^)]+)\)$/);if(a){let l=a[1].split(/[,/\s]+/).filter(Boolean);l.length>=3&&(n=l.slice(0,3).map(c=>{let p=c.endsWith("%"),u=parseFloat(p?c.slice(0,-1):c);return p?u/100*255:u}))}}if(!n||n.some(a=>!Number.isFinite(a)))return;let[o,r,s]=n.map(a=>{let l=Math.max(0,Math.min(255,a))/255;return l<=.03928?l/12.92:Math.pow((l+.055)/1.055,2.4)});return .2126*o+.7152*r+.0722*s},ZR=.179,Rn=(t,e)=>{for(let[n,...o]of e){let r;for(let s of o)if(r=s.charCodeAt(0)===61?s.slice(1):t[_A+s],r!==void 0)break;r!==void 0&&(t[_A+n]=r)}};function VA(t){let e=NA(t),n={};for(let[_,Te]of Object.entries(e)){let He=_.replace(/\./g,"-");n[`--persona-${He}`]=Te.value}Rn(n,[["primary","semantic-colors-primary","palette-colors-primary-500"],["secondary","semantic-colors-secondary","palette-colors-secondary-500"],["accent","semantic-colors-accent","palette-colors-accent-500"],["surface","semantic-colors-surface","palette-colors-gray-50"],["background","semantic-colors-background","palette-colors-gray-50"],["container","semantic-colors-container","palette-colors-gray-100"],["text","semantic-colors-text","palette-colors-gray-900"],["text-muted","semantic-colors-text-muted","palette-colors-gray-500"],["text-inverse","semantic-colors-text-inverse","palette-colors-gray-50"],["border","semantic-colors-border","palette-colors-gray-200"],["divider","semantic-colors-divider","palette-colors-gray-200"],["muted","text-muted"],["voice-recording-indicator","components-voice-recording-indicator","palette-colors-error-500"],["voice-recording-bg","components-voice-recording-background","palette-colors-error-50"],["voice-processing-icon","components-voice-processing-icon","palette-colors-primary-500"],["voice-speaking-icon","components-voice-speaking-icon","palette-colors-success-500"],["approval-bg","components-approval-requested-background","surface"],["approval-border","components-approval-requested-border","border"],["approval-text","components-approval-requested-text","palette-colors-gray-900"],["approval-shadow","components-approval-requested-shadow","=0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"],["approval-approve-bg","components-approval-approve-background","button-primary-bg"],["approval-deny-bg","components-approval-deny-background","container"],["attachment-image-bg","components-attachment-image-background","palette-colors-gray-100"],["attachment-image-border","components-attachment-image-border","palette-colors-gray-200"],["font-family","semantic-typography-fontFamily","palette-typography-fontFamily-sans"],["font-size","semantic-typography-fontSize","palette-typography-fontSize-base"],["font-weight","semantic-typography-fontWeight","palette-typography-fontWeight-normal"],["line-height","semantic-typography-lineHeight","palette-typography-lineHeight-normal"],["input-font-family","font-family"],["input-font-weight","font-weight"],["radius-sm","palette-radius-sm","=0.125rem"],["radius-md","palette-radius-md","=0.375rem"],["radius-lg","palette-radius-lg","=0.5rem"],["radius-xl","palette-radius-xl","=0.75rem"],["radius-full","palette-radius-full","=9999px"],["launcher-radius","components-launcher-borderRadius","palette-radius-full","=9999px"],["launcher-bg","components-launcher-background","surface"],["launcher-fg","components-launcher-foreground","primary"]]);let o=n["--persona-components-launcher-foreground"];n["--persona-launcher-fg-muted"]=o&&o!==n["--persona-primary"]?`color-mix(in srgb, ${o} 70%, transparent)`:n["--persona-muted"],Rn(n,[["launcher-border","components-launcher-border","border"],["button-primary-bg","components-button-primary-background","primary"],["button-primary-fg","components-button-primary-foreground","text-inverse"],["button-radius","components-button-primary-borderRadius","palette-radius-full","=9999px"],["button-stop-bg","components-button-stop-background"],["button-stop-fg","components-button-stop-foreground"]]),Rn(n,[["button-ghost-bg","components-button-ghost-background","=transparent"],["button-ghost-fg","components-button-ghost-foreground","text"],["button-ghost-radius","components-button-ghost-borderRadius","radius-md","=0.375rem"],["button-ghost-hover-bg","components-button-ghost-hoverBackground","=rgba(0, 0, 0, 0.05)"],["panel-radius","components-panel-borderRadius","radius-xl","=0.75rem"]]),n["--persona-panel-border"]=n["--persona-components-panel-border"]??`1px solid ${n["--persona-border"]}`,Rn(n,[["panel-shadow","components-panel-shadow","palette-shadows-xl","=0 25px 50px -12px rgba(0, 0, 0, 0.25)"]]),n["--persona-panel-inset"]=n["--persona-components-panel-inset"]??Wu,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??Bu,Rn(n,[["launcher-shadow","components-launcher-shadow","=0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"],["input-radius","components-input-borderRadius","radius-lg","=0.5rem"],["message-user-radius","components-message-user-borderRadius","radius-lg","=0.5rem"],["message-assistant-radius","components-message-assistant-borderRadius","radius-lg","=0.5rem"]]),Rn(n,[["header-bg","components-header-background","surface"]]);let r=n["--persona-header-bg"],s=n["--persona-components-header-foreground"],a=s?`color-mix(in srgb, ${s} 72%, ${r})`:void 0;n["--persona-header-border"]=n["--persona-components-header-border"]??(s?`color-mix(in srgb, ${s} 14%, ${r})`:void 0)??n["--persona-divider"],Rn(n,[["header-icon-bg","components-header-iconBackground","primary"],["header-icon-fg","components-header-iconForeground","text-inverse"]]),n["--persona-header-title-fg"]=n["--persona-components-header-title-color"]??n["--persona-components-header-titleForeground"]??s??n["--persona-primary"],n["--persona-header-subtitle-fg"]=n["--persona-components-header-subtitle-color"]??n["--persona-components-header-subtitleForeground"]??a??n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=n["--persona-components-header-actionIconForeground"]??a??n["--persona-muted"],Rn(n,[["header-control-size","components-header-controlSize","=32px"],["header-control-icon-size","components-header-controlIconSize","=20px"]]);let l=t.components?.header;l?.shadow&&(n["--persona-header-shadow"]=l.shadow),l?.borderBottom&&(n["--persona-header-border-bottom"]=l.borderBottom),l?.minHeight&&(n["--persona-header-min-height"]=l.minHeight);let c=n["--persona-components-history-railHeader-background"];c&&(n["--persona-history-rail-header-bg"]=c);let p=n["--persona-components-history-railHeader-border"];p&&(n["--persona-history-rail-header-border"]=p);let u=n["--persona-components-history-railHeader-minHeight"];u&&(n["--persona-history-rail-header-min-height"]=u);for(let[_,Te]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let He=n[`--persona-components-history-overlay-${_}`];He&&(n[`--persona-history-overlay-${Te}`]=He)}for(let[_,Te]of[["background","bg"],["borderRadius","radius"]]){let He=n[`--persona-components-history-menu-${_}`];He&&(n[`--persona-history-menu-${Te}`]=He)}let m=t.components?.history?.motion;if(m){let _=ut=>{if(ut===void 0)return;let At=String(ut).trim();return/^\d+(\.\d+)?$/.test(At)?`${At}ms`:At},Te=_(m.enterDurationMs);Te!==void 0&&(n["--persona-history-enter-ms"]=Te);let He=_(m.exitDurationMs);He!==void 0&&(n["--persona-history-exit-ms"]=He),m.enterEasing&&(n["--persona-history-enter-easing"]=m.enterEasing),m.exitEasing&&(n["--persona-history-exit-easing"]=m.exitEasing)}let g=n["--persona-components-history-dangerForeground"];g&&(n["--persona-history-danger-fg"]=g),n["--persona-danger"]=n["--persona-components-history-confirm-dangerBackground"]??n["--persona-palette-colors-error-700"]??"#b42318",n["--persona-danger-fg"]=n["--persona-components-history-confirm-dangerForeground"]??"#ffffff";for(let _ of["scrim","shadow"]){let Te=n[`--persona-components-history-confirm-${_}`];Te&&(n[`--persona-history-confirm-${_}`]=Te)}for(let[_,Te]of[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]]){let He=n[`--persona-components-tooltip-${_}`];He&&(n[`--persona-tooltip-${Te}`]=He)}t.components?.tooltip?.arrow===!1&&(n["--persona-tooltip-arrow-display"]="none");for(let[_,Te]of[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let He=n[`--persona-components-messageActions-${_}`];He&&(n[`--persona-message-action-${Te}`]=He)}Rn(n,[["intro-card-bg","components-introCard-background","=transparent"],["intro-card-radius","components-introCard-borderRadius","=1rem"]]);let h=n["--persona-components-introCard-background"],b=n["--persona-components-introCard-shadow"],C=(!h||h==="transparent"||h==="none")&&(!b||b==="none"),M=n["--persona-components-introCard-padding"]??"1.5rem";n["--persona-intro-card-padding"]=C&&M==="1.5rem"?"1.5rem 0":M,Rn(n,[["intro-card-shadow","components-introCard-shadow","=none"],["intro-card-border","components-introCard-border","=none"],["input-background","components-input-background","surface"],["input-placeholder","components-input-placeholder","text-muted"],["input-backdrop-filter","components-input-backdropFilter","=none"],["message-user-bg","components-message-user-background","accent"],["message-user-text","components-message-user-text","text-inverse"],["message-user-shadow","components-message-user-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["message-assistant-bg","components-message-assistant-background","surface"],["message-assistant-text","components-message-assistant-text","text"],["message-assistant-border","components-message-assistant-border","border"],["message-assistant-shadow","components-message-assistant-shadow","=0 1px 2px 0 rgb(0 0 0 / 0.05)"],["scroll-to-bottom-bg","components-scrollToBottom-background","button-primary-bg","accent"],["scroll-to-bottom-fg","components-scrollToBottom-foreground","button-primary-fg","text-inverse"],["scroll-to-bottom-border","components-scrollToBottom-border","primary"],["scroll-to-bottom-size","components-scrollToBottom-size","=40px"],["scroll-to-bottom-radius","components-scrollToBottom-borderRadius","button-radius","radius-full","=9999px"],["scroll-to-bottom-shadow","components-scrollToBottom-shadow","palette-shadows-sm","=0 1px 2px 0 rgb(0 0 0 / 0.05)"],["scroll-to-bottom-padding","components-scrollToBottom-padding","=0.5rem 0.875rem"],["scroll-to-bottom-gap","components-scrollToBottom-gap","=0.5rem"],["scroll-to-bottom-font-size","components-scrollToBottom-fontSize","palette-typography-fontSize-sm","=0.875rem"],["scroll-to-bottom-icon-size","components-scrollToBottom-iconSize","=14px"],["event-badge-flow-bg","components-eventStream-badge-flow-background","=#dcfce7"],["event-badge-flow-fg","components-eventStream-badge-flow-foreground","=#15803d"],["event-badge-step-bg","components-eventStream-badge-step-background","=#f5f5f5"],["event-badge-step-fg","components-eventStream-badge-step-foreground","=#0a0a0a"],["event-badge-reasoning-bg","components-eventStream-badge-reasoning-background","=#fef9c3"],["event-badge-reasoning-fg","components-eventStream-badge-reasoning-foreground","=#a16207"],["event-badge-tool-bg","components-eventStream-badge-tool-background","=#f3e8ff"],["event-badge-tool-fg","components-eventStream-badge-tool-foreground","=#6b21a8"],["event-badge-agent-bg","components-eventStream-badge-agent-background","=#ccfbf1"],["event-badge-agent-fg","components-eventStream-badge-agent-foreground","=#115e59"],["event-badge-error-bg","components-eventStream-badge-error-background","=#fee2e2"],["event-badge-error-fg","components-eventStream-badge-error-foreground","=#b91c1c"],["event-badge-default-bg","components-eventStream-badge-default-background","=#f3f4f6"],["event-badge-default-fg","components-eventStream-badge-default-foreground","=#4b5563"],["tool-bubble-shadow","components-toolBubble-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["reasoning-bubble-shadow","components-reasoningBubble-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["composer-shadow","components-composer-shadow","=none"]]),Rn(n,[["composer-padding","components-composer-padding","=0.75rem 1rem"],["composer-gap","components-composer-gap","=0.5rem"],["composer-font-size","components-composer-fontSize","=0.875rem"],["composer-line-height","components-composer-lineHeight","=1.25rem"],["composer-control-size","components-composer-controlSize","=40px"],["composer-control-icon-size","components-composer-controlIconSize","=24px"],["motion-duration-fast","components-motion-durationFast","=120ms"],["motion-duration-base","components-motion-durationBase","=200ms"],["motion-easing","components-motion-easing","=cubic-bezier(0.2, 0, 0, 1)"],["composer-border-color","components-composer-borderColor","border","=#e5e7eb"],["composer-overlay-band","components-composer-overlayBand","=transparent"],["scrollbar-thumb","components-scrollbar-thumb","border","=#e5e7eb"],["scrollbar-track","components-scrollbar-track","=transparent"],["md-inline-code-bg","components-markdown-inlineCode-background","container"],["md-inline-code-color","components-markdown-inlineCode-foreground","text"],["md-link-color","components-markdown-link-foreground","accent","=#0f0f0f"]]);let E=n["--persona-components-markdown-heading-h1-fontSize"];E&&(n["--persona-md-h1-size"]=E);let T=n["--persona-components-markdown-heading-h1-fontWeight"];T&&(n["--persona-md-h1-weight"]=T);let H=n["--persona-components-markdown-heading-h2-fontSize"];H&&(n["--persona-md-h2-size"]=H);let A=n["--persona-components-markdown-heading-h2-fontWeight"];A&&(n["--persona-md-h2-weight"]=A);let D=n["--persona-components-markdown-prose-fontFamily"];D&&D!=="inherit"&&(n["--persona-md-prose-font-family"]=D),Rn(n,[["md-code-block-bg","components-markdown-codeBlock-background","container"],["md-code-block-border-color","components-markdown-codeBlock-borderColor","border"],["md-code-block-text-color","components-markdown-codeBlock-textColor","=inherit"]]),Rn(n,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),Rn(n,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),Rn(n,[["md-hr-color","components-markdown-hr-color","divider"]]),Rn(n,[["md-blockquote-border-color","components-markdown-blockquote-borderColor","palette-colors-gray-900"],["md-blockquote-bg","components-markdown-blockquote-background","=transparent"],["md-blockquote-text-color","components-markdown-blockquote-textColor","palette-colors-gray-500"]]);let W=[["container","surface"],["surface","surface"],["border","border"]];for(let[_,Te]of W){let He=n[`--persona-components-collapsibleWidget-${_}`]??n[`--persona-${Te}`];He!==void 0&&(n[`--persona-cw-${_}`]=He,n[`--cw-${_}`]=He)}Rn(n,[["message-border","components-message-border","border"]]),Rn(n,[["message-user-padding","components-message-user-padding"],["message-user-max-width","components-message-user-maxWidth"],["message-user-font-size","components-message-user-fontSize"],["message-user-font-family","components-message-user-fontFamily"],["message-user-line-height","components-message-user-lineHeight"],["message-assistant-padding","components-message-assistant-padding"],["message-assistant-border-width","components-message-assistant-borderWidth"],["message-assistant-max-width","components-message-assistant-maxWidth"],["message-assistant-font-size","components-message-assistant-fontSize"],["message-assistant-font-family","components-message-assistant-fontFamily"],["message-assistant-line-height","components-message-assistant-lineHeight"]]);let U=t.components,B=U?.iconButton;B&&(B.background&&(n["--persona-icon-btn-bg"]=B.background),B.border&&(n["--persona-icon-btn-border"]=B.border),B.color&&(n["--persona-icon-btn-color"]=B.color),B.padding&&(n["--persona-icon-btn-padding"]=B.padding),B.borderRadius&&(n["--persona-icon-btn-radius"]=B.borderRadius),B.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=B.hoverBackground),B.hoverColor&&(n["--persona-icon-btn-hover-color"]=B.hoverColor),B.activeBackground&&(n["--persona-icon-btn-active-bg"]=B.activeBackground),B.activeBorder&&(n["--persona-icon-btn-active-border"]=B.activeBorder));let O=U?.labelButton;O&&(O.background&&(n["--persona-label-btn-bg"]=O.background),O.border&&(n["--persona-label-btn-border"]=O.border),O.color&&(n["--persona-label-btn-color"]=O.color),O.padding&&(n["--persona-label-btn-padding"]=O.padding),O.borderRadius&&(n["--persona-label-btn-radius"]=O.borderRadius),O.hoverBackground&&(n["--persona-label-btn-hover-bg"]=O.hoverBackground),O.fontSize&&(n["--persona-label-btn-font-size"]=O.fontSize),O.gap&&(n["--persona-label-btn-gap"]=O.gap));let R=U?.toggleGroup;R&&(R.gap&&(n["--persona-toggle-group-gap"]=R.gap),R.borderRadius&&(n["--persona-toggle-group-radius"]=R.borderRadius));let S=U?.artifact;if(S?.toolbar){let _=S.toolbar;_.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=_.iconHoverColor),_.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=_.iconHoverBackground),_.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=_.iconPadding),_.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=_.iconBorderRadius),_.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=_.iconBorder),_.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=Bh(_.toggleGroupGap)),_.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=_.toggleBorderRadius),_.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=Bh(_.toggleGroupPadding)),_.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=_.toggleGroupBorder),_.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=_.toggleGroupBorderRadius),_.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=Hn(t,_.toggleGroupBackground)??_.toggleGroupBackground),_.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=_.copyBackground),_.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=_.copyBorder),_.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=_.copyColor),_.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=Bh(_.copyBorderRadius)),_.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=_.copyPadding),_.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=_.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??_.copyMenuBackground),_.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=_.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??_.copyMenuBorder),_.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=_.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??_.copyMenuShadow),_.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=_.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??_.copyMenuBorderRadius),_.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=_.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??_.copyMenuItemHoverBackground),_.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=_.iconBackground),_.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=_.toolbarBorder)}if(S?.tab){let _=S.tab;_.background&&(n["--persona-artifact-tab-bg"]=_.background),_.activeBackground&&(n["--persona-artifact-tab-active-bg"]=_.activeBackground),_.activeBorder&&(n["--persona-artifact-tab-active-border"]=_.activeBorder),_.borderRadius&&(n["--persona-artifact-tab-radius"]=_.borderRadius),_.textColor&&(n["--persona-artifact-tab-color"]=_.textColor),_.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=_.hoverBackground),_.listBackground&&(n["--persona-artifact-tab-list-bg"]=_.listBackground),_.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=_.listBorderColor),_.listPadding&&(n["--persona-artifact-tab-list-padding"]=_.listPadding)}if(S?.pane){let _=S.pane;if(_.toolbarBackground){let Te=Hn(t,_.toolbarBackground)??_.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Te}}if(S?.card){let _=S.card;_.background&&(n["--persona-artifact-card-bg"]=_.background),_.border&&(n["--persona-artifact-card-border"]=_.border),_.borderRadius&&(n["--persona-artifact-card-radius"]=_.borderRadius),_.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=_.hoverBackground),_.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=_.hoverBorderColor)}if(S?.inline){let _=S.inline;_.background&&(n["--persona-artifact-inline-bg"]=Hn(t,_.background)??_.background),_.border&&(n["--persona-artifact-inline-border"]=_.border),_.borderRadius&&(n["--persona-artifact-inline-radius"]=_.borderRadius),_.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=Hn(t,_.chromeBackground)??_.chromeBackground),_.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=Hn(t,_.chromeBorder)??_.chromeBorder),_.titleColor&&(n["--persona-artifact-inline-title-color"]=Hn(t,_.titleColor)??_.titleColor),_.mutedColor&&(n["--persona-artifact-inline-muted-color"]=Hn(t,_.mutedColor)??_.mutedColor),_.frameHeight&&(n["--persona-artifact-inline-frame-height"]=_.frameHeight)}let x=U?.code;x&&(x.keywordColor&&(n["--persona-code-keyword-color"]=x.keywordColor),x.stringColor&&(n["--persona-code-string-color"]=x.stringColor),x.commentColor&&(n["--persona-code-comment-color"]=x.commentColor),x.numberColor&&(n["--persona-code-number-color"]=x.numberColor),x.tagColor&&(n["--persona-code-tag-color"]=x.tagColor),x.attrColor&&(n["--persona-code-attr-color"]=x.attrColor),x.propertyColor&&(n["--persona-code-property-color"]=x.propertyColor),x.lineNumberColor&&(n["--persona-code-line-number-color"]=x.lineNumberColor),x.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=x.gutterBorderColor),x.background&&(n["--persona-code-bg"]=Hn(t,x.background)??x.background));let P=n["--persona-surface"],L=n["--persona-container"],G=n["--persona-palette-colors-gray-100"]??"#f3f4f6",V=n["--persona-palette-colors-gray-200"]??"#e5e7eb",K=n["--persona-palette-colors-gray-300"]??"#d1d5db",ee=!L||L===P,oe=JR(P??n["--persona-background"]),ne=ee&&oe!==void 0&&oe<ZR,le=ne?"rgba(255, 255, 255, 0.08)":G,de=ne?"rgba(255, 255, 255, 0.12)":V,ve=ne?"rgba(255, 255, 255, 0.16)":K,Le=ee?le:L,se=ee?de:L;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??Le,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??se,ee&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??ve),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??Le,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??Le,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??Le,n}var eH=t=>!!t&&"launcher"in t&&(t.launcher?.sidebarMode===!0||t.launcher?.mountMode==="docked"),$A=(t,e)=>{if(!e||!eH(e))return t;let n=e.theme?.components?.panel?.width,o=e.darkTheme?.components?.panel?.width;return(fc(e)==="dark"?o??n:n)!=null?t:{...t,components:{...t.components,panel:{...t.components.panel,width:bs(e)==="v5"?"400px":"420px"}}}},tH={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},mc={components:{button:{ghost:{hoverBackground:"rgba(255, 255, 255, 0.08)"}},markdown:{link:{foreground:"palette.colors.primary.300"}},eventStream:{badge:{flow:{background:"palette.colors.success.900",foreground:"palette.colors.success.300"},step:{background:"palette.colors.primary.800",foreground:"palette.colors.primary.200"},reasoning:{background:"palette.colors.warning.900",foreground:"palette.colors.warning.300"},tool:{background:"palette.colors.purple.900",foreground:"palette.colors.purple.300"},agent:{background:"palette.colors.teal.900",foreground:"palette.colors.teal.300"},error:{background:"palette.colors.error.900",foreground:"palette.colors.error.300"},default:{background:"palette.colors.gray.800",foreground:"palette.colors.gray.300"}}},history:{dangerForeground:"#f87171",confirm:{dangerBackground:"palette.colors.error.600",scrim:"rgba(0, 0, 0, 0.6)"}}}},_h=tH,nH={..._h,colors:{..._h.colors,primary:{50:"#0f0f10",100:"#27272a",200:"#3f3f46",300:"#52525b",400:"#71717a",500:"#f4f4f5",600:"#e4e4e7",700:"#d4d4d8",800:"#a1a1aa",900:"#fafafa",950:"#ffffff"},gray:{50:"#1a1a1b",100:"#27272a",200:"#2a2a2d",300:"#52525b",400:"#71717a",500:"#a1a1aa",600:"#b4b4bd",700:"#d4d4d8",800:"#e4e4e7",900:"#f4f4f5",950:"#fafafa"}}},oH=mc,rH={semantic:{colors:{primary:"palette.colors.primary.500",accent:"palette.colors.primary.600",background:"#0f0f10",surface:"palette.colors.gray.50",container:"#1c1c20",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"#0f0f10",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600"}}},components:{...mc.components,button:{...mc.components?.button,primary:{background:"semantic.colors.primary",foreground:"palette.colors.primary.50"}},markdown:{inlineCode:{background:"palette.colors.gray.100",foreground:"semantic.colors.text"},link:{foreground:"semantic.colors.accent"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"semantic.colors.text"},table:{headerBackground:"palette.colors.gray.100",borderColor:"semantic.colors.border"},blockquote:{background:"semantic.colors.container",borderColor:"palette.colors.gray.300",textColor:"semantic.colors.textMuted"}},eventStream:{...mc.components?.eventStream,badge:{...mc.components?.eventStream?.badge,step:{background:"palette.colors.gray.100",foreground:"palette.colors.gray.700"},default:{background:"palette.colors.gray.100",foreground:"palette.colors.gray.700"}}}}},sH=t=>bs({future:t})==="v5"?{palette:nH,components:rH}:{palette:_h,components:oH},zA=t=>{if(!(!t||typeof t!="object"||Array.isArray(t)))return t},Nh=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",iH=t=>{let e=t?.colorScheme??"light";return e==="light"?"light":e==="dark"?"dark":Nh()},fc=t=>iH(t),aH=(t,e={})=>Na(t,e),lH=(t,e={})=>{let n=sH(e.future),o=jo(n.components,t??{})??{};return Na({...o,palette:{...o.palette,colors:bs(e)==="v5"?jo(n.palette.colors,o.palette?.colors):{...n.palette.colors,...o.palette?.colors}}},{validate:!1,future:e.future})},qr=t=>{let e=fc(t),n=zA(t?.theme),o=Iu(t)==="circle"?Ru:{...Dh.launcher,...t?.future?.v5Defaults?{offset:"1.5rem"}:{}},r=jo({components:{launcher:o}},n),s=zA(t?.darkTheme);return $A(e==="dark"?lH(jo(r??{},s??{}),{future:t?.future}):aH(r,{future:t?.future}),t)},cH=t=>VA(t),gc=(t,e)=>{let n=qr(e),o=cH(n);for(let[r,s]of Object.entries(o))t.style.setProperty(r,s);t.setAttribute("data-persona-color-scheme",fc(e)),t.setAttribute("data-persona-defaults",bs(e))},Du=t=>{let e=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{t(Nh())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),e.push(()=>n.disconnect())}if(typeof window<"u"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>t(Nh());n.addEventListener?(n.addEventListener("change",o),e.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),e.push(()=>n.removeListener(o)))}return()=>{e.forEach(n=>n())}};var Xr=require("lucide");Zt();zn();je();var Is=(t,e)=>t?.layout?.contentMaxWidth??(e?t?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");var Ou="24px",Fh=(t,e)=>e||t?.composer?.placement!=="overlay"?"block":"overlay",hc=t=>{if(typeof t!="string")return null;let e=/^\s*(\d+(?:\.\d+)?)\s*%\s*$/.exec(t);if(!e)return null;let n=Number(e[1])/100;return n>0&&n<1?n:null},UA=t=>Math.max(0,Math.round(t.columnHeight*(1-t.fraction))-t.footerHeight);var qA=null;var Vh=()=>{if(qA!==null)return qA;if(typeof navigator>"u")return!1;let e=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(e)},dH="ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space",_u=(t,e)=>{console.warn(`[persona] ${t} shortcut: ${e}`)},Nu=t=>{let e=t.toLowerCase().split("+").map(r=>r.trim()),n=e.pop(),o={key:n,mod:!1,shift:!1,alt:!1};for(let r of e)if(r==="mod"||r==="cmd"||r==="ctrl")o.mod=!0;else if(r==="shift")o.shift=!0;else if(r==="alt"||r==="option")o.alt=!0;else return _u("unknown modifier in",t),null;return!o.mod||o.shift&&o.alt||/^(enter|esc(ape)?)$/.test(n)||!/^([^+\s]|[a-z]{2,12})$/.test(n)?(_u("unsupported",t),null):(n==="space"&&(o.key=" "),o)},pH=t=>dH.split(" ").find(e=>e.toLowerCase()===t)??(t===" "?"Space":t.length===1?t.toUpperCase():t[0].toUpperCase()+t.slice(1)),jA=(t,e)=>{let n=Nu(t);if(!n)return"";let o=Vh(),r=pH(n.key);if(!e&&o)return`${n.alt?"\u2325":""}${n.shift?"\u21E7":""}\u2318${r}`;let s=[e?o?"Meta":"Control":"Ctrl"];return n.alt&&s.push("Alt"),n.shift&&s.push("Shift"),s.push(r),s.join("+")},Fu=t=>jA(t,!1),yc=t=>jA(t,!0),uH=(t,e)=>e.key?.toLowerCase()===t.key&&(Vh()?e.metaKey:e.ctrlKey)===t.mod&&!(Vh()?e.ctrlKey:e.metaKey)&&e.shiftKey===t.shift&&e.altKey===t.alt,mH=t=>{if(!(t instanceof HTMLElement))return!1;let e=t.tagName;return e==="INPUT"||e==="TEXTAREA"||e==="SELECT"||t.isContentEditable},KA=t=>{let e=new Map,n=t?.ownerDocument??(typeof document<"u"?document:null),o=(s,a)=>{if((s.scope??"widget")==="page")return!0;if(!t)return!1;let l=a.composedPath?.();return l?.length?l.includes(t):t.contains(a.target)},r=s=>{if(s.isComposing||!e.size)return;let a=s.composedPath?.()[0]??s.target;for(let l of e.values())if(uH(l.parsed,s)&&l.when?.()!==!1&&o(l,s)&&!(!l.allowInInput&&mH(a))){s.preventDefault();try{l.run(s)}catch(c){_u(`${l.id} threw on`,l.combo),console.warn(c)}return}};return n?.addEventListener("keydown",r),{register(s){let a=Nu(s.combo);if(!a)return()=>{};let l=`${a.mod?"m":""}${a.shift?"s":""}${a.alt?"a":""}${a.key}`,c=e.get(l);return c?(_u(`${c.id} already owns`,s.combo),()=>{}):(e.set(l,{...s,parsed:a}),s.element?.setAttribute("aria-keyshortcuts",yc(s.combo)),()=>{e.get(l)?.id===s.id&&e.delete(l),s.element?.removeAttribute("aria-keyshortcuts")})},destroy(){e.clear(),n?.removeEventListener("keydown",r)}}};var GA=require("idiomorph"),Vu=(t,e,n={})=>{let{preserveTypingAnimation:o=!0}=n;GA.Idiomorph.morph(t,e.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,s){if(r instanceof HTMLElement&&o){if(r.classList.contains("persona-animate-typing")||r.hasAttribute("data-preserve-runtime"))return!1;if(r.hasAttribute("data-tool-elapsed"))return s instanceof HTMLElement&&s.getAttribute("data-tool-elapsed")===r.getAttribute("data-tool-elapsed")?!1:void 0;if(r.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let a=r.textContent??"",l=s.textContent??"";if(a!==l)return}return!1}}}}})};var YA=t=>t.replace(/^\n+/,"").replace(/\s+$/,"");var $h={index:-1,draft:""};function QA(t){let{direction:e,history:n,currentValue:o,atStart:r,state:s}=t,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(e==="up"){if(!a&&!r)return{handled:!1,state:s};if(!a){let l=n.length-1;return{handled:!0,value:n[l],state:{index:l,draft:o}}}if(s.index>0){let l=s.index-1;return{handled:!0,value:n[l],state:{index:l,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<n.length-1){let l=s.index+1;return{handled:!0,value:n[l],state:{index:l,draft:s.draft}}}return{handled:!0,value:s.draft,state:{index:-1,draft:s.draft}}}function XA(t,e){return[t.id,t.role,t.content?.length??0,t.content?.slice(-32)??"",t.streaming?"1":"0",t.voiceProcessing?"1":"0",t.variant??"",t.rawContent?.length??0,t.llmContent?.length??0,t.approval?.status??"",t.toolCall?.status??"",t.toolCall?.name??"",t.toolCall?.chunks?.length??0,t.toolCall?.chunks?.[t.toolCall.chunks.length-1]?.slice(-32)??"",typeof t.toolCall?.args=="string"?t.toolCall.args.length:t.toolCall?.args?JSON.stringify(t.toolCall.args).length:0,t.reasoning?.chunks?.length??0,t.reasoning?.chunks?.[t.reasoning.chunks.length-1]?.length??0,t.reasoning?.chunks?.[t.reasoning.chunks.length-1]?.slice(-32)??"",t.contentParts?.length??0,t.stopReason??"",e].join("\0")}function JA(){return new Map}function ZA(t,e,n){let o=t.get(e);return o&&o.fingerprint===n?o.wrapper:null}function eM(t,e,n,o){t.set(e,{fingerprint:n,wrapper:o})}function tM(t,e){for(let n of t.keys())e.has(n)||t.delete(n)}Uh();ks();Sc();ro();var{setLoader:z2,load:_H}=Qt({fallbackImport:()=>Promise.resolve().then(()=>(AM(),SM))});var MM=_H;ks();function Qh(t,e=On){let n=t.style.position,o=t.style.zIndex,r=t.style.isolation,s=getComputedStyle(t),a=s.position==="static"||s.position==="";return a&&(t.style.position="relative"),t.style.zIndex=String(e),t.style.isolation="isolate",()=>{a&&(t.style.position=n),t.style.zIndex=o,t.style.isolation=r}}var Mc=0,Rs=null;function Xh(t=document){if(Mc++,Mc===1){let n=t.body,r=(t.defaultView??window).scrollY||t.documentElement.scrollTop;Rs={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:r},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${r}px`,n.style.width="100%"}let e=!1;return()=>{if(!e&&(e=!0,Mc=Math.max(0,Mc-1),Mc===0&&Rs)){let n=t.body,o=t.defaultView??window;n.style.overflow=Rs.originalOverflow,n.style.position=Rs.originalPosition,n.style.top=Rs.originalTop,n.style.width=Rs.originalWidth,o.scrollTo(0,Rs.scrollY),Rs=null}}}var Tc={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},nn=t=>(t?.launcher?.mountMode??"floating")==="docked",Ec=t=>(t?.launcher?.mountMode??"floating")==="composer-bar",Do=t=>{let e=t?.launcher?.dock,n=Nr(t).dockWidth?e?.width:Hn(qr(t),"components.panel.width");return{side:e?.side??Tc.side,width:n??Tc.width,animate:e?.animate??Tc.animate,reveal:e?.reveal??Tc.reveal,maxHeight:e?.maxHeight??Tc.maxHeight}};je();je();var EM=require("lucide");Zt();zn();var Jh=t=>t==="followUp"?"follow-up":t,Zh=(t,e=0)=>{if(typeof t=="string"){let r=t.trim();return r?{id:r,label:r,prompt:r,emphasis:"default"}:null}let n=t.label.trim();if(!n)return null;let o=t.prompt?.trim()||n;return{id:t.id?.trim()||o||`suggestion-${e}`,label:n,prompt:o,description:t.description?.trim()||void 0,icon:t.icon,iconColor:t.iconColor?.trim()||void 0,behavior:t.behavior,emphasis:t.emphasis??"default"}},TM=new WeakSet,NH=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,FH=t=>{NH()||t.forEach((e,n)=>{typeof e.animate=="function"&&e.animate([{opacity:"0",transform:"translateY(4px)"},{opacity:"1",transform:"none"}],{duration:250,delay:n*60,easing:"ease-out",fill:"backwards"})})},ey=t=>{var H,A,D;let{item:e,index:n,surface:o,source:r,variant:s,streaming:a,config:l,plugins:c,chipsConfig:p,session:u,getTextarea:m,eventTarget:g,submitPrompt:h}=t,b=o==="followUp",C=e.behavior,M=()=>{if(u.isStreaming())return;let W={suggestion:{...e},surface:o,source:r,behavior:C},U=g.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:W,bubbles:!0,composed:!0,cancelable:!0}));if(b&&g.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:e.prompt},bubbles:!0,composed:!0})),!U)return;for(let O of c)if(O.onSuggestionSelect?.({suggestion:{...e},surface:o,source:r,variant:s,config:l})===!1)return;let B=m();if(C==="fill"){B.value=e.prompt,B.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),B.focus();return}if(h){h(e.prompt);return}B.value="",u.sendMessage(e.prompt)},E=()=>{let W=v("button",`persona-suggestion persona-suggestion--${s}`);if(W.type="button",W.disabled=a,W.dataset.suggestionId=e.id,W.dataset.emphasis=e.emphasis,W.dataset.behavior=C,s==="chip"&&(p?.fontWeight&&(W.style.fontWeight=p.fontWeight),p?.paddingX&&(W.style.paddingLeft=p.paddingX,W.style.paddingRight=p.paddingX),p?.paddingY&&(W.style.paddingTop=p.paddingY,W.style.paddingBottom=p.paddingY)),e.icon){let B=ke(e.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);B&&(B.classList.add("persona-suggestion__icon"),e.iconColor&&(B.style.color=e.iconColor),W.appendChild(B))}let U=v("span","persona-suggestion__copy");if(U.appendChild(F("span",{className:"persona-suggestion__label",text:e.label})),e.description&&s!=="chip"&&U.appendChild(F("span",{className:"persona-suggestion__description",text:e.description})),W.appendChild(U),s!=="chip"){let B=Ge(EM.ArrowRight,16,"currentColor",1.8);B&&(B.classList.add("persona-suggestion__arrow"),W.appendChild(B))}return W.addEventListener("click",M),W},T=null;for(let W of c)if(W.renderSuggestion&&(T=W.renderSuggestion({suggestion:{...e},index:n,surface:o,source:r,variant:s,streaming:a,config:l,defaultRenderer:E,select:M}),T))break;return T??(T=E()),(H=T.dataset).suggestionId||(H.suggestionId=e.id),(A=T.dataset).behavior||(A.behavior=C),(D=T.dataset).emphasis||(D.emphasis=e.emphasis),T instanceof HTMLButtonElement||T.setAttribute("aria-disabled",a?"true":"false"),T},kc=t=>{let e=[],n=[],o=null,r=null,s=()=>{t.removeAttribute("data-scroll-left"),t.removeAttribute("data-scroll-right")},a=()=>{if(r=null,t.hidden||t.dataset.variant!=="chip"||t.dataset.overflow!=="scroll"){s();return}let u=Math.max(0,t.scrollWidth-t.clientWidth);if(u<=1){s();return}let m=getComputedStyle(t).direction==="rtl",g=Math.min(u,Math.max(0,Math.abs(t.scrollLeft))),h=4,b=g<=h,C=g>=u-h,M=m?!C:!b,E=m?!b:!C;t.toggleAttribute("data-scroll-left",M),t.toggleAttribute("data-scroll-right",E)},l=()=>{if(r!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&a();return}r=requestAnimationFrame(a)};t.addEventListener("scroll",l,{passive:!0});let c=typeof ResizeObserver=="function"?new ResizeObserver(l):null;return c?.observe(t),{buttons:e,elements:n,destroy:()=>{t.removeEventListener("scroll",l),c?.disconnect(),r!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(r),r=null},render:(u,m,g,h,b,C)=>{t.replaceChildren(),e.length=0,n.length=0;let M=C?.source??"config",E=C?.surface??(M==="config"?"starter":"followUp"),T=E==="followUp",H=C?.variant??"chip",A=C?.behavior??"send",D=C?.overflow??"wrap",W=C?.config??{},U=C?.plugins??[],B=typeof C?.maxItems=="number"?Math.max(0,Math.floor(C.maxItems)):void 0,O=T?"followUps":"starters";!TM.has(W)&&W.debug===!0&&H!=="chip"&&W.suggestions?.[O]?.overflow!==void 0&&(TM.add(W),console.info(`[persona] suggestions.${O}.overflow applies to the "chip" variant only; the "${H}" variant manages its own stacking.`));let R=V=>V.map(Zh).filter(K=>K!==null).map(K=>({...K,behavior:K.behavior??A})),S=R(u??[]);U.forEach(V=>{V.transformSuggestions&&(S=R(V.transformSuggestions({suggestions:S.map(K=>({...K})),surface:E,source:M,config:W})))});let x=B===void 0?S:S.slice(0,B);if(!x.length){t.hidden=!0,o=null,s();return}if(!T&&(h??m.getMessages()).some(K=>K.role==="user")){t.hidden=!0,o=null;return}t.hidden=!1,t.classList.add("persona-suggestions"),t.dataset.personaSuggestionSurface=Jh(E),t.dataset.variant=H,t.dataset.overflow=D;let P=document.createDocumentFragment(),L=m.isStreaming();x.forEach((V,K)=>{let ee=ey({item:V,index:K,surface:E,source:M,variant:H,streaming:L,config:W,plugins:U,chipsConfig:b,session:m,getTextarea:()=>g,eventTarget:t,submitPrompt:C?.submitPrompt});P.appendChild(ee),n.push(ee),[...ee instanceof HTMLButtonElement?[ee]:[],...Array.from(ee.querySelectorAll("button"))].forEach(ne=>{e.includes(ne)||(ne.disabled=L,e.push(ne))})}),t.appendChild(P),a(),l();let G=JSON.stringify({normalized:x,surface:E,variant:H,source:M});G!==o&&(o=G,FH(n),t.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:x.map(V=>({...V})),surface:E,source:M,variant:H},bubbles:!0,composed:!0})),T&&t.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:x.map(V=>V.prompt)},bubbles:!0,composed:!0})))}}};var vo={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};ks();je();Zt();je();Zt();var VH="persona-header-control",$H="persona-header-control--glyph",zH="persona-header-control--sparse",UH=20,qH={x:[1.4,1.05]},kM="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",jH="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Gu=(t,e,n={})=>{let{iconSize:o,iconText:r}=n,[s,a]=qH[e]??[1,1.5],l=!o;t.classList.toggle($H,l),t.classList.toggle(zH,l&&s!==1);let c=parseFloat(o??"")||UH,p=ke(e,`${Math.round(c*s)}px`,"currentColor",a);p?(p.style.display="block",l||(p.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((a/1.5).toFixed(4))})`),t.replaceChildren(p)):r&&(t.textContent=r)},ki=t=>{let{ariaLabel:e,tooltip:n=!0,tooltipHint:o,iconName:r,iconText:s,wrapperClassName:a=kM,size:l,iconSize:c,color:p,backgroundColor:u,borderWidth:m,borderColor:g,borderRadius:h,paddingX:b,paddingY:C,hidden:M,extraClassName:E,attrs:T}=t,H=v("div",a),A=!!(m||g),D=F("button",{className:Gt(VH,"persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!u&&"persona-bg-transparent hover:persona-bg-gray-100",!A&&"persona-border-none",!h&&"persona-rounded-full",E),attrs:{type:"button","aria-label":e,...T},style:{width:l,height:l,minWidth:l,minHeight:l,display:M?"none":void 0,color:p||qn.actionIconColor,backgroundColor:u,border:A?`${m||"0px"} solid ${g||"transparent"}`:void 0,borderRadius:h,paddingLeft:b,paddingRight:b,paddingTop:C,paddingBottom:C}});return r?Gu(D,r,{iconSize:c,iconText:s}):s&&(D.textContent=s),H.appendChild(D),In({anchor:D,trigger:H,text:()=>D.getAttribute("aria-label")??e,hint:o,enabled:n}),{button:D,wrapper:H}},Va=(t,e={})=>{let{showClose:n=!0,wrapperClassName:o=kM,buttonSize:r,iconSize:s}=e,a=t?.launcher??{},l=a.closeButtonTooltipText??"Close chat",c=a.closeButtonShowTooltip??!0,{button:p,wrapper:u}=ki({ariaLabel:l,tooltip:c,iconName:a.closeButtonIconName??"x",iconText:a.closeButtonIconText??"\xD7",wrapperClassName:o,size:r??a.closeButtonSize,iconSize:s,color:a.closeButtonColor,backgroundColor:a.closeButtonBackgroundColor,borderWidth:a.closeButtonBorderWidth,borderColor:a.closeButtonBorderColor,borderRadius:a.closeButtonBorderRadius,paddingX:a.closeButtonPaddingX,paddingY:a.closeButtonPaddingY,hidden:!n});return{button:p,wrapper:u}},$a=(t,e={})=>{let{wrapperClassName:n=jH,buttonSize:o,iconSize:r}=e,a=(t?.launcher??{}).clearChat??{},l=a.tooltipText??"Clear chat",c=a.showTooltip??!0,{button:p,wrapper:u}=ki({ariaLabel:l,tooltip:c,iconName:a.iconName??"refresh-cw",wrapperClassName:n,size:o??a.size,iconSize:r,color:a.iconColor,backgroundColor:a.backgroundColor,borderWidth:a.borderWidth,borderColor:a.borderColor,borderRadius:a.borderRadius,paddingX:a.paddingX,paddingY:a.paddingY});return{button:p,wrapper:u}};var qn={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-control-state-fg, var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af)))",minHeight:"var(--persona-header-min-height, auto)"},ty={fontFamily:"var(--persona-components-header-title-fontFamily, inherit)",fontSize:"var(--persona-components-header-title-fontSize, 1rem)",fontWeight:"var(--persona-components-header-title-fontWeight, 600)",lineHeight:"var(--persona-components-header-title-lineHeight, 1.5rem)",letterSpacing:"var(--persona-components-header-title-letterSpacing, normal)"},KH={fontFamily:"var(--persona-components-header-subtitle-fontFamily, inherit)",fontSize:"var(--persona-components-header-subtitle-fontSize, 0.75rem)",fontWeight:"var(--persona-components-header-subtitle-fontWeight, inherit)",lineHeight:"var(--persona-components-header-subtitle-lineHeight, 1rem)",letterSpacing:"var(--persona-components-header-subtitle-letterSpacing, normal)"},Pi=t=>{let{config:e,showClose:n=!0}=t,o=F("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3",attrs:{"data-persona-theme-zone":"header"},style:{padding:"var(--persona-components-header-padding, 20px 24px)",minHeight:qn.minHeight,backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),r=e?.launcher??{},s=r.headerIconSize??Fl,a=r.closeButtonPlacement??"inline",l=r.headerIconHidden??!1,c=r.headerIconName,p=F("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:s,width:s,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!l)if(c){let D=parseFloat(s)||24,W=ke(c,D*.6,"currentColor",1);W?(W.style.width=`calc(${D}px * var(--persona-components-header-iconScale, 0.6))`,W.style.height=`calc(${D}px * var(--persona-components-header-iconScale, 0.6))`,p.replaceChildren(W)):p.textContent=e?.launcher?.agentIconText??"\u{1F4AC}"}else if(e?.launcher?.iconUrl){let D=v("img");D.src=e.launcher.iconUrl,D.alt="",D.className="persona-rounded-xl persona-object-cover",D.style.height=s,D.style.width=s,p.replaceChildren(D)}else p.textContent=e?.launcher?.agentIconText??"\u{1F4AC}";let u=v("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),m=F("span",{className:"persona-text-base persona-font-semibold",text:e?.launcher?.title??"Chat Assistant",style:{color:qn.titleColor,...ty}}),g=F("span",{className:"persona-text-xs",text:e?.launcher?.subtitle??"Here to help you get answers fast",style:{color:qn.subtitleColor,...KH}});u.append(m,g),l?o.append(u):o.append(p,u);let h=r.clearChat??{},b=h.enabled??!0,C=h.placement??"inline",M=null,E=null;if(b){let W=$a(e,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});M=W.button,E=W.wrapper,C==="top-right"&&(E.style.right="48px"),C==="inline"&&o.appendChild(E)}let T=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":b&&C==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:H,wrapper:A}=Va(e,{showClose:n,wrapperClassName:T});return a!=="top-right"&&o.appendChild(A),{header:o,iconHolder:p,headerTitle:m,headerSubtitle:g,closeButton:H,closeButtonWrapper:A,clearChatButton:M,clearChatButtonWrapper:E}},Pc=(t,e,n)=>{let o=n?.launcher??{},r=o.closeButtonPlacement??"inline",s=o.clearChat?.placement??"inline";t.appendChild(e.header),r==="top-right"&&(t.style.position="relative",t.appendChild(e.closeButtonWrapper)),e.clearChatButtonWrapper&&s==="top-right"&&(t.style.position="relative",t.appendChild(e.clearChatButtonWrapper))};je();ny();Ii();var GH=t=>{let e=Pi({config:t.config,showClose:t.showClose,onClose:t.onClose,onClearChat:t.onClearChat}),n=t.layoutHeaderConfig?.onTitleClick;if(n){let o=e.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",r=>{(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),n())}))}return e};function YH(t,e,n){if(e?.length)for(let o of e){let{button:r,wrapper:s}=ki({ariaLabel:o.ariaLabel??o.label??o.id,iconName:o.icon,iconText:o.icon?void 0:o.label,tooltipHint:o.shortcut?Fu(o.shortcut):void 0,wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center"});if(r.setAttribute("data-persona-header-action",o.id),o.shortcut){let a=yc(o.shortcut);a&&r.setAttribute("aria-keyshortcuts",a)}if(o.menuItems?.length){let a=Lc({items:o.menuItems,onSelect:l=>n?.(l),anchor:s,position:"bottom-right"});s.appendChild(a.element),r.addEventListener("click",l=>{l.stopPropagation(),a.toggle()})}else r.addEventListener("click",()=>n?.(o.id));t.appendChild(s)}}var QH=t=>{let{config:e,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=t,a=e?.launcher??{},l=v("div","persona-flex persona-items-center persona-justify-between");l.setAttribute("data-persona-theme-zone","header"),l.style.minHeight=qn.minHeight,l.style.padding="var(--persona-components-header-minimalPadding, var(--persona-components-header-padding, 16px 24px))",l.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",l.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",l.style.boxShadow="var(--persona-header-shadow, none)",l.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let c=r?.titleMenu,p,u;if(c){let A=LM({label:a.title??"Chat Assistant",menuItems:c.menuItems,onSelect:D=>{let W=B=>{B===!1&&A.element.dispatchEvent(new CustomEvent("persona:title-menu-builtin",{bubbles:!0,composed:!0,detail:{actionId:D}}))},U=c.onSelect(D);U instanceof Promise?U.then(W,()=>{}):W(U)},hover:c.hover,className:""});p=A.element,p.style.color=qn.titleColor,u=p.querySelector(".persona-combo-btn-label")??p}else{if(p=v("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=v("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=qn.titleColor,Object.assign(u.style,ty),u.textContent=a.title??"Chat Assistant",p.appendChild(u),r?.onTitleClick){p.style.cursor="pointer",p.setAttribute("role","button"),p.setAttribute("tabindex","0");let D=r.onTitleClick;p.addEventListener("click",W=>{W.target.closest("button")||D()}),p.addEventListener("keydown",W=>{(W.key==="Enter"||W.key===" ")&&(W.preventDefault(),D())})}let A=r?.titleRowHover;A&&(p.style.borderRadius=A.borderRadius??"10px",p.style.padding=A.padding??"6px 4px 6px 12px",p.style.margin="-6px 0 -6px -12px",p.style.border="1px solid transparent",p.style.transition="background-color 0.15s ease, border-color 0.15s ease",p.style.width="fit-content",p.style.flex="none",p.addEventListener("mouseenter",()=>{p.style.backgroundColor=A.background??"",p.style.borderColor=A.border??""}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="",p.style.borderColor="transparent"}))}l.appendChild(p);let m="persona-relative persona-inline-flex persona-items-center persona-justify-center",{button:g,wrapper:h}=Va(e,{showClose:n,wrapperClassName:m});o&&g.addEventListener("click",o);let b=v("div","persona-flex persona-items-center persona-gap-1");c||YH(b,r?.trailingActions,r?.onAction??s);let C=a.clearChat??{},M=null,E=null;if(C.enabled??!0){let A=C.placement??"inline",D=$a(e,{wrapperClassName:A==="top-right"?"persona-absolute persona-top-4 persona-z-50":m});M=D.button,E=D.wrapper,A==="top-right"?E.style.right="48px":b.appendChild(E)}b.appendChild(h),l.appendChild(b);let T=v("div");T.style.display="none";let H=v("span");return H.style.display="none",{header:l,iconHolder:T,headerTitle:u,headerSubtitle:H,closeButton:g,closeButtonWrapper:h,clearChatButton:M,clearChatButtonWrapper:E}},IM={default:GH,minimal:QH},XH=t=>IM[t]??IM.default,Qu=(t,e,n)=>{if(e?.render){let a=e.render({config:t,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:e.trailingActions,onAction:e.onAction}),l=v("div");l.style.display="none";let c=v("span"),p=v("span"),u=v("button");u.style.display="none";let m=v("div");return m.style.display="none",{header:a,iconHolder:l,headerTitle:c,headerSubtitle:p,closeButton:u,closeButtonWrapper:m,clearChatButton:null,clearChatButtonWrapper:null}}let o=e?.layout??"default",s=XH(o)({config:t,showClose:e?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:e,onHeaderAction:e?.onAction});return e&&(e.showIcon===!1&&(s.iconHolder.style.display="none"),e.showTitle===!1&&(s.headerTitle.style.display="none"),e.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),e.showCloseButton===!1&&(s.closeButton.style.display="none"),e.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};je();var Ic=t=>{let{config:e}=t,n=F("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),o=du(),r=F("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-persona-border persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""}}),{textarea:s,attachAutoResize:a}=iu(e);a();let l=au(e),c=Da(e),p=lu(e),u=cu(e),m=F("div",{className:"persona-widget-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});r.append(m),p&&(p.previewsContainer.style.gap="8px",m.append(p.previewsContainer),r.append(p.input)),r.append(s);let g=F("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),h=F("div",{className:"persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-start":""}}),b=F("div",{className:"persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-end":""}});return p&&h.append(p.wrapper),c&&b.append(c.wrapper),b.append(l.wrapper),g.append(h,b),r.append(g),r.addEventListener("click",C=>{C.target!==l.button&&C.target!==l.wrapper&&C.target!==c?.button&&C.target!==c?.wrapper&&C.target!==p?.button&&C.target!==p?.wrapper&&s.focus()}),e?.statusIndicator?.mode==="transient"?n.append(o,u,r):n.append(o,r,u),{footer:n,suggestions:o,composerForm:r,header:m,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:c?.button??null,micButtonWrapper:c?.wrapper??null,statusText:u,attachmentButton:p?.button??null,attachmentButtonWrapper:p?.wrapper??null,attachmentInput:p?.input??null,attachmentPreviewsContainer:p?.previewsContainer??null,actionsRow:g,leftActions:h,rightActions:b,setSendButtonMode:l.setMode}};je();var Xu=require("lucide");zn();var RM=()=>{let t=F("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),e=v("span","persona-pill-peek__icon"),n=Ge(Xu.MessageSquare,16,"currentColor",1.5);n&&e.appendChild(n);let o=v("span","persona-pill-peek__text"),r=v("span","persona-pill-peek__caret"),s=Ge(Xu.ChevronUp,16,"currentColor",1.5);return s&&r.appendChild(s),t.append(e,o,r),{root:t,textNode:o}},Ju=t=>{let{config:e}=t,n=F("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=du(),r=cu(e);r.style.display="none";let{textarea:s,attachAutoResize:a}=iu(e,{defaultMaxLines:5});a();let l=au(e),c=Da(e),p=lu(e);p&&p.previewsContainer.classList.add("persona-pill-composer__previews");let u=F("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""}}),m=F("div",{className:"persona-widget-composer__left-actions persona-pill-composer__left",attrs:{"data-persona-composer-actions-start":""}});p&&m.append(p.wrapper);let g=F("div",{className:"persona-widget-composer__right-actions persona-pill-composer__right",attrs:{"data-persona-composer-actions-end":""}});c&&g.append(c.wrapper),g.append(l.wrapper),u.addEventListener("click",C=>{C.target!==l.button&&C.target!==l.wrapper&&C.target!==c?.button&&C.target!==c?.wrapper&&C.target!==p?.button&&C.target!==p?.wrapper&&s.focus()}),p&&u.append(p.input),u.append(m,s,g);let h=F("div",{className:"persona-pill-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});n.append(h),p&&h.append(p.previewsContainer),n.append(o,u,r);let b=u;return{footer:n,suggestions:o,composerForm:u,header:h,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:c?.button??null,micButtonWrapper:c?.wrapper??null,statusText:r,attachmentButton:p?.button??null,attachmentButtonWrapper:p?.wrapper??null,attachmentInput:p?.input??null,attachmentPreviewsContainer:p?.previewsContainer??null,actionsRow:b,leftActions:m,rightActions:g,setSendButtonMode:l.setMode}};je();Zt();je();Ii();Zt();Sc();var JH=t=>{switch(t){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},ZH=(t,e)=>{if(!t)return null;let n=JH(t);if(n===null)return null;let o=e?.[t],r=o!==void 0?o:n;return r||null},eW=(t,e)=>{let n=v("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",t),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=e,n},tW=t=>{let e=t.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:image/")||!t.includes(":"))},ry=t=>{let e=t.toLowerCase();return e.startsWith("javascript:")||e.startsWith("data:text/html")||e.startsWith("data:text/javascript")||e.startsWith("data:text/xml")||e.startsWith("data:application/xhtml")||e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:")||!t.includes(":"))},sy=320,OM=320,nW=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),oW=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),rW=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),sW=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),iW=t=>{if(!t||t.length===0)return null;let e=F("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});e.style.display="flex";for(let n of t){let o=F("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=v("span","persona-mention-chip-icon"),s=ke(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild(F("span",{className:"persona-mention-chip-label",text:n.label})),e.appendChild(o)}return e},aW=(t,e)=>{let n=document.createDocumentFragment();for(let o of t){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(pc(o.ref,{readonly:!0,render:e}))}return n},HM="\uE000",WM="\uE001",lW=(t,e,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=g=>`${HM}${r}:${g}${WM}`,a=e.map((g,h)=>g.kind==="text"?g.text:s(h)).join(""),l=n(a);if(!e.every((g,h)=>g.kind==="text"||l.includes(s(h)))){t.replaceChildren(aW(e,o));return}t.innerHTML=l;let p=new RegExp(`${HM}${r}:(\\d+)${WM}`),u=document.createTreeWalker(t,NodeFilter.SHOW_TEXT),m=[];for(let g=u.nextNode();g;g=u.nextNode())m.push(g);for(let g of m){let h=g;for(let b=p.exec(h.data);b;b=p.exec(h.data)){let C=e[Number(b[1])],M=h.splitText(b.index);M.data=M.data.slice(b[0].length),C?.kind==="mention"&&M.parentNode?.insertBefore(pc(C.ref,{readonly:!0,render:o}),M),h=M}}},cW=(t,e,n)=>{if(t.length===0)return null;try{let o=v("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),e&&(o.style.marginBottom="8px");let r=0,s=!1,a=()=>{s||(s=!0,o.remove(),n?.())};return t.forEach((l,c)=>{let p=v("img");p.alt=l.alt?.trim()||`Attached image ${c+1}`,p.loading="lazy",p.decoding="async",p.referrerPolicy="no-referrer",p.style.display="block",p.style.width="100%",p.style.maxWidth=`${sy}px`,p.style.maxHeight=`${OM}px`,p.style.height="auto",p.style.objectFit="contain",p.style.borderRadius="10px",p.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",p.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let u=!1;r+=1,p.addEventListener("error",()=>{u||(u=!0,r=Math.max(0,r-1),p.remove(),r===0&&a())}),p.addEventListener("load",()=>{u=!0}),tW(l.image)?(p.src=l.image,o.appendChild(p)):(u=!0,r=Math.max(0,r-1),p.remove())}),r===0?(a(),null):o}catch{return n?.(),null}},dW=t=>{if(t.length===0)return null;try{let e=v("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","audio");let n=0;return t.forEach(o=>{if(!ry(o.audio))return;let r=v("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${sy}px`,e.appendChild(r),n+=1}),n===0?(e.remove(),null):e}catch{return null}},pW=t=>{if(t.length===0)return null;try{let e=v("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","video");let n=0;return t.forEach(o=>{if(!ry(o.video))return;let r=v("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${sy}px`,r.style.maxHeight=`${OM}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",e.appendChild(r),n+=1}),n===0?(e.remove(),null):e}catch{return null}},uW=t=>{if(t.length===0)return null;try{let e=v("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","files");let n=0;return t.forEach(o=>{if(!ry(o.data))return;let r=v("a");r.href=o.data,r.download=o.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=o.filename,r.className="persona-message-file-attachment",r.style.display="inline-flex",r.style.alignItems="center",r.style.gap="6px",r.style.padding="6px 10px",r.style.borderRadius="8px",r.style.fontSize="0.875rem",r.style.textDecoration="underline",r.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",r.style.color="inherit",e.appendChild(r),n+=1}),n===0?(e.remove(),null):e}catch{return null}},Rc=()=>{let t=document.createElement("div");t.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let e=document.createElement("div");e.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",e.style.backgroundColor="currentColor",e.style.opacity="0.4",e.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let r=document.createElement("span");return r.className="persona-sr-only",r.textContent="Loading",t.appendChild(e),t.appendChild(n),t.appendChild(o),t.appendChild(r),t},mW=(t,e,n)=>{let o={config:n??{},streaming:!0,location:t,defaultRenderer:Rc};if(e){let r=e(o);if(r!==null)return r}return Rc()},fW=(t,e)=>{let n=v("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=e==="user"?t.userAvatar:t.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=v("img");r.src=o,r.alt=e==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(r)}else n.textContent=o,n.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=e==="user"?"U":"A",n.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},BM=(t,e,n="div")=>{let o=v(n,"persona-text-xs persona-text-persona-muted"),r=new Date(t.createdAt);return e.format?o.textContent=e.format(r):o.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},Hc=(t,e="bubble")=>{let n=["persona-message-bubble"];switch(e){case"flat":t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-text","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-text-persona-text","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-border","persona-border-persona-message-border","persona-text-persona-text","persona-px-5","persona-py-3");break}return n},DM={bubble:{padding:"0.75rem 1.25rem",fontSize:"0.875rem",lineHeight:"1.75"},minimal:{padding:"0.5rem 0.75rem",fontSize:"0.875rem",lineHeight:"1.75"},flat:{padding:"0.5rem 0",fontSize:"inherit",lineHeight:"inherit"}},gW=(t,e,n="bubble",o)=>{if(!o)return;let r=e==="user"?"user":"assistant",s=DM[n??"bubble"]??DM.bubble;o.padding&&(t.style.padding=`var(--persona-message-${r}-padding, ${s.padding})`),o.fontSize&&(t.style.fontSize=`var(--persona-message-${r}-font-size, ${s.fontSize})`),o.lineHeight&&(t.style.lineHeight=`var(--persona-message-${r}-line-height, ${s.lineHeight})`),o.fontFamily&&(t.style.fontFamily=`var(--persona-message-${r}-font-family, inherit)`)},Zu="custom:",hW=t=>`${Zu}${t}`,_M=(t,e)=>e!=="user"&&e!=="assistant"?[]:(t?.custom??[]).filter(n=>(n.roles??["assistant"]).includes(e)),yW=(t,e,n,o)=>{let r=e.showCopy??!0,s=e.showUpvote??!1,a=e.showDownvote??!1,l=e.showReadAloud??!1,c=(e.showRegenerate??!1)&&o?.canRegenerate===!0,p=(e.showEdit??!1)&&o?.canEdit===!0,u=(e.showQuote??!1)&&o?.canQuote!==!1,m=_M(e,t.role);if(!r&&!s&&!a&&!l&&!c&&!p&&!u&&m.length===0){let H=v("div");return H.style.display="none",H.id=`actions-${t.id}`,H.setAttribute("data-actions-for",t.id),H}let g=e.visibility??"hover",h=e.align??"right",b=e.layout??"pill-inside",C={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[h],M={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[b],E=v("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${C} ${M} ${g==="hover"?"persona-message-actions-hover":""}`);E.id=`actions-${t.id}`,E.setAttribute("data-actions-for",t.id);let T=(H,A,D)=>{let W=vn({icon:H,label:A,size:14,className:"persona-message-action-btn",chromeless:!0});return W.setAttribute("data-action",D),W};r&&E.appendChild(T("copy","Copy message","copy")),l&&E.appendChild(T("volume-2","Read aloud","read-aloud")),s&&E.appendChild(T("thumbs-up","Upvote","upvote")),a&&E.appendChild(T("thumbs-down","Downvote","downvote")),c&&E.appendChild(T("refresh-cw","Regenerate response","regenerate")),p&&E.appendChild(T("pencil","Edit message","edit")),u&&E.appendChild(T("quote","Quote message","quote"));for(let H of m)E.appendChild(T(H.iconName??"ellipsis",H.label,hW(H.id)));return E},iy=(t,e,n,o,r,s)=>{let a=n??{},l=a.layout??"bubble",c=a.avatar,p=a.timestamp,u=c?.show??!1,m=p?.show??!1,g=c?.position??"left",h=p?.position??"below",b=Hc(t.role,l),C=v("div",b.join(" "));C.id=`bubble-${t.id}`,C.setAttribute("data-message-id",t.id),C.setAttribute("data-persona-theme-zone",t.role==="user"?"user-message":"assistant-message");let M=Oh(s?.widgetConfig?.future).components.message,E=s?.widgetConfig?.theme?.components?.message;gW(C,t.role,l,t.role==="user"?{...M.user,...E?.user,...s?.widgetConfig?.darkTheme?.components?.message?.user}:{...M.assistant,...E?.assistant,...s?.widgetConfig?.darkTheme?.components?.message?.assistant}),l==="flat"?(C.style.backgroundColor="transparent",C.style.color=t.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):t.role==="user"?(C.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",C.style.color="var(--persona-message-user-text, white)"):t.role==="assistant"&&(C.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",C.style.color="var(--persona-message-assistant-text, var(--persona-text))");let T=nW(t),H=t.content?.trim()??"",D=T.length>0&&H===Ra,W=qu(s?.widgetConfig?.features?.streamAnimation),U=s?.widgetConfig?.features?.streamAnimation?.plugins,B=t.role==="assistant"&&W.type!=="none"?vc(W.type,U):null,O=t.role==="assistant"&&B?.isAnimating?.(t)===!0,R=t.role==="assistant"&&B!==null&&(!!t.streaming||O);R&&B?.bubbleClass&&C.classList.add(B.bubbleClass);let S=document.createElement("div");S.classList.add("persona-message-content"),t.streaming&&S.classList.add("persona-content-streaming"),R&&B&&(B.containerClass&&S.classList.add(B.containerClass),S.style.setProperty("--persona-stream-step",`${W.speed}ms`),S.style.setProperty("--persona-stream-duration",`${W.duration}ms`));let x=R?ju(t.content??"",W.buffer,B,t,!!t.streaming):t.content??"",P=()=>{let se=e({text:x,message:t,streaming:!!t.streaming,raw:t.rawContent});return R&&B?.wrap==="char"?Cc(se,"char",t.id,{skipTags:B.skipTags}):R&&B?.wrap==="word"?Cc(se,"word",t.id,{skipTags:B.skipTags}):se},L=null;if(D?(L=document.createElement("div"),L.innerHTML=P(),L.style.display="none",S.appendChild(L)):t.contentSegments?.length?lW(S,t.contentSegments,se=>e({text:se,message:t,streaming:!!t.streaming,raw:t.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):S.innerHTML=P(),R&&B?.useCaret&&!D&&H){let se=Ku(),_=S.querySelectorAll(".persona-stream-char, .persona-stream-word"),Te=_[_.length-1];if(Te?.parentNode)Te.parentNode.insertBefore(se,Te.nextSibling);else{let He=S.lastElementChild;He?He.appendChild(se):S.appendChild(se)}}if(m&&h==="inline"&&t.createdAt){let se=BM(t,p,"span");se.classList.add("persona-timestamp-inline");let _=S.lastElementChild;_?_.appendChild(se):S.appendChild(se)}if(T.length>0){let se=cW(T,!D&&!!H,()=>{D&&L&&(L.style.display="")});se?C.appendChild(se):D&&L&&(L.style.display="")}let G=oW(t);if(G.length>0){let se=dW(G);se&&C.appendChild(se)}let V=rW(t);if(V.length>0){let se=pW(V);se&&C.appendChild(se)}let K=sW(t);if(K.length>0){let se=uW(K);se&&C.appendChild(se)}let ee=t.contentSegments?.length?null:iW(t.contextMentions);if(ee&&C.appendChild(ee),C.appendChild(S),m&&h==="below"&&t.createdAt){let se=BM(t,p);se.classList.add("persona-mt-1"),C.appendChild(se)}let oe=t.role==="assistant"?ZH(t.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(t.streaming&&t.role==="assistant"){let se=!!(x&&x.trim()),_=W.placeholder==="skeleton",Te=_&&W.buffer==="line"&&se;if(se)Te&&C.appendChild(wc());else if(_)C.appendChild(wc());else{let He=mW("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);He&&C.appendChild(He)}}oe&&t.stopReason&&!t.streaming&&(H||(S.style.display="none"),C.appendChild(eW(t.stopReason,oe)));let ne=t.role==="assistant"&&!t.streaming&&t.content&&t.content.trim()&&o?.enabled!==!1,le=s?.actionEligibility,de=t.role==="user"&&!t.streaming&&o?.enabled!==!1&&(o?.showEdit===!0&&le?.canEdit===!0||o?.showQuote===!0&&le?.canQuote===!0||_M(o,"user").length>0);if((ne||de)&&o){let se=yW(t,de?{...o,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:o,r,le);C.appendChild(se)}if(!u||t.role==="system")return C;let ve=v("div",`persona-message-with-avatar persona-flex persona-gap-2 ${t.role==="user"?"persona-flex-row-reverse":""}`),Le=fW(c,t.role);return g==="right"||g==="left"&&t.role==="user"?ve.append(C,Le):ve.append(Le,C),ve};var bW=40,vW=(t,e)=>{if(t.replaceChildren(),!e){t.hidden=!0;return}if(typeof e=="function"){let n=null;try{n=e()}catch(o){console.warn("[persona] welcome.icon renderer threw",o)}if(!n){t.hidden=!0;return}t.appendChild(n),t.hidden=!1;return}if(e.type==="lucide"){let n=ke(e.name,bW);if(!n){t.hidden=!0;return}t.appendChild(n)}else e.type==="image"?t.appendChild(F("img",{className:"persona-welcome-icon-image",attrs:{src:e.url,alt:e.alt}})):t.appendChild(F("span",{className:"persona-welcome-icon-text",text:e.text}));t.hidden=!1},NM=(t,e,n={})=>{let o=F("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});o.hidden=!0;let r=v("p","persona-welcome-kicker");r.hidden=!0;let s=v("h2","persona-welcome-title"),a=v("p","persona-welcome-subtitle"),l=F("div",{className:"persona-welcome-head-text"},r,s),c=F("div",{className:"persona-welcome-title-row"},o,l);return{host:F("div",{className:"persona-welcome persona-rounded-2xl",attrs:{"data-persona-welcome":"","data-persona-intro-card":"","data-persona-welcome-variant":"card"},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:n.flatShadow?"none":"var(--persona-intro-card-shadow, none)",border:"var(--persona-intro-card-border, none)"}},c,a,e),iconHolder:o,kicker:r,title:s,subtitle:a,starterSuggestions:e}},za=(t,e,n)=>{e.hidden=!n,e.style.display=n?"":"none",t.classList.toggle("persona-gap-6",n),t.classList.toggle("persona-gap-3",!n)},tm=(t,e)=>{t.title.textContent=e.title,t.kicker.textContent=e.kicker??"",t.kicker.hidden=!e.kicker,t.subtitle.textContent=e.subtitle,t.subtitle.hidden=e.subtitle==="",vW(t.iconHolder,e.icon),t.host.setAttribute("data-persona-welcome-variant",e.variant),t.host.setAttribute("data-persona-welcome-dismiss",e.dismiss),t.host.setAttribute("data-persona-welcome-layout",e.layout??"top"),t.host.setAttribute("data-persona-welcome-anchor",e.anchor??"bottom"),e.iconPlacement==="inline"?t.host.setAttribute("data-persona-welcome-icon-placement","inline"):t.host.removeAttribute("data-persona-welcome-icon-placement"),e.align?t.host.setAttribute("data-persona-welcome-align",e.align):t.host.removeAttribute("data-persona-welcome-align")},CW="data-persona-welcome-plugin",FM="data-persona-welcome-overlay",em="persona-welcome-overlay-active",ay=new WeakMap,ly=(t,e,n)=>{n.setAttribute(CW,""),e.appendChild(n),e.setAttribute("data-persona-welcome-content","plugin"),e.setAttribute(FM,""),t.classList.contains(em)||(ay.set(t,t.scrollTop),t.classList.add(em),t.scrollTop=0)},cy=(t,e,n)=>{n&&n!==e&&n.remove(),e.removeAttribute("data-persona-welcome-content"),e.removeAttribute(FM),t.classList.contains(em)&&(t.classList.remove(em),t.scrollTop=ay.get(t)??t.scrollTop,ay.delete(t))},VM=()=>{let t=F("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return t.hidden=!0,t},nm=(t,e,n)=>{if(t.replaceChildren(),!e){t.hidden=!0;return}let o=n?.layout?.messages?.layout??"bubble",r=F("div",{className:Hc("assistant",o).join(" "),attrs:{"data-persona-theme-zone":"assistant-message"},text:e,style:o==="flat"?{backgroundColor:"transparent",color:"var(--persona-message-assistant-text, var(--persona-text))"}:{backgroundColor:"var(--persona-message-assistant-bg, var(--persona-container))",color:"var(--persona-message-assistant-text, var(--persona-text))"}});t.appendChild(F("div",{className:"persona-flex"},r)),t.hidden=!1},$M=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,zM=(t,e)=>{if($M()||typeof t.animate!="function"||!t.isConnected)return e(null),null;let n=t.getBoundingClientRect(),o=t.parentElement,r=0,s=0,a=0;if(o){let b=getComputedStyle(o);r=parseFloat(b.rowGap)||0;let C=t.previousElementSibling,M=t.nextElementSibling,T=o.getBoundingClientRect().top+(parseFloat(b.borderTopWidth)||0)+(parseFloat(b.paddingTop)||0)-o.scrollTop;s=Math.max(0,C?n.top-C.getBoundingClientRect().bottom-r:n.top-T),a=Math.max(0,M?M.getBoundingClientRect().top-n.bottom-r:0)}let l=t.style.overflow;t.style.overflow="hidden";let c=getComputedStyle(t),p=parseFloat(c.paddingTop)||0,u=parseFloat(c.paddingBottom)||0,m=t.animate([{opacity:"1",transform:"none",height:`${n.height}px`,minHeight:"0px",paddingTop:`${p}px`,paddingBottom:`${u}px`,marginTop:`${s}px`,marginBottom:`${a}px`},{opacity:"0",transform:"translateY(-4px)",height:"0px",minHeight:"0px",paddingTop:"0px",paddingBottom:"0px",marginTop:"0px",marginBottom:`${-r}px`}],{duration:180,easing:"ease-out",fill:"forwards"}),g=!1,h=()=>{g||(g=!0,t.style.overflow=l,e(m))};return m.finished.then(h).catch(h),m},UM=(t,e,n,o=260)=>{if(e<=1||$M()||typeof t.animate!="function"||!t.isConnected)return null;let r=n==="drop"?-e:e;return t.animate([{transform:`translateY(${r}px)`},{transform:"none"}],{duration:o,easing:"cubic-bezier(0.2, 0, 0, 1)",fill:"none"})};var wW="Hello \u{1F44B}",xW="I can answer questions and help you get things done here.",qM=new WeakSet,jn=(t,e)=>!!t&&t[e]!==void 0,SW=(t,e)=>{!t||t.debug!==!0||!e.length||qM.has(t)||(qM.add(t),e.forEach(n=>console.warn(`[persona] ${n}`)))},om=(t,e=t?.launcher?.fullHeight===!0&&!t.launcher.sidebarMode&&t.launcher.mountMode!=="docked")=>{let n=t?.welcome,o=t?.copy,r=t?.future?.v5Defaults===!0,s=n?.layout??(r?"centered":"top"),a=jn(n,"variant")?n.variant:o?.showWelcomeCard===!1?"none":"card",l=a==="hero"&&!r&&n?.layout===void 0?"on-first-message":jn(n,"dismiss")?n.dismiss:r||a==="hero"?"on-first-message":"never",c=[];jn(n,"title")&&jn(o,"welcomeTitle")&&c.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),jn(n,"subtitle")&&jn(o,"welcomeSubtitle")&&c.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),jn(n,"variant")&&jn(o,"showWelcomeCard")&&c.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),a==="hero"&&jn(n,"message")&&c.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),!r&&n?.layout===void 0&&a==="hero"&&jn(n,"dismiss")&&n.dismiss!=="on-first-message"&&c.push('welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".');let p=n?.anchor??(s==="centered"&&e?"center":"bottom"),u=hc(n?.anchorComposerTop)!==null;return jn(n,"anchorComposerTop")&&!u&&c.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),p!=="center"&&(jn(n,"anchorComposerTop")||jn(n,"composerGap"))&&c.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),SW(t,c),{title:jn(n,"title")?n.title:o?.welcomeTitle??(r?"What can I help with?":wW),kicker:n?.kicker??"",subtitle:jn(n,"subtitle")?n.subtitle:o?.welcomeSubtitle??(r?"":xW),icon:n?.icon,align:n?.align==="start"||n?.align==="center"?n.align:s==="centered"?"center":void 0,iconPlacement:n?.icon&&typeof n.icon!="function"&&n.icon.placement==="inline"?"inline":"above",variant:a,dismiss:l,message:a==="hero"?void 0:n?.message,layout:s,anchor:p,anchorComposerTop:u?n.anchorComposerTop:"44%",composerGap:n?.composerGap?.trim()||Ou}},jM=t=>(t??[]).some(e=>e.role==="user")?"active":"empty",Ua=(t,e)=>t.variant==="none"?!1:t.dismiss==="never"?!0:!(e??[]).some(n=>n.role==="user");var AW="var(--persona-components-panel-maxWidth)",KM="var(--persona-components-panel-height)",MW="var(--persona-components-panel-maxHeight)",Ri=t=>{let e=Nr(t),n=e.launcherWidth?t?.launcher?.width:e.legacyLauncherWidth?t?.launcherWidth:void 0,o=t?.launcher?.heightOffset??0,r=o===0?`max(200px, ${KM})`:`max(200px, calc(${KM} - ${o}px))`;return{width:n??yw,maxWidth:n??AW,height:r,maxHeight:MW}},GM="16px",py="10px",uy="14px",YM=t=>{let e=t?.launcher?.enabled??!0,n=nn(t);if(Ec(t)){let p=t?.launcher?.composerBar??{},u=v("div","persona-widget-wrapper persona-fixed persona-transition");u.setAttribute("data-persona-composer-bar",""),u.dataset.state="collapsed",u.dataset.expandedSize=p.expandedSize??"anchored",u.style.zIndex=String(t?.launcher?.zIndex??On);let m=v("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");m.style.width="100%",u.appendChild(m);let g=v("div","persona-widget-pill-root");return g.setAttribute("data-persona-composer-bar",""),g.dataset.state="collapsed",g.dataset.expandedSize=p.expandedSize??"anchored",g.style.zIndex=String(t?.launcher?.zIndex??On),{wrapper:u,panel:m,pillRoot:g}}if(n){let p=v("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),u=v("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return p.appendChild(u),{wrapper:p,panel:u}}if(!e){let p=v("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),u=v("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),m=Nr(t),h=m.launcherWidth||m.legacyLauncherWidth||t?.theme?.components?.panel?.width!==void 0?Ri(t).width:"100%";return p.style.width=h,u.style.width="100%",p.appendChild(u),{wrapper:p,panel:u}}let r=t?.launcher??{},s=r.position&&vo[r.position]?vo[r.position]:vo["bottom-right"],a=v("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String(t?.launcher?.zIndex??On);let l=v("div","persona-widget-panel persona-relative persona-min-h-[320px]"),c=Ri(t);return l.style.width=c.width,l.style.maxWidth=c.maxWidth,a.appendChild(l),{wrapper:a,panel:l}},my=t=>{let e=F("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":Jh(t)}});return e.hidden=!0,e},QM=(t,e)=>{let n=my("starter"),o=NM(t,n,{flatShadow:nn(t)}),r=om(t);tm(o,r),za(e,o.host,Ua(r,t?.initialMessages));let s=VM();return nm(s,r.message,t),{welcome:o,greetingHost:s}},TW=(t,e)=>{let n=v("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:r}=Va(t,{showClose:e,wrapperClassName:"persona-composer-bar-close",buttonSize:GM,iconSize:py});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let s=t?.launcher?.clearChat?.enabled??!0,a=null,l=null;if(s){let U=$a(t,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:GM,iconSize:uy});a=U.button,l=U.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let c=F("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),p=F("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});p.style.setProperty("scrollbar-gutter","stable");let{welcome:u,greetingHost:m}=QM(t,p),{host:g,title:h,subtitle:b}=u,C=u.starterSuggestions,M=v("div","persona-widget-messages persona-flex persona-flex-col");M.style.gap="var(--persona-components-message-gap, 12px)";let E=my("followUp"),T=Is(t,!0);T&&(M.style.maxWidth=T,M.style.marginLeft="auto",M.style.marginRight="auto",M.style.width="100%"),p.append(g,m,M,E);let H=F("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}}),A=Ju({config:t}),{root:D,textNode:W}=RM();return n.append(c,r,p,H),l&&n.appendChild(l),{container:n,body:p,messagesWrapper:M,starterSuggestions:C,transcriptSuggestions:E,composerOverlay:H,suggestions:A.suggestions,textarea:A.textarea,sendButton:A.sendButton,sendButtonWrapper:A.sendButtonWrapper,micButton:A.micButton,micButtonWrapper:A.micButtonWrapper,composerForm:A.composerForm,statusText:A.statusText,welcomeHost:g,welcomeIconHolder:u.iconHolder,greetingHost:m,introKicker:u.kicker,introTitle:h,introSubtitle:b,closeButton:o,closeButtonWrapper:r,clearChatButton:a,clearChatButtonWrapper:l,iconHolder:v("span"),headerTitle:v("span"),headerSubtitle:v("span"),header:c,footer:A.footer,attachmentButton:A.attachmentButton,attachmentButtonWrapper:A.attachmentButtonWrapper,attachmentInput:A.attachmentInput,attachmentPreviewsContainer:A.attachmentPreviewsContainer,actionsRow:A.actionsRow,leftActions:A.leftActions,rightActions:A.rightActions,setSendButtonMode:A.setSendButtonMode,peekBanner:D,peekTextNode:W}},XM=(t,e=!0)=>{if(Ec(t))return TW(t,e);let n=F("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),o=t?.layout?.header,r=t?.layout?.showHeader!==!1,s=o?Qu(t,o,{showClose:e}):Pi({config:t,showClose:e}),a=F("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});a.style.setProperty("scrollbar-gutter","stable");let{welcome:l,greetingHost:c}=QM(t,a),{host:p,title:u,subtitle:m}=l,g=l.starterSuggestions,h=v("div","persona-widget-messages persona-flex persona-flex-col");h.style.gap="var(--persona-components-message-gap, 12px)";let b=my("followUp"),C=Is(t,!1);C&&(h.style.maxWidth=C,h.style.marginLeft="auto",h.style.marginRight="auto",h.style.width="100%"),a.append(p,c,h,b);let M=Ic({config:t}),E=t?.layout?.showFooter!==!1;r?Pc(n,s,t):(s.header.style.display="none",Pc(n,s,t)),n.append(a);let T=F("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}});return E||(M.footer.style.display="none"),n.append(M.footer),n.append(T),{container:n,body:a,messagesWrapper:h,starterSuggestions:g,transcriptSuggestions:b,composerOverlay:T,suggestions:M.suggestions,textarea:M.textarea,sendButton:M.sendButton,sendButtonWrapper:M.sendButtonWrapper,micButton:M.micButton,micButtonWrapper:M.micButtonWrapper,composerForm:M.composerForm,statusText:M.statusText,welcomeHost:p,welcomeIconHolder:l.iconHolder,greetingHost:c,introKicker:l.kicker,introTitle:u,introSubtitle:m,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:M.footer,attachmentButton:M.attachmentButton,attachmentButtonWrapper:M.attachmentButtonWrapper,attachmentInput:M.attachmentInput,attachmentPreviewsContainer:M.attachmentPreviewsContainer,actionsRow:M.actionsRow,leftActions:M.leftActions,rightActions:M.rightActions,setSendButtonMode:M.setSendButtonMode}};je();Zt();ks();var fy=(t,e)=>{let n=v("button");n.type="button",n.innerHTML=`
|
|
1158
|
+
`)[0]).startsWith(D.trigger):!1),s=(A,D)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${A}`,{detail:D}))}catch{}},a=!t.chipRow,l=t.chipRow??F("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),c=null,p=null,u=t.textarea,m=null,g=null,h=null,b=null,C=()=>{if(c)return Promise.resolve(c);if(p)return p;let A=kh().then(D=>(D.setMentionIconRenderer(ke),c=D.mountContextMentions({mentionConfig:e,textarea:t.textarea,composerInput:m??void 0,anchor:t.anchor,contextRow:l,getMessages:t.getMessages,getConfig:()=>t.config,liveRegionHost:t.liveRegionHost,popoverContainer:t.popoverContainer,onPickerOpenChange:R,emit:s}),c)).catch(D=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",D),p===A&&(p=null),null));return p=A,A},M=()=>{jA().then(A=>{let D=A.mountInlineComposer({textarea:t.textarea,renderToken:U=>pc(U,{render:e.renderMentionToken}),onMentionRemoved:U=>c?.untrackMention(U)});m=D.input,g=D.destroy;let W=u;W.replaceWith(D.element),u=D.element,b={next:D.element,prev:W},h?.(D.element,W),c?c.rebindComposer(D.input):p&&p.then(U=>U?.rebindComposer(D.input))}).catch(A=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",A)})};e.display==="inline"&&M();let E=[],T=new Map;for(let A of n){if(!A.showButton)continue;let D=gA({config:{...e,buttonIconName:A.buttonIconName,buttonTooltipText:A.buttonTooltipText},onOpen:()=>{C().then(W=>W?.openMenu(A.trigger))}});E.push(D),T.set(A.trigger,D.button)}let R=(A,D,W)=>{let U=T.get(D);U&&(U.setAttribute("aria-expanded",A?"true":"false"),A?U.setAttribute("aria-controls",W):U.removeAttribute("aria-controls"))};return{affordanceButtons:E.map(A=>A.wrapper),contextRow:l,handleInput:A=>{if(c){c.handleInput();return}if(!mA(A))return;let D=u,W=D.selectionStart??0;ic(D.value,W,n)&&C().then(U=>U?.handleInput())},handleKeydown:A=>{if(c?.isMenuOpen())return c.handleKeydown(A);if(A.key==="Backspace"&&c?.hasMentions()&&!b){let D=u,W=D.selectionStart===0&&D.selectionEnd===0;if((D.value.length===0||W)&&c.removeLastChip())return A.preventDefault(),!0}return!1},isMenuOpen:()=>c?.isMenuOpen()??!1,hasMentions:()=>c?.hasMentions()??!1,getMentionRefs:()=>c?.getMentionRefs()??[],collectForSubmit:()=>c?.collectForSubmit()??null,takeInlineCommand:async A=>r(A)?(c??await C())?.dispatchInlineCommand(A)??null:null,clear:()=>c?.clear(),prefetch:()=>{kh().catch(()=>{})},onComposerSwap:A=>{h=A,b&&A(b.next,b.prev)},destroy:()=>{c?.destroy(),g?.();for(let A of E)A.wrapper.remove();a&&l.remove()}}}var Iu=t=>t?.launcher?.variant??(t?.future?.v5Defaults===!0?"circle":"pill"),Hu={background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",border:"transparent",size:"48px",iconSize:"24px",borderRadius:"palette.radius.full",shadow:"0 8px 24px rgba(0,0,0,.16)",offset:"20px"};var Wu="16px",Bu="transparent",oR=(()=>{let t={};for(let e of[0,1,2,3,4,5,6,8,10,12,16,20,24,32,40,48,56,64])t[e]=e===0?"0px":`${e/4}rem`;return t})(),uc={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"},purple:{50:"#faf5ff",100:"#f3e8ff",200:"#e9d5ff",300:"#d8b4fe",400:"#c084fc",500:"#a855f7",600:"#9333ea",700:"#7e22ce",800:"#6b21a8",900:"#581c87",950:"#3b0764"},teal:{50:"#f0fdfa",100:"#ccfbf1",200:"#99f6e4",300:"#5eead4",400:"#2dd4bf",500:"#14b8a6",600:"#0d9488",700:"#0f766e",800:"#115e59",900:"#134e4a",950:"#042f2e"}},spacing:oR,typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},Ru={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.50",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.info.500"}},spacing:{xs:"palette.spacing.1",sm:"palette.spacing.2",md:"palette.spacing.4",lg:"palette.spacing.6",xl:"palette.spacing.8","2xl":"palette.spacing.10"},typography:{fontFamily:"palette.typography.fontFamily.sans",fontSize:"palette.typography.fontSize.base",fontWeight:"palette.typography.fontWeight.normal",lineHeight:"palette.typography.lineHeight.normal"}},bo={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm",hoverBackground:"rgba(0, 0, 0, 0.05)"}},input:{background:"semantic.colors.surface",placeholder:"semantic.colors.textMuted",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"semantic.colors.surface",foreground:"semantic.colors.primary",border:"semantic.colors.border",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:Sg,maxWidth:"none",height:"min(640px, max(200px, calc(100vh - 64px)))",maxHeight:"none",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:Wu,canvasBackground:Bu,modes:{floating:{border:"1px solid var(--persona-border)",shadow:"palette.shadows.xl",borderRadius:"palette.radius.xl"},inline:{border:"1px solid var(--persona-border)",shadow:"none",borderRadius:"palette.radius.xl"},docked:{border:"none",shadow:"none",borderRadius:"palette.radius.xl"},sidebar:{border:"none",borderRadius:"0"},mobile:{border:"none",shadow:"none",borderRadius:"0"}}},header:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"20px 24px",minimalPadding:"16px 24px",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50"},message:{gap:"12px",user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"semantic.colors.container",text:"semantic.colors.text",borderRadius:"palette.radius.lg",border:"semantic.colors.border",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"transparent",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"palette.shadows.none"},suggestion:{chip:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.full",padding:"0.5rem 0.875rem",gap:"0.5rem",itemGap:"8px",minHeight:"36px",fontSize:"0.8125rem",lineHeight:"1.25",iconSize:"16px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},card:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.xl",padding:"1rem",shadow:"palette.shadows.sm",gap:"0.625rem",itemGap:"8px",minHeight:"72px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"18px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},list:{background:"transparent",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.md",padding:"0.75rem",gap:"0.625rem",itemGap:"8px",minHeight:"44px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"17px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"}},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},scrollbar:{thumb:"semantic.colors.border",track:"transparent"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit",borderRadius:"palette.radius.md"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},eventStream:{badge:{flow:{background:"palette.colors.success.100",foreground:"palette.colors.success.700"},step:{background:"palette.colors.primary.100",foreground:"palette.colors.primary.700"},reasoning:{background:"palette.colors.warning.100",foreground:"palette.colors.warning.700"},tool:{background:"palette.colors.purple.100",foreground:"palette.colors.purple.800"},agent:{background:"palette.colors.teal.100",foreground:"palette.colors.teal.800"},error:{background:"palette.colors.error.100",foreground:"palette.colors.error.700"},default:{background:"palette.colors.gray.100",foreground:"palette.colors.gray.600"}}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}},rR=uc.colors.gray,sR={50:"#fafafa",100:"#f5f5f5",200:"#e5e5e5",300:"#d4d4d4",400:"#a3a3a3",500:"#737373",600:"#525252",700:"#404040",800:"#262626",900:"#171717",950:"#0a0a0a"},iR={...uc,colors:{...uc.colors,gray:rR}},aR={...uc,colors:{...uc.colors,gray:sR},radius:{none:"0px",sm:"4px",md:"8px",lg:"12px",xl:"16px","2xl":"24px",full:"9999px"}};var lR=Ru,cR={...Ru,colors:{...Ru.colors,surface:"#ffffff",background:"#ffffff",container:"semantic.colors.surface",textInverse:"#ffffff"},typography:{...Ru.typography,fontSize:"14px",lineHeight:"1.5"}};var _h=bo,dR={...bo,launcher:Hu,activity:{rowHeight:"32px",labelSize:"13px",iconSize:"16px",indent:"0px",groupIndent:"0px",groupGap:"0px",groupPadding:"0px",transcriptGap:"0px",responseGap:"12px",bodyPadding:"4px 0",bodySize:"13px",bodyLineHeight:"1.5",bodyFontWeight:"400",sectionGap:"8px",bodySurface:"transparent"},toolBubble:{shadow:"none"},reasoningBubble:{shadow:"none"},input:{...bo.input,borderRadius:"palette.radius.full"},introCard:{...bo.introCard,title:{fontSize:"22px",fontWeight:"500"}},suggestion:{chip:{...bo.suggestion.chip,fontWeight:"400"},card:{...bo.suggestion.card,fontWeight:"400"},list:{...bo.suggestion.list,fontWeight:"400"}},panel:{...bo.panel,width:"min(400px, calc(100vw - 24px))",height:"min(704px, calc(100dvh - 104px))",borderRadius:"palette.radius.xl"},header:{...bo.header,background:"semantic.colors.container",foreground:"semantic.colors.text",padding:"8px 8px 8px 16px",minimalPadding:"8px 8px 8px 16px",minHeight:"48px",borderBottom:"none",iconBackground:"transparent",iconForeground:"semantic.colors.text",iconScale:"1",controlSize:"28px",controlIconSize:"18px",controlStrokeWidth:"1.5",actionIconForeground:"semantic.colors.textMuted",controlBorderRadius:"8px",controlHoverBackground:"color-mix(in srgb, var(--persona-text) 8%, transparent)",controlHoverForeground:"semantic.colors.text",controlFocusOutline:"2px solid color-mix(in srgb, var(--persona-text) 50%, transparent)",title:{fontSize:"14px",fontWeight:"500",lineHeight:"1.5"}},message:{...bo.message,gap:"20px",fullscreenGap:"28px",topFadeHeight:"18px",user:{...bo.message.user,background:"palette.colors.gray.100",text:"semantic.colors.text",borderRadius:"palette.radius.xl",shadow:"none",padding:"8px 14px",fontSize:"14px",lineHeight:"1.5"},assistant:{...bo.message.assistant,background:"transparent",border:"transparent",borderWidth:"0px",borderRadius:"0px",shadow:"none",padding:"0px",fontSize:"14px",lineHeight:"1.55"}},composer:{...bo.composer,padding:"8px",fontSize:"15px",lineHeight:"1.5",controlSize:"32px",controlIconSize:"20px",sendIconSize:"18px",sendButtonRadius:"9999px",footerBorder:"none",overlayBand:"linear-gradient(to bottom, transparent, var(--persona-container) 24px)",focusBorderColor:"color-mix(in srgb, var(--persona-text) 28%, var(--persona-border))",focusRing:"1px solid color-mix(in srgb, var(--persona-text) 12%, transparent)"}};var pR=t=>bs({future:t}),Nh=t=>pR(t)==="v5"?{palette:aR,semantic:cR,components:dR}:{palette:iR,semantic:lR,components:_h};function Rn(t,e){if(!e.startsWith("palette.")&&!e.startsWith("semantic.")&&!e.startsWith("components."))return e;let n=e.split("."),o=t;for(let r of n){if(o==null)return;o=o[r]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?Rn(t,o):o}function YA(t){let e={};function n(o,r){for(let[s,a]of Object.entries(o)){let l=`${r}.${s}`;if(typeof a=="string"){let c=Rn(t,a);c!==void 0&&(e[l]={path:l,value:c,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,l)}}return n(t.palette,"palette"),n(t.semantic,"semantic"),n(t.components,"components"),e}function uR(t){let e=[],n=[];return t.palette||e.push({path:"palette",message:"Theme must include a palette",severity:"error"}),t.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),t.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:e.length===0,errors:e,warnings:n}}function QA(t,e){let n={...t};for(let[o,r]of Object.entries(e)){let s=n[o];s&&typeof s=="object"&&!Array.isArray(s)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=QA(s,r):n[o]=r}return n}function mR(t,e){return e?QA(t,e):t}function Na(t,e={}){let n=Nh(e.future),o={palette:n.palette,semantic:n.semantic,components:n.components},r={palette:{...o.palette,...t?.palette,colors:{...o.palette.colors,...t?.palette?.colors},spacing:{...o.palette.spacing,...t?.palette?.spacing},typography:{...o.palette.typography,...t?.palette?.typography},shadows:{...o.palette.shadows,...t?.palette?.shadows},borders:{...o.palette.borders,...t?.palette?.borders},radius:{...o.palette.radius,...t?.palette?.radius}},semantic:{...o.semantic,...t?.semantic,colors:{...o.semantic.colors,...t?.semantic?.colors,interactive:{...o.semantic.colors.interactive,...t?.semantic?.colors?.interactive},feedback:{...o.semantic.colors.feedback,...t?.semantic?.colors?.feedback}},spacing:{...o.semantic.spacing,...t?.semantic?.spacing},typography:{...o.semantic.typography,...t?.semantic?.typography}},components:mR(o.components,t?.components)},s=t?.components?.activity;for(let p of["toolBubble","reasoningBubble"])for(let u of["rowHeight","labelSize","iconSize","indent","bodySurface"])s?.[u]!==void 0&&(r.components[p][u]=s[u]);let a=t?.components?.collapsibleWidget?.surface;a!==void 0&&s?.bodySurface===void 0&&(r.components.activity={...r.components.activity,bodySurface:a});let l=t?.components?.header;l?.padding!==void 0&&l.minimalPadding===void 0&&(r.components.header.minimalPadding=r.components.header.padding);let c=t?.components?.message;if(c?.gap!==void 0&&c.fullscreenGap===void 0&&(r.components.message.fullscreenGap=r.components.message.gap),e.validate!==!1){let p=uR(r);if(!p.valid)throw new Error(`Theme validation failed: ${p.errors.map(u=>u.message).join(", ")}`)}if(e.plugins)for(let p of e.plugins)r=p.transform(r);return r}var Oh=t=>t.trim()==="0"?"0px":t,GA="--persona-",fR=t=>{if(!t)return;let e=t.trim().toLowerCase(),n;if(e.charCodeAt(0)===35){let a=e.slice(1);if(!/^[0-9a-f]+$/.test(a))return;a.length===3||a.length===4?n=[0,1,2].map(l=>parseInt(a[l]+a[l],16)):(a.length===6||a.length===8)&&(n=[0,2,4].map(l=>parseInt(a.slice(l,l+2),16)))}else{let a=e.match(/^rgba?\(([^)]+)\)$/);if(a){let l=a[1].split(/[,/\s]+/).filter(Boolean);l.length>=3&&(n=l.slice(0,3).map(c=>{let p=c.endsWith("%"),u=parseFloat(p?c.slice(0,-1):c);return p?u/100*255:u}))}}if(!n||n.some(a=>!Number.isFinite(a)))return;let[o,r,s]=n.map(a=>{let l=Math.max(0,Math.min(255,a))/255;return l<=.03928?l/12.92:Math.pow((l+.055)/1.055,2.4)});return .2126*o+.7152*r+.0722*s},gR=.179,Hn=(t,e)=>{for(let[n,...o]of e){let r;for(let s of o)if(r=s.charCodeAt(0)===61?s.slice(1):t[GA+s],r!==void 0)break;r!==void 0&&(t[GA+n]=r)}};function XA(t){let e=YA(t),n={};for(let[_,Te]of Object.entries(e)){let Re=_.replace(/\./g,"-");n[`--persona-${Re}`]=Te.value}Hn(n,[["primary","semantic-colors-primary","palette-colors-primary-500"],["secondary","semantic-colors-secondary","palette-colors-secondary-500"],["accent","semantic-colors-accent","palette-colors-accent-500"],["surface","semantic-colors-surface","palette-colors-gray-50"],["background","semantic-colors-background","palette-colors-gray-50"],["container","semantic-colors-container","palette-colors-gray-100"],["text","semantic-colors-text","palette-colors-gray-900"],["text-muted","semantic-colors-text-muted","palette-colors-gray-500"],["text-inverse","semantic-colors-text-inverse","palette-colors-gray-50"],["border","semantic-colors-border","palette-colors-gray-200"],["divider","semantic-colors-divider","palette-colors-gray-200"],["muted","text-muted"],["voice-recording-indicator","components-voice-recording-indicator","palette-colors-error-500"],["voice-recording-bg","components-voice-recording-background","palette-colors-error-50"],["voice-processing-icon","components-voice-processing-icon","palette-colors-primary-500"],["voice-speaking-icon","components-voice-speaking-icon","palette-colors-success-500"],["approval-bg","components-approval-requested-background","surface"],["approval-border","components-approval-requested-border","border"],["approval-text","components-approval-requested-text","palette-colors-gray-900"],["approval-shadow","components-approval-requested-shadow","=0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"],["approval-approve-bg","components-approval-approve-background","button-primary-bg"],["approval-deny-bg","components-approval-deny-background","container"],["attachment-image-bg","components-attachment-image-background","palette-colors-gray-100"],["attachment-image-border","components-attachment-image-border","palette-colors-gray-200"],["font-family","semantic-typography-fontFamily","palette-typography-fontFamily-sans"],["font-size","semantic-typography-fontSize","palette-typography-fontSize-base"],["font-weight","semantic-typography-fontWeight","palette-typography-fontWeight-normal"],["line-height","semantic-typography-lineHeight","palette-typography-lineHeight-normal"],["input-font-family","font-family"],["input-font-weight","font-weight"],["radius-sm","palette-radius-sm","=0.125rem"],["radius-md","palette-radius-md","=0.375rem"],["radius-lg","palette-radius-lg","=0.5rem"],["radius-xl","palette-radius-xl","=0.75rem"],["radius-full","palette-radius-full","=9999px"],["launcher-radius","components-launcher-borderRadius","palette-radius-full","=9999px"],["launcher-bg","components-launcher-background","surface"],["launcher-fg","components-launcher-foreground","primary"]]);let o=n["--persona-components-launcher-foreground"];n["--persona-launcher-fg-muted"]=o&&o!==n["--persona-primary"]?`color-mix(in srgb, ${o} 70%, transparent)`:n["--persona-muted"],Hn(n,[["launcher-border","components-launcher-border","border"],["button-primary-bg","components-button-primary-background","primary"],["button-primary-fg","components-button-primary-foreground","text-inverse"],["button-radius","components-button-primary-borderRadius","palette-radius-full","=9999px"],["button-stop-bg","components-button-stop-background"],["button-stop-fg","components-button-stop-foreground"]]),Hn(n,[["button-ghost-bg","components-button-ghost-background","=transparent"],["button-ghost-fg","components-button-ghost-foreground","text"],["button-ghost-radius","components-button-ghost-borderRadius","radius-md","=0.375rem"],["button-ghost-hover-bg","components-button-ghost-hoverBackground","=rgba(0, 0, 0, 0.05)"],["panel-radius","components-panel-borderRadius","radius-xl","=0.75rem"]]),n["--persona-panel-border"]=n["--persona-components-panel-border"]??`1px solid ${n["--persona-border"]}`,Hn(n,[["panel-shadow","components-panel-shadow","palette-shadows-xl","=0 25px 50px -12px rgba(0, 0, 0, 0.25)"]]),n["--persona-panel-inset"]=n["--persona-components-panel-inset"]??Wu,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??Bu,Hn(n,[["launcher-shadow","components-launcher-shadow","=0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"],["input-radius","components-input-borderRadius","radius-lg","=0.5rem"],["message-user-radius","components-message-user-borderRadius","radius-lg","=0.5rem"],["message-assistant-radius","components-message-assistant-borderRadius","radius-lg","=0.5rem"]]),Hn(n,[["header-bg","components-header-background","surface"]]);let r=n["--persona-header-bg"],s=n["--persona-components-header-foreground"],a=s?`color-mix(in srgb, ${s} 72%, ${r})`:void 0;n["--persona-header-border"]=n["--persona-components-header-border"]??(s?`color-mix(in srgb, ${s} 14%, ${r})`:void 0)??n["--persona-divider"],Hn(n,[["header-icon-bg","components-header-iconBackground","primary"],["header-icon-fg","components-header-iconForeground","text-inverse"]]),n["--persona-header-title-fg"]=n["--persona-components-header-title-color"]??n["--persona-components-header-titleForeground"]??s??n["--persona-primary"],n["--persona-header-subtitle-fg"]=n["--persona-components-header-subtitle-color"]??n["--persona-components-header-subtitleForeground"]??a??n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=n["--persona-components-header-actionIconForeground"]??a??n["--persona-muted"],Hn(n,[["header-control-size","components-header-controlSize","=32px"],["header-control-icon-size","components-header-controlIconSize","=20px"]]);let l=t.components?.header;l?.shadow&&(n["--persona-header-shadow"]=l.shadow),l?.borderBottom&&(n["--persona-header-border-bottom"]=l.borderBottom),l?.minHeight&&(n["--persona-header-min-height"]=l.minHeight);let c=n["--persona-components-history-railHeader-background"];c&&(n["--persona-history-rail-header-bg"]=c);let p=n["--persona-components-history-railHeader-border"];p&&(n["--persona-history-rail-header-border"]=p);let u=n["--persona-components-history-railHeader-minHeight"];u&&(n["--persona-history-rail-header-min-height"]=u);for(let[_,Te]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let Re=n[`--persona-components-history-overlay-${_}`];Re&&(n[`--persona-history-overlay-${Te}`]=Re)}for(let[_,Te]of[["background","bg"],["borderRadius","radius"]]){let Re=n[`--persona-components-history-menu-${_}`];Re&&(n[`--persona-history-menu-${Te}`]=Re)}let m=t.components?.history?.motion;if(m){let _=ut=>{if(ut===void 0)return;let At=String(ut).trim();return/^\d+(\.\d+)?$/.test(At)?`${At}ms`:At},Te=_(m.enterDurationMs);Te!==void 0&&(n["--persona-history-enter-ms"]=Te);let Re=_(m.exitDurationMs);Re!==void 0&&(n["--persona-history-exit-ms"]=Re),m.enterEasing&&(n["--persona-history-enter-easing"]=m.enterEasing),m.exitEasing&&(n["--persona-history-exit-easing"]=m.exitEasing)}let g=n["--persona-components-history-dangerForeground"];g&&(n["--persona-history-danger-fg"]=g),n["--persona-danger"]=n["--persona-components-history-confirm-dangerBackground"]??n["--persona-palette-colors-error-700"]??"#b42318",n["--persona-danger-fg"]=n["--persona-components-history-confirm-dangerForeground"]??"#ffffff";for(let _ of["scrim","shadow"]){let Te=n[`--persona-components-history-confirm-${_}`];Te&&(n[`--persona-history-confirm-${_}`]=Te)}for(let[_,Te]of[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]]){let Re=n[`--persona-components-tooltip-${_}`];Re&&(n[`--persona-tooltip-${Te}`]=Re)}t.components?.tooltip?.arrow===!1&&(n["--persona-tooltip-arrow-display"]="none");for(let[_,Te]of[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let Re=n[`--persona-components-messageActions-${_}`];Re&&(n[`--persona-message-action-${Te}`]=Re)}Hn(n,[["intro-card-bg","components-introCard-background","=transparent"],["intro-card-radius","components-introCard-borderRadius","=1rem"]]);let h=n["--persona-components-introCard-background"],b=n["--persona-components-introCard-shadow"],C=(!h||h==="transparent"||h==="none")&&(!b||b==="none"),M=n["--persona-components-introCard-padding"]??"1.5rem";n["--persona-intro-card-padding"]=C&&M==="1.5rem"?"1.5rem 0":M,Hn(n,[["intro-card-shadow","components-introCard-shadow","=none"],["intro-card-border","components-introCard-border","=none"],["input-background","components-input-background","surface"],["input-placeholder","components-input-placeholder","text-muted"],["input-backdrop-filter","components-input-backdropFilter","=none"],["message-user-bg","components-message-user-background","accent"],["message-user-text","components-message-user-text","text-inverse"],["message-user-shadow","components-message-user-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["message-assistant-bg","components-message-assistant-background","surface"],["message-assistant-text","components-message-assistant-text","text"],["message-assistant-border","components-message-assistant-border","border"],["message-assistant-shadow","components-message-assistant-shadow","=0 1px 2px 0 rgb(0 0 0 / 0.05)"],["scroll-to-bottom-bg","components-scrollToBottom-background","button-primary-bg","accent"],["scroll-to-bottom-fg","components-scrollToBottom-foreground","button-primary-fg","text-inverse"],["scroll-to-bottom-border","components-scrollToBottom-border","primary"],["scroll-to-bottom-size","components-scrollToBottom-size","=40px"],["scroll-to-bottom-radius","components-scrollToBottom-borderRadius","button-radius","radius-full","=9999px"],["scroll-to-bottom-shadow","components-scrollToBottom-shadow","palette-shadows-sm","=0 1px 2px 0 rgb(0 0 0 / 0.05)"],["scroll-to-bottom-padding","components-scrollToBottom-padding","=0.5rem 0.875rem"],["scroll-to-bottom-gap","components-scrollToBottom-gap","=0.5rem"],["scroll-to-bottom-font-size","components-scrollToBottom-fontSize","palette-typography-fontSize-sm","=0.875rem"],["scroll-to-bottom-icon-size","components-scrollToBottom-iconSize","=14px"],["event-badge-flow-bg","components-eventStream-badge-flow-background","=#dcfce7"],["event-badge-flow-fg","components-eventStream-badge-flow-foreground","=#15803d"],["event-badge-step-bg","components-eventStream-badge-step-background","=#f5f5f5"],["event-badge-step-fg","components-eventStream-badge-step-foreground","=#0a0a0a"],["event-badge-reasoning-bg","components-eventStream-badge-reasoning-background","=#fef9c3"],["event-badge-reasoning-fg","components-eventStream-badge-reasoning-foreground","=#a16207"],["event-badge-tool-bg","components-eventStream-badge-tool-background","=#f3e8ff"],["event-badge-tool-fg","components-eventStream-badge-tool-foreground","=#6b21a8"],["event-badge-agent-bg","components-eventStream-badge-agent-background","=#ccfbf1"],["event-badge-agent-fg","components-eventStream-badge-agent-foreground","=#115e59"],["event-badge-error-bg","components-eventStream-badge-error-background","=#fee2e2"],["event-badge-error-fg","components-eventStream-badge-error-foreground","=#b91c1c"],["event-badge-default-bg","components-eventStream-badge-default-background","=#f3f4f6"],["event-badge-default-fg","components-eventStream-badge-default-foreground","=#4b5563"],["tool-bubble-shadow","components-toolBubble-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["reasoning-bubble-shadow","components-reasoningBubble-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["composer-shadow","components-composer-shadow","=none"]]),Hn(n,[["composer-padding","components-composer-padding","=0.75rem 1rem"],["composer-gap","components-composer-gap","=0.5rem"],["composer-font-size","components-composer-fontSize","=0.875rem"],["composer-line-height","components-composer-lineHeight","=1.25rem"],["composer-control-size","components-composer-controlSize","=40px"],["composer-control-icon-size","components-composer-controlIconSize","=24px"],["motion-duration-fast","components-motion-durationFast","=120ms"],["motion-duration-base","components-motion-durationBase","=200ms"],["motion-easing","components-motion-easing","=cubic-bezier(0.2, 0, 0, 1)"],["composer-border-color","components-composer-borderColor","border","=#e5e7eb"],["composer-overlay-band","components-composer-overlayBand","=transparent"],["scrollbar-thumb","components-scrollbar-thumb","border","=#e5e7eb"],["scrollbar-track","components-scrollbar-track","=transparent"],["md-inline-code-bg","components-markdown-inlineCode-background","container"],["md-inline-code-color","components-markdown-inlineCode-foreground","text"],["md-link-color","components-markdown-link-foreground","accent","=#0f0f0f"]]);let E=n["--persona-components-markdown-heading-h1-fontSize"];E&&(n["--persona-md-h1-size"]=E);let T=n["--persona-components-markdown-heading-h1-fontWeight"];T&&(n["--persona-md-h1-weight"]=T);let R=n["--persona-components-markdown-heading-h2-fontSize"];R&&(n["--persona-md-h2-size"]=R);let A=n["--persona-components-markdown-heading-h2-fontWeight"];A&&(n["--persona-md-h2-weight"]=A);let D=n["--persona-components-markdown-prose-fontFamily"];D&&D!=="inherit"&&(n["--persona-md-prose-font-family"]=D),Hn(n,[["md-code-block-bg","components-markdown-codeBlock-background","container"],["md-code-block-border-color","components-markdown-codeBlock-borderColor","border"],["md-code-block-text-color","components-markdown-codeBlock-textColor","=inherit"]]),Hn(n,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),Hn(n,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),Hn(n,[["md-hr-color","components-markdown-hr-color","divider"]]),Hn(n,[["md-blockquote-border-color","components-markdown-blockquote-borderColor","palette-colors-gray-900"],["md-blockquote-bg","components-markdown-blockquote-background","=transparent"],["md-blockquote-text-color","components-markdown-blockquote-textColor","palette-colors-gray-500"]]);let W=[["container","surface"],["surface","surface"],["border","border"]];for(let[_,Te]of W){let Re=n[`--persona-components-collapsibleWidget-${_}`]??n[`--persona-${Te}`];Re!==void 0&&(n[`--persona-cw-${_}`]=Re,n[`--cw-${_}`]=Re)}Hn(n,[["message-border","components-message-border","border"]]),Hn(n,[["message-user-padding","components-message-user-padding"],["message-user-max-width","components-message-user-maxWidth"],["message-user-font-size","components-message-user-fontSize"],["message-user-font-family","components-message-user-fontFamily"],["message-user-line-height","components-message-user-lineHeight"],["message-assistant-padding","components-message-assistant-padding"],["message-assistant-border-width","components-message-assistant-borderWidth"],["message-assistant-max-width","components-message-assistant-maxWidth"],["message-assistant-font-size","components-message-assistant-fontSize"],["message-assistant-font-family","components-message-assistant-fontFamily"],["message-assistant-line-height","components-message-assistant-lineHeight"]]);let U=t.components,B=U?.iconButton;B&&(B.background&&(n["--persona-icon-btn-bg"]=B.background),B.border&&(n["--persona-icon-btn-border"]=B.border),B.color&&(n["--persona-icon-btn-color"]=B.color),B.padding&&(n["--persona-icon-btn-padding"]=B.padding),B.borderRadius&&(n["--persona-icon-btn-radius"]=B.borderRadius),B.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=B.hoverBackground),B.hoverColor&&(n["--persona-icon-btn-hover-color"]=B.hoverColor),B.activeBackground&&(n["--persona-icon-btn-active-bg"]=B.activeBackground),B.activeBorder&&(n["--persona-icon-btn-active-border"]=B.activeBorder));let O=U?.labelButton;O&&(O.background&&(n["--persona-label-btn-bg"]=O.background),O.border&&(n["--persona-label-btn-border"]=O.border),O.color&&(n["--persona-label-btn-color"]=O.color),O.padding&&(n["--persona-label-btn-padding"]=O.padding),O.borderRadius&&(n["--persona-label-btn-radius"]=O.borderRadius),O.hoverBackground&&(n["--persona-label-btn-hover-bg"]=O.hoverBackground),O.fontSize&&(n["--persona-label-btn-font-size"]=O.fontSize),O.gap&&(n["--persona-label-btn-gap"]=O.gap));let H=U?.toggleGroup;H&&(H.gap&&(n["--persona-toggle-group-gap"]=H.gap),H.borderRadius&&(n["--persona-toggle-group-radius"]=H.borderRadius));let S=U?.artifact;if(S?.toolbar){let _=S.toolbar;_.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=_.iconHoverColor),_.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=_.iconHoverBackground),_.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=_.iconPadding),_.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=_.iconBorderRadius),_.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=_.iconBorder),_.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=Oh(_.toggleGroupGap)),_.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=_.toggleBorderRadius),_.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=Oh(_.toggleGroupPadding)),_.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=_.toggleGroupBorder),_.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=_.toggleGroupBorderRadius),_.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=Rn(t,_.toggleGroupBackground)??_.toggleGroupBackground),_.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=_.copyBackground),_.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=_.copyBorder),_.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=_.copyColor),_.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=Oh(_.copyBorderRadius)),_.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=_.copyPadding),_.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=_.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??_.copyMenuBackground),_.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=_.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??_.copyMenuBorder),_.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=_.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??_.copyMenuShadow),_.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=_.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??_.copyMenuBorderRadius),_.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=_.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??_.copyMenuItemHoverBackground),_.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=_.iconBackground),_.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=_.toolbarBorder)}if(S?.tab){let _=S.tab;_.background&&(n["--persona-artifact-tab-bg"]=_.background),_.activeBackground&&(n["--persona-artifact-tab-active-bg"]=_.activeBackground),_.activeBorder&&(n["--persona-artifact-tab-active-border"]=_.activeBorder),_.borderRadius&&(n["--persona-artifact-tab-radius"]=_.borderRadius),_.textColor&&(n["--persona-artifact-tab-color"]=_.textColor),_.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=_.hoverBackground),_.listBackground&&(n["--persona-artifact-tab-list-bg"]=_.listBackground),_.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=_.listBorderColor),_.listPadding&&(n["--persona-artifact-tab-list-padding"]=_.listPadding)}if(S?.pane){let _=S.pane;if(_.toolbarBackground){let Te=Rn(t,_.toolbarBackground)??_.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Te}}if(S?.card){let _=S.card;_.background&&(n["--persona-artifact-card-bg"]=_.background),_.border&&(n["--persona-artifact-card-border"]=_.border),_.borderRadius&&(n["--persona-artifact-card-radius"]=_.borderRadius),_.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=_.hoverBackground),_.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=_.hoverBorderColor)}if(S?.inline){let _=S.inline;_.background&&(n["--persona-artifact-inline-bg"]=Rn(t,_.background)??_.background),_.border&&(n["--persona-artifact-inline-border"]=_.border),_.borderRadius&&(n["--persona-artifact-inline-radius"]=_.borderRadius),_.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=Rn(t,_.chromeBackground)??_.chromeBackground),_.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=Rn(t,_.chromeBorder)??_.chromeBorder),_.titleColor&&(n["--persona-artifact-inline-title-color"]=Rn(t,_.titleColor)??_.titleColor),_.mutedColor&&(n["--persona-artifact-inline-muted-color"]=Rn(t,_.mutedColor)??_.mutedColor),_.frameHeight&&(n["--persona-artifact-inline-frame-height"]=_.frameHeight)}let x=U?.code;x&&(x.keywordColor&&(n["--persona-code-keyword-color"]=x.keywordColor),x.stringColor&&(n["--persona-code-string-color"]=x.stringColor),x.commentColor&&(n["--persona-code-comment-color"]=x.commentColor),x.numberColor&&(n["--persona-code-number-color"]=x.numberColor),x.tagColor&&(n["--persona-code-tag-color"]=x.tagColor),x.attrColor&&(n["--persona-code-attr-color"]=x.attrColor),x.propertyColor&&(n["--persona-code-property-color"]=x.propertyColor),x.lineNumberColor&&(n["--persona-code-line-number-color"]=x.lineNumberColor),x.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=x.gutterBorderColor),x.background&&(n["--persona-code-bg"]=Rn(t,x.background)??x.background));let P=n["--persona-surface"],L=n["--persona-container"],G=n["--persona-palette-colors-gray-100"]??"#f3f4f6",V=n["--persona-palette-colors-gray-200"]??"#e5e7eb",K=n["--persona-palette-colors-gray-300"]??"#d1d5db",ee=!L||L===P,oe=fR(P??n["--persona-background"]),ne=ee&&oe!==void 0&&oe<gR,le=ne?"rgba(255, 255, 255, 0.08)":G,de=ne?"rgba(255, 255, 255, 0.12)":V,ve=ne?"rgba(255, 255, 255, 0.16)":K,Le=ee?le:L,se=ee?de:L;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??Le,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??se,ee&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??ve),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??Le,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??Le,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??Le,n}var hR=t=>!!t&&"launcher"in t&&(t.launcher?.sidebarMode===!0||t.launcher?.mountMode==="docked"),JA=(t,e)=>{if(!e||!hR(e))return t;let n=e.theme?.components?.panel?.width,o=e.darkTheme?.components?.panel?.width;return(fc(e)==="dark"?o??n:n)!=null?t:{...t,components:{...t.components,panel:{...t.components.panel,width:bs(e)==="v5"?"400px":"420px"}}}},yR={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},mc={components:{button:{ghost:{hoverBackground:"rgba(255, 255, 255, 0.08)"}},markdown:{link:{foreground:"palette.colors.primary.300"}},eventStream:{badge:{flow:{background:"palette.colors.success.900",foreground:"palette.colors.success.300"},step:{background:"palette.colors.primary.800",foreground:"palette.colors.primary.200"},reasoning:{background:"palette.colors.warning.900",foreground:"palette.colors.warning.300"},tool:{background:"palette.colors.purple.900",foreground:"palette.colors.purple.300"},agent:{background:"palette.colors.teal.900",foreground:"palette.colors.teal.300"},error:{background:"palette.colors.error.900",foreground:"palette.colors.error.300"},default:{background:"palette.colors.gray.800",foreground:"palette.colors.gray.300"}}},history:{dangerForeground:"#f87171",confirm:{dangerBackground:"palette.colors.error.600",scrim:"rgba(0, 0, 0, 0.6)"}}}},Fh=yR,bR={...Fh,colors:{...Fh.colors,primary:{50:"#0f0f10",100:"#27272a",200:"#3f3f46",300:"#52525b",400:"#71717a",500:"#f4f4f5",600:"#e4e4e7",700:"#d4d4d8",800:"#a1a1aa",900:"#fafafa",950:"#ffffff"},gray:{50:"#1a1a1b",100:"#27272a",200:"#2a2a2d",300:"#52525b",400:"#71717a",500:"#a1a1aa",600:"#b4b4bd",700:"#d4d4d8",800:"#e4e4e7",900:"#f4f4f5",950:"#fafafa"}}},vR=mc,CR={semantic:{colors:{primary:"palette.colors.primary.500",accent:"palette.colors.primary.600",background:"#0f0f10",surface:"palette.colors.gray.50",container:"#1c1c20",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"#0f0f10",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600"}}},components:{...mc.components,button:{...mc.components?.button,primary:{background:"semantic.colors.primary",foreground:"palette.colors.primary.50"}},markdown:{inlineCode:{background:"palette.colors.gray.100",foreground:"semantic.colors.text"},link:{foreground:"semantic.colors.accent"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"semantic.colors.text"},table:{headerBackground:"palette.colors.gray.100",borderColor:"semantic.colors.border"},blockquote:{background:"semantic.colors.container",borderColor:"palette.colors.gray.300",textColor:"semantic.colors.textMuted"}},eventStream:{...mc.components?.eventStream,badge:{...mc.components?.eventStream?.badge,step:{background:"palette.colors.gray.100",foreground:"palette.colors.gray.700"},default:{background:"palette.colors.gray.100",foreground:"palette.colors.gray.700"}}}}},wR=t=>bs({future:t})==="v5"?{palette:bR,components:CR}:{palette:Fh,components:vR},ZA=t=>{if(!(!t||typeof t!="object"||Array.isArray(t)))return t},Vh=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",xR=t=>{let e=t?.colorScheme??"light";return e==="light"?"light":e==="dark"?"dark":Vh()},fc=t=>xR(t),SR=(t,e={})=>Na(t,e),AR=(t,e={})=>{let n=wR(e.future),o=jo(n.components,t??{})??{};return Na({...o,palette:{...o.palette,colors:bs(e)==="v5"?jo(n.palette.colors,o.palette?.colors):{...n.palette.colors,...o.palette?.colors}}},{validate:!1,future:e.future})},qr=t=>{let e=fc(t),n=ZA(t?.theme),o=Iu(t)==="circle"?Hu:{..._h.launcher,...t?.future?.v5Defaults?{offset:"1.5rem"}:{}},r=jo({components:{launcher:o}},n),s=ZA(t?.darkTheme);return JA(e==="dark"?AR(jo(r??{},s??{}),{future:t?.future}):SR(r,{future:t?.future}),t)},MR=t=>XA(t),gc=(t,e)=>{let n=qr(e),o=MR(n);for(let[r,s]of Object.entries(o))t.style.setProperty(r,s);t.setAttribute("data-persona-color-scheme",fc(e)),t.setAttribute("data-persona-defaults",bs(e))},Du=t=>{let e=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{t(Vh())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),e.push(()=>n.disconnect())}if(typeof window<"u"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>t(Vh());n.addEventListener?(n.addEventListener("change",o),e.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),e.push(()=>n.removeListener(o)))}return()=>{e.forEach(n=>n())}};var Xr=require("lucide");Zt();zn();je();var Is=(t,e)=>t?.layout?.contentMaxWidth??(e?t?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");var Ou="24px",$h=(t,e)=>e||t?.composer?.placement!=="overlay"?"block":"overlay",hc=t=>{if(typeof t!="string")return null;let e=/^\s*(\d+(?:\.\d+)?)\s*%\s*$/.exec(t);if(!e)return null;let n=Number(e[1])/100;return n>0&&n<1?n:null},eM=t=>Math.max(0,Math.round(t.columnHeight*(1-t.fraction))-t.footerHeight);var tM=null;var zh=()=>{if(tM!==null)return tM;if(typeof navigator>"u")return!1;let e=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(e)},TR="ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space",_u=(t,e)=>{console.warn(`[persona] ${t} shortcut: ${e}`)},Nu=t=>{let e=t.toLowerCase().split("+").map(r=>r.trim()),n=e.pop(),o={key:n,mod:!1,shift:!1,alt:!1};for(let r of e)if(r==="mod"||r==="cmd"||r==="ctrl")o.mod=!0;else if(r==="shift")o.shift=!0;else if(r==="alt"||r==="option")o.alt=!0;else return _u("unknown modifier in",t),null;return!o.mod||o.shift&&o.alt||/^(enter|esc(ape)?)$/.test(n)||!/^([^+\s]|[a-z]{2,12})$/.test(n)?(_u("unsupported",t),null):(n==="space"&&(o.key=" "),o)},ER=t=>TR.split(" ").find(e=>e.toLowerCase()===t)??(t===" "?"Space":t.length===1?t.toUpperCase():t[0].toUpperCase()+t.slice(1)),nM=(t,e)=>{let n=Nu(t);if(!n)return"";let o=zh(),r=ER(n.key);if(!e&&o)return`${n.alt?"\u2325":""}${n.shift?"\u21E7":""}\u2318${r}`;let s=[e?o?"Meta":"Control":"Ctrl"];return n.alt&&s.push("Alt"),n.shift&&s.push("Shift"),s.push(r),s.join("+")},Fu=t=>nM(t,!1),yc=t=>nM(t,!0),kR=(t,e)=>e.key?.toLowerCase()===t.key&&(zh()?e.metaKey:e.ctrlKey)===t.mod&&!(zh()?e.ctrlKey:e.metaKey)&&e.shiftKey===t.shift&&e.altKey===t.alt,PR=t=>{if(!(t instanceof HTMLElement))return!1;let e=t.tagName;return e==="INPUT"||e==="TEXTAREA"||e==="SELECT"||t.isContentEditable},oM=t=>{let e=new Map,n=t?.ownerDocument??(typeof document<"u"?document:null),o=(s,a)=>{if((s.scope??"widget")==="page")return!0;if(!t)return!1;let l=a.composedPath?.();return l?.length?l.includes(t):t.contains(a.target)},r=s=>{if(s.isComposing||!e.size)return;let a=s.composedPath?.()[0]??s.target;for(let l of e.values())if(kR(l.parsed,s)&&l.when?.()!==!1&&o(l,s)&&!(!l.allowInInput&&PR(a))){s.preventDefault();try{l.run(s)}catch(c){_u(`${l.id} threw on`,l.combo),console.warn(c)}return}};return n?.addEventListener("keydown",r),{register(s){let a=Nu(s.combo);if(!a)return()=>{};let l=`${a.mod?"m":""}${a.shift?"s":""}${a.alt?"a":""}${a.key}`,c=e.get(l);return c?(_u(`${c.id} already owns`,s.combo),()=>{}):(e.set(l,{...s,parsed:a}),s.element?.setAttribute("aria-keyshortcuts",yc(s.combo)),()=>{e.get(l)?.id===s.id&&e.delete(l),s.element?.removeAttribute("aria-keyshortcuts")})},destroy(){e.clear(),n?.removeEventListener("keydown",r)}}};var rM=require("idiomorph"),Vu=(t,e,n={})=>{let{preserveTypingAnimation:o=!0}=n;rM.Idiomorph.morph(t,e.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,s){if(r instanceof HTMLElement&&o){if(r.classList.contains("persona-animate-typing")||r.hasAttribute("data-preserve-runtime"))return!1;if(r.hasAttribute("data-tool-elapsed"))return s instanceof HTMLElement&&s.getAttribute("data-tool-elapsed")===r.getAttribute("data-tool-elapsed")?!1:void 0;if(r.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let a=r.textContent??"",l=s.textContent??"";if(a!==l)return}return!1}}}}})};var sM=t=>t.replace(/^\n+/,"").replace(/\s+$/,"");var Uh={index:-1,draft:""};function iM(t){let{direction:e,history:n,currentValue:o,atStart:r,state:s}=t,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(e==="up"){if(!a&&!r)return{handled:!1,state:s};if(!a){let l=n.length-1;return{handled:!0,value:n[l],state:{index:l,draft:o}}}if(s.index>0){let l=s.index-1;return{handled:!0,value:n[l],state:{index:l,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<n.length-1){let l=s.index+1;return{handled:!0,value:n[l],state:{index:l,draft:s.draft}}}return{handled:!0,value:s.draft,state:{index:-1,draft:s.draft}}}function aM(t,e){return[t.id,t.role,t.content?.length??0,t.content?.slice(-32)??"",t.streaming?"1":"0",t.voiceProcessing?"1":"0",t.variant??"",t.rawContent?.length??0,t.llmContent?.length??0,t.approval?.status??"",t.toolCall?.status??"",t.toolCall?.name??"",t.toolCall?.chunks?.length??0,t.toolCall?.chunks?.[t.toolCall.chunks.length-1]?.slice(-32)??"",typeof t.toolCall?.args=="string"?t.toolCall.args.length:t.toolCall?.args?JSON.stringify(t.toolCall.args).length:0,t.reasoning?.chunks?.length??0,t.reasoning?.chunks?.[t.reasoning.chunks.length-1]?.length??0,t.reasoning?.chunks?.[t.reasoning.chunks.length-1]?.slice(-32)??"",t.contentParts?.length??0,t.stopReason??"",e].join("\0")}function lM(){return new Map}function cM(t,e,n){let o=t.get(e);return o&&o.fingerprint===n?o.wrapper:null}function dM(t,e,n,o){t.set(e,{fingerprint:n,wrapper:o})}function pM(t,e){for(let n of t.keys())e.has(n)||t.delete(n)}jh();ks();Sc();so();var{setLoader:sV,load:eW}=Qt({fallbackImport:()=>Promise.resolve().then(()=>(WM(),RM))});var BM=eW;ks();function Jh(t,e=On){let n=t.style.position,o=t.style.zIndex,r=t.style.isolation,s=getComputedStyle(t),a=s.position==="static"||s.position==="";return a&&(t.style.position="relative"),t.style.zIndex=String(e),t.style.isolation="isolate",()=>{a&&(t.style.position=n),t.style.zIndex=o,t.style.isolation=r}}var Mc=0,Hs=null;function Zh(t=document){if(Mc++,Mc===1){let n=t.body,r=(t.defaultView??window).scrollY||t.documentElement.scrollTop;Hs={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:r},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${r}px`,n.style.width="100%"}let e=!1;return()=>{if(!e&&(e=!0,Mc=Math.max(0,Mc-1),Mc===0&&Hs)){let n=t.body,o=t.defaultView??window;n.style.overflow=Hs.originalOverflow,n.style.position=Hs.originalPosition,n.style.top=Hs.originalTop,n.style.width=Hs.originalWidth,o.scrollTo(0,Hs.scrollY),Hs=null}}}var Tc={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},nn=t=>(t?.launcher?.mountMode??"floating")==="docked",Ec=t=>(t?.launcher?.mountMode??"floating")==="composer-bar",Do=t=>{let e=t?.launcher?.dock,n=Nr(t).dockWidth?e?.width:Rn(qr(t),"components.panel.width");return{side:e?.side??Tc.side,width:n??Tc.width,animate:e?.animate??Tc.animate,reveal:e?.reveal??Tc.reveal,maxHeight:e?.maxHeight??Tc.maxHeight}};je();je();var OM=require("lucide");Zt();zn();var ey=t=>t==="followUp"?"follow-up":t,ty=(t,e=0)=>{if(typeof t=="string"){let r=t.trim();return r?{id:r,label:r,prompt:r,emphasis:"default"}:null}let n=t.label.trim();if(!n)return null;let o=t.prompt?.trim()||n;return{id:t.id?.trim()||o||`suggestion-${e}`,label:n,prompt:o,description:t.description?.trim()||void 0,icon:t.icon,iconColor:t.iconColor?.trim()||void 0,behavior:t.behavior,emphasis:t.emphasis??"default"}},DM=new WeakSet,tW=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,nW=t=>{tW()||t.forEach((e,n)=>{typeof e.animate=="function"&&e.animate([{opacity:"0",transform:"translateY(4px)"},{opacity:"1",transform:"none"}],{duration:250,delay:n*60,easing:"ease-out",fill:"backwards"})})},ny=t=>{var R,A,D;let{item:e,index:n,surface:o,source:r,variant:s,streaming:a,config:l,plugins:c,chipsConfig:p,session:u,getTextarea:m,eventTarget:g,submitPrompt:h}=t,b=o==="followUp",C=e.behavior,M=()=>{if(u.isStreaming())return;let W={suggestion:{...e},surface:o,source:r,behavior:C},U=g.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:W,bubbles:!0,composed:!0,cancelable:!0}));if(b&&g.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:e.prompt},bubbles:!0,composed:!0})),!U)return;for(let O of c)if(O.onSuggestionSelect?.({suggestion:{...e},surface:o,source:r,variant:s,config:l})===!1)return;let B=m();if(C==="fill"){B.value=e.prompt,B.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),B.focus();return}if(h){h(e.prompt);return}B.value="",u.sendMessage(e.prompt)},E=()=>{let W=v("button",`persona-suggestion persona-suggestion--${s}`);if(W.type="button",W.disabled=a,W.dataset.suggestionId=e.id,W.dataset.emphasis=e.emphasis,W.dataset.behavior=C,s==="chip"&&(p?.fontWeight&&(W.style.fontWeight=p.fontWeight),p?.paddingX&&(W.style.paddingLeft=p.paddingX,W.style.paddingRight=p.paddingX),p?.paddingY&&(W.style.paddingTop=p.paddingY,W.style.paddingBottom=p.paddingY)),e.icon){let B=ke(e.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);B&&(B.classList.add("persona-suggestion__icon"),e.iconColor&&(B.style.color=e.iconColor),W.appendChild(B))}let U=v("span","persona-suggestion__copy");if(U.appendChild(F("span",{className:"persona-suggestion__label",text:e.label})),e.description&&s!=="chip"&&U.appendChild(F("span",{className:"persona-suggestion__description",text:e.description})),W.appendChild(U),s!=="chip"){let B=Ge(OM.ArrowRight,16,"currentColor",1.8);B&&(B.classList.add("persona-suggestion__arrow"),W.appendChild(B))}return W.addEventListener("click",M),W},T=null;for(let W of c)if(W.renderSuggestion&&(T=W.renderSuggestion({suggestion:{...e},index:n,surface:o,source:r,variant:s,streaming:a,config:l,defaultRenderer:E,select:M}),T))break;return T??(T=E()),(R=T.dataset).suggestionId||(R.suggestionId=e.id),(A=T.dataset).behavior||(A.behavior=C),(D=T.dataset).emphasis||(D.emphasis=e.emphasis),T instanceof HTMLButtonElement||T.setAttribute("aria-disabled",a?"true":"false"),T},kc=t=>{let e=[],n=[],o=null,r=null,s=()=>{t.removeAttribute("data-scroll-left"),t.removeAttribute("data-scroll-right")},a=()=>{if(r=null,t.hidden||t.dataset.variant!=="chip"||t.dataset.overflow!=="scroll"){s();return}let u=Math.max(0,t.scrollWidth-t.clientWidth);if(u<=1){s();return}let m=getComputedStyle(t).direction==="rtl",g=Math.min(u,Math.max(0,Math.abs(t.scrollLeft))),h=4,b=g<=h,C=g>=u-h,M=m?!C:!b,E=m?!b:!C;t.toggleAttribute("data-scroll-left",M),t.toggleAttribute("data-scroll-right",E)},l=()=>{if(r!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&a();return}r=requestAnimationFrame(a)};t.addEventListener("scroll",l,{passive:!0});let c=typeof ResizeObserver=="function"?new ResizeObserver(l):null;return c?.observe(t),{buttons:e,elements:n,destroy:()=>{t.removeEventListener("scroll",l),c?.disconnect(),r!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(r),r=null},render:(u,m,g,h,b,C)=>{t.replaceChildren(),e.length=0,n.length=0;let M=C?.source??"config",E=C?.surface??(M==="config"?"starter":"followUp"),T=E==="followUp",R=C?.variant??"chip",A=C?.behavior??"send",D=C?.overflow??"wrap",W=C?.config??{},U=C?.plugins??[],B=typeof C?.maxItems=="number"?Math.max(0,Math.floor(C.maxItems)):void 0,O=T?"followUps":"starters";!DM.has(W)&&W.debug===!0&&R!=="chip"&&W.suggestions?.[O]?.overflow!==void 0&&(DM.add(W),console.info(`[persona] suggestions.${O}.overflow applies to the "chip" variant only; the "${R}" variant manages its own stacking.`));let H=V=>V.map(ty).filter(K=>K!==null).map(K=>({...K,behavior:K.behavior??A})),S=H(u??[]);U.forEach(V=>{V.transformSuggestions&&(S=H(V.transformSuggestions({suggestions:S.map(K=>({...K})),surface:E,source:M,config:W})))});let x=B===void 0?S:S.slice(0,B);if(!x.length){t.hidden=!0,o=null,s();return}if(!T&&(h??m.getMessages()).some(K=>K.role==="user")){t.hidden=!0,o=null;return}t.hidden=!1,t.classList.add("persona-suggestions"),t.dataset.personaSuggestionSurface=ey(E),t.dataset.variant=R,t.dataset.overflow=D;let P=document.createDocumentFragment(),L=m.isStreaming();x.forEach((V,K)=>{let ee=ny({item:V,index:K,surface:E,source:M,variant:R,streaming:L,config:W,plugins:U,chipsConfig:b,session:m,getTextarea:()=>g,eventTarget:t,submitPrompt:C?.submitPrompt});P.appendChild(ee),n.push(ee),[...ee instanceof HTMLButtonElement?[ee]:[],...Array.from(ee.querySelectorAll("button"))].forEach(ne=>{e.includes(ne)||(ne.disabled=L,e.push(ne))})}),t.appendChild(P),a(),l();let G=JSON.stringify({normalized:x,surface:E,variant:R,source:M});G!==o&&(o=G,nW(n),t.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:x.map(V=>({...V})),surface:E,source:M,variant:R},bubbles:!0,composed:!0})),T&&t.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:x.map(V=>V.prompt)},bubbles:!0,composed:!0})))}}};var vo={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};ks();je();Zt();je();Zt();var oW="persona-header-control",rW="persona-header-control--glyph",sW="persona-header-control--sparse",iW=20,aW={x:[1.4,1.05]},_M="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",lW="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Gu=(t,e,n={})=>{let{iconSize:o,iconText:r}=n,[s,a]=aW[e]??[1,1.5],l=!o;t.classList.toggle(rW,l),t.classList.toggle(sW,l&&s!==1);let c=parseFloat(o??"")||iW,p=ke(e,`${Math.round(c*s)}px`,"currentColor",a);p?(p.style.display="block",l||(p.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((a/1.5).toFixed(4))})`),t.replaceChildren(p)):r&&(t.textContent=r)},ki=t=>{let{ariaLabel:e,tooltip:n=!0,tooltipHint:o,iconName:r,iconText:s,wrapperClassName:a=_M,size:l,iconSize:c,color:p,backgroundColor:u,borderWidth:m,borderColor:g,borderRadius:h,paddingX:b,paddingY:C,hidden:M,extraClassName:E,attrs:T}=t,R=v("div",a),A=!!(m||g),D=F("button",{className:Gt(oW,"persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!u&&"persona-bg-transparent hover:persona-bg-gray-100",!A&&"persona-border-none",!h&&"persona-rounded-full",E),attrs:{type:"button","aria-label":e,...T},style:{width:l,height:l,minWidth:l,minHeight:l,display:M?"none":void 0,color:p||jn.actionIconColor,backgroundColor:u,border:A?`${m||"0px"} solid ${g||"transparent"}`:void 0,borderRadius:h,paddingLeft:b,paddingRight:b,paddingTop:C,paddingBottom:C}});return r?Gu(D,r,{iconSize:c,iconText:s}):s&&(D.textContent=s),R.appendChild(D),In({anchor:D,trigger:R,text:()=>D.getAttribute("aria-label")??e,hint:o,enabled:n}),{button:D,wrapper:R}},Va=(t,e={})=>{let{showClose:n=!0,wrapperClassName:o=_M,buttonSize:r,iconSize:s}=e,a=t?.launcher??{},l=a.closeButtonTooltipText??"Close chat",c=a.closeButtonShowTooltip??!0,{button:p,wrapper:u}=ki({ariaLabel:l,tooltip:c,iconName:a.closeButtonIconName??"x",iconText:a.closeButtonIconText??"\xD7",wrapperClassName:o,size:r??a.closeButtonSize,iconSize:s,color:a.closeButtonColor,backgroundColor:a.closeButtonBackgroundColor,borderWidth:a.closeButtonBorderWidth,borderColor:a.closeButtonBorderColor,borderRadius:a.closeButtonBorderRadius,paddingX:a.closeButtonPaddingX,paddingY:a.closeButtonPaddingY,hidden:!n});return{button:p,wrapper:u}},$a=(t,e={})=>{let{wrapperClassName:n=lW,buttonSize:o,iconSize:r}=e,a=(t?.launcher??{}).clearChat??{},l=a.tooltipText??"Clear chat",c=a.showTooltip??!0,{button:p,wrapper:u}=ki({ariaLabel:l,tooltip:c,iconName:a.iconName??"refresh-cw",wrapperClassName:n,size:o??a.size,iconSize:r,color:a.iconColor,backgroundColor:a.backgroundColor,borderWidth:a.borderWidth,borderColor:a.borderColor,borderRadius:a.borderRadius,paddingX:a.paddingX,paddingY:a.paddingY});return{button:p,wrapper:u}};var jn={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-control-state-fg, var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af)))",minHeight:"var(--persona-header-min-height, auto)"},oy={fontFamily:"var(--persona-components-header-title-fontFamily, inherit)",fontSize:"var(--persona-components-header-title-fontSize, 1rem)",fontWeight:"var(--persona-components-header-title-fontWeight, 600)",lineHeight:"var(--persona-components-header-title-lineHeight, 1.5rem)",letterSpacing:"var(--persona-components-header-title-letterSpacing, normal)"},cW={fontFamily:"var(--persona-components-header-subtitle-fontFamily, inherit)",fontSize:"var(--persona-components-header-subtitle-fontSize, 0.75rem)",fontWeight:"var(--persona-components-header-subtitle-fontWeight, inherit)",lineHeight:"var(--persona-components-header-subtitle-lineHeight, 1rem)",letterSpacing:"var(--persona-components-header-subtitle-letterSpacing, normal)"},Pi=t=>{let{config:e,showClose:n=!0}=t,o=F("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3",attrs:{"data-persona-theme-zone":"header"},style:{padding:"var(--persona-components-header-padding, 20px 24px)",minHeight:jn.minHeight,backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),r=e?.launcher??{},s=r.headerIconSize??Fl,a=r.closeButtonPlacement??"inline",l=r.headerIconHidden??!1,c=r.headerIconName,p=F("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:s,width:s,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!l)if(c){let D=parseFloat(s)||24,W=ke(c,D*.6,"currentColor",1);W?(W.style.width=`calc(${D}px * var(--persona-components-header-iconScale, 0.6))`,W.style.height=`calc(${D}px * var(--persona-components-header-iconScale, 0.6))`,p.replaceChildren(W)):p.textContent=e?.launcher?.agentIconText??"\u{1F4AC}"}else if(e?.launcher?.iconUrl){let D=v("img");D.src=e.launcher.iconUrl,D.alt="",D.className="persona-rounded-xl persona-object-cover",D.style.height=s,D.style.width=s,p.replaceChildren(D)}else p.textContent=e?.launcher?.agentIconText??"\u{1F4AC}";let u=v("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),m=F("span",{className:"persona-text-base persona-font-semibold",text:e?.launcher?.title??"Chat Assistant",style:{color:jn.titleColor,...oy}}),g=F("span",{className:"persona-text-xs",text:e?.launcher?.subtitle??"Here to help you get answers fast",style:{color:jn.subtitleColor,...cW}});u.append(m,g),l?o.append(u):o.append(p,u);let h=r.clearChat??{},b=h.enabled??!0,C=h.placement??"inline",M=null,E=null;if(b){let W=$a(e,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});M=W.button,E=W.wrapper,C==="top-right"&&(E.style.right="48px"),C==="inline"&&o.appendChild(E)}let T=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":b&&C==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:R,wrapper:A}=Va(e,{showClose:n,wrapperClassName:T});return a!=="top-right"&&o.appendChild(A),{header:o,iconHolder:p,headerTitle:m,headerSubtitle:g,closeButton:R,closeButtonWrapper:A,clearChatButton:M,clearChatButtonWrapper:E}},Pc=(t,e,n)=>{let o=n?.launcher??{},r=o.closeButtonPlacement??"inline",s=o.clearChat?.placement??"inline";t.appendChild(e.header),r==="top-right"&&(t.style.position="relative",t.appendChild(e.closeButtonWrapper)),e.clearChatButtonWrapper&&s==="top-right"&&(t.style.position="relative",t.appendChild(e.clearChatButtonWrapper))};je();ry();Ii();var dW=t=>{let e=Pi({config:t.config,showClose:t.showClose,onClose:t.onClose,onClearChat:t.onClearChat}),n=t.layoutHeaderConfig?.onTitleClick;if(n){let o=e.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",r=>{(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),n())}))}return e};function pW(t,e,n){if(e?.length)for(let o of e){let{button:r,wrapper:s}=ki({ariaLabel:o.ariaLabel??o.label??o.id,iconName:o.icon,iconText:o.icon?void 0:o.label,tooltipHint:o.shortcut?Fu(o.shortcut):void 0,wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center"});if(r.setAttribute("data-persona-header-action",o.id),o.shortcut){let a=yc(o.shortcut);a&&r.setAttribute("aria-keyshortcuts",a)}if(o.menuItems?.length){let a=Lc({items:o.menuItems,onSelect:l=>n?.(l),anchor:s,position:"bottom-right"});s.appendChild(a.element),r.addEventListener("click",l=>{l.stopPropagation(),a.toggle()})}else r.addEventListener("click",()=>n?.(o.id));t.appendChild(s)}}var uW=t=>{let{config:e,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=t,a=e?.launcher??{},l=v("div","persona-flex persona-items-center persona-justify-between");l.setAttribute("data-persona-theme-zone","header"),l.style.minHeight=jn.minHeight,l.style.padding="var(--persona-components-header-minimalPadding, var(--persona-components-header-padding, 16px 24px))",l.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",l.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",l.style.boxShadow="var(--persona-header-shadow, none)",l.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let c=r?.titleMenu,p,u;if(c){let A=FM({label:a.title??"Chat Assistant",menuItems:c.menuItems,onSelect:D=>{let W=B=>{B===!1&&A.element.dispatchEvent(new CustomEvent("persona:title-menu-builtin",{bubbles:!0,composed:!0,detail:{actionId:D}}))},U=c.onSelect(D);U instanceof Promise?U.then(W,()=>{}):W(U)},hover:c.hover,className:""});p=A.element,p.style.color=jn.titleColor,u=p.querySelector(".persona-combo-btn-label")??p}else{if(p=v("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=v("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=jn.titleColor,Object.assign(u.style,oy),u.textContent=a.title??"Chat Assistant",p.appendChild(u),r?.onTitleClick){p.style.cursor="pointer",p.setAttribute("role","button"),p.setAttribute("tabindex","0");let D=r.onTitleClick;p.addEventListener("click",W=>{W.target.closest("button")||D()}),p.addEventListener("keydown",W=>{(W.key==="Enter"||W.key===" ")&&(W.preventDefault(),D())})}let A=r?.titleRowHover;A&&(p.style.borderRadius=A.borderRadius??"10px",p.style.padding=A.padding??"6px 4px 6px 12px",p.style.margin="-6px 0 -6px -12px",p.style.border="1px solid transparent",p.style.transition="background-color 0.15s ease, border-color 0.15s ease",p.style.width="fit-content",p.style.flex="none",p.addEventListener("mouseenter",()=>{p.style.backgroundColor=A.background??"",p.style.borderColor=A.border??""}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="",p.style.borderColor="transparent"}))}l.appendChild(p);let m="persona-relative persona-inline-flex persona-items-center persona-justify-center",{button:g,wrapper:h}=Va(e,{showClose:n,wrapperClassName:m});o&&g.addEventListener("click",o);let b=v("div","persona-flex persona-items-center persona-gap-1");c||pW(b,r?.trailingActions,r?.onAction??s);let C=a.clearChat??{},M=null,E=null;if(C.enabled??!0){let A=C.placement??"inline",D=$a(e,{wrapperClassName:A==="top-right"?"persona-absolute persona-top-4 persona-z-50":m});M=D.button,E=D.wrapper,A==="top-right"?E.style.right="48px":b.appendChild(E)}b.appendChild(h),l.appendChild(b);let T=v("div");T.style.display="none";let R=v("span");return R.style.display="none",{header:l,iconHolder:T,headerTitle:u,headerSubtitle:R,closeButton:g,closeButtonWrapper:h,clearChatButton:M,clearChatButtonWrapper:E}},VM={default:dW,minimal:uW},mW=t=>VM[t]??VM.default,Qu=(t,e,n)=>{if(e?.render){let a=e.render({config:t,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:e.trailingActions,onAction:e.onAction}),l=v("div");l.style.display="none";let c=v("span"),p=v("span"),u=v("button");u.style.display="none";let m=v("div");return m.style.display="none",{header:a,iconHolder:l,headerTitle:c,headerSubtitle:p,closeButton:u,closeButtonWrapper:m,clearChatButton:null,clearChatButtonWrapper:null}}let o=e?.layout??"default",s=mW(o)({config:t,showClose:e?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:e,onHeaderAction:e?.onAction});return e&&(e.showIcon===!1&&(s.iconHolder.style.display="none"),e.showTitle===!1&&(s.headerTitle.style.display="none"),e.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),e.showCloseButton===!1&&(s.closeButton.style.display="none"),e.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};je();var Ic=t=>{let{config:e}=t,n=F("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),o=du(),r=F("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-persona-border persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""}}),{textarea:s,attachAutoResize:a}=iu(e);a();let l=au(e),c=Da(e),p=lu(e),u=cu(e),m=F("div",{className:"persona-widget-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});r.append(m),p&&(p.previewsContainer.style.gap="8px",m.append(p.previewsContainer),r.append(p.input)),r.append(s);let g=F("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),h=F("div",{className:"persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-start":""}}),b=F("div",{className:"persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-end":""}});return p&&h.append(p.wrapper),c&&b.append(c.wrapper),b.append(l.wrapper),g.append(h,b),r.append(g),r.addEventListener("click",C=>{C.target!==l.button&&C.target!==l.wrapper&&C.target!==c?.button&&C.target!==c?.wrapper&&C.target!==p?.button&&C.target!==p?.wrapper&&s.focus()}),e?.statusIndicator?.mode==="transient"?n.append(o,u,r):n.append(o,r,u),{footer:n,suggestions:o,composerForm:r,header:m,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:c?.button??null,micButtonWrapper:c?.wrapper??null,statusText:u,attachmentButton:p?.button??null,attachmentButtonWrapper:p?.wrapper??null,attachmentInput:p?.input??null,attachmentPreviewsContainer:p?.previewsContainer??null,actionsRow:g,leftActions:h,rightActions:b,setSendButtonMode:l.setMode}};je();var Xu=require("lucide");zn();var $M=()=>{let t=F("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),e=v("span","persona-pill-peek__icon"),n=Ge(Xu.MessageSquare,16,"currentColor",1.5);n&&e.appendChild(n);let o=v("span","persona-pill-peek__text"),r=v("span","persona-pill-peek__caret"),s=Ge(Xu.ChevronUp,16,"currentColor",1.5);return s&&r.appendChild(s),t.append(e,o,r),{root:t,textNode:o}},Ju=t=>{let{config:e}=t,n=F("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=du(),r=cu(e);r.style.display="none";let{textarea:s,attachAutoResize:a}=iu(e,{defaultMaxLines:5});a();let l=au(e),c=Da(e),p=lu(e);p&&p.previewsContainer.classList.add("persona-pill-composer__previews");let u=F("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""}}),m=F("div",{className:"persona-widget-composer__left-actions persona-pill-composer__left",attrs:{"data-persona-composer-actions-start":""}});p&&m.append(p.wrapper);let g=F("div",{className:"persona-widget-composer__right-actions persona-pill-composer__right",attrs:{"data-persona-composer-actions-end":""}});c&&g.append(c.wrapper),g.append(l.wrapper),u.addEventListener("click",C=>{C.target!==l.button&&C.target!==l.wrapper&&C.target!==c?.button&&C.target!==c?.wrapper&&C.target!==p?.button&&C.target!==p?.wrapper&&s.focus()}),p&&u.append(p.input),u.append(m,s,g);let h=F("div",{className:"persona-pill-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});n.append(h),p&&h.append(p.previewsContainer),n.append(o,u,r);let b=u;return{footer:n,suggestions:o,composerForm:u,header:h,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:c?.button??null,micButtonWrapper:c?.wrapper??null,statusText:r,attachmentButton:p?.button??null,attachmentButtonWrapper:p?.wrapper??null,attachmentInput:p?.input??null,attachmentPreviewsContainer:p?.previewsContainer??null,actionsRow:b,leftActions:m,rightActions:g,setSendButtonMode:l.setMode}};je();Zt();je();Ii();Zt();Sc();var fW=t=>{switch(t){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},gW=(t,e)=>{if(!t)return null;let n=fW(t);if(n===null)return null;let o=e?.[t],r=o!==void 0?o:n;return r||null},hW=(t,e)=>{let n=v("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",t),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=e,n},yW=t=>{let e=t.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:image/")||!t.includes(":"))},iy=t=>{let e=t.toLowerCase();return e.startsWith("javascript:")||e.startsWith("data:text/html")||e.startsWith("data:text/javascript")||e.startsWith("data:text/xml")||e.startsWith("data:application/xhtml")||e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:")||!t.includes(":"))},ay=320,KM=320,bW=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),vW=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),CW=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),wW=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),xW=t=>{if(!t||t.length===0)return null;let e=F("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});e.style.display="flex";for(let n of t){let o=F("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=v("span","persona-mention-chip-icon"),s=ke(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild(F("span",{className:"persona-mention-chip-label",text:n.label})),e.appendChild(o)}return e},SW=(t,e)=>{let n=document.createDocumentFragment();for(let o of t){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(pc(o.ref,{readonly:!0,render:e}))}return n},zM="\uE000",UM="\uE001",AW=(t,e,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=g=>`${zM}${r}:${g}${UM}`,a=e.map((g,h)=>g.kind==="text"?g.text:s(h)).join(""),l=n(a);if(!e.every((g,h)=>g.kind==="text"||l.includes(s(h)))){t.replaceChildren(SW(e,o));return}t.innerHTML=l;let p=new RegExp(`${zM}${r}:(\\d+)${UM}`),u=document.createTreeWalker(t,NodeFilter.SHOW_TEXT),m=[];for(let g=u.nextNode();g;g=u.nextNode())m.push(g);for(let g of m){let h=g;for(let b=p.exec(h.data);b;b=p.exec(h.data)){let C=e[Number(b[1])],M=h.splitText(b.index);M.data=M.data.slice(b[0].length),C?.kind==="mention"&&M.parentNode?.insertBefore(pc(C.ref,{readonly:!0,render:o}),M),h=M}}},MW=(t,e,n)=>{if(t.length===0)return null;try{let o=v("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),e&&(o.style.marginBottom="8px");let r=0,s=!1,a=()=>{s||(s=!0,o.remove(),n?.())};return t.forEach((l,c)=>{let p=v("img");p.alt=l.alt?.trim()||`Attached image ${c+1}`,p.loading="lazy",p.decoding="async",p.referrerPolicy="no-referrer",p.style.display="block",p.style.width="100%",p.style.maxWidth=`${ay}px`,p.style.maxHeight=`${KM}px`,p.style.height="auto",p.style.objectFit="contain",p.style.borderRadius="10px",p.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",p.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let u=!1;r+=1,p.addEventListener("error",()=>{u||(u=!0,r=Math.max(0,r-1),p.remove(),r===0&&a())}),p.addEventListener("load",()=>{u=!0}),yW(l.image)?(p.src=l.image,o.appendChild(p)):(u=!0,r=Math.max(0,r-1),p.remove())}),r===0?(a(),null):o}catch{return n?.(),null}},TW=t=>{if(t.length===0)return null;try{let e=v("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","audio");let n=0;return t.forEach(o=>{if(!iy(o.audio))return;let r=v("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${ay}px`,e.appendChild(r),n+=1}),n===0?(e.remove(),null):e}catch{return null}},EW=t=>{if(t.length===0)return null;try{let e=v("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","video");let n=0;return t.forEach(o=>{if(!iy(o.video))return;let r=v("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${ay}px`,r.style.maxHeight=`${KM}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",e.appendChild(r),n+=1}),n===0?(e.remove(),null):e}catch{return null}},kW=t=>{if(t.length===0)return null;try{let e=v("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","files");let n=0;return t.forEach(o=>{if(!iy(o.data))return;let r=v("a");r.href=o.data,r.download=o.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=o.filename,r.className="persona-message-file-attachment",r.style.display="inline-flex",r.style.alignItems="center",r.style.gap="6px",r.style.padding="6px 10px",r.style.borderRadius="8px",r.style.fontSize="0.875rem",r.style.textDecoration="underline",r.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",r.style.color="inherit",e.appendChild(r),n+=1}),n===0?(e.remove(),null):e}catch{return null}},Hc=()=>{let t=document.createElement("div");t.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let e=document.createElement("div");e.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",e.style.backgroundColor="currentColor",e.style.opacity="0.4",e.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let r=document.createElement("span");return r.className="persona-sr-only",r.textContent="Loading",t.appendChild(e),t.appendChild(n),t.appendChild(o),t.appendChild(r),t},PW=(t,e,n)=>{let o={config:n??{},streaming:!0,location:t,defaultRenderer:Hc};if(e){let r=e(o);if(r!==null)return r}return Hc()},LW=(t,e)=>{let n=v("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=e==="user"?t.userAvatar:t.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=v("img");r.src=o,r.alt=e==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(r)}else n.textContent=o,n.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=e==="user"?"U":"A",n.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},qM=(t,e,n="div")=>{let o=v(n,"persona-text-xs persona-text-persona-muted"),r=new Date(t.createdAt);return e.format?o.textContent=e.format(r):o.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},Rc=(t,e="bubble")=>{let n=["persona-message-bubble"];switch(e){case"flat":t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-text","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-text-persona-text","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-border","persona-border-persona-message-border","persona-text-persona-text","persona-px-5","persona-py-3");break}return n},jM={bubble:{padding:"0.75rem 1.25rem",fontSize:"0.875rem",lineHeight:"1.75"},minimal:{padding:"0.5rem 0.75rem",fontSize:"0.875rem",lineHeight:"1.75"},flat:{padding:"0.5rem 0",fontSize:"inherit",lineHeight:"inherit"}},IW=(t,e,n="bubble",o)=>{if(!o)return;let r=e==="user"?"user":"assistant",s=jM[n??"bubble"]??jM.bubble;o.padding&&(t.style.padding=`var(--persona-message-${r}-padding, ${s.padding})`),o.fontSize&&(t.style.fontSize=`var(--persona-message-${r}-font-size, ${s.fontSize})`),o.lineHeight&&(t.style.lineHeight=`var(--persona-message-${r}-line-height, ${s.lineHeight})`),o.fontFamily&&(t.style.fontFamily=`var(--persona-message-${r}-font-family, inherit)`)},Zu="custom:",HW=t=>`${Zu}${t}`,GM=(t,e)=>e!=="user"&&e!=="assistant"?[]:(t?.custom??[]).filter(n=>(n.roles??["assistant"]).includes(e)),RW=(t,e,n,o)=>{let r=e.showCopy??!0,s=e.showUpvote??!1,a=e.showDownvote??!1,l=e.showReadAloud??!1,c=(e.showRegenerate??!1)&&o?.canRegenerate===!0,p=(e.showEdit??!1)&&o?.canEdit===!0,u=(e.showQuote??!1)&&o?.canQuote!==!1,m=GM(e,t.role);if(!r&&!s&&!a&&!l&&!c&&!p&&!u&&m.length===0){let R=v("div");return R.style.display="none",R.id=`actions-${t.id}`,R.setAttribute("data-actions-for",t.id),R}let g=e.visibility??"hover",h=e.align??"right",b=e.layout??"pill-inside",C={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[h],M={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[b],E=v("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${C} ${M} ${g==="hover"?"persona-message-actions-hover":""}`);E.id=`actions-${t.id}`,E.setAttribute("data-actions-for",t.id);let T=(R,A,D)=>{let W=vn({icon:R,label:A,size:14,className:"persona-message-action-btn",chromeless:!0});return W.setAttribute("data-action",D),W};r&&E.appendChild(T("copy","Copy message","copy")),l&&E.appendChild(T("volume-2","Read aloud","read-aloud")),s&&E.appendChild(T("thumbs-up","Upvote","upvote")),a&&E.appendChild(T("thumbs-down","Downvote","downvote")),c&&E.appendChild(T("refresh-cw","Regenerate response","regenerate")),p&&E.appendChild(T("pencil","Edit message","edit")),u&&E.appendChild(T("quote","Quote message","quote"));for(let R of m)E.appendChild(T(R.iconName??"ellipsis",R.label,HW(R.id)));return E},ly=(t,e,n,o,r,s)=>{let a=n??{},l=a.layout??"bubble",c=a.avatar,p=a.timestamp,u=c?.show??!1,m=p?.show??!1,g=c?.position??"left",h=p?.position??"below",b=Rc(t.role,l),C=v("div",b.join(" "));C.id=`bubble-${t.id}`,C.setAttribute("data-message-id",t.id),C.setAttribute("data-persona-theme-zone",t.role==="user"?"user-message":"assistant-message");let M=Nh(s?.widgetConfig?.future).components.message,E=s?.widgetConfig?.theme?.components?.message;IW(C,t.role,l,t.role==="user"?{...M.user,...E?.user,...s?.widgetConfig?.darkTheme?.components?.message?.user}:{...M.assistant,...E?.assistant,...s?.widgetConfig?.darkTheme?.components?.message?.assistant}),l==="flat"?(C.style.backgroundColor="transparent",C.style.color=t.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):t.role==="user"?(C.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",C.style.color="var(--persona-message-user-text, white)"):t.role==="assistant"&&(C.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",C.style.color="var(--persona-message-assistant-text, var(--persona-text))");let T=bW(t),R=t.content?.trim()??"",D=T.length>0&&R===Ha,W=qu(s?.widgetConfig?.features?.streamAnimation),U=s?.widgetConfig?.features?.streamAnimation?.plugins,B=t.role==="assistant"&&W.type!=="none"?vc(W.type,U):null,O=t.role==="assistant"&&B?.isAnimating?.(t)===!0,H=t.role==="assistant"&&B!==null&&(!!t.streaming||O);H&&B?.bubbleClass&&C.classList.add(B.bubbleClass);let S=document.createElement("div");S.classList.add("persona-message-content"),t.streaming&&S.classList.add("persona-content-streaming"),H&&B&&(B.containerClass&&S.classList.add(B.containerClass),S.style.setProperty("--persona-stream-step",`${W.speed}ms`),S.style.setProperty("--persona-stream-duration",`${W.duration}ms`));let x=H?ju(t.content??"",W.buffer,B,t,!!t.streaming):t.content??"",P=()=>{let se=e({text:x,message:t,streaming:!!t.streaming,raw:t.rawContent});return H&&B?.wrap==="char"?Cc(se,"char",t.id,{skipTags:B.skipTags}):H&&B?.wrap==="word"?Cc(se,"word",t.id,{skipTags:B.skipTags}):se},L=null;if(D?(L=document.createElement("div"),L.innerHTML=P(),L.style.display="none",S.appendChild(L)):t.contentSegments?.length?AW(S,t.contentSegments,se=>e({text:se,message:t,streaming:!!t.streaming,raw:t.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):S.innerHTML=P(),H&&B?.useCaret&&!D&&R){let se=Ku(),_=S.querySelectorAll(".persona-stream-char, .persona-stream-word"),Te=_[_.length-1];if(Te?.parentNode)Te.parentNode.insertBefore(se,Te.nextSibling);else{let Re=S.lastElementChild;Re?Re.appendChild(se):S.appendChild(se)}}if(m&&h==="inline"&&t.createdAt){let se=qM(t,p,"span");se.classList.add("persona-timestamp-inline");let _=S.lastElementChild;_?_.appendChild(se):S.appendChild(se)}if(T.length>0){let se=MW(T,!D&&!!R,()=>{D&&L&&(L.style.display="")});se?C.appendChild(se):D&&L&&(L.style.display="")}let G=vW(t);if(G.length>0){let se=TW(G);se&&C.appendChild(se)}let V=CW(t);if(V.length>0){let se=EW(V);se&&C.appendChild(se)}let K=wW(t);if(K.length>0){let se=kW(K);se&&C.appendChild(se)}let ee=t.contentSegments?.length?null:xW(t.contextMentions);if(ee&&C.appendChild(ee),C.appendChild(S),m&&h==="below"&&t.createdAt){let se=qM(t,p);se.classList.add("persona-mt-1"),C.appendChild(se)}let oe=t.role==="assistant"?gW(t.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(t.streaming&&t.role==="assistant"){let se=!!(x&&x.trim()),_=W.placeholder==="skeleton",Te=_&&W.buffer==="line"&&se;if(se)Te&&C.appendChild(wc());else if(_)C.appendChild(wc());else{let Re=PW("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);Re&&C.appendChild(Re)}}oe&&t.stopReason&&!t.streaming&&(R||(S.style.display="none"),C.appendChild(hW(t.stopReason,oe)));let ne=t.role==="assistant"&&!t.streaming&&t.content&&t.content.trim()&&o?.enabled!==!1,le=s?.actionEligibility,de=t.role==="user"&&!t.streaming&&o?.enabled!==!1&&(o?.showEdit===!0&&le?.canEdit===!0||o?.showQuote===!0&&le?.canQuote===!0||GM(o,"user").length>0);if((ne||de)&&o){let se=RW(t,de?{...o,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:o,r,le);C.appendChild(se)}if(!u||t.role==="system")return C;let ve=v("div",`persona-message-with-avatar persona-flex persona-gap-2 ${t.role==="user"?"persona-flex-row-reverse":""}`),Le=LW(c,t.role);return g==="right"||g==="left"&&t.role==="user"?ve.append(C,Le):ve.append(Le,C),ve};var WW=40,BW=(t,e)=>{if(t.replaceChildren(),!e){t.hidden=!0;return}if(typeof e=="function"){let n=null;try{n=e()}catch(o){console.warn("[persona] welcome.icon renderer threw",o)}if(!n){t.hidden=!0;return}t.appendChild(n),t.hidden=!1;return}if(e.type==="lucide"){let n=ke(e.name,WW);if(!n){t.hidden=!0;return}t.appendChild(n)}else e.type==="image"?t.appendChild(F("img",{className:"persona-welcome-icon-image",attrs:{src:e.url,alt:e.alt}})):t.appendChild(F("span",{className:"persona-welcome-icon-text",text:e.text}));t.hidden=!1},YM=(t,e,n={})=>{let o=F("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});o.hidden=!0;let r=v("p","persona-welcome-kicker");r.hidden=!0;let s=v("h2","persona-welcome-title"),a=v("p","persona-welcome-subtitle"),l=F("div",{className:"persona-welcome-head-text"},r,s),c=F("div",{className:"persona-welcome-title-row"},o,l);return{host:F("div",{className:"persona-welcome persona-rounded-2xl",attrs:{"data-persona-welcome":"","data-persona-intro-card":"","data-persona-welcome-variant":"card"},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:n.flatShadow?"none":"var(--persona-intro-card-shadow, none)",border:"var(--persona-intro-card-border, none)"}},c,a,e),iconHolder:o,kicker:r,title:s,subtitle:a,starterSuggestions:e}},za=(t,e,n)=>{e.hidden=!n,e.style.display=n?"":"none",t.classList.toggle("persona-gap-6",n),t.classList.toggle("persona-gap-3",!n)},tm=(t,e)=>{t.title.textContent=e.title,t.kicker.textContent=e.kicker??"",t.kicker.hidden=!e.kicker,t.subtitle.textContent=e.subtitle,t.subtitle.hidden=e.subtitle==="",BW(t.iconHolder,e.icon),t.host.setAttribute("data-persona-welcome-variant",e.variant),t.host.setAttribute("data-persona-welcome-dismiss",e.dismiss),t.host.setAttribute("data-persona-welcome-layout",e.layout??"top"),t.host.setAttribute("data-persona-welcome-anchor",e.anchor??"bottom"),e.iconPlacement==="inline"?t.host.setAttribute("data-persona-welcome-icon-placement","inline"):t.host.removeAttribute("data-persona-welcome-icon-placement"),e.align?t.host.setAttribute("data-persona-welcome-align",e.align):t.host.removeAttribute("data-persona-welcome-align")},DW="data-persona-welcome-plugin",QM="data-persona-welcome-overlay",em="persona-welcome-overlay-active",cy=new WeakMap,dy=(t,e,n)=>{n.setAttribute(DW,""),e.appendChild(n),e.setAttribute("data-persona-welcome-content","plugin"),e.setAttribute(QM,""),t.classList.contains(em)||(cy.set(t,t.scrollTop),t.classList.add(em),t.scrollTop=0)},py=(t,e,n)=>{n&&n!==e&&n.remove(),e.removeAttribute("data-persona-welcome-content"),e.removeAttribute(QM),t.classList.contains(em)&&(t.classList.remove(em),t.scrollTop=cy.get(t)??t.scrollTop,cy.delete(t))},XM=()=>{let t=F("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return t.hidden=!0,t},nm=(t,e,n)=>{if(t.replaceChildren(),!e){t.hidden=!0;return}let o=n?.layout?.messages?.layout??"bubble",r=F("div",{className:Rc("assistant",o).join(" "),attrs:{"data-persona-theme-zone":"assistant-message"},text:e,style:o==="flat"?{backgroundColor:"transparent",color:"var(--persona-message-assistant-text, var(--persona-text))"}:{backgroundColor:"var(--persona-message-assistant-bg, var(--persona-container))",color:"var(--persona-message-assistant-text, var(--persona-text))"}});t.appendChild(F("div",{className:"persona-flex"},r)),t.hidden=!1},JM=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,ZM=(t,e)=>{if(JM()||typeof t.animate!="function"||!t.isConnected)return e(null),null;let n=t.getBoundingClientRect(),o=t.parentElement,r=0,s=0,a=0;if(o){let b=getComputedStyle(o);r=parseFloat(b.rowGap)||0;let C=t.previousElementSibling,M=t.nextElementSibling,T=o.getBoundingClientRect().top+(parseFloat(b.borderTopWidth)||0)+(parseFloat(b.paddingTop)||0)-o.scrollTop;s=Math.max(0,C?n.top-C.getBoundingClientRect().bottom-r:n.top-T),a=Math.max(0,M?M.getBoundingClientRect().top-n.bottom-r:0)}let l=t.style.overflow;t.style.overflow="hidden";let c=getComputedStyle(t),p=parseFloat(c.paddingTop)||0,u=parseFloat(c.paddingBottom)||0,m=t.animate([{opacity:"1",transform:"none",height:`${n.height}px`,minHeight:"0px",paddingTop:`${p}px`,paddingBottom:`${u}px`,marginTop:`${s}px`,marginBottom:`${a}px`},{opacity:"0",transform:"translateY(-4px)",height:"0px",minHeight:"0px",paddingTop:"0px",paddingBottom:"0px",marginTop:"0px",marginBottom:`${-r}px`}],{duration:180,easing:"ease-out",fill:"forwards"}),g=!1,h=()=>{g||(g=!0,t.style.overflow=l,e(m))};return m.finished.then(h).catch(h),m},eT=(t,e,n,o=260)=>{if(e<=1||JM()||typeof t.animate!="function"||!t.isConnected)return null;let r=n==="drop"?-e:e;return t.animate([{transform:`translateY(${r}px)`},{transform:"none"}],{duration:o,easing:"cubic-bezier(0.2, 0, 0, 1)",fill:"none"})};var OW="Hello \u{1F44B}",_W="I can answer questions and help you get things done here.",tT=new WeakSet,Kn=(t,e)=>!!t&&t[e]!==void 0,NW=(t,e)=>{!t||t.debug!==!0||!e.length||tT.has(t)||(tT.add(t),e.forEach(n=>console.warn(`[persona] ${n}`)))},om=(t,e=t?.launcher?.fullHeight===!0&&!t.launcher.sidebarMode&&t.launcher.mountMode!=="docked")=>{let n=t?.welcome,o=t?.copy,r=t?.future?.v5Defaults===!0,s=n?.layout??(r?"centered":"top"),a=Kn(n,"variant")?n.variant:o?.showWelcomeCard===!1?"none":"card",l=a==="hero"&&!r&&n?.layout===void 0?"on-first-message":Kn(n,"dismiss")?n.dismiss:r||a==="hero"?"on-first-message":"never",c=[];Kn(n,"title")&&Kn(o,"welcomeTitle")&&c.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),Kn(n,"subtitle")&&Kn(o,"welcomeSubtitle")&&c.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),Kn(n,"variant")&&Kn(o,"showWelcomeCard")&&c.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),a==="hero"&&Kn(n,"message")&&c.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),!r&&n?.layout===void 0&&a==="hero"&&Kn(n,"dismiss")&&n.dismiss!=="on-first-message"&&c.push('welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".');let p=n?.anchor??(s==="centered"&&e?"center":"bottom"),u=hc(n?.anchorComposerTop)!==null;return Kn(n,"anchorComposerTop")&&!u&&c.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),p!=="center"&&(Kn(n,"anchorComposerTop")||Kn(n,"composerGap"))&&c.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),NW(t,c),{title:Kn(n,"title")?n.title:o?.welcomeTitle??(r?"What can I help with?":OW),kicker:n?.kicker??"",subtitle:Kn(n,"subtitle")?n.subtitle:o?.welcomeSubtitle??(r?"":_W),icon:n?.icon,align:n?.align==="start"||n?.align==="center"?n.align:s==="centered"?"center":void 0,iconPlacement:n?.icon&&typeof n.icon!="function"&&n.icon.placement==="inline"?"inline":"above",variant:a,dismiss:l,message:a==="hero"?void 0:n?.message,layout:s,anchor:p,anchorComposerTop:u?n.anchorComposerTop:"44%",composerGap:n?.composerGap?.trim()||Ou}},nT=t=>(t??[]).some(e=>e.role==="user")?"active":"empty",Ua=(t,e)=>t.variant==="none"?!1:t.dismiss==="never"?!0:!(e??[]).some(n=>n.role==="user");var FW="var(--persona-components-panel-maxWidth)",oT="var(--persona-components-panel-height)",VW="var(--persona-components-panel-maxHeight)",Hi=t=>{let e=Nr(t),n=e.launcherWidth?t?.launcher?.width:e.legacyLauncherWidth?t?.launcherWidth:void 0,o=t?.launcher?.heightOffset??0,r=o===0?`max(200px, ${oT})`:`max(200px, calc(${oT} - ${o}px))`;return{width:n??Tw,maxWidth:n??FW,height:r,maxHeight:VW}},rT="16px",my="10px",fy="14px",sT=t=>{let e=t?.launcher?.enabled??!0,n=nn(t);if(Ec(t)){let p=t?.launcher?.composerBar??{},u=v("div","persona-widget-wrapper persona-fixed persona-transition");u.setAttribute("data-persona-composer-bar",""),u.dataset.state="collapsed",u.dataset.expandedSize=p.expandedSize??"anchored",u.style.zIndex=String(t?.launcher?.zIndex??On);let m=v("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");m.style.width="100%",u.appendChild(m);let g=v("div","persona-widget-pill-root");return g.setAttribute("data-persona-composer-bar",""),g.dataset.state="collapsed",g.dataset.expandedSize=p.expandedSize??"anchored",g.style.zIndex=String(t?.launcher?.zIndex??On),{wrapper:u,panel:m,pillRoot:g}}if(n){let p=v("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),u=v("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return p.appendChild(u),{wrapper:p,panel:u}}if(!e){let p=v("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),u=v("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),m=Nr(t),h=m.launcherWidth||m.legacyLauncherWidth||t?.theme?.components?.panel?.width!==void 0?Hi(t).width:"100%";return p.style.width=h,u.style.width="100%",p.appendChild(u),{wrapper:p,panel:u}}let r=t?.launcher??{},s=r.position&&vo[r.position]?vo[r.position]:vo["bottom-right"],a=v("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String(t?.launcher?.zIndex??On);let l=v("div","persona-widget-panel persona-relative persona-min-h-[320px]"),c=Hi(t);return l.style.width=c.width,l.style.maxWidth=c.maxWidth,a.appendChild(l),{wrapper:a,panel:l}},gy=t=>{let e=F("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":ey(t)}});return e.hidden=!0,e},iT=(t,e)=>{let n=gy("starter"),o=YM(t,n,{flatShadow:nn(t)}),r=om(t);tm(o,r),za(e,o.host,Ua(r,t?.initialMessages));let s=XM();return nm(s,r.message,t),{welcome:o,greetingHost:s}},$W=(t,e)=>{let n=v("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:r}=Va(t,{showClose:e,wrapperClassName:"persona-composer-bar-close",buttonSize:rT,iconSize:my});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let s=t?.launcher?.clearChat?.enabled??!0,a=null,l=null;if(s){let U=$a(t,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:rT,iconSize:fy});a=U.button,l=U.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let c=F("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),p=F("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});p.style.setProperty("scrollbar-gutter","stable");let{welcome:u,greetingHost:m}=iT(t,p),{host:g,title:h,subtitle:b}=u,C=u.starterSuggestions,M=v("div","persona-widget-messages persona-flex persona-flex-col");M.style.gap="var(--persona-components-message-gap, 12px)";let E=gy("followUp"),T=Is(t,!0);T&&(M.style.maxWidth=T,M.style.marginLeft="auto",M.style.marginRight="auto",M.style.width="100%"),p.append(g,m,M,E);let R=F("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}}),A=Ju({config:t}),{root:D,textNode:W}=$M();return n.append(c,r,p,R),l&&n.appendChild(l),{container:n,body:p,messagesWrapper:M,starterSuggestions:C,transcriptSuggestions:E,composerOverlay:R,suggestions:A.suggestions,textarea:A.textarea,sendButton:A.sendButton,sendButtonWrapper:A.sendButtonWrapper,micButton:A.micButton,micButtonWrapper:A.micButtonWrapper,composerForm:A.composerForm,statusText:A.statusText,welcomeHost:g,welcomeIconHolder:u.iconHolder,greetingHost:m,introKicker:u.kicker,introTitle:h,introSubtitle:b,closeButton:o,closeButtonWrapper:r,clearChatButton:a,clearChatButtonWrapper:l,iconHolder:v("span"),headerTitle:v("span"),headerSubtitle:v("span"),header:c,footer:A.footer,attachmentButton:A.attachmentButton,attachmentButtonWrapper:A.attachmentButtonWrapper,attachmentInput:A.attachmentInput,attachmentPreviewsContainer:A.attachmentPreviewsContainer,actionsRow:A.actionsRow,leftActions:A.leftActions,rightActions:A.rightActions,setSendButtonMode:A.setSendButtonMode,peekBanner:D,peekTextNode:W}},aT=(t,e=!0)=>{if(Ec(t))return $W(t,e);let n=F("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),o=t?.layout?.header,r=t?.layout?.showHeader!==!1,s=o?Qu(t,o,{showClose:e}):Pi({config:t,showClose:e}),a=F("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});a.style.setProperty("scrollbar-gutter","stable");let{welcome:l,greetingHost:c}=iT(t,a),{host:p,title:u,subtitle:m}=l,g=l.starterSuggestions,h=v("div","persona-widget-messages persona-flex persona-flex-col");h.style.gap="var(--persona-components-message-gap, 12px)";let b=gy("followUp"),C=Is(t,!1);C&&(h.style.maxWidth=C,h.style.marginLeft="auto",h.style.marginRight="auto",h.style.width="100%"),a.append(p,c,h,b);let M=Ic({config:t}),E=t?.layout?.showFooter!==!1;r?Pc(n,s,t):(s.header.style.display="none",Pc(n,s,t)),n.append(a);let T=F("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}});return E||(M.footer.style.display="none"),n.append(M.footer),n.append(T),{container:n,body:a,messagesWrapper:h,starterSuggestions:g,transcriptSuggestions:b,composerOverlay:T,suggestions:M.suggestions,textarea:M.textarea,sendButton:M.sendButton,sendButtonWrapper:M.sendButtonWrapper,micButton:M.micButton,micButtonWrapper:M.micButtonWrapper,composerForm:M.composerForm,statusText:M.statusText,welcomeHost:p,welcomeIconHolder:l.iconHolder,greetingHost:c,introKicker:l.kicker,introTitle:u,introSubtitle:m,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:M.footer,attachmentButton:M.attachmentButton,attachmentButtonWrapper:M.attachmentButtonWrapper,attachmentInput:M.attachmentInput,attachmentPreviewsContainer:M.attachmentPreviewsContainer,actionsRow:M.actionsRow,leftActions:M.leftActions,rightActions:M.rightActions,setSendButtonMode:M.setSendButtonMode}};je();Zt();ks();var hy=(t,e)=>{let n=v("button");n.type="button",n.innerHTML=`
|
|
1159
1159
|
<span class="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-bg-persona-primary persona-text-white" data-role="launcher-icon">\u{1F4AC}</span>
|
|
1160
1160
|
<img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
|
|
1161
1161
|
<span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
|
|
@@ -1163,15 +1163,15 @@ _Details: ${n.message}_`:o}var sh=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
1163
1163
|
<span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-launcher-muted" data-role="launcher-subtitle"></span>
|
|
1164
1164
|
</span>
|
|
1165
1165
|
<span class="persona-ml-2 persona-grid persona-place-items-center persona-rounded-full persona-bg-persona-primary persona-text-persona-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
|
|
1166
|
-
`,n.addEventListener("click",e);let o=s=>{let a=s.launcher??{},l=nn(s),c=Iu(s)==="circle";c?(n.dataset.personaLauncherVariant="circle",n.setAttribute("aria-label",a.title??"Open chat")):(n.removeAttribute("data-persona-launcher-variant"),n.removeAttribute("aria-label"));let p=n.querySelector("[data-role='launcher-title']");if(p){let A=a.title??"Chat Assistant";p.textContent=A,p.setAttribute("title",A)}let u=n.querySelector("[data-role='launcher-subtitle']");if(u){let A=a.subtitle??"Here to help you get answers fast";u.textContent=A,u.setAttribute("title",A)}let m=n.querySelector(".persona-flex-col");m&&(a.textHidden||l||c?m.style.display="none":m.style.display="");let g=n.querySelector("[data-role='launcher-icon']");if(g)if(a.agentIconHidden)g.style.display="none";else{let A=a.agentIconSize??"40px";if(g.style.height=A,g.style.width=A,a.agentIconBackgroundColor?(g.style.backgroundColor=a.agentIconBackgroundColor,g.classList.remove("persona-bg-persona-primary")):(g.style.backgroundColor="",g.classList.add("persona-bg-persona-primary")),g.innerHTML="",a.agentIconName){let D=parseFloat(A)||24,W=ke(a.agentIconName,D*.6,"var(--persona-text-inverse, #ffffff)",1.5);W?(g.appendChild(W),g.style.display=""):(g.textContent=a.agentIconText??"\u{1F4AC}",g.style.display="")}else a.iconUrl?g.style.display="none":(g.textContent=a.agentIconText??"\u{1F4AC}",g.style.display="")}let h=n.querySelector("[data-role='launcher-image']");if(h){let A=a.agentIconSize??"40px";h.style.height=A,h.style.width=A,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(h.src=a.iconUrl,h.style.display="block"):h.style.display="none"}let b=n.querySelector("[data-role='launcher-call-to-action-icon']");if(b){let A=a.callToActionIconSize??"32px";b.style.height=A,b.style.width=A,a.callToActionIconBackgroundColor?(b.style.backgroundColor=a.callToActionIconBackgroundColor,b.classList.remove("persona-bg-persona-primary")):(b.style.backgroundColor="",b.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(b.style.color=a.callToActionIconColor,b.classList.remove("persona-text-persona-call-to-action")):(b.style.color="",b.classList.add("persona-text-persona-call-to-action"));let D=0;if(a.callToActionIconPadding?(b.style.boxSizing="border-box",b.style.padding=a.callToActionIconPadding,D=(parseFloat(a.callToActionIconPadding)||0)*2):(b.style.boxSizing="",b.style.padding=""),a.callToActionIconHidden||c)b.style.display="none";else if(b.style.display=l?"none":"",b.innerHTML="",a.callToActionIconName){let W=parseFloat(A)||24,U=Math.max(W-D,8),B=ke(a.callToActionIconName,U,"currentColor",1.5);B?b.appendChild(B):b.textContent=a.callToActionIconText??"\u2197"}else b.textContent=a.callToActionIconText??"\u2197"}let C=a.position&&vo[a.position]?vo[a.position]:vo["bottom-right"],M="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-launcher persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",E="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-launcher persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=l?E:`${M} ${C}`,l||(n.style.zIndex=String(a.zIndex??On));let T="1px solid var(--persona-launcher-border, var(--persona-border, #e5e7eb))",
|
|
1167
|
-
`):""},
|
|
1168
|
-
`).length>7?{tabindex:"0","aria-label":`${l} content`}:{},style:{color:r.codeBlockTextColor??r.contentTextColor}}),h=F("button",{className:"persona-tool-detail-copy",attrs:{type:"button","data-persona-copy-tool-detail":"","aria-label":`Copy ${l.toLowerCase()}`,title:`Copy ${l.toLowerCase()}`}}),b=ke("copy",14,"currentColor",1.7);b&&h.appendChild(b),p.append(u,g,h),t.appendChild(p)};
|
|
1166
|
+
`,n.addEventListener("click",e);let o=s=>{let a=s.launcher??{},l=nn(s),c=Iu(s)==="circle";c?(n.dataset.personaLauncherVariant="circle",n.setAttribute("aria-label",a.title??"Open chat")):(n.removeAttribute("data-persona-launcher-variant"),n.removeAttribute("aria-label"));let p=n.querySelector("[data-role='launcher-title']");if(p){let A=a.title??"Chat Assistant";p.textContent=A,p.setAttribute("title",A)}let u=n.querySelector("[data-role='launcher-subtitle']");if(u){let A=a.subtitle??"Here to help you get answers fast";u.textContent=A,u.setAttribute("title",A)}let m=n.querySelector(".persona-flex-col");m&&(a.textHidden||l||c?m.style.display="none":m.style.display="");let g=n.querySelector("[data-role='launcher-icon']");if(g)if(a.agentIconHidden)g.style.display="none";else{let A=a.agentIconSize??"40px";if(g.style.height=A,g.style.width=A,a.agentIconBackgroundColor?(g.style.backgroundColor=a.agentIconBackgroundColor,g.classList.remove("persona-bg-persona-primary")):(g.style.backgroundColor="",g.classList.add("persona-bg-persona-primary")),g.innerHTML="",a.agentIconName){let D=parseFloat(A)||24,W=ke(a.agentIconName,D*.6,"var(--persona-text-inverse, #ffffff)",1.5);W?(g.appendChild(W),g.style.display=""):(g.textContent=a.agentIconText??"\u{1F4AC}",g.style.display="")}else a.iconUrl?g.style.display="none":(g.textContent=a.agentIconText??"\u{1F4AC}",g.style.display="")}let h=n.querySelector("[data-role='launcher-image']");if(h){let A=a.agentIconSize??"40px";h.style.height=A,h.style.width=A,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(h.src=a.iconUrl,h.style.display="block"):h.style.display="none"}let b=n.querySelector("[data-role='launcher-call-to-action-icon']");if(b){let A=a.callToActionIconSize??"32px";b.style.height=A,b.style.width=A,a.callToActionIconBackgroundColor?(b.style.backgroundColor=a.callToActionIconBackgroundColor,b.classList.remove("persona-bg-persona-primary")):(b.style.backgroundColor="",b.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(b.style.color=a.callToActionIconColor,b.classList.remove("persona-text-persona-call-to-action")):(b.style.color="",b.classList.add("persona-text-persona-call-to-action"));let D=0;if(a.callToActionIconPadding?(b.style.boxSizing="border-box",b.style.padding=a.callToActionIconPadding,D=(parseFloat(a.callToActionIconPadding)||0)*2):(b.style.boxSizing="",b.style.padding=""),a.callToActionIconHidden||c)b.style.display="none";else if(b.style.display=l?"none":"",b.innerHTML="",a.callToActionIconName){let W=parseFloat(A)||24,U=Math.max(W-D,8),B=ke(a.callToActionIconName,U,"currentColor",1.5);B?b.appendChild(B):b.textContent=a.callToActionIconText??"\u2197"}else b.textContent=a.callToActionIconText??"\u2197"}let C=a.position&&vo[a.position]?vo[a.position]:vo["bottom-right"],M="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-launcher persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",E="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-launcher persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=l?E:`${M} ${C}`,l||(n.style.zIndex=String(a.zIndex??On));let T="1px solid var(--persona-launcher-border, var(--persona-border, #e5e7eb))",R="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=a.border??T,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:R,l?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=a.collapsedMaxWidth??"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},r=()=>{n.removeEventListener("click",e),n.remove()};return t&&o(t),{element:n,update:o,destroy:r}},zW="teaser-dismissed",cT=new Set,lT=t=>{let e=t?.persistState;return`${(typeof e=="object"?e?.keyPrefix:void 0)??"persona-"}${zW}`},UW=(t,e)=>{if(cT.has(t))return!0;if(!e)return!1;try{return window.localStorage.getItem(t)==="1"}catch{return!1}},qW=(t,e)=>{if(cT.add(t),!!e)try{window.localStorage.setItem(t,"1")}catch{}},jW=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,KW=t=>{let e=t?.launcher?.teaser;return!e||!e.text||t?.launcher?.enabled===!1||nn(t??{})?null:e},dT=(t,e)=>{let n=v("div","persona-launcher-surface");n.setAttribute("data-persona-launcher-surface","true");let o=t??{},r=null,s=null,a=null,l=null,c=null,p=!1,u=!1,m=!1,g=!1,h=()=>(r?.frequency??"once")==="once"&&o.persistState!==!1,b=()=>{c!==null&&(clearTimeout(c),c=null)},C=()=>{!s||!p||(p=!1,s.hidden=!0)},M=G=>{b(),m=!0,C(),qW(lT(o),G&&h())},E=G=>{!r||m||M(G==="user"&&p)},T=()=>{c=null,!(!s||m||g)&&(u=!0,p=!0,s.hidden=!1,!(jW()||typeof s.animate!="function")&&s.animate([{opacity:"0",transform:"translateY(6px)"},{opacity:"1",transform:"none"}],{duration:220,easing:"ease-out",fill:"backwards"}))},R=()=>{!r||!s||m||u||g||UW(lT(o),h())||(b(),c=setTimeout(T,Math.max(0,r.delayMs??0)))},A=()=>{M(h()),e()},D=G=>{G.stopPropagation(),M(h())},U=hy(t,()=>{E("user"),e()}),B=()=>{b(),l?.removeEventListener("click",A),a?.removeEventListener("click",D),s?.remove(),s=null,l=null,a=null,p=!1},O=()=>{l=F("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),l.addEventListener("click",A),a=F("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"\xD7"}),a.addEventListener("click",D),s=F("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},l,a),n.insertBefore(s,U.element)},H=()=>{let G=o.launcher?.position??"bottom-right",V=vo[G]??vo["bottom-right"];if(!s){n.className="persona-launcher-surface",n.removeAttribute("data-teaser"),n.style.zIndex="",U.element.style.position="";return}n.className=Gt("persona-launcher-surface",V),n.setAttribute("data-teaser",G),n.style.zIndex=String(o.launcher?.zIndex??On),U.element.style.position="static"},S=G=>{let V=KW(G);if(r=V,!V){B();return}s||O(),l.textContent=V.text,a.hidden=V.dismissible===!1,a.setAttribute("aria-label",V.dismissLabel??"Dismiss message"),R()},x=G=>{o=G,U.update(G),S(G),H()},P=(G,V="user")=>{g=G,G&&E(V)},L=()=>{B(),U.destroy(),n.remove()};return n.appendChild(U.element),t&&(S(t),H()),{element:n,launcher:U,get teaser(){return s?{element:s,show:T,dismiss:M}:null},setPanelOpen:P,update:x,destroy:L}};var pT=({config:t,showClose:e})=>{let{wrapper:n,panel:o,pillRoot:r}=sT(t),s=aT(t,e),a={wrapper:n,panel:o,pillRoot:r},l={container:s.container,body:s.body,messagesWrapper:s.messagesWrapper,starterSuggestions:s.starterSuggestions,transcriptSuggestions:s.transcriptSuggestions,composerOverlay:s.composerOverlay,welcomeHost:s.welcomeHost,welcomeIconHolder:s.welcomeIconHolder,greetingHost:s.greetingHost,introTitle:s.introTitle,introSubtitle:s.introSubtitle},c={element:s.header,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper},p={footer:s.footer,form:s.composerForm,textarea:s.textarea,sendButton:s.sendButton,sendButtonWrapper:s.sendButtonWrapper,micButton:s.micButton,micButtonWrapper:s.micButtonWrapper,statusText:s.statusText,suggestions:s.suggestions,attachmentButton:s.attachmentButton,attachmentButtonWrapper:s.attachmentButtonWrapper,attachmentInput:s.attachmentInput,attachmentPreviewsContainer:s.attachmentPreviewsContainer,actionsRow:s.actionsRow,leftActions:s.leftActions,rightActions:s.rightActions,setSendButtonMode:s.setSendButtonMode,peekBanner:s.peekBanner,peekTextNode:s.peekTextNode};return{shell:a,panelElements:s,transcript:l,header:c,composer:p,replaceHeader:g=>(c.element.replaceWith(g.header),c.element=g.header,c.iconHolder=g.iconHolder,c.headerTitle=g.headerTitle,c.headerSubtitle=g.headerSubtitle,c.closeButton=g.closeButton,c.closeButtonWrapper=g.closeButtonWrapper,c.clearChatButton=g.clearChatButton,c.clearChatButtonWrapper=g.clearChatButtonWrapper,g),replaceComposer:g=>{p.footer.replaceWith(g),p.footer=g}}},yy=({config:t,plugins:e,onToggle:n})=>{let o=e.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:t,defaultRenderer:()=>hy(t,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=dT(t,n);return{instance:r,element:r.element}};var GW=t=>{let e=t?.persistState;return(typeof e=="object"?e?.keyPrefix:void 0)??"persona-"},YW=(t,e,n)=>`${GW(t)}plugin:${e}:${n}`,uT=t=>{let e=new Map,n=!1,o=()=>{if(n||t()?.persistState===!1)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return n=!0,null}};return r=>{let s=a=>YW(t(),r,a);return{get:a=>{let l=s(a),c=o();if(c)try{return c.getItem(l)}catch{n=!0}return e.get(l)??null},set:(a,l)=>{let c=s(a),p=o();if(p)try{p.setItem(c,l);return}catch{n=!0}e.set(c,l)},remove:a=>{let l=s(a);e.delete(l);let c=o();if(c)try{c.removeItem(l)}catch{n=!0}}}}};je();Zt();Ts();rm();var QW=(t,e)=>{let n=t.reasoning?.chunks.join("").trim()??"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,e).join(`
|
|
1167
|
+
`):""},by=(t,e,n)=>{Mp(t,e,{stateSet:n,previewKind:"reasoning",iconColor:"currentColor"})},vy=(t,e,n=new Set)=>{e=Ep(e,"reasoning");let o=t.reasoning,r=wp("persona-reasoning-bubble",t.id);if(!o)return Vr(r,t,e,"reasoning");let s=e?.features?.reasoningDisplay??{},a=s.expandable??wi.expandable,l=a&&n.has(t.id),c=o.status!=="complete",p=QW(t,s.previewMaxLines??wi.previewMaxLines),u=xp({expandable:a,expanded:l,bubbleType:"reasoning"}),m=v("div","persona-flex persona-flex-col persona-text-left"),g=v("span","persona-text-xs persona-text-persona-primary"),h=vs(e,"reasoning")==="row",b=h&&!c?`Thought for ${Vl(o.durationMs??(o.completedAt!==void 0&&o.startedAt!==void 0?o.completedAt-o.startedAt:void 0))}`:"Thinking...",C=e?.reasoning??{},M=String(o.startedAt??Date.now()),E=()=>{let V=v("span","");return V.setAttribute("data-tool-elapsed",M),V.textContent=$p(o),V},T=C.renderCollapsedSummary?.({message:t,reasoning:o,defaultSummary:b,previewText:p,isActive:c,config:e??{},elapsed:$p(o),createElapsedElement:E});typeof T=="string"&&T.trim()?(g.textContent=T,m.appendChild(g)):T instanceof HTMLElement?m.appendChild(T):(g.textContent=b,m.appendChild(g));let R=v("span","persona-text-xs persona-text-persona-primary");R.textContent=Tx(o),h||m.appendChild(R);let A=s.loadingAnimation??wi.loadingAnimation,D=C.activeTextTemplate,W=C.completeTextTemplate,U=c?D:W,B=T instanceof HTMLElement,O=(V,K)=>{g.textContent="";let ee=zp(V,""),oe=0;for(let ne of ee){let le=ne.styles.length>0?(()=>{let de=v("span",ne.styles.map(ve=>`persona-tool-text-${ve}`).join(" "));return g.appendChild(de),de})():g;if(ne.isDuration&&c)le.appendChild(E());else{let de=ne.isDuration?$p(o):ne.text;K?oe=Rs(le,de,oe):le.appendChild(document.createTextNode(de))}}};if(!B&&U)if(R.style.display="none",g.style.display="",c&&A!=="none"){let V=C.loadingAnimationDuration??2e3;g.setAttribute("data-preserve-animation","true"),A==="pulse"?(g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${V}ms`),O(U,!1)):(g.classList.add(`persona-tool-loading-${A}`),g.style.setProperty("--persona-tool-anim-duration",`${V}ms`),A==="shimmer-color"&&(C.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",C.loadingAnimationColor),C.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",C.loadingAnimationSecondaryColor)),O(U,!0))}else O(U,!1);else if(!B&&c&&A!=="none"){g.style.display="";let V=C.loadingAnimationDuration??2e3;if(g.setAttribute("data-preserve-animation","true"),A==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${V}ms`);else{g.classList.add(`persona-tool-loading-${A}`),g.style.setProperty("--persona-tool-anim-duration",`${V}ms`),A==="shimmer-color"&&(C.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",C.loadingAnimationColor),C.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",C.loadingAnimationSecondaryColor));let K=g.textContent||b;g.textContent="",Rs(g,K,0)}o.status==="complete"&&!h&&(g.style.display="none")}else B||(o.status==="complete"&&!h?g.style.display="none":g.style.display="");if(s.iconName&&!B){let V=v("span","persona-reasoning-header-icon"),K=ke(s.iconName,16,"currentColor",2);K&&(V.appendChild(K),u.appendChild(V))}let H="currentColor",S=wa(u,m,{expandable:a,expanded:l,iconColor:H,metaGap:!1}),x=Sp({bubble:r,previewKind:"reasoning",expanded:l,isActive:c,previewText:p,activePreview:s.activePreview,activeMinHeight:s.activeMinHeight,renderPreview:()=>e?.reasoning?.renderCollapsedPreview?.({message:t,reasoning:o,defaultPreview:p,isActive:c,config:e??{}})});if(!a)return r.append(u,x),Vr(r,t,e,"reasoning");let P=v("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");P.style.display=l?"":"none";let L=o.chunks.join(""),G=v("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return G.textContent=L||(o.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),P.appendChild(G),Ap({expanded:l,header:u,toggleIcon:S,content:P,collapsedPreview:x,iconColor:H}),r.append(u,x,P),Vr(r,t,e,"reasoning")};je();Ts();Zt();var mT=t=>{if(t==null)return!0;if(typeof t=="string"){if(!t.trim())return!0;try{return mT(JSON.parse(t))}catch{return!1}}return typeof t=="object"&&Object.keys(t).length===0},XW=t=>{if(t!==null&&typeof t=="object")return!0;if(typeof t!="string")return!1;try{let e=JSON.parse(t);return e!==null&&typeof e=="object"}catch{return!1}};function fT(t,e,n){let o=e.toolCall;if(!o)return;let r=n.toolCall??{},s=(l,c)=>{let p=F("section",{className:"persona-tool-detail",attrs:{"data-persona-tool-detail":l.toLowerCase()},style:{backgroundColor:r.codeBlockBackgroundColor,borderColor:r.codeBlockBorderColor,borderWidth:r.codeBlockBorderColor?"1px":void 0}}),u=F("div",{className:"persona-tool-detail-label",text:l,style:{color:r.labelTextColor}}),m=mr(c),g=F("pre",{className:`persona-tool-detail-value${XW(c)?" persona-tool-detail-code":""}`,text:m,attrs:m.length>420||m.split(`
|
|
1168
|
+
`).length>7?{tabindex:"0","aria-label":`${l} content`}:{},style:{color:r.codeBlockTextColor??r.contentTextColor}}),h=F("button",{className:"persona-tool-detail-copy",attrs:{type:"button","data-persona-copy-tool-detail":"","aria-label":`Copy ${l.toLowerCase()}`,title:`Copy ${l.toLowerCase()}`}}),b=ke("copy",14,"currentColor",1.7);b&&h.appendChild(b),p.append(u,g,h),t.appendChild(p)};mT(o.args)||s("Request",o.args);let a=o.status==="complete"&&o.result!==void 0?o.result:o.chunks?.join("");a!==void 0&&(typeof a!="string"||a.trim())&&s("Response",a),o.success===!1&&t.appendChild(F("div",{className:"persona-text-sm persona-whitespace-pre-wrap",text:o.error||"Tool failed",attrs:{"data-persona-tool-error":"",role:"status"}}))}var Cy=new WeakMap;async function gT(t){let e=t.closest("[data-persona-tool-detail]"),n=e?.querySelector("pre");if(!n)return;let o=`Copy ${e?.getAttribute("data-persona-tool-detail")}`;clearTimeout(Cy.get(t));try{await navigator.clipboard.writeText(n.textContent??""),t.dataset.copied="true",t.setAttribute("aria-label","Copied"),t.title="Copied";let r=ke("check",14,"currentColor",2);r&&t.replaceChildren(r)}catch{t.setAttribute("aria-label","Copy failed \u2014 try again"),t.title="Copy failed \u2014 try again"}Cy.set(t,setTimeout(()=>{delete t.dataset.copied,t.setAttribute("aria-label",o),t.title=o;let r=ke("copy",14,"currentColor",1.7);r&&t.replaceChildren(r),Cy.delete(t)},1800))}je();Ts();rm();var hT=(t,e=!1)=>t.toggleTextColor||t.headerTextColor||(e?"currentColor":"var(--persona-primary, #171717)"),JW=(t,e)=>{let n=t.toolCall;if(!n)return"";let o=(n.chunks??[]).join("").trim();if(o)return o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(-e).join(`
|
|
1169
1169
|
`);let r=mr(n.args).trim();return r?r.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,e).join(`
|
|
1170
|
-
`):""},vy=(t,e)=>{t.style.backgroundColor=e.codeBlockBackgroundColor??"var(--persona-container, #f3f4f6)",t.style.borderColor=e.codeBlockBorderColor??"var(--persona-border, #e5e7eb)",t.style.color=e.codeBlockTextColor??"var(--persona-text, #171717)"},OW=(t,e)=>{let n=t.toolCall,o=e?.features?.toolCallDisplay,r=o?.collapsedMode??Fr.collapsedMode,s=n?.success===!1?n.error||"Tool failed":DW(t,o?.previewMaxLines??Fr.previewMaxLines),a=n?vs(e,"tool")==="row"?`${n.status==="complete"?"Used":"Using"} ${n.name?.trim()||"tool"}`:vx(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let l=n.status!=="complete",c=e?.toolCall??{},p=a;return r==="tool-name"?p=n.name?.trim()||a:r==="tool-preview"&&s&&(p=s),l&&c.activeTextTemplate?p=$g(n,c.activeTextTemplate,p):!l&&c.completeTextTemplate&&(p=$g(n,c.completeTextTemplate,p)),n.success===!1&&(p+=" \xB7 Failed"),{summary:p,previewText:s,isActive:l}},Cy=(t,e,n,o)=>{Mp(t,e,{stateSet:n,previewKind:"tool",iconColor:iT(o?.toolCall??{},e.classList.contains("persona-activity-row"))})},wy=(t,e,n=new Set)=>{e=Ep(e,"tool");let o=t.toolCall,r=e?.toolCall??{},s=wp("persona-tool-bubble",t.id);if(r.backgroundColor&&(s.style.backgroundColor=r.backgroundColor),r.borderColor&&(s.style.borderColor=r.borderColor),r.borderWidth&&(s.style.borderWidth=r.borderWidth),r.borderRadius&&(s.style.borderRadius=r.borderRadius),s.style.boxShadow=r.shadow!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-tool-bubble-shadow)",!o)return Vr(s,t,e,"tool");let a=e?.features?.toolCallDisplay??{},l=a.expandable??Fr.expandable,c=l&&n.has(t.id),{summary:p,previewText:u,isActive:m}=OW(t,e),g=xp({expandable:l,expanded:c,bubbleType:"tool"});r.headerBackgroundColor&&(g.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(g.style.paddingLeft=r.headerPaddingX,g.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(g.style.paddingTop=r.headerPaddingY,g.style.paddingBottom=r.headerPaddingY);let h=v("div","persona-flex persona-flex-col persona-text-left"),b=v("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(b.style.color=r.headerTextColor);let C=String(o.startedAt??Date.now()),M=()=>{let x=v("span","");return x.setAttribute("data-tool-elapsed",C),x.textContent=Kl(o),x},E=r.renderCollapsedSummary?.({message:t,toolCall:o,defaultSummary:p,previewText:u,collapsedMode:a.collapsedMode??Fr.collapsedMode,isActive:m,config:e??{},elapsed:Kl(o),createElapsedElement:M});typeof E=="string"&&E.trim()?(b.textContent=E,h.appendChild(b)):E instanceof HTMLElement?h.appendChild(E):(b.textContent=p,h.appendChild(b));let T=a.loadingAnimation??Fr.loadingAnimation,H=r.activeTextTemplate,A=r.completeTextTemplate,D=m?H:A,W=E instanceof HTMLElement,U=(x,P)=>{b.textContent="";let L=o.name?.trim()||"tool",G=zp(x,L),V=0;for(let K of G){let ee=K.styles.length>0?(()=>{let oe=v("span",K.styles.map(ne=>`persona-tool-text-${ne}`).join(" "));return b.appendChild(oe),oe})():b;if(K.isDuration&&m)ee.appendChild(M());else{let oe=K.isDuration?Kl(o):K.text;P?V=Hs(ee,oe,V):ee.appendChild(document.createTextNode(oe))}}};if(!W)if(m&&T!=="none"){let x=r.loadingAnimationDuration??2e3;if(b.setAttribute("data-preserve-animation","true"),T==="pulse")b.classList.add("persona-tool-loading-pulse"),b.style.setProperty("--persona-tool-anim-duration",`${x}ms`),D&&U(D,!1);else if(b.classList.add(`persona-tool-loading-${T}`),b.style.setProperty("--persona-tool-anim-duration",`${x}ms`),T==="shimmer-color"&&(r.loadingAnimationColor&&b.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&b.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),D)U(D,!0);else{let P=b.textContent||p;b.textContent="",Hs(b,P,0)}}else D&&U(D,!1);let B=iT(r,vs(e,"tool")==="row"),O=wa(g,h,{expandable:l,expanded:c,iconColor:B,metaGap:!0}),R=Sp({bubble:s,previewKind:"tool",expanded:c,isActive:m,previewText:u,activePreview:a.activePreview,activeMinHeight:a.activeMinHeight,renderPreview:()=>r.renderCollapsedPreview?.({message:t,toolCall:o,defaultPreview:u,isActive:m,config:e??{}})});if(!l)return s.append(g,R),Vr(s,t,e,"tool");let S=v("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(S.style.display=c?"":"none",r.contentBackgroundColor&&(S.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(S.style.color=r.contentTextColor),r.contentPaddingX&&(S.style.paddingLeft=r.contentPaddingX,S.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(S.style.paddingTop=r.contentPaddingY,S.style.paddingBottom=r.contentPaddingY),e.future?.v5Defaults===!0)rT(S,t,e);else{if(o.name){let x=v("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?x.style.color=r.contentTextColor:r.headerTextColor&&(x.style.color=r.headerTextColor),x.textContent=o.name,S.appendChild(x)}if(o.args!==void 0){let x=v("div","persona-space-y-1"),P=v("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(P.style.color=r.labelTextColor),P.textContent="Arguments";let L=v("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");L.style.fontSize="0.75rem",L.style.lineHeight="1rem",vy(L,r),L.textContent=mr(o.args),x.append(P,L),S.appendChild(x)}if(o.chunks&&o.chunks.length){let x=v("div","persona-space-y-1"),P=v("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(P.style.color=r.labelTextColor),P.textContent="Activity";let L=v("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");L.style.fontSize="0.75rem",L.style.lineHeight="1rem",vy(L,r),L.textContent=o.chunks.join(""),x.append(P,L),S.appendChild(x)}if(o.success===!1&&S.appendChild(F("div",{className:"persona-text-sm persona-whitespace-pre-wrap",text:o.error||"Tool failed",attrs:{"data-persona-tool-error":""}})),o.status==="complete"&&o.result!==void 0){let x=v("div","persona-space-y-1"),P=v("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(P.style.color=r.labelTextColor),P.textContent="Result";let L=v("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");L.style.fontSize="0.75rem",L.style.lineHeight="1rem",vy(L,r),L.textContent=mr(o.result),x.append(P,L),S.appendChild(x)}if(o.status==="complete"&&typeof o.duration=="number"){let x=v("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(x.style.color=r.contentTextColor),x.textContent=`Duration: ${o.duration}ms`,S.appendChild(x)}}return Ap({expanded:c,header:g,toggleIcon:O,content:S,collapsedPreview:R,iconColor:B}),s.append(g,R,S),Vr(s,t,e,"tool")};Ts();ro();var{setLoader:bz,load:UW,provide:vz,getSync:qW}=Qt({fallbackImport:()=>Promise.resolve().then(()=>(gT(),fT))});var hT=UW;var yT=qW;Aa();ro();var{setLoader:Bz,load:dB}=Qt({fallbackImport:()=>Promise.resolve().then(()=>(PT(),kT))});var Iy=dB;ro();Oc();Si();yp();var Uy=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:KU,load:jB,provide:GU,getSync:KB}=Qt({fallbackImport:()=>Promise.resolve().then(()=>(oE(),nE))}),Ya=null,hm=new Set,rE=t=>{if(Ya)return Ya;Ya=t,t.initArtifactsUi({componentRegistry:Yo});for(let o of Uy)Yo.has(o)||Yo.register(o,o==="PersonaArtifactCard"?t.PersonaArtifactCard:t.PersonaArtifactInline,{bubbleChrome:!1});let e=Ro();e?t.__provideMarkdownParsers(e):xa(()=>{let o=Ro();o&&t.__provideMarkdownParsers(o)}),t.__setIconsExtraLoader(()=>hp());let n=[...hm];hm.clear();for(let o of n)try{o()}catch{}return t};var ym=()=>jB().then(rE);var Gr=()=>{if(Ya)return Ya;let t=KB();return t?rE(t):null},qy=t=>Ya?()=>{}:(hm.add(t),()=>{hm.delete(t)});function Kn(t){return t?.features?.artifacts?.enabled===!0}function sE(t,e){if(t.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),t.style.removeProperty("--persona-artifact-pane-border"),t.style.removeProperty("--persona-artifact-pane-border-left"),!Kn(e))return;let n=e.features?.artifacts?.layout,o=n?.paneBorder?.trim(),r=n?.paneBorderLeft?.trim();o?(t.classList.add("persona-artifact-border-full"),t.style.setProperty("--persona-artifact-pane-border",o)):r&&(t.classList.add("persona-artifact-border-left"),t.style.setProperty("--persona-artifact-pane-border-left",r))}function GB(t){t.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),t.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),t.style.removeProperty("--persona-artifact-doc-toggle-active-border")}var iE=["panel","seamless","detached"];function jy(t){let e=t.features?.artifacts?.layout?.paneAppearance;return e&&iE.includes(e)?e:e?"panel":t.launcher?.detachedPanel?"detached":"panel"}function Ky(t){return!t||!Kn(t)?!1:jy(t)==="detached"}function Uc(t,e){if(!Kn(e)){t.style.removeProperty("--persona-artifact-split-gap"),t.style.removeProperty("--persona-artifact-pane-width"),t.style.removeProperty("--persona-artifact-pane-max-width"),t.style.removeProperty("--persona-artifact-pane-min-width"),t.style.removeProperty("--persona-artifact-drawer-width"),t.style.removeProperty("--persona-artifact-pane-bg"),t.style.removeProperty("--persona-artifact-pane-padding"),GB(t),sE(t,e);return}let n=e.features?.artifacts?.layout,o=jy(e)==="detached"?"var(--persona-panel-inset)":"0";t.style.setProperty("--persona-artifact-split-gap",n?.splitGap??o),t.style.setProperty("--persona-artifact-pane-width",n?.paneWidth??"40%"),t.style.setProperty("--persona-artifact-pane-max-width",n?.paneMaxWidth??"28rem"),n?.drawerWidth?t.style.setProperty("--persona-artifact-drawer-width",n.drawerWidth):t.style.removeProperty("--persona-artifact-drawer-width"),n?.paneMinWidth?t.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):t.style.removeProperty("--persona-artifact-pane-min-width");let r=n?.paneBackground?.trim();r?t.style.setProperty("--persona-artifact-pane-bg",r):t.style.removeProperty("--persona-artifact-pane-bg");let s=n?.panePadding?.trim();s?t.style.setProperty("--persona-artifact-pane-padding",s):t.style.removeProperty("--persona-artifact-pane-padding");let a=[[n?.documentToolbarIconColor,"--persona-artifact-doc-toolbar-icon-color"],[n?.documentToolbarToggleActiveBackground,"--persona-artifact-doc-toggle-active-bg"],[n?.documentToolbarToggleActiveBorderColor,"--persona-artifact-doc-toggle-active-border"],[n?.documentToolbarToggleActiveColor,"--persona-artifact-doc-toggle-active-color"]];for(let[l,c]of a){let p=l?.trim();p?t.style.setProperty(c,p):t.style.removeProperty(c)}sE(t,e)}function qc(t,e){for(let l of iE)t.classList.remove(`persona-artifact-appearance-${l}`);if(t.style.removeProperty("--persona-artifact-pane-radius"),t.style.removeProperty("--persona-artifact-pane-shadow"),t.style.removeProperty("--persona-artifact-chat-shadow"),!Kn(e))return;let n=e.features?.artifacts?.layout,o=jy(e);t.classList.add(`persona-artifact-appearance-${o}`);let r=n?.paneBorderRadius?.trim();r&&t.style.setProperty("--persona-artifact-pane-radius",r);let s=n?.paneShadow?.trim();s&&t.style.setProperty("--persona-artifact-pane-shadow",s);let a=n?.chatShadow?.trim();a&&t.style.setProperty("--persona-artifact-chat-shadow",a)}function aE(t,e){return!e||!Kn(t)?!1:t.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var YB=new Set(["__proto__","prototype","constructor"]),QB=new Set(["collapsed","card","panel","inline"]),lE=new Set(["markdown","component"]),XB=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,Ni=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),vm=t=>!YB.has(t),Gy=t=>typeof t=="string"&&QB.has(t),Fi=t=>Object.keys(t).length>0;function Cr(t,e,n,o){t.push({path:e,code:n,message:o})}var JB="Ignored because this key is not part of the persisted preference schema.",bm="Ignored an unsupported value.",ZB="Expected collapsed, panel, or inline.",e1='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',cE={kind:"mode",message:bm},Qa={kind:"string",message:"Expected a CSS length string."},Yr={kind:"boolean"},t1={paneWidth:Qa,paneMaxWidth:Qa,paneMinWidth:Qa,expandedPanelWidth:Qa,resizableMinWidth:Qa,resizableMaxWidth:Qa,expandLauncherPanelWhenOpen:Yr,resizable:Yr},n1={kind:"object",message:"Expected a preference object.",children:{showToolCalls:Yr,showReasoning:Yr,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:bm},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:bm},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:bm},expandable:Yr,grouped:Yr}},reasoningDisplay:{kind:"object",children:{expandable:Yr,activePreview:Yr}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:cE,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:cE,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:lE,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:lE}}},filePreview:{kind:"object",children:{enabled:Yr}},layout:{kind:"object",children:t1}}}}};function dE(t,e,n,o){if(t!==void 0)switch(e.kind){case"boolean":return typeof t=="boolean"?t:Cr(o,n,"invalid_type","Expected a boolean.");case"string":return typeof t=="string"?t:Cr(o,n,"invalid_type",e.message);case"enum":return typeof t=="string"&&e.values.has(t)?t:Cr(o,n,"invalid_value",e.message);case"mode":return Gy(t)?Ho(t):Cr(o,n,"invalid_value",e.message);case"modeMap":{if(!Ni(t))return Cr(o,n,"invalid_type","Expected an object.");let r=e.keys==="mediaType"?void 0:e.keys,s={};for(let[a,l]of Object.entries(t)){let c=r?a:Ma(a);vm(a)&&(r?r.has(a):XB.test(c))?Gy(l)?s[c]=Ho(l):Cr(o,`${n}.${a}`,"invalid_value",ZB):Cr(o,`${n}.${a}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":e1)}return Fi(s)?s:void 0}case"object":{if(e.bareMode&&Gy(t))return Ho(t);if(!Ni(t))return Cr(o,n,"invalid_type",e.message??"Expected an object.");let r=Object.keys(e.children),s=l=>n?`${n}.${l}`:l;for(let l of Object.keys(t))(!vm(l)||!r.includes(l))&&Cr(o,s(l),"unknown_key",JB);let a={};for(let l of r){let c=e.children[l],p=dE(t[l],c,s(l),o);if(c.deprecated&&t[l]!==void 0&&Cr(o,s(l),"deprecated_key",c.deprecated),p===void 0)continue;let u=c.alias??l,m=a[u];a[u]=Ni(m)&&Ni(p)?{...m,...p}:p}return Fi(a)?a:void 0}}}function o1(t){let e=[];return{preferences:(t===null?void 0:dE(t,n1,"",e))??{},issues:e}}function Xa(t){if(Array.isArray(t))return t.map(Xa);if(!Ni(t))return t;let e={};for(let[n,o]of Object.entries(t))vm(n)&&o!==void 0&&(e[n]=Xa(o));return e}function pE(t,e){let n=Xa(t);for(let[o,r]of Object.entries(e)){if(!vm(o)||r===void 0)continue;let s=n[o];n[o]=Ni(s)&&Ni(r)?pE(s,r):Xa(r)}return n}function r1(t){let e={},n;for(let r of t){let s=o1(r).preferences;n=uE(n,s.artifacts?.display),e=pE(e,s)}let o=e;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function s1(t,e){if(e===void 0)return t===void 0?void 0:Xa(t);if(typeof e=="string")return e;let n=typeof t=="string"?{default:t}:t??{},o=e.default??n.default,r={...n.byMediaType,...e.byMediaType},s={...o?{default:o}:{},...Fi(r)?{byMediaType:r}:{}};return Fi(s)?s:void 0}function uE(t,e){if(e===void 0)return t===void 0?void 0:Xa(t);if(typeof e=="string")return e;let n=typeof t=="string"?{default:t}:t??{},o=e.default??n.default,r={...n.byType,...n.byKind,...e.byType,...e.byKind},s=s1(n.files,e.files),a={...o?{default:o}:{},...Fi(r)?{byKind:r}:{},...s!==void 0?{files:s}:{}};return Fi(a)?a:void 0}function i1(t={},e){let n=r1(e),o={...t};if(n.showToolCalls!==void 0&&(o.showToolCalls=n.showToolCalls),n.showReasoning!==void 0&&(o.showReasoning=n.showReasoning),n.toolCallDisplay&&(o.toolCallDisplay={...t.toolCallDisplay,...n.toolCallDisplay}),n.reasoningDisplay&&(o.reasoningDisplay={...t.reasoningDisplay,...n.reasoningDisplay}),n.artifacts){let r=t.artifacts??{},s={...r};if(n.artifacts.display!==void 0){let a=uE(r.display,n.artifacts.display);a!==void 0&&(s.display=a)}n.artifacts.filePreview&&(s.filePreview={...r.filePreview,enabled:n.artifacts.filePreview.enabled}),n.artifacts.layout&&(s.layout={...r.layout,...n.artifacts.layout}),o.artifacts=s}return o}function Yy(t){let e=t.preferences;return!e||!Fi(e)?t:{...t,features:i1(t.features??{},[e])}}function a1(t,e){if(!t?.trim())return e;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return n?Math.max(0,Number(n[1])):e}function l1(t){if(!t?.trim())return null;let e=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return e?Math.max(0,Number(e[1])):null}function c1(t,e,n){return n<e?e:Math.min(n,Math.max(e,t))}function d1(t,e,n,o){let r=t-o-2*e-n;return Math.max(0,r)}function Qy(t,e){let o=(e.getComputedStyle(t).gap||"0px").trim().split(/\s+/)[0]??"0px",r=/^([\d.]+)px$/i.exec(o);if(r)return Number(r[1]);let s=/^([\d.]+)/.exec(o);return s?Number(s[1]):8}function mE(t,e,n,o,r,s,a=200){let l=a1(r,200),c=d1(e,n,o,a);c=Math.max(l,c);let p=l1(s);return p!==null&&(c=Math.min(c,p)),c1(t,l,c)}ro();var{setLoader:rq,load:p1,provide:sq,getSync:u1}=Qt({fallbackImport:()=>Promise.resolve().then(()=>(yE(),hE))});var bE=p1;var vE=u1;var Xy=class{constructor(){this.plugins=new Map}register(e){this.plugins.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.plugins.set(e.id,e),e.onRegister?.()}unregister(e){let n=this.plugins.get(e);n&&(n.onUnregister?.(),this.plugins.delete(e))}getAll(){return Array.from(this.plugins.values()).sort((e,n)=>(n.priority??0)-(e.priority??0))}getForInstance(e){let n=this.getAll();if(!e||e.length===0)return n;let o=new Set(e.map(s=>s.id));return[...n.filter(s=>!o.has(s.id)),...e].sort((s,a)=>(a.priority??0)-(s.priority??0))}clear(){this.plugins.forEach(e=>e.onUnregister?.()),this.plugins.clear()}},Jy=new Xy;var CE=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),m1=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),wE=(t,e,n)=>{if(!CE(t)||!CE(e)||m1.has(n))return e;let o={...t};for(let r of Object.keys(e)){if(e[r]===void 0){delete o[r];continue}let s=n?`${n}.${r}`:r;o[r]=wE(t[r],e[r],s)}return o};function xE(t,e){let n=up(Ci),o=gw(t,e,n),r=hg(hw(wE(t,e,""),n,o),o);return vg(gp(r),bw(t,e))}var SE=()=>{let t=new Map,e=(r,s)=>(t.has(r)||t.set(r,new Set),t.get(r).add(s),()=>n(r,s)),n=(r,s)=>{t.get(r)?.delete(s)};return{on:e,off:n,emit:(r,s)=>{t.get(r)?.forEach(a=>{try{a(s)}catch(l){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",l)}})}}};var f1=t=>{let e=t.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:t},g1=t=>{let e=t.trim(),n=e.indexOf("{");if(n===-1)return null;let o=0;for(let r=n;r<e.length;r+=1){let s=e[r];if(s==="{"&&(o+=1),s==="}"&&(o-=1,o===0))return e.slice(n,r+1)}return null},eb=({text:t})=>{if(!t||!t.includes("{"))return null;try{let e=f1(t),n=g1(e);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:r,...s}=o;return{type:String(r),payload:s,raw:o}}catch{return null}},Zy=t=>typeof t=="string"?t:t==null?"":String(t),jc={message:t=>t.type!=="message"?void 0:{handled:!0,displayText:Zy(t.payload.text)},messageAndClick:(t,e)=>{if(t.type!=="message_and_click")return;let n=t.payload,o=Zy(n.element);if(o&&e.document?.querySelector){let r=e.document.querySelector(o);r?setTimeout(()=>{r.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:Zy(n.text)}}},AE=t=>Array.isArray(t)?t.map(e=>String(e)):[],tb=t=>{let e=new Set(AE(t.getSessionMetadata().processedActionMessageIds)),n=()=>{e=new Set(AE(t.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(e);t.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||e.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console<"u"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let l=a?t.parsers.reduce((p,u)=>p||u?.({text:a,message:s.message})||null,null):null;if(!l)return null;e.add(s.message.id),o();let c={action:l,message:s.message};t.emit("action:detected",c);for(let p of t.handlers)if(p)try{let u=()=>{t.emit("action:resubmit",c)},m=p(l,{message:s.message,metadata:t.getSessionMetadata(),updateMetadata:t.updateSessionMetadata,document:t.documentRef,triggerResubmit:u});if(!m)continue;if(m.handled){let g=m.persistMessage!==!1;return{text:m.displayText!==void 0?m.displayText:"",persist:g,resubmit:m.resubmit}}}catch(u){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:n}};var h1=t=>{if(!t)return null;try{return JSON.parse(t)}catch(e){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}},y1=t=>t.map(e=>({...e,streaming:!1})),b1=t=>t.map(e=>({...e,status:"complete"})),ME=(t="persona-state")=>{let e=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=e();return n?h1(n.getItem(t)):null},save:n=>{let o=e();if(o)try{let r={...n,messages:n.messages?y1(n.messages):void 0,artifacts:n.artifacts?b1(n.artifacts):void 0};o.setItem(t,JSON.stringify(r))}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=e();if(n)try{n.removeItem(t)}catch(o){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};var v1=t=>{let e=2166136261;for(let n=0;n<t.length;n++)e^=t.charCodeAt(n),e=Math.imul(e,16777619)>>>0;return e.toString(16).padStart(8,"0")},TE=async t=>{let e=globalThis.crypto?.subtle;if(e)try{let n=await e.digest("SHA-256",new TextEncoder().encode(t));return Array.from(new Uint8Array(n)).map(o=>o.toString(16).padStart(2,"0")).join("")}catch{}return v1(t)},C1=async(t,e)=>{let n=await TE(t);return{storageKey:`${e}visitor:${n}`,leaseKey:`${e}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await TE(`${t}\0${e}`)}`}};var EE=(t,e,n)=>{let o="",r="",s="",a=!1,l=!1,c=0,p=null,u=null,m=new Set,g=()=>{if(n||a)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return a=!0,null}},h=()=>{let W=g();if(!W)return p;try{return W.getItem(o)}catch{return a=!0,p}},b=(W,U)=>{if(l||W===p)return;let B=p;p=W,c+=1;let O={previousToken:B,token:W,source:U,revision:c};for(let R of m)R(O)},C=W=>{l||W.key!==null&&W.key!==o||b(W.key===null?null:W.newValue??null,"external")},M=(async()=>{let W=await C1(t,e);o=W.storageKey,r=W.leaseKey,s=W.lockName,p=h(),!n&&typeof window<"u"&&window.addEventListener("storage",C)})(),E=W=>new Promise(U=>setTimeout(U,W)),T=()=>{let W=g();if(!W)return null;try{let U=W.getItem(r);if(!U)return null;let B=JSON.parse(U);return typeof B?.expiresAt=="number"&&typeof B?.ownerNonce=="string"?B:null}catch{return null}},H=W=>{let U=g();if(U)try{T()?.ownerNonce===W&&U.removeItem(r)}catch{}},A=W=>new Promise(U=>{let B=setTimeout(O,W);function O(){clearTimeout(B),window.removeEventListener("storage",R),U()}function R(S){(S.key===null||S.key===r)&&O()}window.addEventListener("storage",R)}),D=async W=>{let U=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,B=Date.now()+15e3;for(;Date.now()<B;){let O=g();if(!O)break;let R=Date.now(),S=T();if(S&&S.expiresAt>R&&S.ownerNonce!==U){await A(Math.min(S.expiresAt-R,500));continue}try{O.setItem(r,JSON.stringify({ownerNonce:U,expiresAt:R+1e4}))}catch{a=!0;break}if(await E(20+Math.random()*40),T()?.ownerNonce!==U){await A(500);continue}u=U;try{return await W()}finally{u=null,H(U)}}return W()};return{ready:M,async get(){return await M,b(h(),"external"),p},async set(W){await M;let U=g();if(U)try{U.setItem(o,W)}catch{a=!0}b(W,"local")},async clear(){await M;let W=g();if(W)try{W.removeItem(o)}catch{a=!0}b(null,"local")},revision(){return c},subscribe(W){return m.add(W),()=>{m.delete(W)}},async withFirstInitLock(W){await M;let U=globalThis.navigator?.locks;return U?.request?U.request(s,()=>W()):g()?D(W):W()},matches(W,U,B){return W===t&&U===e&&B===n},destroy(){l=!0,m.clear(),typeof window<"u"&&window.removeEventListener("storage",C),u&&H(u)}}};ro();var{setLoader:Yq,load:j1}=Qt({fallbackImport:()=>Promise.resolve().then(()=>(UE(),zE))});var ub=j1;var mb=(t,e)=>{console.warn(`[persona] ${t} threw`,e)},Qr=t=>Object.freeze({...t}),qE=t=>Object.freeze({id:t.id,title:t.title,targetId:t.targetId,preview:t.preview,messageCount:t.messageCount,createdAt:t.createdAt,updatedAt:t.updatedAt}),jE=t=>t?Qr(t):null;function KE(t){let{plugins:e,config:n}=t,o=!1,r=!1,s=!1,a=!1,l=null,c=[],p=()=>{for(let A of c.splice(0))try{A()}catch(D){mb("renderHistoryView cleanup",D)}},u=(A,D)=>{for(let W of e){let U=W[A];if(U)try{let B=U(D);if(B)return B}catch(B){mb(A,B)}}return null},m=()=>({presentation:t.getPresentation(),config:n}),g={header:A=>a?u("renderHistoryHeader",Object.freeze({...m(),returnSurface:t.getReturnSurface(),identityStatus:Qr(A.identityStatus),pendingAction:jE(A.pendingAction),copy:Qr(A.copy),actions:Object.freeze({close:C.close,startNewConversation:C.startNewConversation}),defaultRenderer:A.defaultRenderer})):null,conversation:A=>a?u("renderHistoryConversation",Object.freeze({...m(),conversation:qE(A.conversation),active:A.active,pending:A.pending,open:A.open,requestDelete:A.requestDelete,defaultRenderer:A.defaultRenderer})):null,state:A=>a?u("renderHistoryState",Object.freeze({...m(),state:Qr(A.state),identityStatus:Qr(A.identityStatus),copy:Qr(A.copy),...A.retry?{retry:A.retry}:{},...A.startNewConversation?{startNewConversation:A.startNewConversation}:{},defaultRenderer:A.defaultRenderer})):null},h=e.flatMap(A=>(A.railSections??[]).map(D=>({...D,placement:D.placement??"above-conversations",items:[],render:W=>D.render(Object.freeze({collapsed:W,presentation:t.getPresentation(),actions:C}))}))),b=t.createView({slots:g,renderDom:!1,onModelChange:()=>H(),railSections:h}),C=Object.freeze({...b.operations,close:t.close}),M=()=>(a=!0,b.setDomRenderEnabled(!0),b.element),E=A=>Object.freeze({conversations:Object.freeze(A.conversations.map(qE)),activeConversationId:A.activeConversationId,state:Qr(A.state),pendingAction:jE(A.pendingAction),identityStatus:Qr(A.identityStatus),nextCursor:A.nextCursor,presentation:t.getPresentation(),returnSurface:t.getReturnSurface(),config:n,copy:Qr(b.copy),actions:C,defaultRenderer:M,requestRender:()=>H(),onCleanup:D=>{c.push(D)}}),T=()=>{a=!1;let A=null;for(let W of e)if(W.renderHistoryView){try{A=W.renderHistoryView(E(b.getModel()))}catch(U){mb("renderHistoryView",U),A=null}if(A)break}let D=!A||A.contains(b.element);return a=D,b.setDomRenderEnabled(D),A??b.element};function H(){if(!(!s||o||r)){r=!0;try{p();let A=T();if(A===l)return;let D=l;l=A,t.onElementChanged(A,D)}finally{r=!1}}}return s=!0,H(),{view:b,get element(){return l??b.element},requestRender:H,dispose:()=>{o=!0,p()}}}var K1=null;function GE(){return K1}Zl();var G1=new Map([["not_found","not_found"],["conversation_deleted","not_found"],["rate_limited","rate_limited"],["authentication_required","authentication_required"],["invalid_identity_proof","authentication_required"],["visitor_identity_mismatch","authentication_required"],["visitor_required","authentication_required"],["identity_provider_failed","identity_provider_failed"],["proof_not_admitted","proof_not_admitted"],["identity_contract_violation","proof_not_admitted"],["unauthorized","authentication_failed"],["visitor_token_missing","authentication_failed"],["conversation_credential_missing","authentication_failed"]]),Y1=new Map([["not_found","That conversation is no longer available."],["rate_limited","Too many history requests."],["authentication_failed","History access was not authorized."],["authentication_required","Sign in again to view account history."],["identity_provider_failed","The identity provider did not respond."],["proof_not_admitted","Account history is not available for this configuration."],["unsupported_scope","This history scope is not supported."],["unavailable","Conversation history is unavailable right now."]]),fb=t=>Y1.get(t)??"Conversation history is unavailable right now.";function Q1(t){if(t instanceof gr)return t;if(t instanceof it){let e=G1.get(t.code)??"unavailable";return new gr(e,fb(e),{...t.retryAfterSeconds!==void 0?{retryAfterSeconds:t.retryAfterSeconds}:{}})}return new gr("unavailable",fb("unavailable"))}function YE(t){let e=()=>t.getClient?.()??t.client,n=t.getIdentityProofConfigured()?["browser","verified-user"]:["browser"],o={scopes:n},r=l=>{if(!n.includes(l))throw new gr("unsupported_scope",fb("unsupported_scope"))},s=async(l,c)=>{r(l);try{return await c()}catch(p){throw Q1(p)}},a=l=>{let c=!1;return{conversationId:l.session.conversationId??"",conversationRevision:l.session.conversationRevision??"",async commit(){c||(c=!0,l.commit(),await t.onActivationCommitted(l.session))},discard(){c||(c=!0,l.discard())}}};return{capabilities:o,getIdentityStatus(){return e().getHistoryIdentityStatus()},subscribeIdentityStatus(l){return e().subscribeHistoryIdentityStatus(l)},subscribeAvailability(l){return e().subscribeHistoryAvailability(l)},async list(l){return s(l.context.scope,async()=>{let c=await e().listConversations({...l.cursor?{cursor:l.cursor}:{},...l.limit!==void 0?{limit:l.limit}:{},...l.targetId?{targetId:l.targetId}:{},scope:l.context.scope});return{items:c.data,nextCursor:c.nextCursor}})},async getPage(l,c){return s(c.context.scope,async()=>{let p=await e().getConversation(l,{...c.cursor?{messageCursor:c.cursor}:{},scope:c.context.scope}),u=Hx(p.messages,{...c.beforeCreatedAt?{beforeCreatedAt:c.beforeCreatedAt}:{}});return{summary:p.summary,messages:Ql([],u),conversationRevision:p.conversationRevision??"",nextCursor:p.nextMessageCursor}})},async prepareOpen(l,c){return s(c.context.scope,async()=>a(await e().prepareConversationSession(l)))},async prepareStartNew(l){return s(l.context.scope,async()=>a(await e().prepareNewConversationSession()))},async delete(l,c){await s(c.context.scope,()=>e().deleteConversation(l,{scope:c.context.scope}))},async deleteAll(l){return s(l.context.scope,()=>e().deleteAllConversations({...l.targetId!==void 0?{targetId:l.targetId}:{},scope:l.context.scope}))},async resetDevice(){try{return await e().resetVisitor(),{remoteRevocationConfirmed:!0}}catch{return{remoteRevocationConfirmed:!1}}}}}ob();je();var X1="button:not([disabled])";function Mm(t){let e=document.activeElement instanceof HTMLElement?document.activeElement:null,n=Math.random().toString(36).slice(2,8),o=`persona-history-confirm-title-${n}`,r=`persona-history-confirm-desc-${n}`,s=F("button",{className:"persona-history-confirm__cancel",text:t.cancelLabel,attrs:{type:"button"}}),a=F("button",{className:"persona-history-confirm__confirm",text:t.confirmLabel,attrs:{type:"button","data-persona-destructive":"true"}}),l=F("div",{className:"persona-history-confirm__dialog",attrs:{role:"alertdialog","aria-modal":"true","aria-labelledby":o,"aria-describedby":r},style:{maxWidth:"22rem",width:"100%",borderRadius:"var(--persona-radius-lg, 0.75rem)",background:"var(--persona-surface, #ffffff)",color:"var(--persona-text, #111827)",boxShadow:"var(--persona-history-confirm-shadow, 0 20px 40px -12px rgba(0, 0, 0, 0.35))",padding:"20px",display:"flex",flexDirection:"column",gap:"12px"}},F("h2",{className:"persona-history-confirm__title",text:t.title,attrs:{id:o},style:{margin:"0",fontSize:"1rem",fontWeight:"600"}}),F("p",{className:"persona-history-confirm__description",text:t.description,attrs:{id:r},style:{margin:"0",fontSize:"0.875rem",lineHeight:"1.4"}}),F("div",{className:"persona-history-confirm__actions",style:{display:"flex",gap:"8px",justifyContent:"flex-end",flexWrap:"wrap"}},s,a));for(let p of[s,a])p.style.minHeight="44px",p.style.minWidth="88px",p.style.padding="0 16px",p.style.borderRadius="var(--persona-radius-md, 0.5rem)",p.style.cursor="pointer",p.style.font="inherit";s.style.border="1px solid var(--persona-border, rgba(0,0,0,0.12))",s.style.background="transparent",s.style.color="inherit",a.style.border="none",a.style.background="var(--persona-danger, #b42318)",a.style.color="var(--persona-danger-fg, #ffffff)";let c=F("div",{className:"persona-history-confirm",style:{position:"absolute",inset:"0",zIndex:"40",display:"flex",alignItems:"center",justifyContent:"center",padding:"16px",background:"var(--persona-history-confirm-scrim, rgba(15, 23, 42, 0.45))"}},l);return new Promise(p=>{let u=!1,m=h=>{u||(u=!0,c.removeEventListener("keydown",g,!0),c.remove(),e?.focus(),p(h))};function g(h){if(h.key==="Escape"){h.preventDefault(),h.stopPropagation(),m(!1);return}if(h.key!=="Tab")return;let b=Array.from(l.querySelectorAll(X1));if(b.length===0)return;let C=b[0],M=b[b.length-1],E=document.activeElement;h.shiftKey&&(E===C||!l.contains(E))?(h.preventDefault(),M.focus()):!h.shiftKey&&E===M&&(h.preventDefault(),C.focus())}c.addEventListener("keydown",g,!0),c.addEventListener("pointerdown",h=>{h.target===c&&m(!1)}),s.addEventListener("click",()=>m(!1)),a.addEventListener("click",()=>m(!0)),t.host.appendChild(c),s.focus()})}Oc();Oc();var gb=require("partial-json");je();function QE(t,e){let{config:n,message:o,onPropsUpdate:r}=e,s=Yo.get(t.component);if(!s){if(Uy.includes(t.component)){ym().catch(()=>{});let l=v("div","persona-w-full");return l.setAttribute("data-persona-artifact-pending","true"),l}return console.warn(`[ComponentMiddleware] Component "${t.component}" not found in registry. Falling back to default rendering.`),null}let a={message:o,config:n,updateProps:l=>{r&&r(l)}};try{return s(t.props,a)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${t.component}":`,l),null}}function XE(t){if(typeof t.rawContent=="string"&&t.rawContent.length>0)return t.rawContent;if(typeof t.content=="string"){let e=t.content.trim();if(e.startsWith("{")||e.startsWith("["))return t.content}return null}function hb(t){let e=XE(t);if(!e)return!1;try{let n=JSON.parse(e);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function JE(t){let e=XE(t);if(!e)return null;try{let n=JSON.parse(e);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let o=n;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:e}}}catch{}return null}var J1=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function ZE(t){let{onSubmit:e,onDismiss:n,title:o="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:l="Skip",showComment:c=!0,ratingLabels:p=J1}=t,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-csat",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Customer satisfaction feedback");let m=null,g=document.createElement("div");g.className="persona-feedback-content";let h=document.createElement("div");h.className="persona-feedback-header";let b=document.createElement("h3");b.className="persona-feedback-title",b.textContent=o,h.appendChild(b);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=r,h.appendChild(C),g.appendChild(h);let M=document.createElement("div");M.className="persona-feedback-rating persona-feedback-rating-csat",M.setAttribute("role","radiogroup"),M.setAttribute("aria-label","Satisfaction rating from 1 to 5");let E=[];for(let W=1;W<=5;W++){let U=document.createElement("button");U.type="button",U.className="persona-feedback-rating-btn persona-feedback-star-btn",U.setAttribute("role","radio"),U.setAttribute("aria-checked","false"),U.setAttribute("aria-label",`${W} star${W>1?"s":""}: ${p[W-1]}`),U.title=p[W-1],U.dataset.rating=String(W),U.innerHTML=`
|
|
1170
|
+
`):""},wy=(t,e)=>{t.style.backgroundColor=e.codeBlockBackgroundColor??"var(--persona-container, #f3f4f6)",t.style.borderColor=e.codeBlockBorderColor??"var(--persona-border, #e5e7eb)",t.style.color=e.codeBlockTextColor??"var(--persona-text, #171717)"},ZW=(t,e)=>{let n=t.toolCall,o=e?.features?.toolCallDisplay,r=o?.collapsedMode??Fr.collapsedMode,s=n?.success===!1?n.error||"Tool failed":JW(t,o?.previewMaxLines??Fr.previewMaxLines),a=n?vs(e,"tool")==="row"?`${n.status==="complete"?"Used":"Using"} ${n.name?.trim()||"tool"}`:kx(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let l=n.status!=="complete",c=e?.toolCall??{},p=a;return r==="tool-name"?p=n.name?.trim()||a:r==="tool-preview"&&s&&(p=s),l&&c.activeTextTemplate?p=Ug(n,c.activeTextTemplate,p):!l&&c.completeTextTemplate&&(p=Ug(n,c.completeTextTemplate,p)),n.success===!1&&(p+=" \xB7 Failed"),{summary:p,previewText:s,isActive:l}},xy=(t,e,n,o)=>{Mp(t,e,{stateSet:n,previewKind:"tool",iconColor:hT(o?.toolCall??{},e.classList.contains("persona-activity-row"))})},Sy=(t,e,n=new Set)=>{e=Ep(e,"tool");let o=t.toolCall,r=e?.toolCall??{},s=wp("persona-tool-bubble",t.id);if(r.backgroundColor&&(s.style.backgroundColor=r.backgroundColor),r.borderColor&&(s.style.borderColor=r.borderColor),r.borderWidth&&(s.style.borderWidth=r.borderWidth),r.borderRadius&&(s.style.borderRadius=r.borderRadius),s.style.boxShadow=r.shadow!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-tool-bubble-shadow)",!o)return Vr(s,t,e,"tool");let a=e?.features?.toolCallDisplay??{},l=a.expandable??Fr.expandable,c=l&&n.has(t.id),{summary:p,previewText:u,isActive:m}=ZW(t,e),g=xp({expandable:l,expanded:c,bubbleType:"tool"});r.headerBackgroundColor&&(g.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(g.style.paddingLeft=r.headerPaddingX,g.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(g.style.paddingTop=r.headerPaddingY,g.style.paddingBottom=r.headerPaddingY);let h=v("div","persona-flex persona-flex-col persona-text-left"),b=v("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(b.style.color=r.headerTextColor);let C=String(o.startedAt??Date.now()),M=()=>{let x=v("span","");return x.setAttribute("data-tool-elapsed",C),x.textContent=Kl(o),x},E=r.renderCollapsedSummary?.({message:t,toolCall:o,defaultSummary:p,previewText:u,collapsedMode:a.collapsedMode??Fr.collapsedMode,isActive:m,config:e??{},elapsed:Kl(o),createElapsedElement:M});typeof E=="string"&&E.trim()?(b.textContent=E,h.appendChild(b)):E instanceof HTMLElement?h.appendChild(E):(b.textContent=p,h.appendChild(b));let T=a.loadingAnimation??Fr.loadingAnimation,R=r.activeTextTemplate,A=r.completeTextTemplate,D=m?R:A,W=E instanceof HTMLElement,U=(x,P)=>{b.textContent="";let L=o.name?.trim()||"tool",G=zp(x,L),V=0;for(let K of G){let ee=K.styles.length>0?(()=>{let oe=v("span",K.styles.map(ne=>`persona-tool-text-${ne}`).join(" "));return b.appendChild(oe),oe})():b;if(K.isDuration&&m)ee.appendChild(M());else{let oe=K.isDuration?Kl(o):K.text;P?V=Rs(ee,oe,V):ee.appendChild(document.createTextNode(oe))}}};if(!W)if(m&&T!=="none"){let x=r.loadingAnimationDuration??2e3;if(b.setAttribute("data-preserve-animation","true"),T==="pulse")b.classList.add("persona-tool-loading-pulse"),b.style.setProperty("--persona-tool-anim-duration",`${x}ms`),D&&U(D,!1);else if(b.classList.add(`persona-tool-loading-${T}`),b.style.setProperty("--persona-tool-anim-duration",`${x}ms`),T==="shimmer-color"&&(r.loadingAnimationColor&&b.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&b.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),D)U(D,!0);else{let P=b.textContent||p;b.textContent="",Rs(b,P,0)}}else D&&U(D,!1);let B=hT(r,vs(e,"tool")==="row"),O=wa(g,h,{expandable:l,expanded:c,iconColor:B,metaGap:!0}),H=Sp({bubble:s,previewKind:"tool",expanded:c,isActive:m,previewText:u,activePreview:a.activePreview,activeMinHeight:a.activeMinHeight,renderPreview:()=>r.renderCollapsedPreview?.({message:t,toolCall:o,defaultPreview:u,isActive:m,config:e??{}})});if(!l)return s.append(g,H),Vr(s,t,e,"tool");let S=v("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(S.style.display=c?"":"none",r.contentBackgroundColor&&(S.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(S.style.color=r.contentTextColor),r.contentPaddingX&&(S.style.paddingLeft=r.contentPaddingX,S.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(S.style.paddingTop=r.contentPaddingY,S.style.paddingBottom=r.contentPaddingY),e.future?.v5Defaults===!0)fT(S,t,e);else{if(o.name){let x=v("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?x.style.color=r.contentTextColor:r.headerTextColor&&(x.style.color=r.headerTextColor),x.textContent=o.name,S.appendChild(x)}if(o.args!==void 0){let x=v("div","persona-space-y-1"),P=v("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(P.style.color=r.labelTextColor),P.textContent="Arguments";let L=v("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");L.style.fontSize="0.75rem",L.style.lineHeight="1rem",wy(L,r),L.textContent=mr(o.args),x.append(P,L),S.appendChild(x)}if(o.chunks&&o.chunks.length){let x=v("div","persona-space-y-1"),P=v("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(P.style.color=r.labelTextColor),P.textContent="Activity";let L=v("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");L.style.fontSize="0.75rem",L.style.lineHeight="1rem",wy(L,r),L.textContent=o.chunks.join(""),x.append(P,L),S.appendChild(x)}if(o.success===!1&&S.appendChild(F("div",{className:"persona-text-sm persona-whitespace-pre-wrap",text:o.error||"Tool failed",attrs:{"data-persona-tool-error":""}})),o.status==="complete"&&o.result!==void 0){let x=v("div","persona-space-y-1"),P=v("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(P.style.color=r.labelTextColor),P.textContent="Result";let L=v("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");L.style.fontSize="0.75rem",L.style.lineHeight="1rem",wy(L,r),L.textContent=mr(o.result),x.append(P,L),S.appendChild(x)}if(o.status==="complete"&&typeof o.duration=="number"){let x=v("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(x.style.color=r.contentTextColor),x.textContent=`Duration: ${o.duration}ms`,S.appendChild(x)}}return Ap({expanded:c,header:g,toggleIcon:O,content:S,collapsedPreview:H,iconColor:B}),s.append(g,H,S),Vr(s,t,e,"tool")};Ts();so();var{setLoader:Wz,load:iB,provide:Bz,getSync:aB}=Qt({fallbackImport:()=>Promise.resolve().then(()=>(MT(),AT))});var TT=iB;var ET=aB;Aa();so();var{setLoader:Xz,load:TB}=Qt({fallbackImport:()=>Promise.resolve().then(()=>(NT(),_T))});var Ry=TB;so();Oc();Si();yp();var jy=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:cq,load:l1,provide:dq,getSync:c1}=Qt({fallbackImport:()=>Promise.resolve().then(()=>(mE(),uE))}),Ya=null,hm=new Set,fE=t=>{if(Ya)return Ya;Ya=t,t.initArtifactsUi({componentRegistry:Yo});for(let o of jy)Yo.has(o)||Yo.register(o,o==="PersonaArtifactCard"?t.PersonaArtifactCard:t.PersonaArtifactInline,{bubbleChrome:!1});let e=Ho();e?t.__provideMarkdownParsers(e):xa(()=>{let o=Ho();o&&t.__provideMarkdownParsers(o)}),t.__setIconsExtraLoader(()=>hp());let n=[...hm];hm.clear();for(let o of n)try{o()}catch{}return t};var ym=()=>l1().then(fE);var Gr=()=>{if(Ya)return Ya;let t=c1();return t?fE(t):null},Ky=t=>Ya?()=>{}:(hm.add(t),()=>{hm.delete(t)});function Gn(t){return t?.features?.artifacts?.enabled===!0}function gE(t,e){if(t.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),t.style.removeProperty("--persona-artifact-pane-border"),t.style.removeProperty("--persona-artifact-pane-border-left"),!Gn(e))return;let n=e.features?.artifacts?.layout,o=n?.paneBorder?.trim(),r=n?.paneBorderLeft?.trim();o?(t.classList.add("persona-artifact-border-full"),t.style.setProperty("--persona-artifact-pane-border",o)):r&&(t.classList.add("persona-artifact-border-left"),t.style.setProperty("--persona-artifact-pane-border-left",r))}function d1(t){t.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),t.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),t.style.removeProperty("--persona-artifact-doc-toggle-active-border")}var hE=["panel","seamless","detached"];function Gy(t){let e=t.features?.artifacts?.layout?.paneAppearance;return e&&hE.includes(e)?e:e?"panel":t.launcher?.detachedPanel?"detached":"panel"}function Yy(t){return!t||!Gn(t)?!1:Gy(t)==="detached"}function Uc(t,e){if(!Gn(e)){t.style.removeProperty("--persona-artifact-split-gap"),t.style.removeProperty("--persona-artifact-pane-width"),t.style.removeProperty("--persona-artifact-pane-max-width"),t.style.removeProperty("--persona-artifact-pane-min-width"),t.style.removeProperty("--persona-artifact-drawer-width"),t.style.removeProperty("--persona-artifact-pane-bg"),t.style.removeProperty("--persona-artifact-pane-padding"),d1(t),gE(t,e);return}let n=e.features?.artifacts?.layout,o=Gy(e)==="detached"?"var(--persona-panel-inset)":"0";t.style.setProperty("--persona-artifact-split-gap",n?.splitGap??o),t.style.setProperty("--persona-artifact-pane-width",n?.paneWidth??"40%"),t.style.setProperty("--persona-artifact-pane-max-width",n?.paneMaxWidth??"28rem"),n?.drawerWidth?t.style.setProperty("--persona-artifact-drawer-width",n.drawerWidth):t.style.removeProperty("--persona-artifact-drawer-width"),n?.paneMinWidth?t.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):t.style.removeProperty("--persona-artifact-pane-min-width");let r=n?.paneBackground?.trim();r?t.style.setProperty("--persona-artifact-pane-bg",r):t.style.removeProperty("--persona-artifact-pane-bg");let s=n?.panePadding?.trim();s?t.style.setProperty("--persona-artifact-pane-padding",s):t.style.removeProperty("--persona-artifact-pane-padding");let a=[[n?.documentToolbarIconColor,"--persona-artifact-doc-toolbar-icon-color"],[n?.documentToolbarToggleActiveBackground,"--persona-artifact-doc-toggle-active-bg"],[n?.documentToolbarToggleActiveBorderColor,"--persona-artifact-doc-toggle-active-border"],[n?.documentToolbarToggleActiveColor,"--persona-artifact-doc-toggle-active-color"]];for(let[l,c]of a){let p=l?.trim();p?t.style.setProperty(c,p):t.style.removeProperty(c)}gE(t,e)}function qc(t,e){for(let l of hE)t.classList.remove(`persona-artifact-appearance-${l}`);if(t.style.removeProperty("--persona-artifact-pane-radius"),t.style.removeProperty("--persona-artifact-pane-shadow"),t.style.removeProperty("--persona-artifact-chat-shadow"),!Gn(e))return;let n=e.features?.artifacts?.layout,o=Gy(e);t.classList.add(`persona-artifact-appearance-${o}`);let r=n?.paneBorderRadius?.trim();r&&t.style.setProperty("--persona-artifact-pane-radius",r);let s=n?.paneShadow?.trim();s&&t.style.setProperty("--persona-artifact-pane-shadow",s);let a=n?.chatShadow?.trim();a&&t.style.setProperty("--persona-artifact-chat-shadow",a)}function yE(t,e){return!e||!Gn(t)?!1:t.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var p1=new Set(["__proto__","prototype","constructor"]),u1=new Set(["collapsed","card","panel","inline"]),bE=new Set(["markdown","component"]),m1=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,Ni=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),vm=t=>!p1.has(t),Qy=t=>typeof t=="string"&&u1.has(t),Fi=t=>Object.keys(t).length>0;function Cr(t,e,n,o){t.push({path:e,code:n,message:o})}var f1="Ignored because this key is not part of the persisted preference schema.",bm="Ignored an unsupported value.",g1="Expected collapsed, panel, or inline.",h1='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',vE={kind:"mode",message:bm},Qa={kind:"string",message:"Expected a CSS length string."},Yr={kind:"boolean"},y1={paneWidth:Qa,paneMaxWidth:Qa,paneMinWidth:Qa,expandedPanelWidth:Qa,resizableMinWidth:Qa,resizableMaxWidth:Qa,expandLauncherPanelWhenOpen:Yr,resizable:Yr},b1={kind:"object",message:"Expected a preference object.",children:{showToolCalls:Yr,showReasoning:Yr,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:bm},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:bm},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:bm},expandable:Yr,grouped:Yr}},reasoningDisplay:{kind:"object",children:{expandable:Yr,activePreview:Yr}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:vE,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:vE,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:bE,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:bE}}},filePreview:{kind:"object",children:{enabled:Yr}},layout:{kind:"object",children:y1}}}}};function CE(t,e,n,o){if(t!==void 0)switch(e.kind){case"boolean":return typeof t=="boolean"?t:Cr(o,n,"invalid_type","Expected a boolean.");case"string":return typeof t=="string"?t:Cr(o,n,"invalid_type",e.message);case"enum":return typeof t=="string"&&e.values.has(t)?t:Cr(o,n,"invalid_value",e.message);case"mode":return Qy(t)?Ro(t):Cr(o,n,"invalid_value",e.message);case"modeMap":{if(!Ni(t))return Cr(o,n,"invalid_type","Expected an object.");let r=e.keys==="mediaType"?void 0:e.keys,s={};for(let[a,l]of Object.entries(t)){let c=r?a:Ma(a);vm(a)&&(r?r.has(a):m1.test(c))?Qy(l)?s[c]=Ro(l):Cr(o,`${n}.${a}`,"invalid_value",g1):Cr(o,`${n}.${a}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":h1)}return Fi(s)?s:void 0}case"object":{if(e.bareMode&&Qy(t))return Ro(t);if(!Ni(t))return Cr(o,n,"invalid_type",e.message??"Expected an object.");let r=Object.keys(e.children),s=l=>n?`${n}.${l}`:l;for(let l of Object.keys(t))(!vm(l)||!r.includes(l))&&Cr(o,s(l),"unknown_key",f1);let a={};for(let l of r){let c=e.children[l],p=CE(t[l],c,s(l),o);if(c.deprecated&&t[l]!==void 0&&Cr(o,s(l),"deprecated_key",c.deprecated),p===void 0)continue;let u=c.alias??l,m=a[u];a[u]=Ni(m)&&Ni(p)?{...m,...p}:p}return Fi(a)?a:void 0}}}function v1(t){let e=[];return{preferences:(t===null?void 0:CE(t,b1,"",e))??{},issues:e}}function Xa(t){if(Array.isArray(t))return t.map(Xa);if(!Ni(t))return t;let e={};for(let[n,o]of Object.entries(t))vm(n)&&o!==void 0&&(e[n]=Xa(o));return e}function wE(t,e){let n=Xa(t);for(let[o,r]of Object.entries(e)){if(!vm(o)||r===void 0)continue;let s=n[o];n[o]=Ni(s)&&Ni(r)?wE(s,r):Xa(r)}return n}function C1(t){let e={},n;for(let r of t){let s=v1(r).preferences;n=xE(n,s.artifacts?.display),e=wE(e,s)}let o=e;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function w1(t,e){if(e===void 0)return t===void 0?void 0:Xa(t);if(typeof e=="string")return e;let n=typeof t=="string"?{default:t}:t??{},o=e.default??n.default,r={...n.byMediaType,...e.byMediaType},s={...o?{default:o}:{},...Fi(r)?{byMediaType:r}:{}};return Fi(s)?s:void 0}function xE(t,e){if(e===void 0)return t===void 0?void 0:Xa(t);if(typeof e=="string")return e;let n=typeof t=="string"?{default:t}:t??{},o=e.default??n.default,r={...n.byType,...n.byKind,...e.byType,...e.byKind},s=w1(n.files,e.files),a={...o?{default:o}:{},...Fi(r)?{byKind:r}:{},...s!==void 0?{files:s}:{}};return Fi(a)?a:void 0}function x1(t={},e){let n=C1(e),o={...t};if(n.showToolCalls!==void 0&&(o.showToolCalls=n.showToolCalls),n.showReasoning!==void 0&&(o.showReasoning=n.showReasoning),n.toolCallDisplay&&(o.toolCallDisplay={...t.toolCallDisplay,...n.toolCallDisplay}),n.reasoningDisplay&&(o.reasoningDisplay={...t.reasoningDisplay,...n.reasoningDisplay}),n.artifacts){let r=t.artifacts??{},s={...r};if(n.artifacts.display!==void 0){let a=xE(r.display,n.artifacts.display);a!==void 0&&(s.display=a)}n.artifacts.filePreview&&(s.filePreview={...r.filePreview,enabled:n.artifacts.filePreview.enabled}),n.artifacts.layout&&(s.layout={...r.layout,...n.artifacts.layout}),o.artifacts=s}return o}function Xy(t){let e=t.preferences;return!e||!Fi(e)?t:{...t,features:x1(t.features??{},[e])}}function S1(t,e){if(!t?.trim())return e;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return n?Math.max(0,Number(n[1])):e}function A1(t){if(!t?.trim())return null;let e=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return e?Math.max(0,Number(e[1])):null}function M1(t,e,n){return n<e?e:Math.min(n,Math.max(e,t))}function T1(t,e,n,o){let r=t-o-2*e-n;return Math.max(0,r)}function Jy(t,e){let o=(e.getComputedStyle(t).gap||"0px").trim().split(/\s+/)[0]??"0px",r=/^([\d.]+)px$/i.exec(o);if(r)return Number(r[1]);let s=/^([\d.]+)/.exec(o);return s?Number(s[1]):8}function SE(t,e,n,o,r,s,a=200){let l=S1(r,200),c=T1(e,n,o,a);c=Math.max(l,c);let p=A1(s);return p!==null&&(c=Math.min(c,p)),M1(t,l,c)}so();var{setLoader:Cq,load:E1,provide:wq,getSync:k1}=Qt({fallbackImport:()=>Promise.resolve().then(()=>(EE(),TE))});var kE=E1;var PE=k1;var Zy=class{constructor(){this.plugins=new Map}register(e){this.plugins.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.plugins.set(e.id,e),e.onRegister?.()}unregister(e){let n=this.plugins.get(e);n&&(n.onUnregister?.(),this.plugins.delete(e))}getAll(){return Array.from(this.plugins.values()).sort((e,n)=>(n.priority??0)-(e.priority??0))}getForInstance(e){let n=this.getAll();if(!e||e.length===0)return n;let o=new Set(e.map(s=>s.id));return[...n.filter(s=>!o.has(s.id)),...e].sort((s,a)=>(a.priority??0)-(s.priority??0))}clear(){this.plugins.forEach(e=>e.onUnregister?.()),this.plugins.clear()}},eb=new Zy;var LE=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),P1=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),IE=(t,e,n)=>{if(!LE(t)||!LE(e)||P1.has(n))return e;let o={...t};for(let r of Object.keys(e)){if(e[r]===void 0){delete o[r];continue}let s=n?`${n}.${r}`:r;o[r]=IE(t[r],e[r],s)}return o};function HE(t,e){let n=up(Ci),o=Aw(t,e,n),r=bg(Mw(IE(t,e,""),n,o),o);return wg(gp(r),Ew(t,e))}var RE=()=>{let t=new Map,e=(r,s)=>(t.has(r)||t.set(r,new Set),t.get(r).add(s),()=>n(r,s)),n=(r,s)=>{t.get(r)?.delete(s)};return{on:e,off:n,emit:(r,s)=>{t.get(r)?.forEach(a=>{try{a(s)}catch(l){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",l)}})}}};var L1=t=>{let e=t.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:t},I1=t=>{let e=t.trim(),n=e.indexOf("{");if(n===-1)return null;let o=0;for(let r=n;r<e.length;r+=1){let s=e[r];if(s==="{"&&(o+=1),s==="}"&&(o-=1,o===0))return e.slice(n,r+1)}return null},nb=({text:t})=>{if(!t||!t.includes("{"))return null;try{let e=L1(t),n=I1(e);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:r,...s}=o;return{type:String(r),payload:s,raw:o}}catch{return null}},tb=t=>typeof t=="string"?t:t==null?"":String(t),jc={message:t=>t.type!=="message"?void 0:{handled:!0,displayText:tb(t.payload.text)},messageAndClick:(t,e)=>{if(t.type!=="message_and_click")return;let n=t.payload,o=tb(n.element);if(o&&e.document?.querySelector){let r=e.document.querySelector(o);r?setTimeout(()=>{r.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:tb(n.text)}}},WE=t=>Array.isArray(t)?t.map(e=>String(e)):[],ob=t=>{let e=new Set(WE(t.getSessionMetadata().processedActionMessageIds)),n=()=>{e=new Set(WE(t.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(e);t.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||e.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console<"u"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let l=a?t.parsers.reduce((p,u)=>p||u?.({text:a,message:s.message})||null,null):null;if(!l)return null;e.add(s.message.id),o();let c={action:l,message:s.message};t.emit("action:detected",c);for(let p of t.handlers)if(p)try{let u=()=>{t.emit("action:resubmit",c)},m=p(l,{message:s.message,metadata:t.getSessionMetadata(),updateMetadata:t.updateSessionMetadata,document:t.documentRef,triggerResubmit:u});if(!m)continue;if(m.handled){let g=m.persistMessage!==!1;return{text:m.displayText!==void 0?m.displayText:"",persist:g,resubmit:m.resubmit}}}catch(u){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:n}};var H1=t=>{if(!t)return null;try{return JSON.parse(t)}catch(e){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}},R1=t=>t.map(e=>({...e,streaming:!1})),W1=t=>t.map(e=>({...e,status:"complete"})),BE=(t="persona-state")=>{let e=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=e();return n?H1(n.getItem(t)):null},save:n=>{let o=e();if(o)try{let r={...n,messages:n.messages?R1(n.messages):void 0,artifacts:n.artifacts?W1(n.artifacts):void 0};o.setItem(t,JSON.stringify(r))}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=e();if(n)try{n.removeItem(t)}catch(o){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};var B1=t=>{let e=2166136261;for(let n=0;n<t.length;n++)e^=t.charCodeAt(n),e=Math.imul(e,16777619)>>>0;return e.toString(16).padStart(8,"0")},DE=async t=>{let e=globalThis.crypto?.subtle;if(e)try{let n=await e.digest("SHA-256",new TextEncoder().encode(t));return Array.from(new Uint8Array(n)).map(o=>o.toString(16).padStart(2,"0")).join("")}catch{}return B1(t)},D1=async(t,e)=>{let n=await DE(t);return{storageKey:`${e}visitor:${n}`,leaseKey:`${e}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await DE(`${t}\0${e}`)}`}};var OE=(t,e,n)=>{let o="",r="",s="",a=!1,l=!1,c=0,p=null,u=null,m=new Set,g=()=>{if(n||a)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return a=!0,null}},h=()=>{let W=g();if(!W)return p;try{return W.getItem(o)}catch{return a=!0,p}},b=(W,U)=>{if(l||W===p)return;let B=p;p=W,c+=1;let O={previousToken:B,token:W,source:U,revision:c};for(let H of m)H(O)},C=W=>{l||W.key!==null&&W.key!==o||b(W.key===null?null:W.newValue??null,"external")},M=(async()=>{let W=await D1(t,e);o=W.storageKey,r=W.leaseKey,s=W.lockName,p=h(),!n&&typeof window<"u"&&window.addEventListener("storage",C)})(),E=W=>new Promise(U=>setTimeout(U,W)),T=()=>{let W=g();if(!W)return null;try{let U=W.getItem(r);if(!U)return null;let B=JSON.parse(U);return typeof B?.expiresAt=="number"&&typeof B?.ownerNonce=="string"?B:null}catch{return null}},R=W=>{let U=g();if(U)try{T()?.ownerNonce===W&&U.removeItem(r)}catch{}},A=W=>new Promise(U=>{let B=setTimeout(O,W);function O(){clearTimeout(B),window.removeEventListener("storage",H),U()}function H(S){(S.key===null||S.key===r)&&O()}window.addEventListener("storage",H)}),D=async W=>{let U=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,B=Date.now()+15e3;for(;Date.now()<B;){let O=g();if(!O)break;let H=Date.now(),S=T();if(S&&S.expiresAt>H&&S.ownerNonce!==U){await A(Math.min(S.expiresAt-H,500));continue}try{O.setItem(r,JSON.stringify({ownerNonce:U,expiresAt:H+1e4}))}catch{a=!0;break}if(await E(20+Math.random()*40),T()?.ownerNonce!==U){await A(500);continue}u=U;try{return await W()}finally{u=null,R(U)}}return W()};return{ready:M,async get(){return await M,b(h(),"external"),p},async set(W){await M;let U=g();if(U)try{U.setItem(o,W)}catch{a=!0}b(W,"local")},async clear(){await M;let W=g();if(W)try{W.removeItem(o)}catch{a=!0}b(null,"local")},revision(){return c},subscribe(W){return m.add(W),()=>{m.delete(W)}},async withFirstInitLock(W){await M;let U=globalThis.navigator?.locks;return U?.request?U.request(s,()=>W()):g()?D(W):W()},matches(W,U,B){return W===t&&U===e&&B===n},destroy(){l=!0,m.clear(),typeof window<"u"&&window.removeEventListener("storage",C),u&&R(u)}}};so();var{setLoader:pj,load:lD}=Qt({fallbackImport:()=>Promise.resolve().then(()=>(e0(),ZE))});var fb=lD;var gb=(t,e)=>{console.warn(`[persona] ${t} threw`,e)},Qr=t=>Object.freeze({...t}),t0=t=>Object.freeze({id:t.id,title:t.title,targetId:t.targetId,preview:t.preview,messageCount:t.messageCount,createdAt:t.createdAt,updatedAt:t.updatedAt}),n0=t=>t?Qr(t):null;function o0(t){let{plugins:e,config:n}=t,o=!1,r=!1,s=!1,a=!1,l=null,c=[],p=()=>{for(let A of c.splice(0))try{A()}catch(D){gb("renderHistoryView cleanup",D)}},u=(A,D)=>{for(let W of e){let U=W[A];if(U)try{let B=U(D);if(B)return B}catch(B){gb(A,B)}}return null},m=()=>({presentation:t.getPresentation(),config:n}),g={header:A=>a?u("renderHistoryHeader",Object.freeze({...m(),returnSurface:t.getReturnSurface(),identityStatus:Qr(A.identityStatus),pendingAction:n0(A.pendingAction),copy:Qr(A.copy),actions:Object.freeze({close:C.close,startNewConversation:C.startNewConversation}),defaultRenderer:A.defaultRenderer})):null,conversation:A=>a?u("renderHistoryConversation",Object.freeze({...m(),conversation:t0(A.conversation),active:A.active,pending:A.pending,open:A.open,requestDelete:A.requestDelete,defaultRenderer:A.defaultRenderer})):null,state:A=>a?u("renderHistoryState",Object.freeze({...m(),state:Qr(A.state),identityStatus:Qr(A.identityStatus),copy:Qr(A.copy),...A.retry?{retry:A.retry}:{},...A.startNewConversation?{startNewConversation:A.startNewConversation}:{},defaultRenderer:A.defaultRenderer})):null},h=e.flatMap(A=>(A.railSections??[]).map(D=>({...D,placement:D.placement??"above-conversations",items:[],render:W=>D.render(Object.freeze({collapsed:W,presentation:t.getPresentation(),actions:C}))}))),b=t.createView({slots:g,renderDom:!1,onModelChange:()=>R(),railSections:h}),C=Object.freeze({...b.operations,close:t.close}),M=()=>(a=!0,b.setDomRenderEnabled(!0),b.element),E=A=>Object.freeze({conversations:Object.freeze(A.conversations.map(t0)),activeConversationId:A.activeConversationId,state:Qr(A.state),pendingAction:n0(A.pendingAction),identityStatus:Qr(A.identityStatus),nextCursor:A.nextCursor,presentation:t.getPresentation(),returnSurface:t.getReturnSurface(),config:n,copy:Qr(b.copy),actions:C,defaultRenderer:M,requestRender:()=>R(),onCleanup:D=>{c.push(D)}}),T=()=>{a=!1;let A=null;for(let W of e)if(W.renderHistoryView){try{A=W.renderHistoryView(E(b.getModel()))}catch(U){gb("renderHistoryView",U),A=null}if(A)break}let D=!A||A.contains(b.element);return a=D,b.setDomRenderEnabled(D),A??b.element};function R(){if(!(!s||o||r)){r=!0;try{p();let A=T();if(A===l)return;let D=l;l=A,t.onElementChanged(A,D)}finally{r=!1}}}return s=!0,R(),{view:b,get element(){return l??b.element},requestRender:R,dispose:()=>{o=!0,p()}}}var cD=null;function r0(){return cD}Zl();var dD=new Map([["not_found","not_found"],["conversation_deleted","not_found"],["rate_limited","rate_limited"],["authentication_required","authentication_required"],["invalid_identity_proof","authentication_required"],["visitor_identity_mismatch","authentication_required"],["visitor_required","authentication_required"],["identity_provider_failed","identity_provider_failed"],["proof_not_admitted","proof_not_admitted"],["identity_contract_violation","proof_not_admitted"],["unauthorized","authentication_failed"],["visitor_token_missing","authentication_failed"],["conversation_credential_missing","authentication_failed"]]),pD=new Map([["not_found","That conversation is no longer available."],["rate_limited","Too many history requests."],["authentication_failed","History access was not authorized."],["authentication_required","Sign in again to view account history."],["identity_provider_failed","The identity provider did not respond."],["proof_not_admitted","Account history is not available for this configuration."],["unsupported_scope","This history scope is not supported."],["unavailable","Conversation history is unavailable right now."]]),hb=t=>pD.get(t)??"Conversation history is unavailable right now.";function uD(t){if(t instanceof gr)return t;if(t instanceof it){let e=dD.get(t.code)??"unavailable";return new gr(e,hb(e),{...t.retryAfterSeconds!==void 0?{retryAfterSeconds:t.retryAfterSeconds}:{}})}return new gr("unavailable",hb("unavailable"))}function s0(t){let e=()=>t.getClient?.()??t.client,n=t.getIdentityProofConfigured()?["browser","verified-user"]:["browser"],o={scopes:n},r=l=>{if(!n.includes(l))throw new gr("unsupported_scope",hb("unsupported_scope"))},s=async(l,c)=>{r(l);try{return await c()}catch(p){throw uD(p)}},a=l=>{let c=!1;return{conversationId:l.session.conversationId??"",conversationRevision:l.session.conversationRevision??"",async commit(){c||(c=!0,l.commit(),await t.onActivationCommitted(l.session))},discard(){c||(c=!0,l.discard())}}};return{capabilities:o,getIdentityStatus(){return e().getHistoryIdentityStatus()},subscribeIdentityStatus(l){return e().subscribeHistoryIdentityStatus(l)},subscribeAvailability(l){return e().subscribeHistoryAvailability(l)},async list(l){return s(l.context.scope,async()=>{let c=await e().listConversations({...l.cursor?{cursor:l.cursor}:{},...l.limit!==void 0?{limit:l.limit}:{},...l.targetId?{targetId:l.targetId}:{},scope:l.context.scope});return{items:c.data,nextCursor:c.nextCursor}})},async getPage(l,c){return s(c.context.scope,async()=>{let p=await e().getConversation(l,{...c.cursor?{messageCursor:c.cursor}:{},scope:c.context.scope}),u=$x(p.messages,{...c.beforeCreatedAt?{beforeCreatedAt:c.beforeCreatedAt}:{}});return{summary:p.summary,messages:Ql([],u),conversationRevision:p.conversationRevision??"",nextCursor:p.nextMessageCursor}})},async prepareOpen(l,c){return s(c.context.scope,async()=>a(await e().prepareConversationSession(l)))},async prepareStartNew(l){return s(l.context.scope,async()=>a(await e().prepareNewConversationSession()))},async delete(l,c){await s(c.context.scope,()=>e().deleteConversation(l,{scope:c.context.scope}))},async deleteAll(l){return s(l.context.scope,()=>e().deleteAllConversations({...l.targetId!==void 0?{targetId:l.targetId}:{},scope:l.context.scope}))},async resetDevice(){try{return await e().resetVisitor(),{remoteRevocationConfirmed:!0}}catch{return{remoteRevocationConfirmed:!1}}}}}sb();je();var mD="button:not([disabled])";function Mm(t){let e=document.activeElement instanceof HTMLElement?document.activeElement:null,n=Math.random().toString(36).slice(2,8),o=`persona-history-confirm-title-${n}`,r=`persona-history-confirm-desc-${n}`,s=F("button",{className:"persona-history-confirm__cancel",text:t.cancelLabel,attrs:{type:"button"}}),a=F("button",{className:"persona-history-confirm__confirm",text:t.confirmLabel,attrs:{type:"button","data-persona-destructive":"true"}}),l=F("div",{className:"persona-history-confirm__dialog",attrs:{role:"alertdialog","aria-modal":"true","aria-labelledby":o,"aria-describedby":r},style:{maxWidth:"22rem",width:"100%",borderRadius:"var(--persona-radius-lg, 0.75rem)",background:"var(--persona-surface, #ffffff)",color:"var(--persona-text, #111827)",boxShadow:"var(--persona-history-confirm-shadow, 0 20px 40px -12px rgba(0, 0, 0, 0.35))",padding:"20px",display:"flex",flexDirection:"column",gap:"12px"}},F("h2",{className:"persona-history-confirm__title",text:t.title,attrs:{id:o},style:{margin:"0",fontSize:"1rem",fontWeight:"600"}}),F("p",{className:"persona-history-confirm__description",text:t.description,attrs:{id:r},style:{margin:"0",fontSize:"0.875rem",lineHeight:"1.4"}}),F("div",{className:"persona-history-confirm__actions",style:{display:"flex",gap:"8px",justifyContent:"flex-end",flexWrap:"wrap"}},s,a));for(let p of[s,a])p.style.minHeight="44px",p.style.minWidth="88px",p.style.padding="0 16px",p.style.borderRadius="var(--persona-radius-md, 0.5rem)",p.style.cursor="pointer",p.style.font="inherit";s.style.border="1px solid var(--persona-border, rgba(0,0,0,0.12))",s.style.background="transparent",s.style.color="inherit",a.style.border="none",a.style.background="var(--persona-danger, #b42318)",a.style.color="var(--persona-danger-fg, #ffffff)";let c=F("div",{className:"persona-history-confirm",style:{position:"absolute",inset:"0",zIndex:"40",display:"flex",alignItems:"center",justifyContent:"center",padding:"16px",background:"var(--persona-history-confirm-scrim, rgba(15, 23, 42, 0.45))"}},l);return new Promise(p=>{let u=!1,m=h=>{u||(u=!0,c.removeEventListener("keydown",g,!0),c.remove(),e?.focus(),p(h))};function g(h){if(h.key==="Escape"){h.preventDefault(),h.stopPropagation(),m(!1);return}if(h.key!=="Tab")return;let b=Array.from(l.querySelectorAll(mD));if(b.length===0)return;let C=b[0],M=b[b.length-1],E=document.activeElement;h.shiftKey&&(E===C||!l.contains(E))?(h.preventDefault(),M.focus()):!h.shiftKey&&E===M&&(h.preventDefault(),C.focus())}c.addEventListener("keydown",g,!0),c.addEventListener("pointerdown",h=>{h.target===c&&m(!1)}),s.addEventListener("click",()=>m(!1)),a.addEventListener("click",()=>m(!0)),t.host.appendChild(c),s.focus()})}Oc();Oc();var yb=require("partial-json");je();function i0(t,e){let{config:n,message:o,onPropsUpdate:r}=e,s=Yo.get(t.component);if(!s){if(jy.includes(t.component)){ym().catch(()=>{});let l=v("div","persona-w-full");return l.setAttribute("data-persona-artifact-pending","true"),l}return console.warn(`[ComponentMiddleware] Component "${t.component}" not found in registry. Falling back to default rendering.`),null}let a={message:o,config:n,updateProps:l=>{r&&r(l)}};try{return s(t.props,a)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${t.component}":`,l),null}}function a0(t){if(typeof t.rawContent=="string"&&t.rawContent.length>0)return t.rawContent;if(typeof t.content=="string"){let e=t.content.trim();if(e.startsWith("{")||e.startsWith("["))return t.content}return null}function bb(t){let e=a0(t);if(!e)return!1;try{let n=JSON.parse(e);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function l0(t){let e=a0(t);if(!e)return null;try{let n=JSON.parse(e);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let o=n;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:e}}}catch{}return null}var fD=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function c0(t){let{onSubmit:e,onDismiss:n,title:o="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:l="Skip",showComment:c=!0,ratingLabels:p=fD}=t,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-csat",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Customer satisfaction feedback");let m=null,g=document.createElement("div");g.className="persona-feedback-content";let h=document.createElement("div");h.className="persona-feedback-header";let b=document.createElement("h3");b.className="persona-feedback-title",b.textContent=o,h.appendChild(b);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=r,h.appendChild(C),g.appendChild(h);let M=document.createElement("div");M.className="persona-feedback-rating persona-feedback-rating-csat",M.setAttribute("role","radiogroup"),M.setAttribute("aria-label","Satisfaction rating from 1 to 5");let E=[];for(let W=1;W<=5;W++){let U=document.createElement("button");U.type="button",U.className="persona-feedback-rating-btn persona-feedback-star-btn",U.setAttribute("role","radio"),U.setAttribute("aria-checked","false"),U.setAttribute("aria-label",`${W} star${W>1?"s":""}: ${p[W-1]}`),U.title=p[W-1],U.dataset.rating=String(W),U.innerHTML=`
|
|
1171
1171
|
<svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
1172
1172
|
<polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
|
|
1173
1173
|
</svg>
|
|
1174
|
-
`,U.addEventListener("click",()=>{m=W,E.forEach((B,O)=>{let R=O<W;B.classList.toggle("selected",R),B.setAttribute("aria-checked",O===W-1?"true":"false")})}),E.push(U),M.appendChild(U)}g.appendChild(M);let T=null;if(c){let W=document.createElement("div");W.className="persona-feedback-comment-container",T=document.createElement("textarea"),T.className="persona-feedback-comment",T.placeholder=s,T.rows=3,T.setAttribute("aria-label","Additional comments"),W.appendChild(T),g.appendChild(W)}let H=document.createElement("div");H.className="persona-feedback-actions";let A=document.createElement("button");A.type="button",A.className="persona-feedback-btn persona-feedback-btn-skip",A.textContent=l,A.addEventListener("click",()=>{n?.(),u.remove()});let D=document.createElement("button");return D.type="button",D.className="persona-feedback-btn persona-feedback-btn-submit",D.textContent=a,D.addEventListener("click",async()=>{if(m===null){M.classList.add("persona-feedback-shake"),setTimeout(()=>M.classList.remove("persona-feedback-shake"),500);return}D.disabled=!0,D.textContent="Submitting...";try{let W=T?.value.trim()||void 0;await e(m,W),u.remove()}catch(W){D.disabled=!1,D.textContent=a,console.error("[CSAT Feedback] Failed to submit:",W)}}),H.appendChild(A),H.appendChild(D),g.appendChild(H),u.appendChild(g),u}function e0(t){let{onSubmit:e,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:l="Skip",showComment:c=!0,lowLabel:p="Not likely",highLabel:u="Very likely"}=t,m=document.createElement("div");m.className="persona-feedback-container persona-feedback-nps",m.setAttribute("role","dialog"),m.setAttribute("aria-label","Net Promoter Score feedback");let g=null,h=document.createElement("div");h.className="persona-feedback-content";let b=document.createElement("div");b.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=o,b.appendChild(C);let M=document.createElement("p");M.className="persona-feedback-subtitle",M.textContent=r,b.appendChild(M),h.appendChild(b);let E=document.createElement("div");E.className="persona-feedback-rating persona-feedback-rating-nps",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Likelihood rating from 0 to 10");let T=document.createElement("div");T.className="persona-feedback-labels";let H=document.createElement("span");H.className="persona-feedback-label-low",H.textContent=p;let A=document.createElement("span");A.className="persona-feedback-label-high",A.textContent=u,T.appendChild(H),T.appendChild(A);let D=document.createElement("div");D.className="persona-feedback-numbers";let W=[];for(let S=0;S<=10;S++){let x=document.createElement("button");x.type="button",x.className="persona-feedback-rating-btn persona-feedback-number-btn",x.setAttribute("role","radio"),x.setAttribute("aria-checked","false"),x.setAttribute("aria-label",`Rating ${S} out of 10`),x.textContent=String(S),x.dataset.rating=String(S),S<=6?x.classList.add("persona-feedback-detractor"):S<=8?x.classList.add("persona-feedback-passive"):x.classList.add("persona-feedback-promoter"),x.addEventListener("click",()=>{g=S,W.forEach((P,L)=>{P.classList.toggle("selected",L===S),P.setAttribute("aria-checked",L===S?"true":"false")})}),W.push(x),D.appendChild(x)}E.appendChild(T),E.appendChild(D),h.appendChild(E);let U=null;if(c){let S=document.createElement("div");S.className="persona-feedback-comment-container",U=document.createElement("textarea"),U.className="persona-feedback-comment",U.placeholder=s,U.rows=3,U.setAttribute("aria-label","Additional comments"),S.appendChild(U),h.appendChild(S)}let B=document.createElement("div");B.className="persona-feedback-actions";let O=document.createElement("button");O.type="button",O.className="persona-feedback-btn persona-feedback-btn-skip",O.textContent=l,O.addEventListener("click",()=>{n?.(),m.remove()});let R=document.createElement("button");return R.type="button",R.className="persona-feedback-btn persona-feedback-btn-submit",R.textContent=a,R.addEventListener("click",async()=>{if(g===null){D.classList.add("persona-feedback-shake"),setTimeout(()=>D.classList.remove("persona-feedback-shake"),500);return}R.disabled=!0,R.textContent="Submitting...";try{let S=U?.value.trim()||void 0;await e(g,S),m.remove()}catch(S){R.disabled=!1,R.textContent=a,console.error("[NPS Feedback] Failed to submit:",S)}}),B.appendChild(O),B.appendChild(R),h.appendChild(B),m.appendChild(h),m}var Ja="persona-chat-history",tD=30*1e3,nD=641,Za="data-persona-composer-reason",oD={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","image/bmp":"bmp","image/tiff":"tiff"};function rD(t){if(!t)return[];let e=[],n=Array.from(t.items??[]);for(let o of n){if(o.kind!=="file"||!o.type.startsWith("image/"))continue;let r=o.getAsFile();if(!r)continue;if(r.name){e.push(r);continue}let s=oD[r.type]??"png";e.push(new File([r],`clipboard-image-${Date.now()}.${s}`,{type:r.type,lastModified:Date.now()}))}if(e.length>0)return e;for(let o of Array.from(t.files??[]))o.type.startsWith("image/")&&e.push(o);return e}function Tm(t){if(!t)return!1;let e=t.types;return e?typeof e.contains=="function"?e.contains("Files"):Array.from(e).includes("Files"):!1}function sD(t){return t?t===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:t.storage??"session",keyPrefix:t.keyPrefix??"persona-",persist:{openState:t.persist?.openState??!0,voiceState:t.persist?.voiceState??!0,focusInput:t.persist?.focusInput??!0},clearOnChatClear:t.clearOnChatClear??!0}:null}function iD(t){try{let e=t==="local"?localStorage:sessionStorage,n="__persist_test__";return e.setItem(n,"1"),e.removeItem(n),e}catch{return null}}var yb=t=>!t||typeof t!="object"?{}:{...t},t0=t=>t.map(e=>({...e,streaming:!1})),n0=(t,e,n)=>{let o=t?.markdown?Pp(t.markdown):null,r=Ip(t?.sanitize);t?.postprocessMessage&&r&&t?.sanitize===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function.");let s=!1,a=l=>{let c=l.text??"",p=l.message.rawContent??null;if(e){let g=e.process({text:c,raw:p??c,message:l.message,streaming:l.streaming});g!==null&&(c=g.text,g.persist||(l.message.__skipPersist=!0),g.resubmit&&!l.streaming&&n&&n())}let u=Ro()!==null,m;if(t?.postprocessMessage){let g=t.postprocessMessage({...l,text:c,raw:p??l.text??""});m=r?r(g):g}else if(o){let g=l.streaming?Ow(c):c,h=o(g);m=r&&u?r(h):h}else m=$r(c);return m};return l=>{try{return a(l)}catch(c){return s||(s=!0,console.error("[Persona] markdown rendering failed; falling back to plain text:",c)),$r(l.text??"")}}};function o0(t){let e=v("div","persona-attachment-drop-overlay");t?.background&&e.style.setProperty("--persona-drop-overlay-bg",t.background),t?.backdropBlur!==void 0&&e.style.setProperty("--persona-drop-overlay-blur",t.backdropBlur),t?.border&&e.style.setProperty("--persona-drop-overlay-border",t.border),t?.borderRadius&&e.style.setProperty("--persona-drop-overlay-radius",t.borderRadius),t?.inset&&e.style.setProperty("--persona-drop-overlay-inset",t.inset),t?.labelSize&&e.style.setProperty("--persona-drop-overlay-label-size",t.labelSize),t?.labelColor&&e.style.setProperty("--persona-drop-overlay-label-color",t.labelColor);let n=t?.iconName??"upload",o=t?.iconSize??"48px",r=t?.iconColor??"rgba(59, 130, 246, 0.6)",s=t?.iconStrokeWidth??.5,a=ke(n,o,r,s);if(a&&e.appendChild(a),t?.label){let l=v("span","persona-drop-overlay-label");l.textContent=t.label,e.appendChild(l)}return e}var aD=(t,e)=>{let n={...t};for(let[o,r]of Object.entries(e)){let s=n[o];n[o]=s?{...s,...r}:r}return n},lD=t=>t.reduce((e,n)=>({blocks:[...e.blocks,...n.blocks],contentParts:[...e.contentParts,...n.contentParts],context:aD(e.context,n.context)}),{blocks:[],contentParts:[],context:{}}),r0=(t,e,n)=>{if(t==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');t.id&&!t.getAttribute("data-persona-instance")&&t.setAttribute("data-persona-instance",t.id),t.hasAttribute("data-persona-root")||t.setAttribute("data-persona-root","true");let o=gp(e),r=new Set,s=new Set,a=Aw((i,d)=>{mn.delete(i);let f=Array.from(We.querySelectorAll("[data-message-id]")).find(y=>y.dataset.messageId===i);f&&(d==="tool"?Cy(i,f,r,o):hy(i,f,s))}),l=new Map,c=()=>{hS({delayMs:o.tooltip?.delayMs??200,skipDelayMs:o.tooltip?.skipDelayMs??300})};c();let p=o.features;o=Yy(o);let u=Jy.getForInstance(o.plugins),m=KA(t),g=[],h=!1,b=nT(()=>o),C=null,M=null,E=null,T=!1,H=null,A=i=>{C=i,i.initApprovalUi({webMcpToolTitle:Rp});let d=i.createBuiltInApprovalPlugin(l);M=d.plugin,E=d.teardown},D=()=>{if(C)return C;let i=yT();return i?(A(i),i):(hT().then(d=>{T||C||(A(d),H?.())}).catch(()=>{}),null)},W=!1,U=!1,B=null,O=(i,d,f,y)=>{if(!i.querySelector("[data-tv-form]"))return;let w=vE();if(w){w.enhanceWithForms(i,d,f,y);return}bE().then(()=>{W||U||!B||(U=!0,B())}).catch(()=>{})};o.components&&Yo.registerAll(o.components);let R=SE(),x=o.persistState===!1?null:o.storageAdapter??ME(),P=!!o.clientToken&&typeof o.reconnectStream!="function",L={},G=null,V,K=new Promise(i=>{V=i}),ee,oe=!1,ne=i=>{if(o.onStateLoaded)try{let d=o.onStateLoaded(i);if(d&&typeof d=="object"&&"state"in d){let{state:f,open:y}=d;return y&&(oe=!0),f}return d}catch(d){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",d)}return i};if(x?.load)try{let i=x.load();if(i&&typeof i.then=="function")G=i.then(d=>ne(d??{messages:[],metadata:{}}));else{let f=ne(i??{messages:[],metadata:{}});f.metadata&&(L=yb(f.metadata)),f.messages?.length&&(o={...o,initialMessages:f.messages}),f.artifacts?.length&&(o={...o,initialArtifacts:f.artifacts,initialSelectedArtifactId:f.selectedArtifactId??null}),ee=f.draft}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",i)}else if(o.onStateLoaded)try{let i=ne({messages:[],metadata:{}});i.messages?.length&&(o={...o,initialMessages:i.messages})}catch(i){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",i)}G||V();let le=()=>L,de=i=>{L=i({...L})??{},Zi()},ve=o.actionParsers&&o.actionParsers.length?o.actionParsers:[eb],Le=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[jc.message,jc.messageAndClick],se=tb({parsers:ve,handlers:Le,getSessionMetadata:le,updateSessionMetadata:de,emit:R.emit,documentRef:typeof document<"u"?document:null});se.syncFromMetadata();let _=o.launcher?.enabled??!0,Te=o.launcher?.autoExpand??!1,He=o.autoFocusInput??!1,ut=Te,At=_,Wt=o.layout?.header?.layout,bt=!1,xe=()=>Ec(o),Ne=()=>_||xe(),Ae=xe()?!1:_?Te:!0,vt=!1,X=null,I=()=>{vt=!0,X&&clearTimeout(X),X=setTimeout(()=>{vt&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),vt=!1)},1e4)},j=n0(o,se,I),J=o.features?.showReasoning??!0,Y=o.features?.showToolCalls??!0,ie=o.features?.showEventStreamToggle??!1,Me=o.features?.scrollToBottom??{},Ee=o.features?.scrollBehavior??{},Oe=()=>(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-",Ot=`${Oe()}event-stream`,rt=null,Ze=o.features?.eventStream?.maxEvents??2e3,ct=null,Rt=null,Z=null,Fe=!1,Re=null,nt=!1,Bt=null,Ie=0,Be=(i,d)=>{ct?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i,timestamp:Date.now(),payload:JSON.stringify(d)})},qe=(i,d)=>{Rt?.processEvent(i,d),ct?Be(i,d):Z&&(Z.length>=Ze&&Z.shift(),Z.push({type:i,payload:d}))},Tt=()=>{ct||!ie||(Z??(Z=[]),Iy().then(i=>{if(Fe||ct||!ie)return;rt=new i.EventStreamStore(Ot),ct=new i.EventStreamBuffer(Ze,rt),Rt=Rt??new i.ThroughputTracker,rt.open().then(()=>ct?.restore()).catch(f=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",f)});let d=Z??[];Z=null;for(let f of d)Rt?.processEvent(f.type,f.payload),Be(f.type,f.payload)}).catch(()=>{}))};ie&&Tt();let mt=!1,xt=null,Mn=()=>{},ft=()=>{},_t=()=>{},Vt=()=>{},pn=()=>{},ao=()=>nt||mt&&xt==="panel",Gn={onCopy:i=>{R.emit("message:copy",i),N?.isClientTokenMode()&&N.submitMessageFeedback(i.id,"copy").catch(d=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",d)}),o.messageActions?.onCopy?.(i)},onFeedback:i=>{R.emit("message:feedback",i),N?.isClientTokenMode()&&N.submitMessageFeedback(i.messageId,i.type).catch(d=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",d)}),o.messageActions?.onFeedback?.(i)}},Zc=o.statusIndicator??{},_s=(i,d=o.statusIndicator??{})=>i==="idle"?d.idleText??dn.idle:i==="connecting"?d.connectingText??dn.connecting:i==="connected"?d.connectedText??dn.connected:i==="error"?d.errorText??dn.error:i==="paused"?d.pausedText??dn.paused:i==="resuming"?d.resumingText??dn.resuming:dn[i];function Qo(i,d,f,y){if(!xe()&&(f.mode==="transient"||i.classList.contains("persona-mb-2"))&&(Eg(i,Tn,f),xi(i,f,y)),!i.hasAttribute(Za))if(y==="idle"&&f.idleLink){i.textContent="";let w=document.createElement("a");w.href=f.idleLink,w.target="_blank",w.rel="noopener noreferrer",w.textContent=d,w.style.color="inherit",w.style.textDecoration="none",i.appendChild(w)}else i.textContent=d}let Cn=tT({config:o,showClose:Ne()}),{wrapper:dt,panel:Se,pillRoot:Nt}=Cn.shell,ot=Cn.panelElements,{container:Pe,body:pe,messagesWrapper:We,starterSuggestions:Ns,transcriptSuggestions:Xo,suggestions:lo,textarea:we,sendButton:Ve,composerForm:Tn,statusText:pt,welcomeHost:gn,welcomeIconHolder:km,greetingHost:z,introKicker:ge,introTitle:Ue,introSubtitle:at,closeButton:Ce,iconHolder:St,headerTitle:Bn,headerSubtitle:Yn,header:$e,footer:Qe,actionsRow:y0}=ot,Pm=ot.leftActions,ed=ot.rightActions,Jo=ot.sendButtonWrapper,Ab=ot.setSendButtonMode,ye=ot.micButton,co=ot.micButtonWrapper,on=ot.attachmentButton,Qn=ot.attachmentButtonWrapper,Xt=ot.attachmentInput,Xn=ot.attachmentPreviewsContainer;Pe.classList.add("persona-relative"),pe.classList.add("persona-relative");let b0=12,tl=()=>Me.label??"",v0=()=>Me.iconName??"arrow-down",C0=()=>Me.enabled!==!1,po=()=>Ee.mode??"anchor-top",Jr=()=>po()==="follow"||po()==="anchor-top"&&ul,nl=()=>Ee.anchorTopOffset??16,w0=()=>Ee.restorePosition??"bottom",Mb=()=>Ee.pauseOnInteraction===!0,Tb=()=>Ee.showActivityWhilePinned!==!1,Eb=()=>Ee.announce===!0,Lm=()=>Ee.scrollbar??"on-scroll",hn=v("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");hn.type="button",hn.style.display="none",hn.setAttribute("data-persona-scroll-to-bottom","true");let ol=v("span","persona-flex persona-items-center"),Im=v("span",""),Fs=v("span","");Fs.setAttribute("data-persona-scroll-to-bottom-count",""),Fs.style.display="none",hn.append(ol,Im,Fs),Pe.appendChild(hn);let Co=v("div","persona-stream-anchor-spacer");Co.setAttribute("aria-hidden","true"),Co.setAttribute("data-persona-anchor-spacer",""),Co.style.flexShrink="0",Co.style.pointerEvents="none",Co.style.height="0px",Co.style.display="none",pe.appendChild(Co);let xr=v("div","persona-sr-only");xr.setAttribute("aria-live","polite"),xr.setAttribute("aria-atomic","true"),xr.setAttribute("role","status"),xr.setAttribute("data-persona-live-region",""),Object.assign(xr.style,{position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}),Pe.appendChild(xr);let rl=null,td=null,nd=i=>{!Eb()||!i||(td=i,rl===null&&(rl=setTimeout(()=>{rl=null,td&&Eb()&&(xr.textContent=td),td=null},400)))},sl=()=>{let i=t.ownerDocument.defaultView??window;return(o.launcher?.mobileFullscreen??!0)&&i.innerWidth<=(o.launcher?.mobileBreakpoint??640)&&(_||nn(o))||o.launcher?.fullHeight===!0&&!o.launcher.sidebarMode&&!nn(o)},Vs=()=>om(o,sl()),od="empty",rd=0,Rm=()=>rd||parseFloat(t.style.getPropertyValue("--persona-composer-lift"))||0,$s=()=>{let d=Qe.style.display==="none"?0:Qe.offsetHeight;hn.style.bottom=`${d+Rm()+b0}px`};$s();let Hm=()=>{ji||(Qe.style.marginBottom=rd>0?`${rd}px`:"")},sd=()=>{let i=Fh(o,xe()),d=Vs();t.setAttribute("data-persona-welcome-fullscreen",String(sl())),t.setAttribute("data-persona-welcome-layout",d.layout??"top"),t.setAttribute("data-persona-welcome-layout-explicit",o.welcome?.layout??""),t.setAttribute("data-persona-welcome-anchor",d.anchor??"bottom");let y=Qe.style.display==="none"?0:Qe.offsetHeight,w=d.anchor==="center"&&od==="empty"?hc(d.anchorComposerTop)??hc("44%"):null,k=w!==null&&d.layout==="centered"&&o.welcome?.anchor===void 0&&o.welcome?.anchorComposerTop===void 0,q=k?getComputedStyle(pe):null,te=parseFloat(t.style.getPropertyValue("--persona-composer-overlay-height"))||0,Q=parseFloat(t.style.getPropertyValue("--persona-composer-lift"))||0,re=Math.max(0,(parseFloat(q?.paddingBottom??"")||0)-(i==="overlay"?te+Q:0)),ce=k?pe.getBoundingClientRect().top-Pe.getBoundingClientRect().top:0,he=!k||gn.hidden?0:(gn.querySelector("[data-persona-welcome-plugin]")??gn).offsetHeight,De=w===null||xe()?0:k?Math.max(0,Math.round((Pe.clientHeight-ce-he-re-y)/2)):UA({columnHeight:Pe.clientHeight,footerHeight:y,fraction:w});t.style.setProperty("--persona-composer-overlay-height",`${y}px`),t.style.setProperty("--persona-composer-lift",`${i==="overlay"?De:0}px`),rd=i==="block"?De:0,Hm(),$s()},kb=()=>{let i=!!tl();hn.setAttribute("aria-label",tl()||"Jump to latest"),hn.title=tl(),hn.setAttribute("data-persona-scroll-to-bottom-has-label",i?"true":"false"),ol.innerHTML="";let d=ke(v0(),"14px","currentColor",2);d?(ol.appendChild(d),ol.style.display=""):ol.style.display="none",Im.textContent=tl(),Im.style.display=i?"":"none"};kb();let Lt=null,un=null,ze=dS(),x0=i=>{try{Pe.dispatchEvent(new CustomEvent("persona:composer:state",{detail:i,bubbles:!0,composed:!0}))}catch{}};ze.subscribe(x0);let Zo=()=>{ze.setText(we?.value??"")},zs=()=>{ze.setMentionRefs(un?.getMentionRefs()??[])},S0=i=>({id:i.id,name:i.file.name,mimeType:i.file.type,size:i.file.size,status:i.status,progress:i.progress,error:i.error}),Pb=i=>{let d=Object.freeze(i.map(S0));ze.setAttachments(d);try{o.attachments?.onChange?.(d)}catch(f){console.error("[AgentWidget] attachments.onChange failed:",f)}cf()};ze.setSelectedModelId(o.composer?.selectedModelId);let il=()=>o.composer?.modes??[],$i=()=>_S(il(),o.composer?.modeGroups);{let i=hu(o.composer?.defaultActiveModeIds??[],il());i.length&&ze.setActiveModeIds(i)}function Lb(i){if(ze.getState().selectedModelId!==i){ze.setSelectedModelId(i),Zr?.repaint();try{o.composer?.onModelChange?.(i)}catch(d){console.error("[AgentWidget] composer.onModelChange failed:",d)}}}function id(i){ze.setActiveModeIds(i),Sr?.render(i,$i()),zi.forEach(d=>d.repaint()),tr?.resolve(),Id(),_o()}function Wm(i){id(NS(ze.getState().activeModeIds,i,il(),o.composer?.modeGroups))}let Zr=null,Bm=null,Sr=null,zi=new Map,es=null;function er(i){ze.setQuote(i),es?.render(ze.getState().quote),_o(),wv()}let Ib=!1;function Dm(){let i=o.composer?.streamingSubmitBehavior??"block";return i!=="interrupt"?i:o.clientToken?"interrupt":(!Ib&&o.debug===!0&&(Ib=!0,typeof console<"u"&&console.warn('[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".')),"block")}let ts=null;function Ui(i){ze.setPendingSubmission(i),ts?.render(ze.getState().pendingSubmission),_o()}let A0=i=>{let d=zi.get(i);if(d)return d;let f=$S({groupId:i,getGroup:()=>o.composer?.modeGroups?.find(y=>y.id===i),getModes:()=>il().filter(y=>y.groupId===i),getActiveIds:()=>ze.getState().activeModeIds,onSelect:y=>Wm(y)});return zi.set(i,f),f},M0=()=>{let i=[],d=ze.getState().activeModeIds,f=new Set;if(il().forEach((y,w)=>{if(gu(y.groupId,o.composer?.modeGroups)){let k=y.groupId;if(f.has(k))return;f.add(k);let q=A0(k);q.action.order=Ch(w),q.action.label=o.composer?.modeGroups?.find(te=>te.id===k)?.label??k,i.push(q.action);return}i.push({id:DS(y.id),kind:"button",placement:"start",order:Ch(w),presentation:y.presentation??"auto",label:y.label,shortLabel:y.shortLabel,iconName:y.iconName,pressed:d.includes(y.id),onSelect:()=>Wm(y.id)})}),o.composer?.models?.length&&!u.some(y=>y.renderComposer)){let y=o.composer?.modelPicker?.presentation??"native";(!Zr||Bm!==y)&&(Bm=y,Zr=WS({getModels:()=>o.composer?.models??[],getSelectedModelId:()=>ze.getState().selectedModelId,onSelect:w=>Lb(w),presentation:y,getSuffix:()=>o.composer?.modelPicker?.suffix})),i.push(Zr.action)}return i},Om=null,Rb=u.find(i=>i.renderHeader);if(Rb?.renderHeader){let i=Rb.renderHeader({config:o,defaultRenderer:()=>{let d=Pi({config:o,showClose:Ne()});return Pc(Pe,d,o),d.header},onClose:()=>qt(!1,"user")});if(i){let d=$e;d&&(d.replaceWith(i),$e=i,Cn.header.element=i)}}let Hb=()=>{Re&&(pe.style.display="none",Qe.parentNode?.insertBefore(Re.element,Qe),Re.update())},_m=()=>{if(!ct){Tt();return}if(nt=!0,Re?Hb():Iy().then(d=>{Re||!nt||!ct||(Re=d.createEventStreamView({buffer:ct,getFullHistory:()=>ct.getAllFromStore(),onClose:()=>qi(),config:o,plugins:u,getThroughput:()=>Rt?.getMetric()??{status:"idle"},renderIconByName:ke}),Hb())}).catch(()=>{qi()}),Ht){Ht.style.boxShadow=`inset 0 0 0 1.5px ${qn.actionIconColor}`;let d=o.features?.eventStream?.classNames?.toggleButtonActive;d&&d.split(/\s+/).forEach(f=>f&&Ht.classList.add(f))}let i=()=>{if(!nt)return;let d=Date.now();d-Ie>=200&&(Re?.update(),Ie=d),Bt=requestAnimationFrame(i)};Ie=0,Bt=requestAnimationFrame(i),xn(),R.emit("eventStream:opened",{timestamp:Date.now()})},qi=()=>{if(nt){if(nt=!1,Re&&Re.element.remove(),pe.style.display="",Ht){Ht.style.boxShadow="";let i=o.features?.eventStream?.classNames?.toggleButtonActive;i&&i.split(/\s+/).forEach(d=>d&&Ht.classList.remove(d))}Bt!==null&&(cancelAnimationFrame(Bt),Bt=null),xn(),R.emit("eventStream:closed",{timestamp:Date.now()})}},Ht=null;if(ie){let i=o.features?.eventStream?.classNames,d="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(i?.toggleButton?" "+i.toggleButton:"");Ht=v("button",d),Ht.style.width="28px",Ht.style.height="28px",Ht.style.color=qn.actionIconColor,Ht.type="button",Ht.setAttribute("aria-label","Event Stream"),Ht.title="Event Stream";let f=Ge(Xr.Activity,"18px","currentColor",1.5);f&&Ht.appendChild(f);let y=ot.clearChatButtonWrapper,w=ot.closeButtonWrapper,k=y||w;k&&k.parentNode===$e?$e.insertBefore(Ht,k):$e.appendChild(Ht),Ht.addEventListener("click",()=>{nt?qi():_m()})}let Wb=i=>{let d=o.attachments;if(!d?.enabled)return;let f=i.querySelector("[data-persona-composer-attachment-previews]")??i.querySelector(".persona-attachment-previews");if(!f){f=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),f.setAttribute("data-persona-composer-attachment-previews",""),f.style.display="none";let w=i.querySelector("[data-persona-composer-form]");w?.parentNode?w.parentNode.insertBefore(f,w):i.insertBefore(f,i.firstChild)}if(!(i.querySelector("[data-persona-composer-attachment-input]")??i.querySelector('input[type="file"]'))){let w=v("input");w.type="file",w.setAttribute("data-persona-composer-attachment-input",""),w.accept=(d.allowedTypes??Ur).join(","),w.multiple=(d.maxFiles??4)>1,w.style.display="none",w.setAttribute("aria-label",d.buttonTooltipText??"Attach files"),i.appendChild(w)}},ji=!1,Bb=i=>{let d=u.find(w=>w.renderComposer);if(!d?.renderComposer)return null;let f=o.composer,y=h?N.isStreaming():!1;return d.renderComposer({config:o,defaultRenderer:i,requestRender:()=>ZC(),storage:b(d.id),onSubmit:w=>{!N||N.isStreaming()||rp(w.trim(),{consumeDraft:!1})},streaming:y,disabled:y,openAttachmentPicker:()=>{sr()||Xt?.click()},models:f?.models,selectedModelId:ze.getState().selectedModelId??f?.selectedModelId,onModelChange:w=>Lb(w),onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{Om?.()}:void 0})},Db=Bb(()=>Ic({config:o}).footer);Db&&(Cn.replaceComposer(Db),Qe=Cn.composer.footer,ji=!0);let Et=null,T0=i=>{Tn=i.form,we=i.input,Jo=i.sendButton?i.sendButton.parentElement:null,i.sendButton&&(Ve=i.sendButton),i.micButton&&(ye=i.micButton,co=i.micButton.parentElement),i.found.status&&(pt=i.found.status),i.found.suggestions&&(lo=i.found.suggestions),i.attachmentButton&&(on=i.attachmentButton,Qn=i.attachmentButton.parentElement),Xt=i.attachmentInput??null,Xn=i.attachmentPreviews??null,i.found.actionsRow&&(y0=i.found.actionsRow),Pm=i.found.actionsStart,ed=i.found.actionsEnd};function Nm(){let i=we;if(!i)return;let d=o.composer?.inputAttributes,f=!d?.ariaLabel&&!(i instanceof HTMLTextAreaElement)?i.getAttribute("aria-label"):null;ru(i,d),f&&i.setAttribute("aria-label",f),ou(i,{submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:rc(i)}),vS(i,nu(o.composer?.maxLines,xe()?5:3))}let Ob=i=>{Et=uS(i,{debug:o.debug===!0}),Et&&T0(Et),Nm()};Wb(Qe),Ob(Qe),Zo();let al=Is(o,xe());al&&(We.style.maxWidth=al,We.style.marginLeft="auto",We.style.marginRight="auto",We.style.width="100%",z.style.maxWidth=al,z.style.marginLeft="auto",z.style.marginRight="auto",z.style.width="100%",Ns.style.maxWidth=al,Xo.style.maxWidth=al,Xo.style.marginLeft="auto",Xo.style.marginRight="auto",Xo.style.width="100%");let _b=()=>{let i=Is(o,xe());if(!(!i||xe()))for(let d of[Tn,lo,Xn,pt])d&&(d.style.maxWidth=i,d.style.marginLeft="auto",d.style.marginRight="auto",d.style.width="100%")};_b();let Nb=()=>{!o.attachments?.enabled||!Xt||!Xn||(Lt?Lt.remountPreviews(Xn):(Lt=oc.fromConfig(o.attachments,Pb),Lt.setPreviewsContainer(Xn)),Et?.addListener(Xt,"change",i=>{let d=i.target;Lt?.handleFileSelect(d.files),d.value=""}),Pe.querySelector(".persona-attachment-drop-overlay")||Pe.appendChild(o0(o.attachments.dropOverlay)))};Nb();let E0=()=>un?.prefetch(),Fb=()=>{if(!o.contextMentions?.enabled||!we)return;let i=Et?.header??null,d=i?vh(i):void 0;if(un=OA({config:o,textarea:we,anchor:Tn??we,getMessages:()=>N.getMessages(),liveRegionHost:Pe,chipRow:d}),un&&!d){let f=we;f.parentElement?.insertBefore(un.contextRow,f)}};Fb();let tr=null,k0={getState:()=>ze.getState(),getValue:()=>we?.value??"",setValue:i=>{we&&(we.value=i,we.dispatchEvent(new Event("input",{bubbles:!0})),Zo())},submit:()=>{sc(Et?.form??null)},openAttachmentPicker:()=>{sr()||Xt?.click()},toggleVoice:()=>{Om?.()},requestRender:()=>tr?.resolve()},P0=()=>{let i=[];return(un?.affordanceButtons??[]).forEach((f,y)=>{i.push({id:`core:mention-${y}`,placement:"start",order:yr.mention+y,element:f,managed:!0})}),Qn&&i.push({id:"core:attachment",placement:"start",order:yr.attachment,element:Qn}),co&&i.push({id:"core:mic",placement:"end",order:yr.mic,element:co}),Jo&&i.push({id:"core:send",placement:"end",order:yr.send,element:Jo}),i},Vb=()=>{tr?.destroy(),tr=IS({getBindings:()=>Et,collect:()=>({builtIns:P0(),configActions:[...M0(),...o.composer?.actions??[]],plugins:u,contributionContext:{config:o,getState:()=>ze.getState(),requestRender:()=>tr?.resolve()},debug:o.debug===!0}),actionContext:k0,getState:()=>ze.getState(),getOverflow:()=>o.composer?.actionOverflow,reportError:(i,d)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${d.actionId}" failed:`,i)}}),tr.resolve()};Vb();let Fm=()=>{if(Sr?.destroy(),Sr=null,!$i().length)return;let i=Et?.header;i&&(Sr=BS({row:vh(i),onRemove:d=>Wm(d),initialIds:ze.getState().activeModeIds}),Sr.render(ze.getState().activeModeIds,$i()))};Fm();let $b=()=>{es?.destroy(),es=null,ts?.destroy(),ts=null;let i=Et?.header;i&&(es=zS({onDismiss:()=>er(void 0)}),i.appendChild(es.element),es.render(ze.getState().quote),Dm()==="defer-one"&&(ts=US({onEdit:()=>nP(),onRemove:()=>Ui(void 0)}),i.appendChild(ts.element),ts.render(ze.getState().pendingSubmission)))};$b();let Vm=QS(),L0=()=>{let i=Et?.header?.querySelector(bh);if(i)return i.childElementCount>0;let d=ze.getState();return d.mentionRefs.length>0||hu(d.activeModeIds,$i()).length>0};function _o(){let i=ze.getState(),d=Vm.observe(XS(we),i.text);Qe.toggleAttribute("data-persona-composer-compact",YS({text:i.text,wrapped:d,hasAttachments:i.attachments.length>0,hasChips:L0(),hasQuote:i.quote!==void 0,hasPendingSubmission:i.pendingSubmission!==void 0}))}function zb(){o.composer?.layout==="single-row"&&!xe()?Qe.setAttribute("data-persona-composer-layout","single-row"):Qe.removeAttribute("data-persona-composer-layout")}zb(),ze.subscribe(()=>{tr?.sync(),cf(),Pd(),_o(),wv()}),Pd();let Ub=!1,I0=i=>{if(Ub||o.debug!==!0)return;let d=["messages","composer"].filter(f=>i[f]);d.length&&(Ub=!0,console.warn(`[persona] layout.slots.${d.join(" and layout.slots.")} ${d.length>1?"are":"is"} deprecated and unsupported: the renderer never runs. Use the message render hooks for the transcript and the renderComposer plugin hook for the composer.`))};(()=>{let i=o.layout?.slots??{};I0(i);let d=y=>{switch(y){case"body-top":return pe.querySelector("[data-persona-intro-card]");case"messages":return We;case"footer-top":return lo;case"composer":return Tn;case"footer-bottom":return pt;default:return null}},f=(y,w)=>{switch(y){case"header-left":case"header-center":case"header-right":if(y==="header-left")$e.insertBefore(w,$e.firstChild);else if(y==="header-right")$e.appendChild(w);else{let k=$e.querySelector(".persona-flex-col");k?k.parentNode?.insertBefore(w,k.nextSibling):$e.appendChild(w)}break;case"body-top":{let k=pe.querySelector("[data-persona-intro-card]");k?k.replaceWith(w):pe.insertBefore(w,pe.firstChild);break}case"body-bottom":pe.appendChild(w);break;case"footer-top":lo.replaceWith(w);break;case"footer-bottom":pt.replaceWith(w);break;default:break}};for(let[y,w]of Object.entries(i))if(w)try{let k=w({config:o,defaultContent:()=>d(y)});k&&f(y,k)}catch(k){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${y}":`,k)}})(),We.addEventListener("click",i=>{let d=i.target;if(!(d instanceof Element))return;let f=d.closest("button[data-persona-copy-tool-detail]");f&&(i.preventDefault(),i.stopPropagation(),sT(f))});let $m=i=>{let f=i.target.closest('button[data-expand-header="true"]');if(!f)return;let y=f.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!y)return;let w=y.getAttribute("data-message-id");if(!w)return;is(),na();let k=f.getAttribute("data-bubble-type");if(y.classList.contains("persona-activity-row")){a.manual(w);let q=y.parentElement?.closest("[data-persona-tool-group]");q?.dataset.messageId&&a.manual(q.dataset.messageId)}if(k==="reasoning")s.has(w)?s.delete(w):s.add(w),hy(w,y,s);else if(k==="tool")r.has(w)?r.delete(w):r.add(w),Cy(w,y,r,o);else if(k==="approval"&&C){let te=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",Q=l.get(w)??te;l.set(w,!Q),C.updateApprovalDetailsUI(w,y,o,l)}mn.delete(w)};We.addEventListener("pointerdown",i=>{i.target.closest('button[data-expand-header="true"]')&&(i.preventDefault(),$m(i))}),We.addEventListener("click",i=>{i.detail===0&&i.target.closest(".persona-activity-row")&&$m(i)}),We.addEventListener("keydown",i=>{let d=i.target;(i.key==="Enter"||i.key===" ")&&d.closest('button[data-expand-header="true"]')&&(i.preventDefault(),$m(i))}),We.addEventListener("copy",i=>{let{clipboardData:d}=i;if(!d)return;let f=We.getRootNode(),y=typeof f.getSelection=="function"?f.getSelection():window.getSelection();if(!y||y.isCollapsed)return;let w=y.toString(),k=YA(w);!k||k===w||(d.setData("text/plain",k),i.preventDefault())});let zm=new Map,qb=null,jb="idle",R0={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},H0=(i,d)=>{let{icon:f,label:y}=R0[d];i.setAttribute("aria-label",y),i.title=y,i.setAttribute("aria-pressed",d==="idle"?"false":"true"),i.classList.toggle("persona-message-action-active",d!=="idle"),i.classList.toggle("persona-message-action-loading",d==="loading");let w=ke(f,14,"currentColor",2);w&&(i.innerHTML="",i.appendChild(w))},Kb=()=>{We.querySelectorAll('[data-action="read-aloud"]').forEach(d=>{let y=d.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;H0(d,y&&y===qb?jb:"idle")})};We.addEventListener("click",i=>{let f=i.target.closest(".persona-message-action-btn[data-action]");if(!f)return;i.preventDefault(),i.stopPropagation();let y=f.closest("[data-actions-for]");if(!y)return;let w=y.getAttribute("data-actions-for");if(!w)return;let k=f.getAttribute("data-action");if(k==="copy"){let te=N.getMessages().find(Q=>Q.id===w);if(te&&Gn.onCopy){let Q=te.content||"";navigator.clipboard.writeText(Q).then(()=>{f.classList.add("persona-message-action-success");let re=Ge(Xr.Check,14,"currentColor",2);re&&(f.innerHTML="",f.appendChild(re)),setTimeout(()=>{f.classList.remove("persona-message-action-success");let ce=Ge(Xr.Copy,14,"currentColor",2);ce&&(f.innerHTML="",f.appendChild(ce))},2e3)}).catch(re=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",re)}),Gn.onCopy(te)}}else if(k==="read-aloud")N.toggleReadAloud(w);else if(k==="upvote"||k==="downvote"){let te=(zm.get(w)??null)===k,Q=k==="upvote"?"thumbs-up":"thumbs-down";if(te){zm.delete(w),f.classList.remove("persona-message-action-active");let re=ke(Q,14,"currentColor",2);re&&(f.innerHTML="",f.appendChild(re))}else{let re=k==="upvote"?"downvote":"upvote",ce=y.querySelector(`[data-action="${re}"]`);if(ce){ce.classList.remove("persona-message-action-active");let kt=ke(re==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);kt&&(ce.innerHTML="",ce.appendChild(kt))}zm.set(w,k),f.classList.add("persona-message-action-active");let he=ke(Q,14,"currentColor",2);he&&(he.setAttribute("fill","currentColor"),f.innerHTML="",f.appendChild(he)),f.classList.remove("persona-message-action-pop"),f.offsetWidth,f.classList.add("persona-message-action-pop");let lt=N.getMessages().find(It=>It.id===w);lt&&Gn.onFeedback&&Gn.onFeedback({type:k,messageId:lt.id,message:lt})}}else if(k==="regenerate")ad?.regenerate(w);else if(k==="edit")ad?.edit(w);else if(k==="quote")ad?.quote(w);else if(k?.startsWith(Zu)){let q=k.slice(Zu.length),te=o.messageActions?.custom?.find(re=>re.id===q),Q=N.getMessages().find(re=>re.id===w);if(!te||!Q)return;try{te.onSelect(Q)}catch(re){console.error(`[AgentWidget] messageActions.custom "${q}" onSelect failed:`,re)}}});let ad=null;We.addEventListener("click",i=>{let f=i.target.closest("button[data-approval-action]");if(!f)return;i.preventDefault(),i.stopPropagation();let y=f.closest(".persona-approval-bubble");if(!y)return;let w=y.getAttribute("data-message-id");if(!w)return;let k=f.getAttribute("data-approval-action");if(!k)return;let q=k==="approve"?"approved":"denied",Q=N.getMessages().find(ce=>ce.id===w);if(!Q?.approval)return;let re=y.querySelector("[data-approval-buttons]");re&&re.querySelectorAll("button").forEach(he=>{he.disabled=!0,he.style.opacity="0.5",he.style.cursor="not-allowed"}),Q.approval.toolType==="webmcp"?N.resolveWebMcpApproval(w,q):N.resolveApproval(Q.approval,q)});let gt=null,Gb=!1,ll=null,Us=()=>{},cl="none",ld=null,wo={artifacts:[],selectedId:null},Ar=!1,No=!1,dl=!1,Ki=!1,Yb=()=>Ki||wo.artifacts.some(i=>Cs(o.features?.artifacts,i)==="panel"),cd=()=>wo.artifacts.length>0&&!Ar&&Yb(),Ft={current:null},Um=(i,d)=>{let f=N.getArtifactById(d),y=f?.markdown,w=f?.title||"artifact",k=f?.file,q=f?.artifactType??"markdown";if(!y){let re=i.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(re){let he=N.getMessages().find(De=>De.id===re);if(he?.rawContent)try{let De=JSON.parse(he.rawContent);y=De?.props?.markdown,w=De?.props?.title||w,De?.props?.file&&typeof De.props.file=="object"&&(k=De.props.file),!f&&typeof De?.props?.artifactType=="string"&&(q=De.props.artifactType)}catch{}}}return{markdown:y,title:w,file:k,artifactType:q}};We.addEventListener("click",i=>{let f=i.target.closest("[data-download-artifact]");if(!f)return;i.preventDefault(),i.stopPropagation();let y=f.getAttribute("data-download-artifact");if(!y||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:y})===!0)return;let{markdown:k,title:q,file:te}=Um(f,y);if(!k)return;let Q=Gr();Q&&Q.triggerArtifactDownload(Q.downloadInfoFor({title:q,markdown:k,file:te}))}),We.addEventListener("click",i=>{let f=i.target.closest("[data-artifact-custom-action]");if(!f)return;i.preventDefault(),i.stopPropagation();let y=f.getAttribute("data-artifact-custom-action");if(!y)return;let w=f.closest("[data-artifact-inline]"),k=w?null:f.closest("[data-open-artifact]"),q=w?w.getAttribute("data-artifact-inline"):k?.getAttribute("data-open-artifact")??null,Q=(w?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(It=>It.id===y);if(!Q)return;let{markdown:re,title:ce,file:he,artifactType:De}=Um(f,q??""),lt={artifactId:q,title:ce,artifactType:De,markdown:re,file:he};try{Promise.resolve(Q.onClick(lt)).catch(()=>{})}catch{}}),We.addEventListener("click",i=>{let f=i.target.closest("[data-copy-artifact]");if(!f)return;i.preventDefault(),i.stopPropagation();let y=f.getAttribute("data-copy-artifact");if(!y)return;let w=N.getArtifactById(y),k=Gr();if(!k)return;let q="";if(w)q=k.artifactCopyText(w);else{let{markdown:te,file:Q,artifactType:re}=Um(f,y);re==="markdown"&&(q=k.artifactCopyText({id:y,artifactType:"markdown",status:"complete",markdown:te??"",...Q?{file:Q}:{}}))}q&&navigator.clipboard.writeText(q).then(()=>{let te=Ge(Xr.Check,16,"currentColor",2);te&&(f.replaceChildren(te),setTimeout(()=>{let Q=Ge(Xr.Copy,16,"currentColor",2);Q&&f.replaceChildren(Q)},1500))}).catch(()=>{})}),We.addEventListener("click",i=>{let f=i.target.closest("[data-expand-artifact-inline]");if(!f)return;i.preventDefault(),i.stopPropagation();let y=f.getAttribute("data-expand-artifact-inline");!y||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:y})===!0||(Ar=!1,Ki=!0,No=!0,dl=!0,N.selectArtifact(y),Fo())}),We.addEventListener("click",i=>{let d=i.target;if(d.closest("[data-download-artifact]")||d.closest("[data-artifact-custom-action]"))return;let f=d.closest("[data-open-artifact]");if(!f)return;let y=f.getAttribute("data-open-artifact");!y||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:y})===!0||(i.preventDefault(),i.stopPropagation(),Ar=!1,Ki=!0,N.selectArtifact(y),Fo())}),We.addEventListener("keydown",i=>{if(i.key!=="Enter"&&i.key!==" ")return;let d=i.target;!d.hasAttribute("data-open-artifact")&&!d.hasAttribute("data-expand-artifact-inline")||(i.preventDefault(),d.click())});let Gi=ot.composerOverlay,Yi=(i,d,f)=>{let y=d.trim();if(!y||!Ft.current)return;let w=i.getAttribute("data-tool-call-id")??"",k=f.source==="free-text";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:w,answer:y,answers:f.structured,values:f.values??(f.source==="multi"?y.split(", "):[y]),isFreeText:k,source:f.source},bubbles:!0,composed:!0})),La(Gi,w);let q=Ft.current.getMessages().find(te=>te.toolCall?.id===w);q?.agentMetadata?.awaitingLocalTool?Ft.current.resolveAskUserQuestion(q,f.structured??y):Ft.current.sendMessage(y)},qs=i=>{let d=Ft.current;if(!d)return;let f=i.getAttribute("data-tool-call-id")??"",y=d.getMessages().find(w=>w.toolCall?.id===f);y&&d.persistAskUserQuestionProgress(y,{answers:Op(i,y),currentIndex:Wo(i)})},Qb=i=>Object.entries(i).map(([d,f])=>`${d}: ${Array.isArray(f)?f.join(", "):f}`).join(" | "),qm=i=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let d=Wo(i),f=Pa(i);if(d>=f-1)return;let y=Ft.current?.getMessages().find(w=>w.toolCall?.id===i.getAttribute("data-tool-call-id"));y&&(Np(i,y,o,d+1),qs(i))};Gi.addEventListener("click",i=>{let f=i.target.closest("[data-ask-user-action]");if(!f)return;let y=f.closest("[data-persona-ask-sheet-for]");if(!y)return;let w=f.getAttribute("data-ask-user-action");if(i.preventDefault(),i.stopPropagation(),w==="dismiss"){let k=y.getAttribute("data-tool-call-id")??"";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:k},bubbles:!0,composed:!0})),La(Gi,k);let q=Ft.current?.getMessages().find(te=>te.toolCall?.id===k);q?.agentMetadata?.awaitingLocalTool&&(Ft.current?.markAskUserQuestionResolved(q),Ft.current?.resolveAskUserQuestion(q,"(dismissed)"));return}if(w==="pick"){let k=f.getAttribute("data-option-label");if(!k)return;let q=y.getAttribute("data-multi-select")==="true",te=xs(y);if(te&&q){let Q=Mi(y)[Wo(y)],re=new Set(Array.isArray(Q)?Q:[]);re.has(k)?re.delete(k):re.add(k),Ss(y,Array.from(re)),qs(y);return}if(te){Ss(y,k),qs(y),qm(y);return}if(q){let Q=f.getAttribute("aria-pressed")==="true";f.setAttribute("aria-pressed",Q?"false":"true"),f.classList.toggle("persona-ask-pill-selected",!Q);let re=y.querySelector('[data-ask-user-action="submit-multi"]');re&&(re.disabled=Fg(y).length===0);return}Yi(y,k,{source:"pick",values:[k]});return}if(w==="submit-multi"){let k=Fg(y);if(k.length===0)return;Yi(y,k.join(", "),{source:"multi",values:k});return}if(w==="open-free-text"){let k=y.querySelector('[data-ask-free-text-row="true"]');k&&(k.classList.remove("persona-hidden"),k.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(w==="focus-free-text"){y.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(w==="submit-free-text"){let q=y.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!q.trim())return;if(xs(y)){Ss(y,q.trim()),qs(y),qm(y);return}Yi(y,q,{source:"free-text"});return}if(w==="next"||w==="back"){if(!Ft.current)return;let k=y.getAttribute("data-tool-call-id")??"",q=Ft.current.getMessages().find(he=>he.toolCall?.id===k);if(!q)return;let Q=y.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(Q){let he=Mi(y)[Wo(y)];(typeof he!="string"||he!==Q)&&Ss(y,Q)}let re=w==="next"?1:-1,ce=Wo(y)+re;Np(y,q,o,ce),qs(y);return}if(w==="submit-all"){if(!Ft.current)return;let k=y.getAttribute("data-tool-call-id")??"",q=Ft.current.getMessages().find(he=>he.toolCall?.id===k);if(!q)return;let Q=y.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";Q&&Ss(y,Q);let re=Op(y,q);Ft.current.persistAskUserQuestionProgress(q,{answers:re,currentIndex:Wo(y)});let ce=Qb(re);Yi(y,ce||"(submitted)",{source:"submit-all",structured:re});return}if(w==="skip"){if(!Ft.current)return;let k=y.getAttribute("data-tool-call-id")??"",q=Ft.current.getMessages().find(De=>De.toolCall?.id===k);if(!q)return;let te=xs(y),Q=Wo(y),re=Pa(y),ce=Q>=re-1;if(!te){t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:k},bubbles:!0,composed:!0})),La(Gi,k),q.agentMetadata?.awaitingLocalTool&&(Ft.current.markAskUserQuestionResolved(q),Ft.current.resolveAskUserQuestion(q,"(dismissed)"));return}Ss(y,"");let he=y.querySelector('[data-ask-free-text-input="true"]');if(he&&(he.value=""),ce){let De=Op(y,q),lt=Qb(De);Yi(y,lt||"(skipped)",{source:"submit-all",structured:De});return}Np(y,q,o,Q+1),qs(y);return}}),Gi.addEventListener("keydown",i=>{if(i.key!=="Enter")return;let f=i.target;if(!f.matches?.('[data-ask-free-text-input="true"]'))return;let y=f.closest("[data-persona-ask-sheet-for]");if(!y)return;i.preventDefault();let w=f.value;if(w.trim()){if(xs(y)){Ss(y,w.trim()),qs(y),qm(y);return}Yi(y,w,{source:"free-text"})}});let Xb=i=>{if(!/^[1-9]$/.test(i.key)||i.metaKey||i.ctrlKey||i.altKey)return;let d=i.target;if(d?.tagName==="INPUT"||d?.tagName==="TEXTAREA"||d?.isContentEditable)return;let f=Gi.querySelector("[data-persona-ask-sheet-for]");if(!f||f.getAttribute("data-ask-layout")!=="rows"||f.getAttribute("data-multi-select")==="true")return;let y=Number(i.key),k=f.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[y-1];k&&(i.preventDefault(),k.click())};document.addEventListener("keydown",Xb);let nr=null,en=null,pl=null,dd=null,pd=()=>{},Jb=!1,ud="",md="";function jm(){dd?.(),dd=null}let W0=()=>{let i=ca&&pi?.isConnected?pi:null,d=i?i.getBoundingClientRect().width:0;return d<=0?200:d+360},Zb=()=>{if(!nr||!en)return;let i=t.classList.contains("persona-artifact-welded-split"),d=t.ownerDocument.defaultView??window,f=d.innerWidth<=640;if(!i||t.classList.contains("persona-artifact-narrow-host")||f){en.style.removeProperty("position"),en.style.removeProperty("left"),en.style.removeProperty("top"),en.style.removeProperty("bottom"),en.style.removeProperty("width"),en.style.removeProperty("z-index");return}let y=nr.firstElementChild;if(!y||y===en)return;let w=10;en.style.position="absolute",en.style.top="0",en.style.bottom="0",en.style.width=`${w}px`,en.style.zIndex="5";let k=Qy(nr,d),q=y.offsetWidth+k/2-w/2;en.style.left=`${Math.max(0,q)}px`},fd=()=>{},ev=()=>{let i=t.ownerDocument.defaultView??window,d=o.launcher?.mobileFullscreen??!0,f=o.launcher?.mobileBreakpoint??640;return!d||i.innerWidth>f?!1:_||nn(o)},gd=()=>!Kn(o)||!cd()||t.classList.contains("persona-artifact-narrow-host")||ev()||(t.ownerDocument.defaultView??window).innerWidth<nD?"none":Ky(o)?"detached":"welded",Fo=()=>{if(!gt||!Kn(o))return;Uc(t,o),qc(t,o),fd();let i=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,d=Se.getBoundingClientRect().width||0;t.classList.toggle("persona-artifact-narrow-host",d>0&&d<=i);let f=cd();gt.setVisible(f),gt.update(wo),Ar?(gt.setMobileOpen(!1),gt.element.classList.add("persona-hidden"),gt.backdrop?.classList.add("persona-hidden"),No=!1,dl=!1):wo.artifacts.length>0&&Yb()?(gt.element.classList.remove("persona-hidden"),gt.setMobileOpen(!0)):(gt.setMobileOpen(!1),gt.element.classList.add("persona-hidden"),gt.backdrop?.classList.add("persona-hidden"),No=!1,dl=!1);let y=o.features?.artifacts?.layout?.showExpandToggle===!0;if(gt.setExpandToggleVisible(y),gt.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),gt.setRefreshButtonVisible(typeof o.features?.artifacts?.layout?.onDocumentToolbarRefresh=="function"),gt.setCustomActions(o.features?.artifacts?.toolbarActions??[]),gt.setTabFade(o.features?.artifacts?.layout?.tabFade),gt.setRenderTabBar(o.features?.artifacts?.renderTabBar),!y&&!dl&&(No=!1),No!==Jb){let k=gt.element;No?(ud=k.style.width,md=k.style.maxWidth,k.style.removeProperty("width"),k.style.removeProperty("max-width")):(ud&&(k.style.width=ud),md&&(k.style.maxWidth=md),ud="",md=""),Jb=No}t.classList.toggle("persona-artifact-expanded",No),gt.setExpanded(No);let w=gd();w!==cl&&(cl=w,Us()),pd()};if(Kn(o)){Se.style.position="relative";let i=v("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),d=v("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");i.appendChild(Pe),nr=d,d.appendChild(i),Se.appendChild(d);let f=w=>{Gb||gt||(gt=w.createArtifactPane(o,{onSelect:k=>Ft.current?.selectArtifact(k),onDismiss:()=>{Ar=!0,Fo()},onToggleExpand:()=>{let k=!No,q=wo.selectedId??wo.artifacts[wo.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:q,expanded:k})!==!0&&(No=k,k||(dl=!1),Fo())}}),gt.element.classList.add("persona-hidden"),d.appendChild(gt.element),gt.backdrop&&Se.appendChild(gt.backdrop),pd(),Fo())},y=Gr();y?f(y):(qy(()=>{let w=Gr();w&&f(w)}),ym().catch(()=>{})),pd=()=>{if(!nr||!gt)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){pl?.(),pl=null,jm(),en&&(en.remove(),en=null),gt.element.style.removeProperty("width"),gt.element.style.removeProperty("maxWidth");return}if(!en){let k=v("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");k.setAttribute("role","separator"),k.setAttribute("aria-orientation","vertical"),k.setAttribute("aria-label","Resize artifacts panel"),k.tabIndex=0;let q=t.ownerDocument,te=q.defaultView??window,Q=re=>{if(!gt||re.button!==0||t.classList.contains("persona-artifact-narrow-host")||t.classList.contains("persona-artifact-expanded")||te.innerWidth<=640)return;re.preventDefault(),jm();let ce=re.clientX,he=gt.element.getBoundingClientRect().width,De=o.features?.artifacts?.layout,lt=kt=>{let no=nr.getBoundingClientRect().width,Jt=t.classList.contains("persona-artifact-welded-split"),rn=Qy(nr,te),Vn=Jt?0:k.getBoundingClientRect().width||6,ln=he-(kt.clientX-ce),$t=mE(ln,no,rn,Vn,De?.resizableMinWidth,De?.resizableMaxWidth,W0());gt.element.style.width=`${$t}px`,gt.element.style.maxWidth="none",Zb()},It=()=>{q.removeEventListener("pointermove",lt),q.removeEventListener("pointerup",It),q.removeEventListener("pointercancel",It),dd=null;try{k.releasePointerCapture(re.pointerId)}catch{}};dd=It,q.addEventListener("pointermove",lt),q.addEventListener("pointerup",It),q.addEventListener("pointercancel",It);try{k.setPointerCapture(re.pointerId)}catch{}};k.addEventListener("pointerdown",Q),en=k,nr.insertBefore(k,gt.element),pl=()=>{k.removeEventListener("pointerdown",Q)}}if(en){let k=cd();en.classList.toggle("persona-hidden",!k),Zb()}},fd=()=>{if(!_||!gt||(o.launcher?.sidebarMode??!1)||nn(o)&&Do(o).reveal==="emerge")return;let k=t.ownerDocument.defaultView??window,q=o.launcher?.mobileFullscreen??!0,te=o.launcher?.mobileBreakpoint??640;if(q&&k.innerWidth<=te||!aE(o,_))return;let Q=Ri(o).width,re=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";cd()?(Se.style.width=re,Se.style.maxWidth=re):(Se.style.width=Q,Se.style.maxWidth=Q)},typeof ResizeObserver<"u"&&(ll=new ResizeObserver(()=>{Fo()}),ll.observe(Se))}else Se.appendChild(Pe);xe()&&Nt&&(ot.peekBanner&&Nt.appendChild(ot.peekBanner),Nt.appendChild(Qe)),t.appendChild(dt),Nt&&t.appendChild(Nt);let Km=()=>{let i=ev()||xe()&&o.launcher?.composerBar?.expandedSize==="fullscreen"||o.launcher?.fullHeight===!0&&!o.launcher?.sidebarMode&&!nn(o);if(We.style.gap=i?"var(--persona-components-message-fullscreenGap, var(--persona-components-message-gap, 12px))":"var(--persona-components-message-gap, 12px)",We.style.setProperty("--persona-transcript-gap",We.style.gap),xe()){Se.style.width="100%",Se.style.maxWidth="100%";let Ye=o.launcher?.composerBar??{},st=dt.dataset.state==="expanded",tt=Ye.expandedSize??"anchored";if(!(st&&tt!=="fullscreen")){Pe.style.background="",Pe.style.border="",Pe.style.borderRadius="",Pe.style.overflow="",Pe.style.boxShadow="";return}let bn=o.theme?.components?.panel,oo=qr(o),Or=(_r,bi)=>_r==null||_r===""?bi:Hn(oo,_r)??_r,ug="1px solid var(--persona-border)",yi="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",mg="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";Pe.style.background="var(--persona-surface, #ffffff)",Pe.style.border=Or(bn?.border,ug),Pe.style.borderRadius=Or(bn?.borderRadius,mg),Pe.style.boxShadow=Or(bn?.shadow,yi),Pe.style.overflow="hidden";return}let d=nn(o),f=o.launcher?.sidebarMode??!1,y=d||f||(o.launcher?.fullHeight??!1),w=o.launcher?.enabled===!1,k=o.launcher?.detachedPanel===!0,q=o.theme?.components?.panel,te=o.darkTheme?.components?.panel,Q=fc(o)==="dark"?jo(q??{},te??{}):q,re=qr(o),ce=(Ye,st)=>Ye==null||Ye===""?st:Hn(re,Ye)??Ye,he=t.ownerDocument.defaultView??window,De=o.launcher?.mobileFullscreen??!0,lt=o.launcher?.mobileBreakpoint??640,It=he.innerWidth<=lt,kt=De&&It&&_,no=d&&De&&It,Jt=o.launcher?.position??"bottom-left",rn=Jt==="bottom-left"||Jt==="top-left",Vn=o.launcher?.zIndex??On,ln=(Ye,st,tt)=>`var(--persona-components-panel-modes-${Ye}-${st}, ${tt})`,$t=Q?.modes?.floating,cr=ce($t?.border??Q?.border,ln("floating","border","var(--persona-panel-border, 1px solid var(--persona-border))")),dr=ce($t?.shadow??Q?.shadow,ln("floating","shadow","var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))")),Po=ce($t?.borderRadius??Q?.borderRadius,ln("floating","borderRadius","var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))")),Lo=k&&!kt&&!no,gs=kt||no?"mobile":Lo?"floating":d?"docked":f?"sidebar":w?"inline":"floating",pr=Q?.modes?.[gs];Lo?t.setAttribute("data-persona-panel-detached","true"):t.removeAttribute("data-persona-panel-detached");let zo=Lo?cr:f||kt?"none":cr,hs=Lo?dr:kt?"none":f?rn?"2px 0 12px rgba(0, 0, 0, 0.08)":"-2px 0 12px rgba(0, 0, 0, 0.08)":w?"none":dr;d&&!kt&&!Lo&&(hs="none",zo="none");let Ol=Lo?Po:f||kt?"0":Po,hi=ce(pr?.border??Q?.border,ln(gs,"border",zo)),$=ce(pr?.shadow??Q?.shadow,ln(gs,"shadow",hs)),Xe=ce(pr?.borderRadius??Q?.borderRadius,ln(gs,"borderRadius",Ol)),Je=gd(),fe=Je==="detached",zt=Je==="welded";t.classList.toggle("persona-artifact-detached-split",fe),t.classList.toggle("persona-artifact-welded-split",zt);let fn="var(--persona-artifact-chat-shadow, var(--persona-artifact-pane-shadow, var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))))",jt=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&Kn(o)&&Ky(o)&&w&&!d;t.classList.toggle("persona-artifact-chat-flush",jt);let cn=fe||jt?"none":$,Sn=fe?cr:zt?"none":hi,Ke=fe?Po:Xe;jt&&(Sn="none",Ke="0");let Kt=pr?.borderRadius!=null&&pr.borderRadius!==""||Q?.borderRadius!=null&&Q.borderRadius!=="",et=jt&&!Kt?"0":Xe,An=pe.scrollTop;t.style.cssText="",dt.style.cssText="",Se.style.cssText="",Pe.style.cssText="",pe.style.cssText="",ji||(Qe.style.cssText=""),nt&&(pe.style.display="none"),(y||w)&&(t.style.minWidth="0");let Io=()=>{if(An<=0)return;(pe.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(pe.scrollTop===An)return;let st=pe.scrollHeight-pe.clientHeight;st<=0||(pe.scrollTop=Math.min(An,st))})};if(kt){dt.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),dt.style.cssText=`
|
|
1174
|
+
`,U.addEventListener("click",()=>{m=W,E.forEach((B,O)=>{let H=O<W;B.classList.toggle("selected",H),B.setAttribute("aria-checked",O===W-1?"true":"false")})}),E.push(U),M.appendChild(U)}g.appendChild(M);let T=null;if(c){let W=document.createElement("div");W.className="persona-feedback-comment-container",T=document.createElement("textarea"),T.className="persona-feedback-comment",T.placeholder=s,T.rows=3,T.setAttribute("aria-label","Additional comments"),W.appendChild(T),g.appendChild(W)}let R=document.createElement("div");R.className="persona-feedback-actions";let A=document.createElement("button");A.type="button",A.className="persona-feedback-btn persona-feedback-btn-skip",A.textContent=l,A.addEventListener("click",()=>{n?.(),u.remove()});let D=document.createElement("button");return D.type="button",D.className="persona-feedback-btn persona-feedback-btn-submit",D.textContent=a,D.addEventListener("click",async()=>{if(m===null){M.classList.add("persona-feedback-shake"),setTimeout(()=>M.classList.remove("persona-feedback-shake"),500);return}D.disabled=!0,D.textContent="Submitting...";try{let W=T?.value.trim()||void 0;await e(m,W),u.remove()}catch(W){D.disabled=!1,D.textContent=a,console.error("[CSAT Feedback] Failed to submit:",W)}}),R.appendChild(A),R.appendChild(D),g.appendChild(R),u.appendChild(g),u}function d0(t){let{onSubmit:e,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:l="Skip",showComment:c=!0,lowLabel:p="Not likely",highLabel:u="Very likely"}=t,m=document.createElement("div");m.className="persona-feedback-container persona-feedback-nps",m.setAttribute("role","dialog"),m.setAttribute("aria-label","Net Promoter Score feedback");let g=null,h=document.createElement("div");h.className="persona-feedback-content";let b=document.createElement("div");b.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=o,b.appendChild(C);let M=document.createElement("p");M.className="persona-feedback-subtitle",M.textContent=r,b.appendChild(M),h.appendChild(b);let E=document.createElement("div");E.className="persona-feedback-rating persona-feedback-rating-nps",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Likelihood rating from 0 to 10");let T=document.createElement("div");T.className="persona-feedback-labels";let R=document.createElement("span");R.className="persona-feedback-label-low",R.textContent=p;let A=document.createElement("span");A.className="persona-feedback-label-high",A.textContent=u,T.appendChild(R),T.appendChild(A);let D=document.createElement("div");D.className="persona-feedback-numbers";let W=[];for(let S=0;S<=10;S++){let x=document.createElement("button");x.type="button",x.className="persona-feedback-rating-btn persona-feedback-number-btn",x.setAttribute("role","radio"),x.setAttribute("aria-checked","false"),x.setAttribute("aria-label",`Rating ${S} out of 10`),x.textContent=String(S),x.dataset.rating=String(S),S<=6?x.classList.add("persona-feedback-detractor"):S<=8?x.classList.add("persona-feedback-passive"):x.classList.add("persona-feedback-promoter"),x.addEventListener("click",()=>{g=S,W.forEach((P,L)=>{P.classList.toggle("selected",L===S),P.setAttribute("aria-checked",L===S?"true":"false")})}),W.push(x),D.appendChild(x)}E.appendChild(T),E.appendChild(D),h.appendChild(E);let U=null;if(c){let S=document.createElement("div");S.className="persona-feedback-comment-container",U=document.createElement("textarea"),U.className="persona-feedback-comment",U.placeholder=s,U.rows=3,U.setAttribute("aria-label","Additional comments"),S.appendChild(U),h.appendChild(S)}let B=document.createElement("div");B.className="persona-feedback-actions";let O=document.createElement("button");O.type="button",O.className="persona-feedback-btn persona-feedback-btn-skip",O.textContent=l,O.addEventListener("click",()=>{n?.(),m.remove()});let H=document.createElement("button");return H.type="button",H.className="persona-feedback-btn persona-feedback-btn-submit",H.textContent=a,H.addEventListener("click",async()=>{if(g===null){D.classList.add("persona-feedback-shake"),setTimeout(()=>D.classList.remove("persona-feedback-shake"),500);return}H.disabled=!0,H.textContent="Submitting...";try{let S=U?.value.trim()||void 0;await e(g,S),m.remove()}catch(S){H.disabled=!1,H.textContent=a,console.error("[NPS Feedback] Failed to submit:",S)}}),B.appendChild(O),B.appendChild(H),h.appendChild(B),m.appendChild(h),m}var Ja="persona-chat-history",yD=30*1e3,bD=641,Za="data-persona-composer-reason",vD={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","image/bmp":"bmp","image/tiff":"tiff"};function CD(t){if(!t)return[];let e=[],n=Array.from(t.items??[]);for(let o of n){if(o.kind!=="file"||!o.type.startsWith("image/"))continue;let r=o.getAsFile();if(!r)continue;if(r.name){e.push(r);continue}let s=vD[r.type]??"png";e.push(new File([r],`clipboard-image-${Date.now()}.${s}`,{type:r.type,lastModified:Date.now()}))}if(e.length>0)return e;for(let o of Array.from(t.files??[]))o.type.startsWith("image/")&&e.push(o);return e}function Tm(t){if(!t)return!1;let e=t.types;return e?typeof e.contains=="function"?e.contains("Files"):Array.from(e).includes("Files"):!1}function wD(t){return t?t===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:t.storage??"session",keyPrefix:t.keyPrefix??"persona-",persist:{openState:t.persist?.openState??!0,voiceState:t.persist?.voiceState??!0,focusInput:t.persist?.focusInput??!0},clearOnChatClear:t.clearOnChatClear??!0}:null}function xD(t){try{let e=t==="local"?localStorage:sessionStorage,n="__persist_test__";return e.setItem(n,"1"),e.removeItem(n),e}catch{return null}}var vb=t=>!t||typeof t!="object"?{}:{...t},p0=t=>t.map(e=>({...e,streaming:!1})),u0=(t,e,n)=>{let o=t?.markdown?Pp(t.markdown):null,r=Ip(t?.sanitize);t?.postprocessMessage&&r&&t?.sanitize===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function.");let s=!1,a=l=>{let c=l.text??"",p=l.message.rawContent??null;if(e){let g=e.process({text:c,raw:p??c,message:l.message,streaming:l.streaming});g!==null&&(c=g.text,g.persist||(l.message.__skipPersist=!0),g.resubmit&&!l.streaming&&n&&n())}let u=Ho()!==null,m;if(t?.postprocessMessage){let g=t.postprocessMessage({...l,text:c,raw:p??l.text??""});m=r?r(g):g}else if(o){let g=l.streaming?jw(c):c,h=o(g);m=r&&u?r(h):h}else m=$r(c);return m};return l=>{try{return a(l)}catch(c){return s||(s=!0,console.error("[Persona] markdown rendering failed; falling back to plain text:",c)),$r(l.text??"")}}};function m0(t){let e=v("div","persona-attachment-drop-overlay");t?.background&&e.style.setProperty("--persona-drop-overlay-bg",t.background),t?.backdropBlur!==void 0&&e.style.setProperty("--persona-drop-overlay-blur",t.backdropBlur),t?.border&&e.style.setProperty("--persona-drop-overlay-border",t.border),t?.borderRadius&&e.style.setProperty("--persona-drop-overlay-radius",t.borderRadius),t?.inset&&e.style.setProperty("--persona-drop-overlay-inset",t.inset),t?.labelSize&&e.style.setProperty("--persona-drop-overlay-label-size",t.labelSize),t?.labelColor&&e.style.setProperty("--persona-drop-overlay-label-color",t.labelColor);let n=t?.iconName??"upload",o=t?.iconSize??"48px",r=t?.iconColor??"rgba(59, 130, 246, 0.6)",s=t?.iconStrokeWidth??.5,a=ke(n,o,r,s);if(a&&e.appendChild(a),t?.label){let l=v("span","persona-drop-overlay-label");l.textContent=t.label,e.appendChild(l)}return e}var SD=(t,e)=>{let n={...t};for(let[o,r]of Object.entries(e)){let s=n[o];n[o]=s?{...s,...r}:r}return n},AD=t=>t.reduce((e,n)=>({blocks:[...e.blocks,...n.blocks],contentParts:[...e.contentParts,...n.contentParts],context:SD(e.context,n.context)}),{blocks:[],contentParts:[],context:{}}),f0=(t,e,n)=>{if(t==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');t.id&&!t.getAttribute("data-persona-instance")&&t.setAttribute("data-persona-instance",t.id),t.hasAttribute("data-persona-root")||t.setAttribute("data-persona-root","true");let o=gp(e),r=new Set,s=new Set,a=Rw((i,d)=>{mn.delete(i);let f=Array.from(We.querySelectorAll("[data-message-id]")).find(y=>y.dataset.messageId===i);f&&(d==="tool"?xy(i,f,r,o):by(i,f,s))}),l=new Map,c=()=>{TS({delayMs:o.tooltip?.delayMs??200,skipDelayMs:o.tooltip?.skipDelayMs??300})};c();let p=o.features;o=Xy(o);let u=eb.getForInstance(o.plugins),m=oM(t),g=[],h=!1,b=uT(()=>o),C=null,M=null,E=null,T=!1,R=null,A=i=>{C=i,i.initApprovalUi({webMcpToolTitle:Hp});let d=i.createBuiltInApprovalPlugin(l);M=d.plugin,E=d.teardown},D=()=>{if(C)return C;let i=ET();return i?(A(i),i):(TT().then(d=>{T||C||(A(d),R?.())}).catch(()=>{}),null)},W=!1,U=!1,B=null,O=(i,d,f,y)=>{if(!i.querySelector("[data-tv-form]"))return;let w=PE();if(w){w.enhanceWithForms(i,d,f,y);return}kE().then(()=>{W||U||!B||(U=!0,B())}).catch(()=>{})};o.components&&Yo.registerAll(o.components);let H=RE(),x=o.persistState===!1?null:o.storageAdapter??BE(),P=!!o.clientToken&&typeof o.reconnectStream!="function",L={},G=null,V,K=new Promise(i=>{V=i}),ee,oe=!1,ne=i=>{if(o.onStateLoaded)try{let d=o.onStateLoaded(i);if(d&&typeof d=="object"&&"state"in d){let{state:f,open:y}=d;return y&&(oe=!0),f}return d}catch(d){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",d)}return i};if(x?.load)try{let i=x.load();if(i&&typeof i.then=="function")G=i.then(d=>ne(d??{messages:[],metadata:{}}));else{let f=ne(i??{messages:[],metadata:{}});f.metadata&&(L=vb(f.metadata)),f.messages?.length&&(o={...o,initialMessages:f.messages}),f.artifacts?.length&&(o={...o,initialArtifacts:f.artifacts,initialSelectedArtifactId:f.selectedArtifactId??null}),ee=f.draft}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",i)}else if(o.onStateLoaded)try{let i=ne({messages:[],metadata:{}});i.messages?.length&&(o={...o,initialMessages:i.messages})}catch(i){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",i)}G||V();let le=()=>L,de=i=>{L=i({...L})??{},Zi()},ve=o.actionParsers&&o.actionParsers.length?o.actionParsers:[nb],Le=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[jc.message,jc.messageAndClick],se=ob({parsers:ve,handlers:Le,getSessionMetadata:le,updateSessionMetadata:de,emit:H.emit,documentRef:typeof document<"u"?document:null});se.syncFromMetadata();let _=o.launcher?.enabled??!0,Te=o.launcher?.autoExpand??!1,Re=o.autoFocusInput??!1,ut=Te,At=_,Wt=o.layout?.header?.layout,bt=!1,xe=()=>Ec(o),Ne=()=>_||xe(),Ae=xe()?!1:_?Te:!0,vt=!1,X=null,I=()=>{vt=!0,X&&clearTimeout(X),X=setTimeout(()=>{vt&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),vt=!1)},1e4)},j=u0(o,se,I),J=o.features?.showReasoning??!0,Y=o.features?.showToolCalls??!0,ie=o.features?.showEventStreamToggle??!1,Me=o.features?.scrollToBottom??{},Ee=o.features?.scrollBehavior??{},_e=()=>(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-",Ot=`${_e()}event-stream`,rt=null,Ze=o.features?.eventStream?.maxEvents??2e3,ct=null,Ht=null,Z=null,Fe=!1,He=null,nt=!1,Bt=null,Ie=0,Be=(i,d)=>{ct?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i,timestamp:Date.now(),payload:JSON.stringify(d)})},qe=(i,d)=>{Ht?.processEvent(i,d),ct?Be(i,d):Z&&(Z.length>=Ze&&Z.shift(),Z.push({type:i,payload:d}))},Tt=()=>{ct||!ie||(Z??(Z=[]),Ry().then(i=>{if(Fe||ct||!ie)return;rt=new i.EventStreamStore(Ot),ct=new i.EventStreamBuffer(Ze,rt),Ht=Ht??new i.ThroughputTracker,rt.open().then(()=>ct?.restore()).catch(f=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",f)});let d=Z??[];Z=null;for(let f of d)Ht?.processEvent(f.type,f.payload),Be(f.type,f.payload)}).catch(()=>{}))};ie&&Tt();let mt=!1,xt=null,Mn=()=>{},ft=()=>{},_t=()=>{},Vt=()=>{},pn=()=>{},ao=()=>nt||mt&&xt==="panel",Yn={onCopy:i=>{H.emit("message:copy",i),N?.isClientTokenMode()&&N.submitMessageFeedback(i.id,"copy").catch(d=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",d)}),o.messageActions?.onCopy?.(i)},onFeedback:i=>{H.emit("message:feedback",i),N?.isClientTokenMode()&&N.submitMessageFeedback(i.messageId,i.type).catch(d=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",d)}),o.messageActions?.onFeedback?.(i)}},Zc=o.statusIndicator??{},_s=(i,d=o.statusIndicator??{})=>i==="idle"?d.idleText??dn.idle:i==="connecting"?d.connectingText??dn.connecting:i==="connected"?d.connectedText??dn.connected:i==="error"?d.errorText??dn.error:i==="paused"?d.pausedText??dn.paused:i==="resuming"?d.resumingText??dn.resuming:dn[i];function Qo(i,d,f,y){if(!xe()&&(f.mode==="transient"||i.classList.contains("persona-mb-2"))&&(Pg(i,Tn,f),xi(i,f,y)),!i.hasAttribute(Za))if(y==="idle"&&f.idleLink){i.textContent="";let w=document.createElement("a");w.href=f.idleLink,w.target="_blank",w.rel="noopener noreferrer",w.textContent=d,w.style.color="inherit",w.style.textDecoration="none",i.appendChild(w)}else i.textContent=d}let Cn=pT({config:o,showClose:Ne()}),{wrapper:dt,panel:Se,pillRoot:Nt}=Cn.shell,ot=Cn.panelElements,{container:Pe,body:pe,messagesWrapper:We,starterSuggestions:Ns,transcriptSuggestions:Xo,suggestions:lo,textarea:we,sendButton:Ve,composerForm:Tn,statusText:pt,welcomeHost:gn,welcomeIconHolder:km,greetingHost:z,introKicker:ge,introTitle:Ue,introSubtitle:at,closeButton:Ce,iconHolder:St,headerTitle:Bn,headerSubtitle:Qn,header:$e,footer:Qe,actionsRow:E0}=ot,Pm=ot.leftActions,ed=ot.rightActions,Jo=ot.sendButtonWrapper,Tb=ot.setSendButtonMode,he=ot.micButton,co=ot.micButtonWrapper,on=ot.attachmentButton,Xn=ot.attachmentButtonWrapper,Xt=ot.attachmentInput,Jn=ot.attachmentPreviewsContainer;Pe.classList.add("persona-relative"),pe.classList.add("persona-relative");let k0=12,tl=()=>Me.label??"",P0=()=>Me.iconName??"arrow-down",L0=()=>Me.enabled!==!1,po=()=>Ee.mode??"anchor-top",Jr=()=>po()==="follow"||po()==="anchor-top"&&ul,nl=()=>Ee.anchorTopOffset??16,I0=()=>Ee.restorePosition??"bottom",Eb=()=>Ee.pauseOnInteraction===!0,kb=()=>Ee.showActivityWhilePinned!==!1,Pb=()=>Ee.announce===!0,Lm=()=>Ee.scrollbar??"on-scroll",hn=v("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");hn.type="button",hn.style.display="none",hn.setAttribute("data-persona-scroll-to-bottom","true");let ol=v("span","persona-flex persona-items-center"),Im=v("span",""),Fs=v("span","");Fs.setAttribute("data-persona-scroll-to-bottom-count",""),Fs.style.display="none",hn.append(ol,Im,Fs),Pe.appendChild(hn);let Co=v("div","persona-stream-anchor-spacer");Co.setAttribute("aria-hidden","true"),Co.setAttribute("data-persona-anchor-spacer",""),Co.style.flexShrink="0",Co.style.pointerEvents="none",Co.style.height="0px",Co.style.display="none",pe.appendChild(Co);let xr=v("div","persona-sr-only");xr.setAttribute("aria-live","polite"),xr.setAttribute("aria-atomic","true"),xr.setAttribute("role","status"),xr.setAttribute("data-persona-live-region",""),Object.assign(xr.style,{position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}),Pe.appendChild(xr);let rl=null,td=null,nd=i=>{!Pb()||!i||(td=i,rl===null&&(rl=setTimeout(()=>{rl=null,td&&Pb()&&(xr.textContent=td),td=null},400)))},sl=()=>{let i=t.ownerDocument.defaultView??window;return(o.launcher?.mobileFullscreen??!0)&&i.innerWidth<=(o.launcher?.mobileBreakpoint??640)&&(_||nn(o))||o.launcher?.fullHeight===!0&&!o.launcher.sidebarMode&&!nn(o)},Vs=()=>om(o,sl()),od="empty",rd=0,Hm=()=>rd||parseFloat(t.style.getPropertyValue("--persona-composer-lift"))||0,$s=()=>{let d=Qe.style.display==="none"?0:Qe.offsetHeight;hn.style.bottom=`${d+Hm()+k0}px`};$s();let Rm=()=>{ji||(Qe.style.marginBottom=rd>0?`${rd}px`:"")},sd=()=>{let i=$h(o,xe()),d=Vs();t.setAttribute("data-persona-welcome-fullscreen",String(sl())),t.setAttribute("data-persona-welcome-layout",d.layout??"top"),t.setAttribute("data-persona-welcome-layout-explicit",o.welcome?.layout??""),t.setAttribute("data-persona-welcome-anchor",d.anchor??"bottom");let y=Qe.style.display==="none"?0:Qe.offsetHeight,w=d.anchor==="center"&&od==="empty"?hc(d.anchorComposerTop)??hc("44%"):null,k=w!==null&&d.layout==="centered"&&o.welcome?.anchor===void 0&&o.welcome?.anchorComposerTop===void 0,q=k?getComputedStyle(pe):null,te=parseFloat(t.style.getPropertyValue("--persona-composer-overlay-height"))||0,Q=parseFloat(t.style.getPropertyValue("--persona-composer-lift"))||0,re=Math.max(0,(parseFloat(q?.paddingBottom??"")||0)-(i==="overlay"?te+Q:0)),ce=k?pe.getBoundingClientRect().top-Pe.getBoundingClientRect().top:0,ye=!k||gn.hidden?0:(gn.querySelector("[data-persona-welcome-plugin]")??gn).offsetHeight,De=w===null||xe()?0:k?Math.max(0,Math.round((Pe.clientHeight-ce-ye-re-y)/2)):eM({columnHeight:Pe.clientHeight,footerHeight:y,fraction:w});t.style.setProperty("--persona-composer-overlay-height",`${y}px`),t.style.setProperty("--persona-composer-lift",`${i==="overlay"?De:0}px`),rd=i==="block"?De:0,Rm(),$s()},Lb=()=>{let i=!!tl();hn.setAttribute("aria-label",tl()||"Jump to latest"),hn.title=tl(),hn.setAttribute("data-persona-scroll-to-bottom-has-label",i?"true":"false"),ol.innerHTML="";let d=ke(P0(),"14px","currentColor",2);d?(ol.appendChild(d),ol.style.display=""):ol.style.display="none",Im.textContent=tl(),Im.style.display=i?"":"none"};Lb();let Lt=null,un=null,ze=CS(),H0=i=>{try{Pe.dispatchEvent(new CustomEvent("persona:composer:state",{detail:i,bubbles:!0,composed:!0}))}catch{}};ze.subscribe(H0);let Zo=()=>{ze.setText(we?.value??"")},zs=()=>{ze.setMentionRefs(un?.getMentionRefs()??[])},R0=i=>({id:i.id,name:i.file.name,mimeType:i.file.type,size:i.file.size,status:i.status,progress:i.progress,error:i.error}),Ib=i=>{let d=Object.freeze(i.map(R0));ze.setAttachments(d);try{o.attachments?.onChange?.(d)}catch(f){console.error("[AgentWidget] attachments.onChange failed:",f)}cf()};ze.setSelectedModelId(o.composer?.selectedModelId);let il=()=>o.composer?.modes??[],$i=()=>GS(il(),o.composer?.modeGroups);{let i=hu(o.composer?.defaultActiveModeIds??[],il());i.length&&ze.setActiveModeIds(i)}function Hb(i){if(ze.getState().selectedModelId!==i){ze.setSelectedModelId(i),Zr?.repaint();try{o.composer?.onModelChange?.(i)}catch(d){console.error("[AgentWidget] composer.onModelChange failed:",d)}}}function id(i){ze.setActiveModeIds(i),Sr?.render(i,$i()),zi.forEach(d=>d.repaint()),tr?.resolve(),Id(),_o()}function Wm(i){id(YS(ze.getState().activeModeIds,i,il(),o.composer?.modeGroups))}let Zr=null,Bm=null,Sr=null,zi=new Map,es=null;function er(i){ze.setQuote(i),es?.render(ze.getState().quote),_o(),Sv()}let Rb=!1;function Dm(){let i=o.composer?.streamingSubmitBehavior??"block";return i!=="interrupt"?i:o.clientToken?"interrupt":(!Rb&&o.debug===!0&&(Rb=!0,typeof console<"u"&&console.warn('[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".')),"block")}let ts=null;function Ui(i){ze.setPendingSubmission(i),ts?.render(ze.getState().pendingSubmission),_o()}let W0=i=>{let d=zi.get(i);if(d)return d;let f=JS({groupId:i,getGroup:()=>o.composer?.modeGroups?.find(y=>y.id===i),getModes:()=>il().filter(y=>y.groupId===i),getActiveIds:()=>ze.getState().activeModeIds,onSelect:y=>Wm(y)});return zi.set(i,f),f},B0=()=>{let i=[],d=ze.getState().activeModeIds,f=new Set;if(il().forEach((y,w)=>{if(gu(y.groupId,o.composer?.modeGroups)){let k=y.groupId;if(f.has(k))return;f.add(k);let q=W0(k);q.action.order=xh(w),q.action.label=o.composer?.modeGroups?.find(te=>te.id===k)?.label??k,i.push(q.action);return}i.push({id:jS(y.id),kind:"button",placement:"start",order:xh(w),presentation:y.presentation??"auto",label:y.label,shortLabel:y.shortLabel,iconName:y.iconName,pressed:d.includes(y.id),onSelect:()=>Wm(y.id)})}),o.composer?.models?.length&&!u.some(y=>y.renderComposer)){let y=o.composer?.modelPicker?.presentation??"native";(!Zr||Bm!==y)&&(Bm=y,Zr=US({getModels:()=>o.composer?.models??[],getSelectedModelId:()=>ze.getState().selectedModelId,onSelect:w=>Hb(w),presentation:y,getSuffix:()=>o.composer?.modelPicker?.suffix})),i.push(Zr.action)}return i},Om=null,Wb=u.find(i=>i.renderHeader);if(Wb?.renderHeader){let i=Wb.renderHeader({config:o,defaultRenderer:()=>{let d=Pi({config:o,showClose:Ne()});return Pc(Pe,d,o),d.header},onClose:()=>qt(!1,"user")});if(i){let d=$e;d&&(d.replaceWith(i),$e=i,Cn.header.element=i)}}let Bb=()=>{He&&(pe.style.display="none",Qe.parentNode?.insertBefore(He.element,Qe),He.update())},_m=()=>{if(!ct){Tt();return}if(nt=!0,He?Bb():Ry().then(d=>{He||!nt||!ct||(He=d.createEventStreamView({buffer:ct,getFullHistory:()=>ct.getAllFromStore(),onClose:()=>qi(),config:o,plugins:u,getThroughput:()=>Ht?.getMetric()??{status:"idle"},renderIconByName:ke}),Bb())}).catch(()=>{qi()}),Rt){Rt.style.boxShadow=`inset 0 0 0 1.5px ${jn.actionIconColor}`;let d=o.features?.eventStream?.classNames?.toggleButtonActive;d&&d.split(/\s+/).forEach(f=>f&&Rt.classList.add(f))}let i=()=>{if(!nt)return;let d=Date.now();d-Ie>=200&&(He?.update(),Ie=d),Bt=requestAnimationFrame(i)};Ie=0,Bt=requestAnimationFrame(i),xn(),H.emit("eventStream:opened",{timestamp:Date.now()})},qi=()=>{if(nt){if(nt=!1,He&&He.element.remove(),pe.style.display="",Rt){Rt.style.boxShadow="";let i=o.features?.eventStream?.classNames?.toggleButtonActive;i&&i.split(/\s+/).forEach(d=>d&&Rt.classList.remove(d))}Bt!==null&&(cancelAnimationFrame(Bt),Bt=null),xn(),H.emit("eventStream:closed",{timestamp:Date.now()})}},Rt=null;if(ie){let i=o.features?.eventStream?.classNames,d="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(i?.toggleButton?" "+i.toggleButton:"");Rt=v("button",d),Rt.style.width="28px",Rt.style.height="28px",Rt.style.color=jn.actionIconColor,Rt.type="button",Rt.setAttribute("aria-label","Event Stream"),Rt.title="Event Stream";let f=Ge(Xr.Activity,"18px","currentColor",1.5);f&&Rt.appendChild(f);let y=ot.clearChatButtonWrapper,w=ot.closeButtonWrapper,k=y||w;k&&k.parentNode===$e?$e.insertBefore(Rt,k):$e.appendChild(Rt),Rt.addEventListener("click",()=>{nt?qi():_m()})}let Db=i=>{let d=o.attachments;if(!d?.enabled)return;let f=i.querySelector("[data-persona-composer-attachment-previews]")??i.querySelector(".persona-attachment-previews");if(!f){f=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),f.setAttribute("data-persona-composer-attachment-previews",""),f.style.display="none";let w=i.querySelector("[data-persona-composer-form]");w?.parentNode?w.parentNode.insertBefore(f,w):i.insertBefore(f,i.firstChild)}if(!(i.querySelector("[data-persona-composer-attachment-input]")??i.querySelector('input[type="file"]'))){let w=v("input");w.type="file",w.setAttribute("data-persona-composer-attachment-input",""),w.accept=(d.allowedTypes??Ur).join(","),w.multiple=(d.maxFiles??4)>1,w.style.display="none",w.setAttribute("aria-label",d.buttonTooltipText??"Attach files"),i.appendChild(w)}},ji=!1,Ob=i=>{let d=u.find(w=>w.renderComposer);if(!d?.renderComposer)return null;let f=o.composer,y=h?N.isStreaming():!1;return d.renderComposer({config:o,defaultRenderer:i,requestRender:()=>lw(),storage:b(d.id),onSubmit:w=>{!N||N.isStreaming()||rp(w.trim(),{consumeDraft:!1})},streaming:y,disabled:y,openAttachmentPicker:()=>{sr()||Xt?.click()},models:f?.models,selectedModelId:ze.getState().selectedModelId??f?.selectedModelId,onModelChange:w=>Hb(w),onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{Om?.()}:void 0})},_b=Ob(()=>Ic({config:o}).footer);_b&&(Cn.replaceComposer(_b),Qe=Cn.composer.footer,ji=!0);let Et=null,D0=i=>{Tn=i.form,we=i.input,Jo=i.sendButton?i.sendButton.parentElement:null,i.sendButton&&(Ve=i.sendButton),i.micButton&&(he=i.micButton,co=i.micButton.parentElement),i.found.status&&(pt=i.found.status),i.found.suggestions&&(lo=i.found.suggestions),i.attachmentButton&&(on=i.attachmentButton,Xn=i.attachmentButton.parentElement),Xt=i.attachmentInput??null,Jn=i.attachmentPreviews??null,i.found.actionsRow&&(E0=i.found.actionsRow),Pm=i.found.actionsStart,ed=i.found.actionsEnd};function Nm(){let i=we;if(!i)return;let d=o.composer?.inputAttributes,f=!d?.ariaLabel&&!(i instanceof HTMLTextAreaElement)?i.getAttribute("aria-label"):null;ru(i,d),f&&i.setAttribute("aria-label",f),ou(i,{submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:rc(i)}),PS(i,nu(o.composer?.maxLines,xe()?5:3))}let Nb=i=>{Et=xS(i,{debug:o.debug===!0}),Et&&D0(Et),Nm()};Db(Qe),Nb(Qe),Zo();let al=Is(o,xe());al&&(We.style.maxWidth=al,We.style.marginLeft="auto",We.style.marginRight="auto",We.style.width="100%",z.style.maxWidth=al,z.style.marginLeft="auto",z.style.marginRight="auto",z.style.width="100%",Ns.style.maxWidth=al,Xo.style.maxWidth=al,Xo.style.marginLeft="auto",Xo.style.marginRight="auto",Xo.style.width="100%");let Fb=()=>{let i=Is(o,xe());if(!(!i||xe()))for(let d of[Tn,lo,Jn,pt])d&&(d.style.maxWidth=i,d.style.marginLeft="auto",d.style.marginRight="auto",d.style.width="100%")};Fb();let Vb=()=>{!o.attachments?.enabled||!Xt||!Jn||(Lt?Lt.remountPreviews(Jn):(Lt=oc.fromConfig(o.attachments,Ib),Lt.setPreviewsContainer(Jn)),Et?.addListener(Xt,"change",i=>{let d=i.target;Lt?.handleFileSelect(d.files),d.value=""}),Pe.querySelector(".persona-attachment-drop-overlay")||Pe.appendChild(m0(o.attachments.dropOverlay)))};Vb();let O0=()=>un?.prefetch(),$b=()=>{if(!o.contextMentions?.enabled||!we)return;let i=Et?.header??null,d=i?wh(i):void 0;if(un=KA({config:o,textarea:we,anchor:Tn??we,getMessages:()=>N.getMessages(),liveRegionHost:Pe,chipRow:d}),un&&!d){let f=we;f.parentElement?.insertBefore(un.contextRow,f)}};$b();let tr=null,_0={getState:()=>ze.getState(),getValue:()=>we?.value??"",setValue:i=>{we&&(we.value=i,we.dispatchEvent(new Event("input",{bubbles:!0})),Zo())},submit:()=>{sc(Et?.form??null)},openAttachmentPicker:()=>{sr()||Xt?.click()},toggleVoice:()=>{Om?.()},requestRender:()=>tr?.resolve()},N0=()=>{let i=[];return(un?.affordanceButtons??[]).forEach((f,y)=>{i.push({id:`core:mention-${y}`,placement:"start",order:yr.mention+y,element:f,managed:!0})}),Xn&&i.push({id:"core:attachment",placement:"start",order:yr.attachment,element:Xn}),co&&i.push({id:"core:mic",placement:"end",order:yr.mic,element:co}),Jo&&i.push({id:"core:send",placement:"end",order:yr.send,element:Jo}),i},zb=()=>{tr?.destroy(),tr=VS({getBindings:()=>Et,collect:()=>({builtIns:N0(),configActions:[...B0(),...o.composer?.actions??[]],plugins:u,contributionContext:{config:o,getState:()=>ze.getState(),requestRender:()=>tr?.resolve()},debug:o.debug===!0}),actionContext:_0,getState:()=>ze.getState(),getOverflow:()=>o.composer?.actionOverflow,reportError:(i,d)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${d.actionId}" failed:`,i)}}),tr.resolve()};zb();let Fm=()=>{if(Sr?.destroy(),Sr=null,!$i().length)return;let i=Et?.header;i&&(Sr=qS({row:wh(i),onRemove:d=>Wm(d),initialIds:ze.getState().activeModeIds}),Sr.render(ze.getState().activeModeIds,$i()))};Fm();let Ub=()=>{es?.destroy(),es=null,ts?.destroy(),ts=null;let i=Et?.header;i&&(es=ZS({onDismiss:()=>er(void 0)}),i.appendChild(es.element),es.render(ze.getState().quote),Dm()==="defer-one"&&(ts=eA({onEdit:()=>uP(),onRemove:()=>Ui(void 0)}),i.appendChild(ts.element),ts.render(ze.getState().pendingSubmission)))};Ub();let Vm=iA(),F0=()=>{let i=Et?.header?.querySelector(Ch);if(i)return i.childElementCount>0;let d=ze.getState();return d.mentionRefs.length>0||hu(d.activeModeIds,$i()).length>0};function _o(){let i=ze.getState(),d=Vm.observe(aA(we),i.text);Qe.toggleAttribute("data-persona-composer-compact",sA({text:i.text,wrapped:d,hasAttachments:i.attachments.length>0,hasChips:F0(),hasQuote:i.quote!==void 0,hasPendingSubmission:i.pendingSubmission!==void 0}))}function qb(){o.composer?.layout==="single-row"&&!xe()?Qe.setAttribute("data-persona-composer-layout","single-row"):Qe.removeAttribute("data-persona-composer-layout")}qb(),ze.subscribe(()=>{tr?.sync(),cf(),Pd(),_o(),Sv()}),Pd();let jb=!1,V0=i=>{if(jb||o.debug!==!0)return;let d=["messages","composer"].filter(f=>i[f]);d.length&&(jb=!0,console.warn(`[persona] layout.slots.${d.join(" and layout.slots.")} ${d.length>1?"are":"is"} deprecated and unsupported: the renderer never runs. Use the message render hooks for the transcript and the renderComposer plugin hook for the composer.`))};(()=>{let i=o.layout?.slots??{};V0(i);let d=y=>{switch(y){case"body-top":return pe.querySelector("[data-persona-intro-card]");case"messages":return We;case"footer-top":return lo;case"composer":return Tn;case"footer-bottom":return pt;default:return null}},f=(y,w)=>{switch(y){case"header-left":case"header-center":case"header-right":if(y==="header-left")$e.insertBefore(w,$e.firstChild);else if(y==="header-right")$e.appendChild(w);else{let k=$e.querySelector(".persona-flex-col");k?k.parentNode?.insertBefore(w,k.nextSibling):$e.appendChild(w)}break;case"body-top":{let k=pe.querySelector("[data-persona-intro-card]");k?k.replaceWith(w):pe.insertBefore(w,pe.firstChild);break}case"body-bottom":pe.appendChild(w);break;case"footer-top":lo.replaceWith(w);break;case"footer-bottom":pt.replaceWith(w);break;default:break}};for(let[y,w]of Object.entries(i))if(w)try{let k=w({config:o,defaultContent:()=>d(y)});k&&f(y,k)}catch(k){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${y}":`,k)}})(),We.addEventListener("click",i=>{let d=i.target;if(!(d instanceof Element))return;let f=d.closest("button[data-persona-copy-tool-detail]");f&&(i.preventDefault(),i.stopPropagation(),gT(f))});let $m=i=>{let f=i.target.closest('button[data-expand-header="true"]');if(!f)return;let y=f.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!y)return;let w=y.getAttribute("data-message-id");if(!w)return;is(),na();let k=f.getAttribute("data-bubble-type");if(y.classList.contains("persona-activity-row")){a.manual(w);let q=y.parentElement?.closest("[data-persona-tool-group]");q?.dataset.messageId&&a.manual(q.dataset.messageId)}if(k==="reasoning")s.has(w)?s.delete(w):s.add(w),by(w,y,s);else if(k==="tool")r.has(w)?r.delete(w):r.add(w),xy(w,y,r,o);else if(k==="approval"&&C){let te=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",Q=l.get(w)??te;l.set(w,!Q),C.updateApprovalDetailsUI(w,y,o,l)}mn.delete(w)};We.addEventListener("pointerdown",i=>{i.target.closest('button[data-expand-header="true"]')&&(i.preventDefault(),$m(i))}),We.addEventListener("click",i=>{i.detail===0&&i.target.closest(".persona-activity-row")&&$m(i)}),We.addEventListener("keydown",i=>{let d=i.target;(i.key==="Enter"||i.key===" ")&&d.closest('button[data-expand-header="true"]')&&(i.preventDefault(),$m(i))}),We.addEventListener("copy",i=>{let{clipboardData:d}=i;if(!d)return;let f=We.getRootNode(),y=typeof f.getSelection=="function"?f.getSelection():window.getSelection();if(!y||y.isCollapsed)return;let w=y.toString(),k=sM(w);!k||k===w||(d.setData("text/plain",k),i.preventDefault())});let zm=new Map,Kb=null,Gb="idle",$0={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},z0=(i,d)=>{let{icon:f,label:y}=$0[d];i.setAttribute("aria-label",y),i.title=y,i.setAttribute("aria-pressed",d==="idle"?"false":"true"),i.classList.toggle("persona-message-action-active",d!=="idle"),i.classList.toggle("persona-message-action-loading",d==="loading");let w=ke(f,14,"currentColor",2);w&&(i.innerHTML="",i.appendChild(w))},Yb=()=>{We.querySelectorAll('[data-action="read-aloud"]').forEach(d=>{let y=d.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;z0(d,y&&y===Kb?Gb:"idle")})};We.addEventListener("click",i=>{let f=i.target.closest(".persona-message-action-btn[data-action]");if(!f)return;i.preventDefault(),i.stopPropagation();let y=f.closest("[data-actions-for]");if(!y)return;let w=y.getAttribute("data-actions-for");if(!w)return;let k=f.getAttribute("data-action");if(k==="copy"){let te=N.getMessages().find(Q=>Q.id===w);if(te&&Yn.onCopy){let Q=te.content||"";navigator.clipboard.writeText(Q).then(()=>{f.classList.add("persona-message-action-success");let re=Ge(Xr.Check,14,"currentColor",2);re&&(f.innerHTML="",f.appendChild(re)),setTimeout(()=>{f.classList.remove("persona-message-action-success");let ce=Ge(Xr.Copy,14,"currentColor",2);ce&&(f.innerHTML="",f.appendChild(ce))},2e3)}).catch(re=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",re)}),Yn.onCopy(te)}}else if(k==="read-aloud")N.toggleReadAloud(w);else if(k==="upvote"||k==="downvote"){let te=(zm.get(w)??null)===k,Q=k==="upvote"?"thumbs-up":"thumbs-down";if(te){zm.delete(w),f.classList.remove("persona-message-action-active");let re=ke(Q,14,"currentColor",2);re&&(f.innerHTML="",f.appendChild(re))}else{let re=k==="upvote"?"downvote":"upvote",ce=y.querySelector(`[data-action="${re}"]`);if(ce){ce.classList.remove("persona-message-action-active");let kt=ke(re==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);kt&&(ce.innerHTML="",ce.appendChild(kt))}zm.set(w,k),f.classList.add("persona-message-action-active");let ye=ke(Q,14,"currentColor",2);ye&&(ye.setAttribute("fill","currentColor"),f.innerHTML="",f.appendChild(ye)),f.classList.remove("persona-message-action-pop"),f.offsetWidth,f.classList.add("persona-message-action-pop");let lt=N.getMessages().find(It=>It.id===w);lt&&Yn.onFeedback&&Yn.onFeedback({type:k,messageId:lt.id,message:lt})}}else if(k==="regenerate")ad?.regenerate(w);else if(k==="edit")ad?.edit(w);else if(k==="quote")ad?.quote(w);else if(k?.startsWith(Zu)){let q=k.slice(Zu.length),te=o.messageActions?.custom?.find(re=>re.id===q),Q=N.getMessages().find(re=>re.id===w);if(!te||!Q)return;try{te.onSelect(Q)}catch(re){console.error(`[AgentWidget] messageActions.custom "${q}" onSelect failed:`,re)}}});let ad=null;We.addEventListener("click",i=>{let f=i.target.closest("button[data-approval-action]");if(!f)return;i.preventDefault(),i.stopPropagation();let y=f.closest(".persona-approval-bubble");if(!y)return;let w=y.getAttribute("data-message-id");if(!w)return;let k=f.getAttribute("data-approval-action");if(!k)return;let q=k==="approve"?"approved":"denied",Q=N.getMessages().find(ce=>ce.id===w);if(!Q?.approval)return;let re=y.querySelector("[data-approval-buttons]");re&&re.querySelectorAll("button").forEach(ye=>{ye.disabled=!0,ye.style.opacity="0.5",ye.style.cursor="not-allowed"}),Q.approval.toolType==="webmcp"?N.resolveWebMcpApproval(w,q):N.resolveApproval(Q.approval,q)});let gt=null,Qb=!1,ll=null,Us=()=>{},cl="none",ld=null,wo={artifacts:[],selectedId:null},Ar=!1,No=!1,dl=!1,Ki=!1,Xb=()=>Ki||wo.artifacts.some(i=>Cs(o.features?.artifacts,i)==="panel"),cd=()=>wo.artifacts.length>0&&!Ar&&Xb(),Ft={current:null},Um=(i,d)=>{let f=N.getArtifactById(d),y=f?.markdown,w=f?.title||"artifact",k=f?.file,q=f?.artifactType??"markdown";if(!y){let re=i.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(re){let ye=N.getMessages().find(De=>De.id===re);if(ye?.rawContent)try{let De=JSON.parse(ye.rawContent);y=De?.props?.markdown,w=De?.props?.title||w,De?.props?.file&&typeof De.props.file=="object"&&(k=De.props.file),!f&&typeof De?.props?.artifactType=="string"&&(q=De.props.artifactType)}catch{}}}return{markdown:y,title:w,file:k,artifactType:q}};We.addEventListener("click",i=>{let f=i.target.closest("[data-download-artifact]");if(!f)return;i.preventDefault(),i.stopPropagation();let y=f.getAttribute("data-download-artifact");if(!y||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:y})===!0)return;let{markdown:k,title:q,file:te}=Um(f,y);if(!k)return;let Q=Gr();Q&&Q.triggerArtifactDownload(Q.downloadInfoFor({title:q,markdown:k,file:te}))}),We.addEventListener("click",i=>{let f=i.target.closest("[data-artifact-custom-action]");if(!f)return;i.preventDefault(),i.stopPropagation();let y=f.getAttribute("data-artifact-custom-action");if(!y)return;let w=f.closest("[data-artifact-inline]"),k=w?null:f.closest("[data-open-artifact]"),q=w?w.getAttribute("data-artifact-inline"):k?.getAttribute("data-open-artifact")??null,Q=(w?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(It=>It.id===y);if(!Q)return;let{markdown:re,title:ce,file:ye,artifactType:De}=Um(f,q??""),lt={artifactId:q,title:ce,artifactType:De,markdown:re,file:ye};try{Promise.resolve(Q.onClick(lt)).catch(()=>{})}catch{}}),We.addEventListener("click",i=>{let f=i.target.closest("[data-copy-artifact]");if(!f)return;i.preventDefault(),i.stopPropagation();let y=f.getAttribute("data-copy-artifact");if(!y)return;let w=N.getArtifactById(y),k=Gr();if(!k)return;let q="";if(w)q=k.artifactCopyText(w);else{let{markdown:te,file:Q,artifactType:re}=Um(f,y);re==="markdown"&&(q=k.artifactCopyText({id:y,artifactType:"markdown",status:"complete",markdown:te??"",...Q?{file:Q}:{}}))}q&&navigator.clipboard.writeText(q).then(()=>{let te=Ge(Xr.Check,16,"currentColor",2);te&&(f.replaceChildren(te),setTimeout(()=>{let Q=Ge(Xr.Copy,16,"currentColor",2);Q&&f.replaceChildren(Q)},1500))}).catch(()=>{})}),We.addEventListener("click",i=>{let f=i.target.closest("[data-expand-artifact-inline]");if(!f)return;i.preventDefault(),i.stopPropagation();let y=f.getAttribute("data-expand-artifact-inline");!y||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:y})===!0||(Ar=!1,Ki=!0,No=!0,dl=!0,N.selectArtifact(y),Fo())}),We.addEventListener("click",i=>{let d=i.target;if(d.closest("[data-download-artifact]")||d.closest("[data-artifact-custom-action]"))return;let f=d.closest("[data-open-artifact]");if(!f)return;let y=f.getAttribute("data-open-artifact");!y||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:y})===!0||(i.preventDefault(),i.stopPropagation(),Ar=!1,Ki=!0,N.selectArtifact(y),Fo())}),We.addEventListener("keydown",i=>{if(i.key!=="Enter"&&i.key!==" ")return;let d=i.target;!d.hasAttribute("data-open-artifact")&&!d.hasAttribute("data-expand-artifact-inline")||(i.preventDefault(),d.click())});let Gi=ot.composerOverlay,Yi=(i,d,f)=>{let y=d.trim();if(!y||!Ft.current)return;let w=i.getAttribute("data-tool-call-id")??"",k=f.source==="free-text";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:w,answer:y,answers:f.structured,values:f.values??(f.source==="multi"?y.split(", "):[y]),isFreeText:k,source:f.source},bubbles:!0,composed:!0})),La(Gi,w);let q=Ft.current.getMessages().find(te=>te.toolCall?.id===w);q?.agentMetadata?.awaitingLocalTool?Ft.current.resolveAskUserQuestion(q,f.structured??y):Ft.current.sendMessage(y)},qs=i=>{let d=Ft.current;if(!d)return;let f=i.getAttribute("data-tool-call-id")??"",y=d.getMessages().find(w=>w.toolCall?.id===f);y&&d.persistAskUserQuestionProgress(y,{answers:Op(i,y),currentIndex:Wo(i)})},Jb=i=>Object.entries(i).map(([d,f])=>`${d}: ${Array.isArray(f)?f.join(", "):f}`).join(" | "),qm=i=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let d=Wo(i),f=Pa(i);if(d>=f-1)return;let y=Ft.current?.getMessages().find(w=>w.toolCall?.id===i.getAttribute("data-tool-call-id"));y&&(Np(i,y,o,d+1),qs(i))};Gi.addEventListener("click",i=>{let f=i.target.closest("[data-ask-user-action]");if(!f)return;let y=f.closest("[data-persona-ask-sheet-for]");if(!y)return;let w=f.getAttribute("data-ask-user-action");if(i.preventDefault(),i.stopPropagation(),w==="dismiss"){let k=y.getAttribute("data-tool-call-id")??"";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:k},bubbles:!0,composed:!0})),La(Gi,k);let q=Ft.current?.getMessages().find(te=>te.toolCall?.id===k);q?.agentMetadata?.awaitingLocalTool&&(Ft.current?.markAskUserQuestionResolved(q),Ft.current?.resolveAskUserQuestion(q,"(dismissed)"));return}if(w==="pick"){let k=f.getAttribute("data-option-label");if(!k)return;let q=y.getAttribute("data-multi-select")==="true",te=xs(y);if(te&&q){let Q=Mi(y)[Wo(y)],re=new Set(Array.isArray(Q)?Q:[]);re.has(k)?re.delete(k):re.add(k),Ss(y,Array.from(re)),qs(y);return}if(te){Ss(y,k),qs(y),qm(y);return}if(q){let Q=f.getAttribute("aria-pressed")==="true";f.setAttribute("aria-pressed",Q?"false":"true"),f.classList.toggle("persona-ask-pill-selected",!Q);let re=y.querySelector('[data-ask-user-action="submit-multi"]');re&&(re.disabled=$g(y).length===0);return}Yi(y,k,{source:"pick",values:[k]});return}if(w==="submit-multi"){let k=$g(y);if(k.length===0)return;Yi(y,k.join(", "),{source:"multi",values:k});return}if(w==="open-free-text"){let k=y.querySelector('[data-ask-free-text-row="true"]');k&&(k.classList.remove("persona-hidden"),k.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(w==="focus-free-text"){y.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(w==="submit-free-text"){let q=y.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!q.trim())return;if(xs(y)){Ss(y,q.trim()),qs(y),qm(y);return}Yi(y,q,{source:"free-text"});return}if(w==="next"||w==="back"){if(!Ft.current)return;let k=y.getAttribute("data-tool-call-id")??"",q=Ft.current.getMessages().find(ye=>ye.toolCall?.id===k);if(!q)return;let Q=y.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(Q){let ye=Mi(y)[Wo(y)];(typeof ye!="string"||ye!==Q)&&Ss(y,Q)}let re=w==="next"?1:-1,ce=Wo(y)+re;Np(y,q,o,ce),qs(y);return}if(w==="submit-all"){if(!Ft.current)return;let k=y.getAttribute("data-tool-call-id")??"",q=Ft.current.getMessages().find(ye=>ye.toolCall?.id===k);if(!q)return;let Q=y.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";Q&&Ss(y,Q);let re=Op(y,q);Ft.current.persistAskUserQuestionProgress(q,{answers:re,currentIndex:Wo(y)});let ce=Jb(re);Yi(y,ce||"(submitted)",{source:"submit-all",structured:re});return}if(w==="skip"){if(!Ft.current)return;let k=y.getAttribute("data-tool-call-id")??"",q=Ft.current.getMessages().find(De=>De.toolCall?.id===k);if(!q)return;let te=xs(y),Q=Wo(y),re=Pa(y),ce=Q>=re-1;if(!te){t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:k},bubbles:!0,composed:!0})),La(Gi,k),q.agentMetadata?.awaitingLocalTool&&(Ft.current.markAskUserQuestionResolved(q),Ft.current.resolveAskUserQuestion(q,"(dismissed)"));return}Ss(y,"");let ye=y.querySelector('[data-ask-free-text-input="true"]');if(ye&&(ye.value=""),ce){let De=Op(y,q),lt=Jb(De);Yi(y,lt||"(skipped)",{source:"submit-all",structured:De});return}Np(y,q,o,Q+1),qs(y);return}}),Gi.addEventListener("keydown",i=>{if(i.key!=="Enter")return;let f=i.target;if(!f.matches?.('[data-ask-free-text-input="true"]'))return;let y=f.closest("[data-persona-ask-sheet-for]");if(!y)return;i.preventDefault();let w=f.value;if(w.trim()){if(xs(y)){Ss(y,w.trim()),qs(y),qm(y);return}Yi(y,w,{source:"free-text"})}});let Zb=i=>{if(!/^[1-9]$/.test(i.key)||i.metaKey||i.ctrlKey||i.altKey)return;let d=i.target;if(d?.tagName==="INPUT"||d?.tagName==="TEXTAREA"||d?.isContentEditable)return;let f=Gi.querySelector("[data-persona-ask-sheet-for]");if(!f||f.getAttribute("data-ask-layout")!=="rows"||f.getAttribute("data-multi-select")==="true")return;let y=Number(i.key),k=f.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[y-1];k&&(i.preventDefault(),k.click())};document.addEventListener("keydown",Zb);let nr=null,en=null,pl=null,dd=null,pd=()=>{},ev=!1,ud="",md="";function jm(){dd?.(),dd=null}let U0=()=>{let i=ca&&pi?.isConnected?pi:null,d=i?i.getBoundingClientRect().width:0;return d<=0?200:d+360},tv=()=>{if(!nr||!en)return;let i=t.classList.contains("persona-artifact-welded-split"),d=t.ownerDocument.defaultView??window,f=d.innerWidth<=640;if(!i||t.classList.contains("persona-artifact-narrow-host")||f){en.style.removeProperty("position"),en.style.removeProperty("left"),en.style.removeProperty("top"),en.style.removeProperty("bottom"),en.style.removeProperty("width"),en.style.removeProperty("z-index");return}let y=nr.firstElementChild;if(!y||y===en)return;let w=10;en.style.position="absolute",en.style.top="0",en.style.bottom="0",en.style.width=`${w}px`,en.style.zIndex="5";let k=Jy(nr,d),q=y.offsetWidth+k/2-w/2;en.style.left=`${Math.max(0,q)}px`},fd=()=>{},nv=()=>{let i=t.ownerDocument.defaultView??window,d=o.launcher?.mobileFullscreen??!0,f=o.launcher?.mobileBreakpoint??640;return!d||i.innerWidth>f?!1:_||nn(o)},gd=()=>!Gn(o)||!cd()||t.classList.contains("persona-artifact-narrow-host")||nv()||(t.ownerDocument.defaultView??window).innerWidth<bD?"none":Yy(o)?"detached":"welded",Fo=()=>{if(!gt||!Gn(o))return;Uc(t,o),qc(t,o),fd();let i=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,d=Se.getBoundingClientRect().width||0;t.classList.toggle("persona-artifact-narrow-host",d>0&&d<=i);let f=cd();gt.setVisible(f),gt.update(wo),Ar?(gt.setMobileOpen(!1),gt.element.classList.add("persona-hidden"),gt.backdrop?.classList.add("persona-hidden"),No=!1,dl=!1):wo.artifacts.length>0&&Xb()?(gt.element.classList.remove("persona-hidden"),gt.setMobileOpen(!0)):(gt.setMobileOpen(!1),gt.element.classList.add("persona-hidden"),gt.backdrop?.classList.add("persona-hidden"),No=!1,dl=!1);let y=o.features?.artifacts?.layout?.showExpandToggle===!0;if(gt.setExpandToggleVisible(y),gt.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),gt.setRefreshButtonVisible(typeof o.features?.artifacts?.layout?.onDocumentToolbarRefresh=="function"),gt.setCustomActions(o.features?.artifacts?.toolbarActions??[]),gt.setTabFade(o.features?.artifacts?.layout?.tabFade),gt.setRenderTabBar(o.features?.artifacts?.renderTabBar),!y&&!dl&&(No=!1),No!==ev){let k=gt.element;No?(ud=k.style.width,md=k.style.maxWidth,k.style.removeProperty("width"),k.style.removeProperty("max-width")):(ud&&(k.style.width=ud),md&&(k.style.maxWidth=md),ud="",md=""),ev=No}t.classList.toggle("persona-artifact-expanded",No),gt.setExpanded(No);let w=gd();w!==cl&&(cl=w,Us()),pd()};if(Gn(o)){Se.style.position="relative";let i=v("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),d=v("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");i.appendChild(Pe),nr=d,d.appendChild(i),Se.appendChild(d);let f=w=>{Qb||gt||(gt=w.createArtifactPane(o,{onSelect:k=>Ft.current?.selectArtifact(k),onDismiss:()=>{Ar=!0,Fo()},onToggleExpand:()=>{let k=!No,q=wo.selectedId??wo.artifacts[wo.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:q,expanded:k})!==!0&&(No=k,k||(dl=!1),Fo())}}),gt.element.classList.add("persona-hidden"),d.appendChild(gt.element),gt.backdrop&&Se.appendChild(gt.backdrop),pd(),Fo())},y=Gr();y?f(y):(Ky(()=>{let w=Gr();w&&f(w)}),ym().catch(()=>{})),pd=()=>{if(!nr||!gt)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){pl?.(),pl=null,jm(),en&&(en.remove(),en=null),gt.element.style.removeProperty("width"),gt.element.style.removeProperty("maxWidth");return}if(!en){let k=v("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");k.setAttribute("role","separator"),k.setAttribute("aria-orientation","vertical"),k.setAttribute("aria-label","Resize artifacts panel"),k.tabIndex=0;let q=t.ownerDocument,te=q.defaultView??window,Q=re=>{if(!gt||re.button!==0||t.classList.contains("persona-artifact-narrow-host")||t.classList.contains("persona-artifact-expanded")||te.innerWidth<=640)return;re.preventDefault(),jm();let ce=re.clientX,ye=gt.element.getBoundingClientRect().width,De=o.features?.artifacts?.layout,lt=kt=>{let oo=nr.getBoundingClientRect().width,Jt=t.classList.contains("persona-artifact-welded-split"),rn=Jy(nr,te),Vn=Jt?0:k.getBoundingClientRect().width||6,ln=ye-(kt.clientX-ce),$t=SE(ln,oo,rn,Vn,De?.resizableMinWidth,De?.resizableMaxWidth,U0());gt.element.style.width=`${$t}px`,gt.element.style.maxWidth="none",tv()},It=()=>{q.removeEventListener("pointermove",lt),q.removeEventListener("pointerup",It),q.removeEventListener("pointercancel",It),dd=null;try{k.releasePointerCapture(re.pointerId)}catch{}};dd=It,q.addEventListener("pointermove",lt),q.addEventListener("pointerup",It),q.addEventListener("pointercancel",It);try{k.setPointerCapture(re.pointerId)}catch{}};k.addEventListener("pointerdown",Q),en=k,nr.insertBefore(k,gt.element),pl=()=>{k.removeEventListener("pointerdown",Q)}}if(en){let k=cd();en.classList.toggle("persona-hidden",!k),tv()}},fd=()=>{if(!_||!gt||(o.launcher?.sidebarMode??!1)||nn(o)&&Do(o).reveal==="emerge")return;let k=t.ownerDocument.defaultView??window,q=o.launcher?.mobileFullscreen??!0,te=o.launcher?.mobileBreakpoint??640;if(q&&k.innerWidth<=te||!yE(o,_))return;let Q=Hi(o).width,re=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";cd()?(Se.style.width=re,Se.style.maxWidth=re):(Se.style.width=Q,Se.style.maxWidth=Q)},typeof ResizeObserver<"u"&&(ll=new ResizeObserver(()=>{Fo()}),ll.observe(Se))}else Se.appendChild(Pe);xe()&&Nt&&(ot.peekBanner&&Nt.appendChild(ot.peekBanner),Nt.appendChild(Qe)),t.appendChild(dt),Nt&&t.appendChild(Nt);let Km=()=>{let i=nv()||xe()&&o.launcher?.composerBar?.expandedSize==="fullscreen"||o.launcher?.fullHeight===!0&&!o.launcher?.sidebarMode&&!nn(o);if(We.style.gap=i?"var(--persona-components-message-fullscreenGap, var(--persona-components-message-gap, 12px))":"var(--persona-components-message-gap, 12px)",We.style.setProperty("--persona-transcript-gap",We.style.gap),xe()){Se.style.width="100%",Se.style.maxWidth="100%";let Ye=o.launcher?.composerBar??{},st=dt.dataset.state==="expanded",tt=Ye.expandedSize??"anchored";if(!(st&&tt!=="fullscreen")){Pe.style.background="",Pe.style.border="",Pe.style.borderRadius="",Pe.style.overflow="",Pe.style.boxShadow="";return}let bn=o.theme?.components?.panel,ro=qr(o),Or=(_r,bi)=>_r==null||_r===""?bi:Rn(ro,_r)??_r,fg="1px solid var(--persona-border)",yi="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",gg="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";Pe.style.background="var(--persona-surface, #ffffff)",Pe.style.border=Or(bn?.border,fg),Pe.style.borderRadius=Or(bn?.borderRadius,gg),Pe.style.boxShadow=Or(bn?.shadow,yi),Pe.style.overflow="hidden";return}let d=nn(o),f=o.launcher?.sidebarMode??!1,y=d||f||(o.launcher?.fullHeight??!1),w=o.launcher?.enabled===!1,k=o.launcher?.detachedPanel===!0,q=o.theme?.components?.panel,te=o.darkTheme?.components?.panel,Q=fc(o)==="dark"?jo(q??{},te??{}):q,re=qr(o),ce=(Ye,st)=>Ye==null||Ye===""?st:Rn(re,Ye)??Ye,ye=t.ownerDocument.defaultView??window,De=o.launcher?.mobileFullscreen??!0,lt=o.launcher?.mobileBreakpoint??640,It=ye.innerWidth<=lt,kt=De&&It&&_,oo=d&&De&&It,Jt=o.launcher?.position??"bottom-left",rn=Jt==="bottom-left"||Jt==="top-left",Vn=o.launcher?.zIndex??On,ln=(Ye,st,tt)=>`var(--persona-components-panel-modes-${Ye}-${st}, ${tt})`,$t=Q?.modes?.floating,cr=ce($t?.border??Q?.border,ln("floating","border","var(--persona-panel-border, 1px solid var(--persona-border))")),dr=ce($t?.shadow??Q?.shadow,ln("floating","shadow","var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))")),Po=ce($t?.borderRadius??Q?.borderRadius,ln("floating","borderRadius","var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))")),Lo=k&&!kt&&!oo,gs=kt||oo?"mobile":Lo?"floating":d?"docked":f?"sidebar":w?"inline":"floating",pr=Q?.modes?.[gs];Lo?t.setAttribute("data-persona-panel-detached","true"):t.removeAttribute("data-persona-panel-detached");let zo=Lo?cr:f||kt?"none":cr,hs=Lo?dr:kt?"none":f?rn?"2px 0 12px rgba(0, 0, 0, 0.08)":"-2px 0 12px rgba(0, 0, 0, 0.08)":w?"none":dr;d&&!kt&&!Lo&&(hs="none",zo="none");let Ol=Lo?Po:f||kt?"0":Po,hi=ce(pr?.border??Q?.border,ln(gs,"border",zo)),$=ce(pr?.shadow??Q?.shadow,ln(gs,"shadow",hs)),Xe=ce(pr?.borderRadius??Q?.borderRadius,ln(gs,"borderRadius",Ol)),Je=gd(),fe=Je==="detached",zt=Je==="welded";t.classList.toggle("persona-artifact-detached-split",fe),t.classList.toggle("persona-artifact-welded-split",zt);let fn="var(--persona-artifact-chat-shadow, var(--persona-artifact-pane-shadow, var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))))",jt=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&Gn(o)&&Yy(o)&&w&&!d;t.classList.toggle("persona-artifact-chat-flush",jt);let cn=fe||jt?"none":$,Sn=fe?cr:zt?"none":hi,Ke=fe?Po:Xe;jt&&(Sn="none",Ke="0");let Kt=pr?.borderRadius!=null&&pr.borderRadius!==""||Q?.borderRadius!=null&&Q.borderRadius!=="",et=jt&&!Kt?"0":Xe,An=pe.scrollTop;t.style.cssText="",dt.style.cssText="",Se.style.cssText="",Pe.style.cssText="",pe.style.cssText="",ji||(Qe.style.cssText=""),nt&&(pe.style.display="none"),(y||w)&&(t.style.minWidth="0");let Io=()=>{if(An<=0)return;(pe.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(pe.scrollTop===An)return;let st=pe.scrollHeight-pe.clientHeight;st<=0||(pe.scrollTop=Math.min(An,st))})};if(kt){dt.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),dt.style.cssText=`
|
|
1175
1175
|
position: fixed !important;
|
|
1176
1176
|
inset: 0 !important;
|
|
1177
1177
|
width: 100% !important;
|
|
@@ -1207,7 +1207,7 @@ _Details: ${n.message}_`:o}var sh=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
1207
1207
|
overflow: hidden !important;
|
|
1208
1208
|
border-radius: 0 !important;
|
|
1209
1209
|
border: none !important;
|
|
1210
|
-
`,pe.style.flex="1 1 0%",pe.style.minHeight="0",pe.style.overflowY="auto",Qe.style.flexShrink="0",
|
|
1210
|
+
`,pe.style.flex="1 1 0%",pe.style.minHeight="0",pe.style.overflowY="auto",Qe.style.flexShrink="0",Rm(),bt=!0,Io();return}let kn=Hi(o);if(!f&&!d)w&&y?(Se.style.width="100%",Se.style.maxWidth="100%"):(Se.style.width=kn.width,Se.style.maxWidth=kn.maxWidth);else if(d)if(Do(o).reveal==="emerge"&&!k){let st=Do(o).width;Se.style.width=st,Se.style.maxWidth=st}else Se.style.width="100%",Se.style.maxWidth="100%";if(fd(),Se.style.boxShadow=cn,Se.style.borderRadius=et,fe?Se.style.border="none":zt&&(Se.style.border=hi),Pe.style.border=Sn,Pe.style.borderRadius=Ke,Pe.style.boxShadow=fe&&!jt?fn:"",jt&&(Pe.style.background="transparent",pe.style.background="transparent",Qe.style.background="transparent",Qe.style.borderTop="none"),zt){let Ye=o.features?.artifacts?.layout;ld=Ye?.unifiedSplitOuterRadius?.trim()||Ye?.paneBorderRadius?.trim()||Xe}else ld=null;let Ut=pr?.border!=null||Q?.border!=null;if(d&&!kt&&!Lo&&!fe&&!zt&&!Ut&&(Pe.style.border="none",Do(o).side==="right"?Pe.style.borderLeft="1px solid var(--persona-border)":Pe.style.borderRight="1px solid var(--persona-border)"),d&&!kt&&zt&&!Ut&&(Do(o).side==="right"?Se.style.borderLeft="1px solid var(--persona-border)":Se.style.borderRight="1px solid var(--persona-border)"),y&&(t.style.display="flex",t.style.flexDirection="column",t.style.height="100%",t.style.minHeight="0",w&&(t.style.width="100%"),dt.style.display="flex",dt.style.flexDirection="column",dt.style.flex="1 1 0%",dt.style.minHeight="0",dt.style.maxHeight="100%",dt.style.height="100%",w&&(dt.style.overflow="hidden"),Se.style.display="flex",Se.style.flexDirection="column",Se.style.flex="1 1 0%",Se.style.minHeight="0",Se.style.maxHeight="100%",Se.style.height="100%",fe||(Se.style.overflow="hidden"),Pe.style.display="flex",Pe.style.flexDirection="column",Pe.style.flex="1 1 0%",Pe.style.minHeight="0",Pe.style.maxHeight="100%",Pe.style.overflow="hidden",pe.style.flex="1 1 0%",pe.style.minHeight="0",pe.style.overflowY="auto",Qe.style.flexShrink="0"),w&&(Lo||fe||jt)&&!d&&(jt||(dt.style.padding="var(--persona-panel-inset)"),dt.style.background="var(--persona-panel-canvas-bg)"),dt.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!f&&!w&&!d&&(vo[Jt]??vo["bottom-right"]).split(" ").forEach(st=>dt.classList.add(st)),f){let Ye=Nr(o).sidebarWidth?o.launcher?.sidebarWidth??"420px":Rn(qr(o),"components.panel.width")??"420px";k?dt.style.cssText=`
|
|
1211
1211
|
position: fixed !important;
|
|
1212
1212
|
top: var(--persona-panel-inset) !important;
|
|
1213
1213
|
bottom: var(--persona-panel-inset) !important;
|
|
@@ -1265,7 +1265,7 @@ _Details: ${n.message}_`:o}var sh=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
1265
1265
|
border-top: none !important;
|
|
1266
1266
|
padding: 8px 16px 12px 16px !important;
|
|
1267
1267
|
${jt?"background: transparent !important;":""}
|
|
1268
|
-
`)}if(!w&&!d){let Ye="max-height: -moz-available !important; max-height: stretch !important;",st=f?"":"padding-top: 1.25em !important;",tt=f?"":`z-index: ${o.launcher?.zIndex??On} !important;`;dt.style.cssText+=Ye+st+tt}Hm(),Io()},Gm=()=>{t.style.setProperty("--persona-content-max-width",Is(o,xe()))},tv=!1;function nv(){o.layout?.topFade&&pe.scrollTop>1?pe.setAttribute("data-persona-top-fade","true"):pe.removeAttribute("data-persona-top-fade")}let Ym=()=>{nv();let i=Fh(o,xe());xe()&&o.composer?.placement&&o.debug===!0&&!tv&&(tv=!0,console.warn("[persona] composer.placement is ignored in composer-bar mount mode."));let d=Vs();t.setAttribute("data-persona-composer-placement",i),t.setAttribute("data-persona-conversation-state",od),t.setAttribute("data-persona-welcome-anchor",d.anchor??"bottom"),t.style.setProperty("--persona-composer-anchor-gap",d.composerGap??Ou),sd()},ov=()=>{if(xe())return;let i=nn(o),d=o.launcher?.sidebarMode??!1;if(i||d||(o.launcher?.fullHeight??!1)||!_)return;let y=t.ownerDocument.defaultView??window,w=o.launcher?.mobileFullscreen??!0,k=o.launcher?.mobileBreakpoint??640;if(w&&y.innerWidth<=k)return;let q=Ri(o);Se.style.height=q.height,Se.style.maxHeight=q.maxHeight};Km(),gc(t,o),Uc(t,o),qc(t,o),Gm(),Ym(),Us=()=>{Km(),ov(),gc(t,o),Uc(t,o),qc(t,o),Gm(),Ym(),ld?t.style.setProperty("--persona-artifact-welded-outer-radius",ld):t.style.removeProperty("--persona-artifact-welded-outer-radius"),ft(),Mn()};let _e=[];_e.push(()=>{Gb=!0}),_e.push(()=>{g.forEach(i=>i()),m.destroy()}),_e.push(()=>{document.removeEventListener("keydown",Xb)}),_e.push(()=>{rl!==null&&clearTimeout(rl)});let or=null,rr=null;_e.push(()=>{or?.(),or=null,rr?.(),rr=null}),ll&&_e.push(()=>{ll?.disconnect(),ll=null}),_e.push(()=>{pl?.(),pl=null,jm(),en&&(en.remove(),en=null),gt?.element.style.removeProperty("width"),gt?.element.style.removeProperty("maxWidth"),gt?.destroy()}),ie&&_e.push(()=>{Fe=!0,Z=null,Bt!==null&&(cancelAnimationFrame(Bt),Bt=null),Re?.destroy(),Re=null,ct?.destroy(),ct=null,rt=null});let js=null,rv=()=>{js&&(js(),js=null),o.colorScheme==="auto"&&(js=Du(()=>{gc(t,o)}))};rv(),_e.push(()=>{js&&(js(),js=null)}),_e.push(()=>{T=!0,E?.()}),_e.push(()=>{W=!0});let sv=!1;_e.push(()=>{sv=!0});let Qm=(i,d)=>{let f=vc(i,d);return f||!iM.includes(i)?f:(MM().then(y=>{if(sv)return;Ei(y.wipe),Ei(y.glyphCycle);let w=vc(i,d);w&&xc(w,t)}).catch(()=>{}),null)},hd=o.features?.streamAnimation;if(hd?.type&&hd.type!=="none"){let i=Qm(hd.type,hd.plugins);i&&xc(i,t),_e.push(()=>aM(t))}let Mr=kc(lo),iv=kc(Ns),av=kc(Xo),Ks=[Mr,iv,av];_e.push(()=>{Ks.forEach(i=>i.destroy())});let Gs=null,N,Ys=null,lv=!1,cv=0,dv=null,pv=i=>i.reduce((d,f)=>f.role==="user"?d+1:d,0),uv=i=>{for(let d=i.length-1;d>=0;d--)if(ql(i[d]))return i[d].id??null;return null},mv=!1,B0=()=>{mv||o.debug!==!0||(mv=!0,console.warn('[persona] suggestions.starters.placement is pinned to "welcome" but the welcome surface is hidden (welcome.variant: "none" or copy.showWelcomeCard: false), so no starters render. Use "auto" or "composer".'))},fv=!1,gv=!1,hv=(i,d)=>{fv||o.debug!==!0||!d.enabled||d.expose||lv||gv&&(N.isStreaming()||i.some(ql)||(fv=!0,console.info("[persona] Follow-up suggestions are enabled but the agent has not called suggest_replies. The model needs the tool declared (runtimeTools server-side, suggestions.followUps.expose: true from the widget, or your own backend's tool definition) and benefits from instructions telling it when to offer follow-ups. See the integration paths table in UI-COMPONENTS.md.")))},Qs=i=>{if(!N)return;let d=i??N.getMessages(),f=he=>{he.render([],N,we,d)},y=he=>{Ks.forEach(De=>{De!==he&&f(De)})};Ys&&(pv(d)>cv||uv(d)!==dv)&&(Ys=null);let w=Ms(o);hv(d,w);let k=w.enabled?gx(d):null,q=Ys??k,te=Ys?"host":"agent";if(q){let he=o.suggestions?.followUps,De=he?.placement??(he?"auto":"composer"),It=(De==="auto"?xe()?"composer":"after-message":De)==="after-message"?av:Mr;y(It),It.render(q,N,we,d,o.suggestionChipsConfig,{source:te,surface:"followUp",variant:he?.variant??"chip",behavior:he?.behavior??"send",overflow:he?.overflow??"wrap",maxItems:he?.maxItems??4,config:o,plugins:u,submitPrompt:op});return}if(d.some(he=>he.role==="user")){Ks.forEach(f);return}let Q=o.future?.v5Defaults===!0,re=sl(),ce=o.suggestions?.starters??(Q?{}:void 0);if(ce){let he=Ua(Vs(),d),De=ce.placement??"auto",lt=De==="auto"?he?"welcome":"composer":De;if(lt==="welcome"&&!he){B0(),Ks.forEach(f);return}let It=lt==="welcome"?iv:Mr;y(It),It.render(ce.items??o.suggestionChips,N,we,d,o.suggestionChipsConfig,{surface:"starter",variant:ce.variant??(Q&&!re?"chip":"card"),behavior:ce.behavior??"send",overflow:ce.overflow??"wrap",maxItems:ce.maxItems??(Q&&!re?3:4),config:o,plugins:u,submitPrompt:op});return}y(Mr),Mr.render(o.suggestionChips,N,we,d,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",maxItems:4,config:o,plugins:u,submitPrompt:op})},yv=()=>{Ys&&(Ys=null,Qs())},D0=i=>{let d=Array.isArray(i)?[...i]:[];if(!d.length){yv();return}let f=N?N.getMessages():[];Ys=d,lv=!0,cv=pv(f),dv=uv(f),Qs(f)},uo=!1,mn=JA(),Qi=new Map,Xs=new Map,ns=new Map,Js=null,os=null;function Zs(){if(!Js)return;let i=Js;Js=null,os?.destroy(),os=null,mn.delete(i),Pe.querySelector(`#wrapper-${i}`)?.removeAttribute("data-preserve-runtime"),N&&xo(We,N.getMessages(),j)}let ei=0,O0=Ro()!==null,mo=$u(),fo=0,rs=null,Jn=!1,yd=!1,ss=0,wn=null,ti=null,Xm=!1,Xi=!1,ni=null,ul=!0,bd=!1,Ji=null,vd=!1,is=()=>{vd=!0,V0()},Jm=null,_0=4,Tr=24,N0=80,F0=1e3,Er=null,bv=()=>{t.setAttribute("data-persona-scrollbar",Lm()),Lm()!=="on-scroll"&&(Er!==null&&clearTimeout(Er),Er=null,pe.removeAttribute("data-persona-scrollbar-visible"))},V0=()=>{Lm()==="on-scroll"&&(pe.setAttribute("data-persona-scrollbar-visible",""),Er!==null&&clearTimeout(Er),Er=setTimeout(()=>{Er=null,jr(pe,Tr)&&pe.removeAttribute("data-persona-scrollbar-visible")},F0))};bv(),_e.push(()=>{Er!==null&&clearTimeout(Er)});let Zm=new Map,wt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};_o();let vv=o.voiceRecognition?.autoResume??!1,kr=i=>{R.emit("voice:state",{active:wt.active,source:i,timestamp:Date.now()})},Vo=()=>{de(i=>({...i,voiceState:{active:wt.active,timestamp:Date.now(),manuallyDeactivated:wt.manuallyDeactivated}}))},$0=()=>{if(o.voiceRecognition?.enabled===!1)return;let i=yb(L.voiceState),d=!!i.active,f=Number(i.timestamp??0);wt.manuallyDeactivated=!!i.manuallyDeactivated,d&&Date.now()-f<tD&&setTimeout(()=>{wt.active||(wt.manuallyDeactivated=!1,so(o.voiceRecognition?.provider)?N.toggleVoice().then(()=>{wt.active=N.isVoiceActive(),kr("restore"),N.isVoiceActive()&&ba()}):ip("restore"))},1e3)},z0=()=>N?t0(N.getMessages()).filter(i=>!i.__skipPersist):[],Cd=null,Cv=(i,d)=>{typeof console<"u"&&console.error(i,d)},wd=(i,d)=>{let f=()=>{try{let q=i();return!q||typeof q.then!="function"?null:Promise.resolve(q).catch(te=>{Cv(d,te)})}catch(q){return Cv(d,q),null}},y=Cd,w=y?y.then(()=>f()??void 0):f();if(!w)return;let k=w.finally(()=>{Cd===k&&(Cd=null)});Cd=k};function Zi(i){if(!x?.save)return;let d=i?t0(i):N?z0():[],f=P&&N?.getResumableHandle();f&&(L={...L,durableResume:{executionId:f.executionId,after:f.lastEventId}});let y={messages:d,metadata:L,artifacts:wo.artifacts,selectedArtifactId:wo.selectedId,...oi?{draft:oi}:{}};wd(()=>x.save(y),"[AgentWidget] Failed to persist state:")}let oi,xd=()=>!x?.save||o.persistState===!1?!1:typeof o.persistState=="object"?o.persistState.persist?.draft!==!1:!0,ml=GS({write:()=>{if(!xd())return;let i=ze.getState(),d=jS({text:i.text,mentionRefs:i.mentionRefs,contentSegments:Jf(),selectedModelId:i.selectedModelId,activeModeIds:i.activeModeIds,quote:i.quote});JSON.stringify(d)!==JSON.stringify(oi)&&(oi=d,Zi())}});function wv(){xd()&&ml.schedule()}function ef(){ml.flush()}function xv(i){if(!xd())return;let d=KS(i,{mentionSourceIds:(o.contextMentions?.sources??[]).map(f=>f.id),modelIds:(o.composer?.models??[]).map(f=>f.id),modes:o.composer?.modes??[]});d&&(oi=i,we&&!we.value&&(we.value=d.text,we.dispatchEvent(new Event("input",{bubbles:!0})),Zo()),d.selectedModelId&&(ze.setSelectedModelId(d.selectedModelId),Zr?.repaint()),id(d.activeModeIds??[]),d.quote&&er(d.quote),ml.cancel())}function Sd(){ml.cancel(),oi&&(oi=void 0,xd()&&Zi())}let ea=null,Sv=()=>dt.querySelector("#persona-scroll-container")||pe,ta=()=>{ea!==null&&(cancelAnimationFrame(ea),ea=null),Jn=!1},Av=()=>{rs!==null&&(cancelAnimationFrame(rs),rs=null),yd=!1,ta()},U0=()=>uo&&nf()&&(po()!=="anchor-top"||Tb()),tf=()=>{let i=tl()||"Jump to latest",d=U0();hn.toggleAttribute("data-persona-scroll-to-bottom-streaming",d),ss>0?(Fs.textContent=String(ss),Fs.style.display="",hn.setAttribute("aria-label",`${i} (${ss} new)`)):(Fs.textContent="",Fs.style.display="none",hn.setAttribute("aria-label",d?`${i} (response streaming below)`:i))},Mv=()=>{ss!==0&&(ss=0,tf())},q0=()=>{let i=wn?.spacerHeight??0;return i<=0?jr(pe,Tr):Ed(i)-pe.scrollTop-pe.clientHeight<=Tr},nf=()=>Jr()?!mo.isFollowing():!q0(),of=()=>!!N&&N.getMessages().length>0,xn=()=>{if(!C0()||ao()){hn.parentNode&&hn.remove(),hn.style.display="none";return}hn.parentNode!==Pe&&Pe.appendChild(hn),$s();let d=br(pe)>0&&nf()&&of();d?tf():Mv(),hn.style.display=d?"":"none"},na=()=>{mo.pause()&&(Av(),xn())},Zn=()=>{mo.resume(),Mv(),xn()},as=(i=!1)=>{Jr()&&of()&&mo.isFollowing()&&(!i&&!uo||(rs!==null&&(cancelAnimationFrame(rs),rs=null),yd=!0,rs=requestAnimationFrame(()=>{rs=null,yd=!1,mo.isFollowing()&&j0(Sv(),i?220:140)})))},Tv=(i,d,f,y=()=>!0)=>{let w=i.scrollTop,k=d(),q=k-w;if(ta(),Math.abs(q)<1){Jn=!0,i.scrollTop=k,fo=i.scrollTop,Jn=!1;return}let te=performance.now();Jn=!0;let Q=ce=>1-Math.pow(1-ce,3),re=ce=>{if(!y()){ta();return}let he=d();he!==k&&(k=he,q=k-w);let De=ce-te,lt=Math.min(De/f,1),It=Q(lt),kt=w+q*It;i.scrollTop=kt,fo=i.scrollTop,lt<1?ea=requestAnimationFrame(re):(i.scrollTop=k,fo=i.scrollTop,ea=null,Jn=!1)};ea=requestAnimationFrame(re)},j0=(i,d=500)=>{let f=br(i)-i.scrollTop;if(Math.abs(f)<1){fo=i.scrollTop;return}if(Math.abs(f)>=N0){ta(),Jn=!0,i.scrollTop=br(i),fo=i.scrollTop,Jn=!1;return}Tv(i,()=>br(i),d,()=>mo.isFollowing())},Ad=()=>{if(!of()){xn();return}let i=Sv();Jn=!0,i.scrollTop=br(i),fo=i.scrollTop,Jn=!1,xn()},ri=i=>{let d=0,f=i;for(;f&&f!==pe;)d+=f.offsetTop,f=f.offsetParent;return d},K0=()=>{let i=pe.getRootNode();return(typeof i.getSelection=="function"?i.getSelection():null)??pe.ownerDocument.getSelection()},Md=()=>oM(K0(),pe),rf=()=>{if(w0()!=="last-user-turn")return!1;let i=N?.getMessages()??[];if(i.length<2)return!1;let d=[...i].reverse().find(k=>k.role==="user");if(!d)return!1;let f=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(d.id):d.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),y=pe.querySelector(`[data-message-id="${f}"]`);if(!y)return!1;let w=Math.min(Math.max(0,ri(y)-nl()),br(pe));return Jn=!0,pe.scrollTop=w,fo=pe.scrollTop,Jn=!1,po()==="follow"&&!jr(pe,Tr)&&mo.pause(),xn(),!0},Td=i=>{let d=Math.max(0,Math.round(i));Co.style.height=`${d}px`,Co.style.display=d>0?"":"none",wn&&(wn.spacerHeight=Math.max(0,i))},Ed=i=>{let d=parseFloat(getComputedStyle(pe).paddingBottom)||0,f=0;for(let w of Array.from(pe.children)){if(w===Co||w.offsetHeight===0)continue;let k=ri(w)+w.offsetHeight;k>f&&(f=k)}let y=pe.scrollHeight-i;return f>0?Math.min(f+d,y):y},G0=()=>{if(!wn||wn.spacerHeight<=0)return;let i=Ed(wn.spacerHeight),d=Math.max(0,Math.round(pe.scrollTop)+pe.clientHeight-i+Tr);d<wn.spacerHeight&&(Td(d),xn())},$o=()=>{ti!==null&&(cancelAnimationFrame(ti),ti=null),ta(),wn=null,Co.style.height="0px",Co.style.display="none"},Ev=i=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(i):i.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),sf=i=>pe.querySelector(`[data-message-id="${Ev(i)}"]`),kv=i=>{ti!==null&&cancelAnimationFrame(ti),ti=requestAnimationFrame(()=>{ti=null;let d=Ev(i),f=pe.querySelector(`[data-message-id="${d}"]`);if(!f)return;let y=ri(f),w=wn?.spacerHeight??0,k=Ed(w),{targetScrollTop:q,spacerHeight:te}=zh({anchorOffsetTop:y,topOffset:nl(),viewportHeight:pe.clientHeight,contentHeight:k,slack:Tr});wn={initialSpacerHeight:te,contentHeightAtAnchor:k,spacerHeight:te},Td(te),Tv(pe,()=>f.isConnected?Math.max(0,ri(f)-nl()):q,220)})},eo=()=>{if(po()!=="anchor-top"||!wn||!Ji)return;let i=sf(Ji);if(!i)return;ta();let d=wn.spacerHeight,f=Ed(d),{targetScrollTop:y,spacerHeight:w}=zh({anchorOffsetTop:ri(i),topOffset:nl(),viewportHeight:pe.clientHeight,contentHeight:f,slack:Tr});wn={initialSpacerHeight:w,contentHeightAtAnchor:f,spacerHeight:w},Td(w),Jn=!0,pe.scrollTop=y,fo=pe.scrollTop,Jn=!1,xn()},Y0=()=>{if(Jr()){if(!mo.isFollowing()||jr(pe,1))return;as(!uo);return}if(wn&&wn.initialSpacerHeight>0){let i=pe.scrollHeight-wn.spacerHeight,d=rM({initialSpacerHeight:wn.initialSpacerHeight,contentHeightAtAnchor:wn.contentHeightAtAnchor,currentContentHeight:i});d!==wn.spacerHeight&&Td(d)}xn()},Q0=i=>{let d=po();d==="follow"?(Zn(),as(!0)):d==="anchor-top"&&(ul=!1,bd=!0,vd=!1,Ji=i,kv(i))},X0=()=>{if(po()==="anchor-top"){if(bd){ul=!1;return}ul=!0,$o(),Zn(),as(!0)}},J0=96,Z0=i=>{if(ni===null)return!0;let d=sf(ni),f=sf(i);if(!d||!f)return!0;let y=ri(f)-ri(d);return nl()+y>pe.clientHeight-J0},ek=i=>{if(po()!=="anchor-top"||!bd||vd||Md())return;let d=ni===null;for(let f of i){if(!d){f.id===ni&&(d=!0);continue}if(nM(f)){if(f.id===Ji||!Z0(f.id))return;Ji=f.id,kv(f.id);return}}},tk=i=>{let d=new Map;i.forEach(f=>{let y=Zm.get(f.id);d.set(f.id,{streaming:f.streaming,role:f.role}),!y&&f.role==="assistant"&&(R.emit("assistant:message",f),!Xi&&(po()!=="anchor-top"||Tb())&&nf()&&(ss+=1,tf(),xn(),nd(ss===1?"1 new message below.":`${ss} new messages below.`))),f.role==="assistant"&&y?.streaming&&f.streaming===!1&&R.emit("assistant:complete",f),f.variant==="approval"&&f.approval&&(y?f.approval.status!=="pending"&&R.emit("approval:resolved",{approval:f.approval,decision:f.approval.status}):R.emit("approval:requested",{approval:f.approval,message:f}))}),Zm.clear(),d.forEach((f,y)=>{Zm.set(y,f)})},fl=(i,d)=>{let f=d==="user"?"user":"assistant",y=o.layout?.messages?.[f],w=y?.width??"content",k=y?.maxWidth??(w==="full"?`var(--persona-message-${f}-max-width, 100%)`:void 0);i.classList.add("persona-message-row"),i.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),i.classList.add(`persona-message-row-${d}`,`persona-message-width-${w}`),i.classList.toggle("persona-justify-end",d==="user"),i.setAttribute("data-message-role",d),i.setAttribute("data-message-width",w),k?i.style.setProperty("--persona-message-row-max-width",k):i.style.removeProperty("--persona-message-row-max-width")},Pr=(i,d)=>{let f=document.createElement("div");return f.className="persona-flex",f.id=`wrapper-${i}`,f.setAttribute("data-wrapper-id",i),fl(f,d),f},nk=(i,d,f)=>{let y=new Set;for(let $ of d){let Xe=$.variant==="tool"?"tool":$.variant==="reasoning"?"reasoning":null;if(!Xe||vs(o,Xe)!=="row")continue;let Je=Xe==="tool"?o.features?.toolCallDisplay:o.features?.reasoningDisplay;Je?.expandable!==!1&&(y.add($.id),a.observe($,Xe,Xe==="tool"?r:s,Je))}let w=document.createElement("div"),q=(()=>{let $=u.find(Xe=>Xe.renderLoadingIndicator);if($?.renderLoadingIndicator)return $.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),te=($,Xe)=>Xe==null?!1:typeof Xe=="string"?($.textContent=Xe,!0):($.appendChild(Xe),!0),Q=new Set,re=new Map,ce=new Set,he=u.some($=>$.renderAskUserQuestion),De=[],lt=[],It=o.enableComponentStreaming!==!1,kt=o.approval!==!1,no=[],Jt=o.messageActions,rn=Jt?.showRegenerate===!0&&Jt.enabled!==!1&&Ft.current?.isStreaming()!==!0?Kx(d):null,Vn=Jt?.showEdit===!0&&Jt.enabled!==!1,ln=Jt?.showQuote===!0&&Jt.enabled!==!1,$t=null,cr=o.features?.reasoningDisplay?.completedVisibility,dr=$=>cr==="removed"?!0:cr==="removed-when-short"?bx($,o.features?.reasoningDisplay?.shortThinkThreshold):!1,Po=o.features?.toolCallDisplay?.completedVisibility==="removed",Lo=$=>$.variant==="reasoning"&&$.reasoning?.status==="complete"?dr($.reasoning):Po&&$.variant==="tool"&&$.toolCall?.status==="complete";if(d.forEach($=>{if(Lo($))return;if(Q.add($.id),re.set($.id,$.role),Js===$.id&&os){let et=Pr($.id,$.role);et.setAttribute("data-persona-message-edit-stub","true"),et.setAttribute("data-preserve-runtime","true"),w.appendChild(et),$t={messageId:$.id,element:os.element};return}let Xe=he&&Ai($),Je=kt&&$.variant==="approval"&&!!$.approval,fe=!Xe&&$.role==="assistant"&&!$.variant&&It&&hb($);!Je&&ns.has($.id)&&(i.querySelector(`#wrapper-${$.id}`)?.removeAttribute("data-preserve-runtime"),ns.delete($.id)),!fe&&Xs.has($.id)&&(i.querySelector(`#wrapper-${$.id}`)?.removeAttribute("data-preserve-runtime"),Xs.delete($.id));let zt=Ai($)?`:${$.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${$.agentMetadata?.askUserQuestionAnswers?Object.keys($.agentMetadata.askUserQuestionAnswers).length:0}`:"",fn={canRegenerate:rn===$.id,canEdit:Vn&&Yg($),canQuote:ln&&!$.variant&&($.content?.trim().length??0)>0},_n=`${fn.canRegenerate?"r":""}${fn.canEdit?"e":""}${fn.canQuote?"q":""}`,En=XA($,ei)+zt+`:${_n}`,jt=Xe||Je||fe?null:ZA(mn,$.id,En);if(jt){w.appendChild(jt.cloneNode(!0)),Ai($)&&$.toolCall?.id&&$.agentMetadata?.awaitingLocalTool===!0&&!$.agentMetadata?.askUserQuestionAnswered&&(ce.add($.toolCall.id),_p($,o,ot.composerOverlay));return}let cn=null,Sn=u.find(et=>!!($.variant==="reasoning"&&et.renderReasoning||$.variant==="tool"&&et.renderToolCall||!$.variant&&et.renderMessage)),Ke=o.layout?.messages;if(Ai($)&&$.agentMetadata?.askUserQuestionAnswered===!0){Qi.delete($.id),i.querySelector(`#wrapper-${$.id}`)?.removeAttribute("data-preserve-runtime");return}if(ql($)&&Ms(o).enabled)return;if(Ai($)&&o.features?.askUserQuestion?.enabled!==!1){let et=u.find(An=>typeof An.renderAskUserQuestion=="function");if(et&&Ft.current){let An=Qi.get($.id),Io=An!==En,kn=null;if(Io){let{payload:st,complete:tt}=ka($),ys=$.id,bn=()=>Ft.current?.getMessages().find(oo=>oo.id===ys);kn=et.renderAskUserQuestion({message:$,payload:st,complete:tt,resolve:oo=>{let Or=bn();Or&&Ft.current?.resolveAskUserQuestion(Or,oo)},dismiss:()=>{let oo=bn();oo?.agentMetadata?.awaitingLocalTool&&(Ft.current?.markAskUserQuestionResolved(oo),Ft.current?.resolveAskUserQuestion(oo,"(dismissed)"))},config:o})}let Ut=An!=null;if(Io&&kn===null&&!Ut){$.agentMetadata?.awaitingLocalTool===!0&&!$.agentMetadata?.askUserQuestionAnswered&&(ce.add($.toolCall.id),_p($,o,ot.composerOverlay));return}let Ye=Pr($.id,$.role);Ye.setAttribute("data-ask-plugin-stub","true"),Ye.setAttribute("data-preserve-runtime","true"),w.appendChild(Ye),De.push({messageId:$.id,fingerprint:En,bubble:kn});return}else{$.agentMetadata?.awaitingLocalTool===!0&&!$.agentMetadata?.askUserQuestionAnswered&&(ce.add($.toolCall.id),_p($,o,ot.composerOverlay));return}}else if(Je){let et=D();if(!et){w.appendChild(Pr($.id,$.role));return}let An=u.find(Ye=>typeof Ye.renderApproval=="function")??M,kn=ns.get($.id)!==En,Ut=null;if(kn&&An?.renderApproval){let Ye=$.id,st=(tt,ys)=>{let bn=Ft.current?.getMessages().find(oo=>oo.id===Ye);bn?.approval&&(bn.approval.toolType==="webmcp"?Ft.current?.resolveWebMcpApproval(bn.id,tt):Ft.current?.resolveApproval(bn.approval,tt,ys))};Ut=An.renderApproval({message:$,defaultRenderer:()=>et.createApprovalBubble($,o,l),config:o,approve:tt=>st("approved",tt),deny:tt=>st("denied",tt)})}if(kn&&Ut===null)i.querySelector(`#wrapper-${$.id}`)?.removeAttribute("data-preserve-runtime"),ns.delete($.id),cn=et.createApprovalBubble($,o,l);else{let Ye=Pr($.id,$.role);Ye.setAttribute("data-approval-plugin-stub","true"),Ye.setAttribute("data-preserve-runtime","true"),w.appendChild(Ye),no.push({messageId:$.id,fingerprint:En,bubble:Ut});return}}else if(Sn)if($.variant==="reasoning"&&$.reasoning&&Sn.renderReasoning){if(!J)return;cn=Sn.renderReasoning({message:$,defaultRenderer:()=>yy($,o,s),config:o})}else if($.variant==="tool"&&$.toolCall&&Sn.renderToolCall){if(!Y)return;cn=Sn.renderToolCall({message:$,defaultRenderer:()=>wy($,o,r),config:o})}else Sn.renderMessage&&(cn=Sn.renderMessage({message:$,defaultRenderer:()=>{let et=iy($,f,Ke,o.messageActions,Gn,{loadingIndicatorRenderer:q,widgetConfig:o,actionEligibility:fn});return $.role!=="user"&&O(et,$,o,N),et},config:o}));if(!cn&&fe){let et=JE($);if(et){let An=Xs.get($.id),Io=An!==En,kn=o.wrapComponentDirectiveInBubble!==!1&&Yo.getOptions(et.component)?.bubbleChrome!==!1,Ut=null;if(Io){let Ye=QE(et,{config:o,message:$,transform:f});if(Ye&&et.component==="PersonaArtifactInline"){let st=Ye.hasAttribute("data-artifact-inline")?Ye:Ye.querySelector("[data-artifact-inline]"),tt=st?.getAttribute("data-artifact-inline")??"",ys=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(tt):tt,bn=tt?i.querySelector(`#wrapper-${$.id}`)?.querySelector(`[data-artifact-inline="${ys}"]`)??null:null;st&&bn&&bn!==st&&Gr()?.hasLiveInlineArtifactBlock(bn)&&(st===Ye?Ye=bn:st.replaceWith(bn))}if(Ye)if(kn){let st=document.createElement("div");if(st.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),st.id=`bubble-${$.id}`,st.setAttribute("data-message-id",$.id),$.content&&$.content.trim()){let tt=document.createElement("div");tt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",tt.innerHTML=f({text:$.content,message:$,streaming:!!$.streaming,raw:$.rawContent}),st.appendChild(tt)}st.appendChild(Ye),Ut=st}else{let st=document.createElement("div");if(st.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",st.id=`bubble-${$.id}`,st.setAttribute("data-message-id",$.id),st.setAttribute("data-persona-component-directive","true"),$.content&&$.content.trim()){let tt=document.createElement("div");tt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",tt.innerHTML=f({text:$.content,message:$,streaming:!!$.streaming,raw:$.rawContent}),st.appendChild(tt)}st.appendChild(Ye),Ut=st}}if(Ut||An!=null){let Ye=Pr($.id,$.role);Ye.setAttribute("data-component-directive-stub","true"),Ye.setAttribute("data-preserve-runtime","true"),w.appendChild(Ye),lt.push({messageId:$.id,fingerprint:En,bubble:Ut});return}}}if(!cn)if($.variant==="reasoning"&&$.reasoning){if(!J)return;cn=yy($,o,s)}else if($.variant==="tool"&&$.toolCall){if(!Y)return;cn=wy($,o,r)}else if($.variant==="approval"&&$.approval){if(o.approval===!1)return;let et=D();if(!et)return;cn=et.createApprovalBubble($,o,l)}else{let et=o.layout?.messages;et?.renderUserMessage&&$.role==="user"?cn=et.renderUserMessage({message:$,config:o,streaming:!!$.streaming}):et?.renderAssistantMessage&&$.role==="assistant"?cn=et.renderAssistantMessage({message:$,config:o,streaming:!!$.streaming}):cn=iy($,f,et,o.messageActions,Gn,{loadingIndicatorRenderer:q,widgetConfig:o,actionEligibility:fn}),$.role!=="user"&&cn&&O(cn,$,o,N)}let Kt=Pr($.id,$.role);Kt.appendChild(cn),eM(mn,$.id,En,Kt),w.appendChild(Kt)}),ot.composerOverlay&&ot.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Xe=>{let Je=Xe.getAttribute("data-persona-ask-sheet-for");Je&&!ce.has(Je)&&La(ot.composerOverlay,Je)}),o.features?.toolCallDisplay?.grouped){let $=[],Xe=[],Je=o.features.toolCallDisplay.groupedMode==="summary";d.forEach(fe=>{if(fe.variant==="tool"&&fe.toolCall&&Y){if(Po&&fe.toolCall.status==="complete")return;Xe.push(fe);return}fe.variant==="reasoning"&&(!J||fe.reasoning?.status==="complete"&&dr(fe.reasoning))||((Xe.length>1||Je&&Xe.length>0)&&$.push(Xe),Xe=[])}),(Xe.length>1||Je&&Xe.length>0)&&$.push(Xe),$.forEach(fe=>{let zt=fe.map(Ke=>Array.from(w.children).find(Kt=>Kt instanceof HTMLElement&&Kt.getAttribute("data-wrapper-id")===Ke.id)).filter(Ke=>!!Ke);if(zt.length<(Je?1:2))return;let fn=Pr(`tool-group-${fe[0].id}`,"assistant");if(fn.setAttribute("data-persona-tool-group-row","true"),o.features?.toolCallDisplay?.groupedMode==="collapsible"){let Ke=`tool-group-${fe[0].id}`,Kt=fe.some(Ut=>Ut.toolCall?.status!=="complete"),et={...fe[0],id:Ke,toolCall:{id:Ke,name:`${fe.length} tools`,status:Kt?"running":"complete",chunks:fe.flatMap(Ut=>Ut.toolCall?.chunks??[]),success:!fe.some(Ut=>Ut.toolCall?.success===!1)}};y.add(Ke),a.observe(et,"tool",r,o.features.toolCallDisplay);let An=`${Kt?"Using":"Used"} ${fe.length} tools`,Io=o.toolCall?.renderGroupedSummary?.({messages:fe,toolCalls:fe.map(Ut=>Ut.toolCall),defaultSummary:An,config:o}),kn=Mw(et,o,r.has(Ke),Io??An);kn.bubble.classList.add("persona-tool-group"),kn.body.dataset.personaToolGroupStack="true",zt[0].before(fn),fn.appendChild(kn.bubble),zt.forEach((Ut,Ye)=>{Ut.style.setProperty("--persona-message-row-max-width","100%"),Ut.style.setProperty("--persona-activity-stagger",`${Ye*40}ms`),Ut.classList.add("persona-activity-group-child"),kn.body.appendChild(Ut)});return}let _n=document.createElement("div");_n.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",_n.setAttribute("data-persona-tool-group","true");let En=document.createElement("div");En.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",En.id=`tool-group-summary-${fe[0].id}`;let jt=`Called ${fe.length} ${fe.length===1?"tool":"tools"}`,cn=o.toolCall?.renderGroupedSummary?.({messages:fe,toolCalls:fe.map(Ke=>Ke.toolCall).filter(Ke=>!!Ke),defaultSummary:jt,config:o});te(En,cn)||(En.textContent=jt);let Sn=document.createElement("div");Sn.className="persona-tool-group-stack persona-flex persona-flex-col",Sn.id=`tool-group-stack-${fe[0].id}`,Sn.setAttribute("data-persona-tool-group-stack","true"),_n.appendChild(En),Je||_n.appendChild(Sn),fn.appendChild(_n),zt[0].before(fn),zt.forEach((Ke,Kt)=>{if(Je){Ke.remove();return}Ke.style.setProperty("--persona-message-row-max-width","100%");let et=document.createElement("div");et.className="persona-tool-group-item persona-relative",et.setAttribute("data-persona-tool-group-item","true"),Kt<zt.length-1&&et.setAttribute("data-persona-tool-group-connector","true"),et.appendChild(Ke),Sn.appendChild(et)})})}a.prune(y),tM(mn,Q);let gs=$=>$.variant==="tool"&&!Y||$.variant==="reasoning"&&!J||Lo($),pr=d.some($=>$.role==="assistant"&&$.streaming&&!gs($)),zo=d.length-1;for(;zo>=0&&gs(d[zo]);)zo--;let hs=zo>=0?d[zo]:void 0,Ol=zo<d.length-1,hi=hs?.role==="assistant"&&!hs.streaming&&hs.variant!=="approval"&&!Ol;if(uo&&d.some($=>$.role==="user")&&!pr&&!hi){let $={config:o,streaming:!0,location:"standalone",defaultRenderer:Rc},Xe=u.find(fe=>fe.renderLoadingIndicator),Je=null;if(Xe?.renderLoadingIndicator&&(Je=Xe.renderLoadingIndicator($)),Je===null&&o.loadingIndicator?.render&&(Je=o.loadingIndicator.render($)),Je===null&&(Je=Rc()),Je){let fe=document.createElement("div"),zt=o.loadingIndicator?.showBubble!==!1,fn=o.layout?.messages?.layout??"bubble";fe.className=zt?Hc("assistant",fn).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),fe.setAttribute("data-typing-indicator","true"),zt&&(fe.style.color="var(--persona-message-assistant-text, var(--persona-text))",fn!=="flat"&&(fe.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",fe.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),fe.appendChild(Je);let _n=Pr("typing-indicator","assistant");_n.appendChild(fe),w.appendChild(_n)}}if(!uo&&d.length>0){let $=d[d.length-1],Xe={config:o,lastMessage:$,messageCount:d.length},Je=u.find(zt=>zt.renderIdleIndicator),fe=null;if(Je?.renderIdleIndicator&&(fe=Je.renderIdleIndicator(Xe)),fe===null&&o.loadingIndicator?.renderIdle&&(fe=o.loadingIndicator.renderIdle(Xe)),fe){let zt=document.createElement("div"),fn=o.loadingIndicator?.showBubble!==!1;zt.className=fn?["persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),zt.setAttribute("data-idle-indicator","true"),zt.appendChild(fe);let _n=Pr("idle-indicator","assistant");_n.appendChild(zt),w.appendChild(_n)}}if(Vw(w),Vu(i,w),Rg(i),$t){let{messageId:$,element:Xe}=$t,Je=i.querySelector(`#wrapper-${$}`);Je&&Xe.parentElement!==Je&&(fl(Je,re.get($)??"user"),Je.replaceChildren(Xe))}if(De.length>0)for(let{messageId:$,fingerprint:Xe,bubble:Je}of De){let fe=i.querySelector(`#wrapper-${$}`);fe&&(fl(fe,re.get($)??"assistant"),Je!==null&&(fe.replaceChildren(Je),fe.setAttribute("data-bubble-fp",Xe),Qi.set($,Xe)))}if(Qi.size>0)for(let $ of Qi.keys())Q.has($)||Qi.delete($);if(lt.length>0)for(let{messageId:$,fingerprint:Xe,bubble:Je}of lt){let fe=i.querySelector(`#wrapper-${$}`);fe&&(fl(fe,re.get($)??"assistant"),Je!==null&&(fe.replaceChildren(Je),fe.setAttribute("data-bubble-fp",Xe),Xs.set($,Xe)))}if(Xs.size>0)for(let $ of Xs.keys())Q.has($)||Xs.delete($);if(no.length>0)for(let{messageId:$,fingerprint:Xe,bubble:Je}of no){let fe=i.querySelector(`#wrapper-${$}`);fe&&(fl(fe,re.get($)??"assistant"),Je!==null&&(fe.replaceChildren(Je),fe.setAttribute("data-bubble-fp",Xe),ns.set($,Xe)))}if(ns.size>0)for(let $ of ns.keys())Q.has($)||ns.delete($)},af=!1,kd=()=>{af||(af=!0,Hw().catch(()=>{af=!1}))},xo=(i,d,f)=>{d.length>0&&kd(),nk(i,d,f),Kb()},gl=null,ok=()=>{if(gl)return;let i=f=>{let y=f.composedPath();y.includes(dt)||Nt&&y.includes(Nt)||qt(!1,"user")};gl=i,(t.ownerDocument??document).addEventListener("pointerdown",i,!0)},Pv=()=>{if(!gl)return;(t.ownerDocument??document).removeEventListener("pointerdown",gl,!0),gl=null};_e.push(()=>Pv());let hl=null,rk=()=>{if(hl)return;let i=f=>{f.key==="Escape"&&(f.isComposing||qt(!1,"user"))};hl=i,(t.ownerDocument??document).addEventListener("keydown",i,!0)},Lv=()=>{if(!hl)return;(t.ownerDocument??document).removeEventListener("keydown",hl,!0),hl=null};_e.push(()=>Lv());let yl=!1,Iv=new Set,sk=()=>{let i=o.launcher?.composerBar?.peek?.streamAnimation;return i||o.features?.streamAnimation},oa=()=>{if(!xe())return;let i=ot.peekBanner,d=ot.peekTextNode;if(!i||!d)return;if(Ae){i.classList.remove("persona-pill-peek--visible");return}let f=N?.getMessages()??[],y;for(let Jt=f.length-1;Jt>=0;Jt--){let rn=f[Jt];if(rn.role==="assistant"&&rn.content){y=rn;break}}if(!y){i.classList.remove("persona-pill-peek--visible");return}let w=y.content,k=!!y.streaming,q=sk(),te=qu(q),Q=te.type!=="none"?Qm(te.type,q?.plugins):null,re=Q?.isAnimating?.(y)===!0,ce=Q!==null&&(k||re);ce&&Q&&!Iv.has(Q.name)&&(xc(Q,t),Iv.add(Q.name));let he=ce&&Q?.containerClass?Q.containerClass:null,De=d.dataset.personaPeekStreamClass??null;De&&De!==he&&(d.classList.remove(De),delete d.dataset.personaPeekStreamClass),he&&De!==he&&(d.classList.add(he),d.dataset.personaPeekStreamClass=he),ce?(d.style.setProperty("--persona-stream-step",`${te.speed}ms`),d.style.setProperty("--persona-stream-duration",`${te.duration}ms`)):(d.style.removeProperty("--persona-stream-step"),d.style.removeProperty("--persona-stream-duration"));let lt=ce?ju(w,te.buffer,Q,y,k):w;if(ce&&te.placeholder==="skeleton"&&k&&(!lt||!lt.trim())){let Jt=document.createElement("div"),rn=wc();rn.classList.add("persona-pill-peek__skeleton"),Jt.appendChild(rn),Vu(d,Jt)}else{let Jt=Math.max(0,lt.length-100),rn=lt.length>100?lt.slice(-100):lt,Vn=$r(rn);if(!ce||!Q){let ln=lt.length>100?`\u2026${rn}`:rn;d.textContent!==ln&&(d.textContent=ln)}else{let ln=Vn;(Q.wrap==="char"||Q.wrap==="word")&&(ln=Cc(Vn,Q.wrap,`peek-${y.id}`,{skipTags:Q.skipTags,startIndex:Jt}));let $t=document.createElement("div");if($t.innerHTML=ln,Q.useCaret&&rn.length>0){let cr=Ku(),dr=$t.querySelectorAll(".persona-stream-char, .persona-stream-word"),Po=dr[dr.length-1];Po?.parentNode?Po.parentNode.insertBefore(cr,Po.nextSibling):$t.appendChild(cr)}Vu(d,$t),Q.onAfterRender?.({container:d,bubble:i,messageId:y.id,message:y,speed:te.speed,duration:te.duration})}}let no=uo||yl;i.classList.toggle("persona-pill-peek--visible",no)};if(xe()){let i=ot.peekBanner;if(i){let y=w=>{w.preventDefault(),w.stopPropagation(),qt(!0,"user")};i.addEventListener("pointerdown",y),_e.push(()=>{i.removeEventListener("pointerdown",y)})}let d=()=>{yl||(yl=!0,oa())},f=()=>{yl&&(yl=!1,oa())};Se.addEventListener("pointerenter",d),Se.addEventListener("pointerleave",f),_e.push(()=>{Se.removeEventListener("pointerenter",d),Se.removeEventListener("pointerleave",f)}),Nt&&(Nt.addEventListener("pointerenter",d),Nt.addEventListener("pointerleave",f),_e.push(()=>{Nt.removeEventListener("pointerenter",d),Nt.removeEventListener("pointerleave",f)}))}let ik=i=>{let d=o.launcher?.composerBar??{},f=d.expandedSize??"anchored",y=d.bottomOffset??"16px",w=d.collapsedMaxWidth,k=d.expandedMaxWidth??"880px",q=d.expandedTopOffset??"5vh",te=d.modalMaxWidth??"880px",Q=d.modalMaxHeight??"min(90vh, 800px)",re="calc(100vw - 32px)",ce="var(--persona-pill-area-height, 80px)",he=dt.style;if(he.left="",he.right="",he.top="",he.bottom="",he.transform="",he.width="",he.maxWidth="",he.height="",he.maxHeight="",Nt){let De=Nt.style;De.bottom=y,De.width=w??""}if(i&&f!=="fullscreen"){if(f==="modal"){he.top="50%",he.left="50%",he.transform="translate(-50%, -50%)",he.bottom="auto",he.right="auto",he.width=te,he.maxWidth=re,he.maxHeight=Q,he.height=Q;return}he.left="50%",he.transform="translateX(-50%)",he.bottom=`calc(${y} + ${ce})`,he.top=q,he.width=k,he.maxWidth=re}},bl=()=>{if(Ae&&kd(),!Ne())return;if(xe()){let re=(o.launcher?.composerBar??{}).expandedSize??"anchored",ce=Ae?"expanded":"collapsed";dt.dataset.state=ce,dt.dataset.expandedSize=re,Nt&&(Nt.dataset.state=ce,Nt.dataset.expandedSize=re),dt.style.removeProperty("display"),dt.classList.remove("persona-pointer-events-none","persona-opacity-0"),Se.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),ik(Ae),Pe.style.display=Ae?"flex":"none",Us(),Ae?(ok(),rk()):(Pv(),Lv()),oa();return}let i=nn(o),d=t.ownerDocument.defaultView??window,f=o.launcher?.mobileBreakpoint??640,y=o.launcher?.mobileFullscreen??!0,w=d.innerWidth<=f,k=y&&w&&_,q=Do(o).reveal;Ae?(dt.style.removeProperty("display"),dt.style.display=i?"flex":"",dt.classList.remove("persona-pointer-events-none","persona-opacity-0"),Se.classList.remove("persona-scale-95","persona-opacity-0"),Se.classList.add("persona-scale-100","persona-opacity-100"),sn?(sn.setPanelOpen(!0),sn.element.style.display="none"):Fn&&(Fn.style.display="none")):(i?i&&(q==="overlay"||q==="push")&&!k?(dt.style.removeProperty("display"),dt.style.display="flex",dt.classList.remove("persona-pointer-events-none","persona-opacity-0"),Se.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(dt.style.setProperty("display","none","important"),dt.classList.remove("persona-pointer-events-none","persona-opacity-0"),Se.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(dt.style.display="",dt.classList.add("persona-pointer-events-none","persona-opacity-0"),Se.classList.remove("persona-scale-100","persona-opacity-100"),Se.classList.add("persona-scale-95","persona-opacity-0")),sn?(sn.setPanelOpen(!1),sn.element.style.display=i?"none":""):Fn&&(Fn.style.display=i?"none":""))},qt=(i,d="user")=>{if(!Ne()||Ae===i)return;let f=Ae;Ae=i,bl();let y=(()=>{let k=o.launcher?.sidebarMode??!1,q=t.ownerDocument.defaultView??window,te=o.launcher?.mobileFullscreen??!0,Q=o.launcher?.mobileBreakpoint??640,re=q.innerWidth<=Q,ce=nn(o)&&te&&re,he=xe()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return k||te&&re&&_||ce||he})();if(Ae&&y){if(!or){let k=t.getRootNode(),q=k instanceof ShadowRoot?k.host:t.closest(".persona-host");q&&(or=Qh(q,o.launcher?.zIndex??On))}rr||(rr=Xh(t.ownerDocument))}else Ae||(or?.(),or=null,rr?.(),rr=null);Ae&&(Wl(),rf()||(po()==="follow"?as(!0):Ad()));let w={open:Ae,source:d,timestamp:Date.now()};Ae&&!f?R.emit("widget:opened",w):!Ae&&f&&R.emit("widget:closed",w),R.emit("widget:state",{open:Ae,launcherEnabled:_,voiceActive:wt.active,streaming:N.isStreaming()})},ls={inputDisabled:!1,sendDisabled:!1},sr=()=>ls.inputDisabled,lf=()=>so(o.voiceRecognition?.provider)&&!!N&&(N.isBargeInActive()||["listening","processing","speaking"].includes(N.getVoiceStatus())),si=()=>ls.inputDisabled||ls.sendDisabled,ak=()=>(ls.inputDisabled?ls.inputReason:void 0)??(ls.sendDisabled?ls.sendReason:void 0);function cf(){if(!Ve)return;if(ze.getState().phase==="streaming"){Ve.disabled=!1;return}let i=Lt?!Lt.isReady():!1;Ve.disabled=si()||i}function Pd(){if(!Jo)return;let i=ze.getState(),d=o.sendButton?.visibility==="when-text"&&i.phase!=="streaming"&&i.text.trim().length===0&&i.attachments.length===0;Jo.toggleAttribute("data-persona-send-hidden",d)}function lk(){let i=ak();if(xe()){let d=Tn??Qe;i?d.setAttribute("title",i):d.removeAttribute("title"),Qe.toggleAttribute(Za,!!i);return}if(i){pt.setAttribute("role","status"),pt.setAttribute("aria-live","polite"),pt.setAttribute(Za,""),pt.textContent=i,xi(pt,o.statusIndicator??{},"idle");return}if(pt.hasAttribute(Za)&&(pt.removeAttribute("role"),pt.removeAttribute("aria-live"),pt.removeAttribute(Za),h)){let d=N.getStatus();Qo(pt,_s(d),o.statusIndicator??{},d)}}function df(){let i=dh(o.composer?.inputDisabled),d=dh(o.composer?.sendDisabled);ls={inputDisabled:i.disabled,inputReason:i.reason,sendDisabled:d.disabled,sendReason:d.reason},ze.setInputDisabled(i.disabled),ze.setSendDisabled(d.disabled);let f=ze.getState().phase==="streaming",y=i.disabled,w=f||y;we&&(we instanceof HTMLTextAreaElement?we.disabled=y:we.setAttribute("contenteditable",y?"false":"true"),we.setAttribute("aria-disabled",y?"true":"false")),on&&(on.disabled=y),Xt&&(Xt.disabled=y);for(let k of un?.affordanceButtons??[])k.querySelectorAll("button").forEach(q=>{q.disabled=y});ye&&(ye.disabled=y||f&&!lf()),Ks.forEach(k=>{k.elements.forEach(q=>{q.toggleAttribute("data-disabled",w),q instanceof HTMLButtonElement||q.setAttribute("aria-disabled",w?"true":"false")}),k.buttons.forEach(q=>{q.disabled=w})}),gf.forEach(k=>{k.toggleAttribute("data-disabled",w),k instanceof HTMLButtonElement?k.disabled=w:k.setAttribute("aria-disabled",w?"true":"false"),k.querySelectorAll("button").forEach(q=>{q.disabled=w})}),Qe.dataset.personaComposerStreaming=f?"true":"false",Qe.dataset.personaComposerInputDisabled=y?"true":"false",Qe.dataset.personaComposerSendDisabled=si()?"true":"false",Qe.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(k=>{(k instanceof HTMLButtonElement||k instanceof HTMLInputElement||k instanceof HTMLTextAreaElement||k instanceof HTMLSelectElement)&&(k.disabled=f)}),cf(),lk()}let vl=i=>{ze.setStreaming(i),Ab(i?"stop":"send"),df()},ii=()=>{wt.active||we&&we.focus()};R.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>ii(),200)});let ai=null,Cl=!1,pf=!gn.hidden,cs=null,uf=!G,Ld=null;_e.push(()=>{Ld?.cancel(),Ld=null});let ck=i=>{let d=jM(i);if(d===od)return;od=d,t.setAttribute("data-persona-conversation-state",d);let f=Rm();sd(),uf&&(Ld?.cancel(),Ld=UM(Qe,d==="active"?f:Rm(),d==="active"?"drop":"rise",Vs().layout==="centered"?320:260)),eo()},Rv=null,Hv,Wv=null,ra=null,mf=!1,sa=i=>{let d=Vs(),f=`${d.variant}|${d.layout}|${d.dismiss}|${d.anchor??"bottom"}|${d.align??""}|${d.iconPlacement}|${d.kicker??""}|${d.title}|${d.subtitle}`;(f!==Rv||d.icon!==Hv)&&(Rv=f,Hv=d.icon,tm({host:gn,iconHolder:km,kicker:ge,title:Ue,subtitle:at,starterSuggestions:Ns},d));let y=d.message===void 0?null:`${o.layout?.messages?.layout??"bubble"}|${d.message}`;y!==Wv&&(Wv=y,nm(z,d.message,o));let w=i??(N?N.getMessages():o.initialMessages);ck(w);let k=Cl,q=!k&&Ua(d,w),te=q!==pf;if(pf=q,ra){cs?.cancel(),cs=null,k!==mf&&(mf=k,k?cy(pe,gn,null):ly(pe,gn,ra)),za(pe,gn,!k);return}if(te&&!q&&!k&&d.dismiss==="on-first-message"&&uf){cs=zM(gn,re=>{cs===re&&(cs=null),!pf&&!ra&&(za(pe,gn,!1),eo()),re?.cancel()});return}if(cs){if(!q&&!k)return;cs.cancel(),cs=null}let Q=!gn.hidden;za(pe,gn,q),!q&&Q&&eo()},ff=[],gf=[],hf=!1,Bv=null,Dv,Ov=()=>{gf.length=0;let i=ff.splice(0,ff.length);for(let d of i)try{d()}catch(f){console.warn("[persona] renderWelcome cleanup threw",f)}};_e.push(Ov);let dk=(i,d)=>{let f=Zh(i,d);if(!f)return o.debug===!0&&console.warn("[persona] renderStarter received a suggestion with no label"),v("span");let y=o.suggestions?.starters,w=ey({item:{...f,behavior:f.behavior??y?.behavior??"send"},index:d,surface:"starter",source:"config",variant:y?.variant??"card",streaming:h?N.isStreaming():!1,config:o,plugins:u,chipsConfig:o.suggestionChipsConfig,session:N,getTextarea:()=>we,eventTarget:gn,submitPrompt:op});return gf.push(w),w},yf=()=>{if(hf)return;hf=!0;let i=Vs();Bv=`${i.variant}|${i.layout}|${i.dismiss}|${i.title}|${i.subtitle}|${i.message??""}`,Dv=i.icon;try{Ov(),cy(pe,gn,ra),ra=null,mf=!1;let d=N?N.getMessages():o.initialMessages,f=Ua(i,d),y=0,w=null;for(let k of u)if(k.renderWelcome&&(w=k.renderWelcome({config:i,variant:i.variant,visible:f,defaultRenderer:()=>gn,sendMessage:q=>{if(!N||N.isStreaming())return;let te=q.trim();te&&N.sendMessage(te)},requestRender:()=>yf(),renderStarter:q=>dk(q,y++),storage:b(k.id),onCleanup:q=>{ff.push(q)}}),w))break;w&&w!==gn&&(ra=w,ly(pe,gn,w))}finally{hf=!1}sa()},pk=()=>{let i=Vs();`${i.variant}|${i.layout}|${i.dismiss}|${i.title}|${i.subtitle}|${i.message??""}`===Bv&&i.icon===Dv||yf()},Id=()=>{sa(),ji||(we.placeholder=VS(ze.getState().activeModeIds,o.composer?.modes)??o.copy?.inputPlaceholder??"How can I help...",!(o.sendButton?.useIcon??!1)&&!N?.isStreaming()&&(Ve.textContent=o.copy?.sendButtonLabel??"Send")),we.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',we.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},uk=!!o.setStoredConversationId,ia=i=>de(d=>{let f={...d};return delete f[i],f}),Rd=i=>{let d=L[i];return typeof d=="string"?d:null},_v=()=>{let i=L.durableResume;if(!i||typeof i!="object")return null;let d=i;return typeof d.executionId=="string"&&d.executionId.length>0&&typeof d.after=="string"&&d.after.length>0?{executionId:d.executionId,after:d.after}:null};o.clientToken&&(o={...o,getStoredSessionId:()=>Rd("sessionId"),setStoredSessionId:i=>{de(d=>({...d,sessionId:i}))},clearStoredSessionId:o.clearStoredSessionId??(()=>ia("sessionId")),getStoredConversationId:o.getStoredConversationId??(()=>Rd("conversationId")),setStoredConversationId:o.setStoredConversationId??(i=>{de(d=>({...d,conversationId:i}))}),clearStoredConversationId:o.clearStoredConversationId??(()=>ia("conversationId"))});let Nv=()=>o.clientToken??null,Fv=i=>EE(i,Oe(),o.persistState===!1),Vv=Nv(),So=Vv?Fv(Vv):null,Lr={...So?{visitorStore:So}:{},historyBootstrapReady:K,getStoredMessageCursor:()=>Rd("historyMessageCursor"),setStoredMessageCursor:i=>{if(i===null){ia("historyMessageCursor");return}de(d=>({...d,historyMessageCursor:i}))},getPendingDisplayProjections:()=>{let i=L.pendingDisplayProjections;if(!i||typeof i!="object")return null;let d=i;return typeof d.conversationId!="string"||!Array.isArray(d.messageIds)?null:{conversationId:d.conversationId,messageIds:d.messageIds.filter(f=>typeof f=="string")}},setPendingDisplayProjections:i=>{if(!i){ia("pendingDisplayProjections");return}de(d=>({...d,pendingDisplayProjections:i}))},getStoredResumableHandle:_v,setStoredResumableHandle:i=>{if(!i){ia("durableResume");return}de(d=>({...d,durableResume:i}))},shouldResumeDurableConversation:()=>P&&_v()!==null,...uk?{}:{getStoredConversationRevision:()=>Rd("conversationRevision"),setStoredConversationRevision:i=>{if(i===null){ia("conversationRevision");return}de(d=>({...d,conversationRevision:i}))}}};if(P){let i=o.onExecutionState,d=t.ownerDocument.defaultView,f=!1,y=()=>f=!0,w=()=>f=!1;d?.addEventListener("pagehide",y),d?.addEventListener("pageshow",w),_e.push(()=>{d?.removeEventListener("pagehide",y),d?.removeEventListener("pageshow",w)}),o={...o,reconnectStream:o.reconnectStream??(k=>N.getClient().reconnectClientTokenStream(k)),onExecutionState:k=>{(k||!f)&&Lr.setStoredResumableHandle?.(k?{executionId:k.executionId,after:k.lastEventId}:null),i?.(k)}}}let mk=()=>{let i=Nv();if(i&&So?.matches(i,Oe(),o.persistState===!1)||!i&&!So)return;So?.destroy(),So=i?Fv(i):null;let d={...Lr};So?d.visitorStore=So:delete d.visitorStore,Lr=d,N.setHistoryInternals(Lr)},li=null,fk=()=>{li==null&&(li=setInterval(()=>{let i=We.querySelectorAll("[data-tool-elapsed]");if(i.length===0){clearInterval(li),li=null;return}let d=Date.now();i.forEach(f=>{let y=Number(f.getAttribute("data-tool-elapsed"));y&&(f.textContent=f.closest(".persona-activity-row")?Vl(d-y):Vp(d-y))})},100))},bf=(i,d)=>{if(Object.is(i,d))return!0;if(i===null||d===null||typeof i!="object"||typeof d!="object")return!1;if(Array.isArray(i)||Array.isArray(d))return!Array.isArray(i)||!Array.isArray(d)||i.length!==d.length?!1:i.every((q,te)=>bf(q,d[te]));let f=i,y=d,w=Object.keys(f),k=Object.keys(y);return w.length===k.length&&w.every(q=>Object.prototype.hasOwnProperty.call(y,q)&&bf(f[q],y[q]))},$v=i=>{let{content:d,rawContent:f,llmContent:y,...w}=i;return w},vf=i=>i.role==="assistant"&&i.streaming===!0&&!i.variant&&!i.toolCall&&!i.tools&&!i.approval&&!i.reasoning&&!i.contentParts&&!i.stopReason&&!hb(i),gk=(i,d,f)=>{if(i.length!==d.length)return!1;let y=i[f.index],w=d[f.index];return!y||!w||y.id!==f.id||w.id!==f.id?!1:(!Object.is(y.content,w.content)||!Object.is(y.rawContent,w.rawContent)||!Object.is(y.llmContent,w.llmContent))&&vf(y)&&vf(w)&&bf($v(y),$v(w))},Cf=null,aa=null,ci=null,Ir=null,wf=null,hk=i=>{if(!P)return Zi(i);wf=i,queueMicrotask(()=>{wf===i&&(wf=null,Zi(i))})},Hd=i=>{Cf=i;let d,f;aa=null;for(let w=i.length-1;w>=0;w-=1){let k=i[w];if(!d&&k.role==="user"&&(d=k),!f&&k.role==="assistant"&&(f=k),!aa&&vf(k)&&(aa={index:w,id:k.id}),d&&f&&aa)break}xo(We,i,j),Gr()?.updateInlineArtifactBlocks(We,wo.artifacts,{suppressTransition:uo}),fk(),sa(i),Qs(i),as(!uo),tk(i),i.length===0&&($o(),ul=!0,bd=!1,Ji=null,vd=!1),!Xm||Xi?(Xm=!0,ni=d?.id??null,Jm=f?.id??null):d&&d.id!==ni?(ni=d.id,Q0(d.id)):f&&f.id!==Jm&&X0(),f&&(Jm=f.id),ek(i);let y=wt.lastUserMessageId;d&&d.id!==y&&(wt.lastUserMessageId=d.id,R.emit("user:message",d)),wt.lastUserMessageWasVoice=!!d?.viaVoice,hk(i),oa()},xf=()=>{Ir!==null&&(cancelAnimationFrame(Ir),Ir=null);let i=ci;ci=null,i&&Hd(i)},zv=()=>{Ir!==null&&cancelAnimationFrame(Ir),Ir=null,ci=null},yk=i=>{let d=ci??Cf;if(uo&&d&&aa&&gk(d,i,aa)){ci=i,Ir===null&&(Ir=requestAnimationFrame(()=>{Ir=null;let f=ci;ci=null,f&&Hd(f)}));return}if(i.length===0){zv(),Hd(i);return}xf(),Hd(i)};N=new Jp(o,{onMessagesChanged(i){yk(i)},onStatusChanged(i){let d=o.statusIndicator??{};Qo(pt,(y=>y==="idle"?d.idleText??dn.idle:y==="connecting"?d.connectingText??dn.connecting:y==="connected"?d.connectedText??dn.connected:y==="error"?d.errorText??dn.error:y==="paused"?d.pausedText??dn.paused:y==="resuming"?d.resumingText??dn.resuming:dn[y])(i),d,i),pn()},onStreamingChanged(i){i||(N?.getMessages().length===0?zv():xf()),uo=i,vl(i),pn(),N&&xo(We,N.getMessages(),j),i||(as(!0),G0(),gv=!0,N&&hv(N.getMessages(),Ms(o))),xn(),nd(i?"Responding\u2026":"Response complete."),oa()},onVoiceStatusChanged(i){if(R.emit("voice:status",{status:i,timestamp:Date.now()}),!(i!=="disconnected"&&!so(o.voiceRecognition?.provider)))switch(i){case"listening":Dr(),ba();break;case"processing":Dr(),vP();break;case"speaking":Dr(),CP();break;default:i==="idle"&&N.isBargeInActive()?(Dr(),ba(),ye?.setAttribute("aria-label","End voice session")):(wt.active=!1,Dr(),kr("system"),Vo());break}},onArtifactsState(i){wo=i,i.artifacts.length===0&&(Ki=!1),Gr()?.updateInlineArtifactBlocks(We,i.artifacts,{suppressTransition:uo}),Fo(),Zi()},onHistoryStateChanged(i){_t(i)},onHistoryNotice(i){Vt(i)},onReconnect(i){let{executionId:d,lastEventId:f}=i.handle;i.phase==="paused"?R.emit("stream:paused",{executionId:d,after:f}):i.phase==="resuming"?R.emit("stream:resuming",{executionId:d,after:f,attempt:i.attempt??1}):R.emit("stream:resumed",{executionId:d,after:f})}},Lr),Ft.current=N,_e.push(()=>N.cancel()),_e.push(()=>{N.destroy(),So?.destroy(),So=null});let Sf=null;if(N.onReadAloudChange((i,d)=>{qb=i,jb=d,Kb();let f=i??Sf;i&&(Sf=i);let y=f?N.getMessages().find(w=>w.id===f)??null:null;R.emit("message:read-aloud",{messageId:f,message:y,state:d,timestamp:Date.now()}),d==="idle"&&(Sf=null)}),h=!0,Xm=!0,o.voiceRecognition?.enabled===!0&&so(o.voiceRecognition.provider))try{N.setupVoice()}catch(i){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",i)}let bk=720,vk=250,Mt=nb(o.features?.history?.copy),go=null,Af=!1,Dt=null,Wd=null,Bd="conversation",Mf=null,Nn=null,ir=null,Dd=N.getHistoryState(),Tf=null,wl=0,Ef=null,Od=null,_d=null,kf=`persona-history-${Math.random().toString(36).slice(2,8)}`,Pf=()=>o.features?.history?.enabled===!0,ar=()=>Pf()&&!!go&&!Af,Uv=()=>{let i=N.getStatus();return uo||i==="paused"||i==="resuming"},Lf=()=>{let i=o.features?.history?.scope;if(i)return i;let d=o.getIdentityProof?"verified-user":"browser",f=go?.capabilities.scopes;return!f||f.includes(d)?d:f[0]??d},la=()=>Wd?.scope??Lf(),qv=()=>N.getClientSession()?.targetId??null,jv=i=>`${i.state}:${"reason"in i?i.reason:""}`,Ck=i=>{let d=jv(i);d!==Tf&&(Tf=d,R.emit("history:identityStatusChanged",{status:i,timestamp:Date.now()}))},Nd=i=>{i&&(xr.textContent="",xr.textContent=i)},Kv=null,Gv=null,wk=()=>{if(!Pf())return null;let i=GE();if(i)return i();let d=o.features?.history?.provider;return d?typeof d!="function"?d:(Kv!==d&&(Kv=d,Gv=d()),Gv):N.isClientTokenMode()?YE({client:N.getClient(),getIdentityProofConfigured:()=>typeof o.getIdentityProof=="function",onActivationCommitted:f=>N.bindActivatedSession(f),getClient:()=>N.getClient()}):null},Yv=()=>{Od?.(),Od=null,_d?.(),_d=null,Af=!1,go=wk();let i={...Lr};go?i.historyProvider=go:delete i.historyProvider,Lr=i,N.setHistoryInternals(Lr),go&&(Od=go.subscribeAvailability?.(d=>{Af=!d,d||to({restoreFocus:!1}),ps()})??null,_d=go.subscribeIdentityStatus(d=>Ck(d)),Tf=jv(go.getIdentityStatus()))},If=()=>{let i=o.features?.history?.presentation??"panel";if(i==="panel"||i==="auto"&&!(!_||nn(o)))return"panel";let d=nr??Pe;return(d.getBoundingClientRect().width||d.clientWidth)>=bk?"rail":"panel"},Ao=(i,d)=>{d?(i.setAttribute("aria-hidden","true"),i.setAttribute("inert","")):(i.removeAttribute("aria-hidden"),i.removeAttribute("inert"))},Fd="data-persona-history-suppressed",ho=null,ds=null,di=null,xl=null,Rf=null,Qv="",Xv=()=>$e===Rf?Qv:o.layout?.showHeader===!1?"none":"",xk=()=>xt==="panel"&&!!di&&xl===di.element&&o.layout?.showHeader!==!1&&Xv()!=="none",Sk=()=>{for(let i of Array.from($e.children))i!==ho&&i.setAttribute(Fd,"")},Ak=()=>{for(let i of Array.from(Pe.querySelectorAll(`[${Fd}]`)))i.removeAttribute(Fd)},Mk=()=>{let i=di;if(!i)return;if(Array.from($e.children).some(y=>y!==ho&&!y.hasAttribute(Fd))){ds&&ds!==$e&&(ds.style.removeProperty("min-height"),ds=null);let y=$e.offsetHeight;y>0&&($e.style.minHeight=`${y}px`,ds=$e)}ho||(ho=v("div","persona-history-header-host")),i.setHeaderPlacement("external");let f=i.getHeaderElement();f.parentNode!==ho&&ho.replaceChildren(f),ho.parentNode!==$e&&$e.appendChild(ho),Sk()},Jv=()=>{ds&&(ds.style.removeProperty("min-height"),ds=null),ho&&(di?.setHeaderPlacement("inline"),ho.remove(),ho=null,Ak())},Vd=null,Hf=()=>{if(Vd){if(pe.style.display="none",Ao(pe,!0),Qe.hidden=!0,Ao(Qe,!0),xk()){Mk(),$e.style.display=Xv(),Ao($e,!1);return}Jv(),$e.style.display="none",Ao($e,!0)}};Mn=Hf;let Tk=i=>{let d=pe.style.display,f=Qe.hidden,y=Qe,w=$e,k=$e.style.display;Rf=w,Qv=k,Vd=()=>{Vd=null,Jv(),Rf=null,pe.style.display=d,Ao(pe,!1),y.hidden=f,Ao(y,!1),Qe!==y&&(Qe.hidden=!1,Ao(Qe,!1)),w.style.display=k,Ao(w,!1),$e!==w&&($e.style.display=o.layout?.showHeader===!1?"none":"",Ao($e,!1))},Qe.parentNode?.insertBefore(i,Qe),Hf()},ca=null,pi=null,Sl=null,da=null,Zv=()=>[$e,ot.closeButtonWrapper,ot.clearChatButtonWrapper,pe,Qe],Ek=52,$d=()=>o.features?.history?.rail?.collapsible!==!1,pa=()=>o.features?.history?.rail?.side==="right"?"right":"left",Wf=200,Bf=400,Df=i=>Math.min(Bf,Math.max(Wf,Math.round(i))),kk=()=>o.features?.history?.rail?.resizable===!0,Al,Pk=()=>{if(Al===void 0&&(Al=null,o.persistState!==!1))try{let i=Number(window.localStorage.getItem(`${Oe()}rail-width`));i&&(Al=i)}catch{}return Al},Ml=()=>Df(Pk()??o.features?.history?.rail?.width??260),Lk=i=>{if(Al=i,o.persistState!==!1)try{window.localStorage.setItem(`${Oe()}rail-width`,String(i))}catch{}},zd=()=>$d()&&o.features?.history?.rail?.collapsedBehavior==="overlay",yn=!1,eC=i=>{let d=v("img");return d.src=i,d.alt="",d.setAttribute("aria-hidden","true"),d},Ik=()=>{let i=o.features?.history?.rail?.brand;if(!i)return;let d=!1,f;return y=>{if(i.render)try{return i.render({collapsed:y})??null}catch(w){return d||(d=!0,console.warn("[persona] history rail brand threw",w)),null}return f===void 0&&(i.iconUrl?f=eC(i.iconUrl):f=i.icon?ke(i.icon,20):null),f?f.cloneNode(!0):null}},Rk=()=>o.features?.history?.rail?.sections?.map(i=>{let d=!1,f=y=>{d||(d=!0,console.warn("[persona] history rail section threw",i.id,y))};return{id:i.id,title:i.title,placement:i.placement??"above-conversations",items:i.items.map(y=>{let w;return{id:y.id,label:y.label,badge:y.badge,iconNode:()=>{if(w!==void 0)return w;try{y.renderIcon?w=y.renderIcon()??null:y.iconUrl?w=eC(y.iconUrl):w=y.icon?ke(y.icon,20):null}catch(k){f(k),w=null}return w},onSelect:()=>{try{y.onSelect()}catch(k){f(k)}}}})}})??[],Hk=i=>{let d=Rk();for(let f of i)d.some(y=>y.id===f.id)?console.warn("[persona] duplicate history rail section id",f.id):d.push(f);return d.length?d:void 0},Tl=null,tC=()=>`${Oe()}rail-collapsed`,Of=()=>{if(Tl===null&&(Tl=o.features?.history?.rail?.defaultCollapsed===!0,o.persistState!==!1))try{let i=window.localStorage.getItem(tC());i&&(Tl=i==="1")}catch{}return Tl},_f=i=>{if(Tl=i,o.persistState!==!1)try{window.localStorage.setItem(tC(),i?"1":"0")}catch{}},El=()=>xt==="rail"&&$d()&&!zd()&&Of(),Nf=()=>{},nC=()=>{if(zd()){Nf();return}_f(!Of()),Dt?.view.setCollapsed(El()),ft(),eo()},Ff=()=>{let i=o.features?.history?.rail?.collapseShortcut;return!i||!Nu(i)?null:{combo:i,hint:Fu(i),aria:yc(i)}},oC=()=>{g.forEach(d=>d()),g=[];let i=Ff();i&&g.push(m.register({id:"history-rail-collapse",combo:i.combo,scope:o.features?.history?.rail?.collapseShortcutScope==="page"?"page":"widget",when:()=>mt&&xt==="rail"&&$d()||ma(),run:()=>zd()?Nf():nC()}));for(let d of o.layout?.header?.trailingActions??[])d.shortcut&&g.push(m.register({id:`header-action-${d.id}`,combo:d.shortcut,run:()=>{let f=t.querySelector(`[data-persona-header-action="${d.id}"]`);f?f.click():o.layout?.header?.onAction?.(d.id)}}));for(let d of u)for(let f of d.shortcuts??[])g.push(m.register({...f,id:`${d.id}:${f.id}`}))};oC();let Wk=300,Ud="var(--persona-history-overlay-margin,8px)",Mo=null,Rr=null,qd=0,Hr=null,ua=null,ui=!1,Vf=0,rC=()=>window.matchMedia?.("(pointer: coarse)").matches===!0,ma=()=>ar()&&zd()&&(xt??If())==="rail",Bk=()=>mt&&!yn,kl=()=>{ua!==null&&clearTimeout(ua),ua=null},Dk=()=>{ub().catch(()=>{})},sC=()=>{kl(),yn&&(ua=setTimeout(()=>{ua=null,!(ui||!yn)&&(Hr?.contains(document.activeElement)||to({restoreFocus:!1}))},Wk))},Ok=(i,d)=>{let f=Hr?.getBoundingClientRect();if(!f)return!1;let y=Mo?.getBoundingClientRect(),w=y?Math.min(y.top,f.top):f.top;return i>=f.left&&i<=f.right&&d>=w&&d<=f.bottom||!!y&&i>=y.left&&i<=y.right&&d>=y.top&&d<=y.bottom},$f=i=>{yn&&(ui=Ok(i.clientX,i.clientY),ui?kl():ua===null&&sC())},iC=i=>{mt||!ma()||(yn=!0,Ll({invoker:Mo,keyboard:i?.keyboard===!0}).then(()=>{mt?!ui&&document.activeElement!==Mo&&to():yn=!1}))},aC=()=>{let i=xl?.querySelector('[data-persona-history-focus="collapse"]');i&&(i.setAttribute("aria-label",yn?Mt.expandLabel:Mt.collapseLabel),i.setAttribute("aria-expanded",yn?"false":"true"))},lC=()=>{_f(!1);let i=Dt;if(!yn||!i){Ll({invoker:Mo});return}let d=document.activeElement===Mo;yn=!1,jd(),i.element.remove(),Uf(i.element),aC(),d&&Gd(),eo(),ps()},_k=()=>{_f(!0),to()};Nf=()=>{!mt||yn?lC():_k()};let Nk=()=>{let i=Ff(),d=ki({ariaLabel:Mt.expandLabel,iconName:"panel-left",wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center",extraClassName:"persona-rail-trigger",tooltip:!1,attrs:{"data-persona-rail-trigger":"","aria-controls":kf,...i?{"aria-keyshortcuts":i.aria}:{}}}),f=d.button;f.addEventListener("mouseenter",()=>{ui=!0,kl(),!(rC()||Date.now()<Vf)&&iC()}),f.addEventListener("mouseleave",()=>{ui=!1,Vf=0,sC()}),f.addEventListener("focus",()=>{mt||Dk()}),f.addEventListener("click",y=>{ar()&&(y.detail!==0&&rC()&&!mt?iC():lC())}),Mo=f,Rr=d.wrapper},Pl=()=>{if(Rr&&!Rr.isConnected&&(Rr=null,Mo=null),!ma()){Rr?.remove(),Rr=null,Mo=null;return}Mo||Nk();let i=Rr,d=Mo;if(!i||!d)return;let f=pa()!=="right"?$e.firstChild:null;(f??$e.lastChild)!==i&&$e.insertBefore(i,f),i.style.display=Bk()||qd>0?"none":"",d.setAttribute("aria-label",Mt.expandLabel),d.setAttribute("aria-expanded",mt?"true":"false"),Hr&&ft()},cC=i=>{if(!yn)return;let d=i.target;d instanceof Node&&(Hr?.contains(d)||Rr?.contains(d)||d instanceof Element&&d.closest('.persona-dropdown-menu,[role="alertdialog"]')||to({restoreFocus:!1}))};document.addEventListener("pointerdown",cC,!0),_e.push(()=>{document.removeEventListener("pointerdown",cC,!0),document.removeEventListener("pointermove",$f),fa?.(),kl()});let zf=null,fa=null,dC=16,pC=i=>{Lk(Df(i)),ft(),eo()},Fk=()=>{let i=v("div","persona-rail-resizer");return i.tabIndex=0,i.setAttribute("role","separator"),i.setAttribute("aria-orientation","vertical"),i.setAttribute("aria-valuemin",String(Wf)),i.setAttribute("aria-valuemax",String(Bf)),i.addEventListener("pointerdown",d=>{let f=pi;if(!f||d.button!==0)return;d.preventDefault(),fa?.();let y=d.clientX,w=f.getBoundingClientRect().width||Ml(),k=pa()==="right"?-1:1,q=w,te=t.ownerDocument;f.style.transition="none";let Q=ce=>{q=Df(w+k*(ce.clientX-y)),f.style.flex=`0 0 ${q}px`,i.setAttribute("aria-valuenow",String(q))},re=()=>{fa=null,te.removeEventListener("pointermove",Q),te.removeEventListener("pointerup",re),te.removeEventListener("pointercancel",re),f.style.removeProperty("transition");try{i.releasePointerCapture(d.pointerId)}catch{}pC(q)};fa=re,te.addEventListener("pointermove",Q),te.addEventListener("pointerup",re),te.addEventListener("pointercancel",re);try{i.setPointerCapture(d.pointerId)}catch{}}),i.addEventListener("keydown",d=>{let f=pa()==="right"?-dC:dC,y=Ml(),w=d.key==="ArrowRight"?y+f:d.key==="ArrowLeft"?y-f:d.key==="Home"?Wf:d.key==="End"?Bf:null;w!==null&&(d.preventDefault(),pC(w))}),i},Vk=(i,d)=>{if(!kk()||El()){fa?.(),zf?.remove();return}let f=zf??Fk();zf=f,f.setAttribute("aria-label",Mt.resizeLabel),f.setAttribute("aria-valuenow",String(Ml())),f.nextElementSibling!==d&&i.insertBefore(f,d)};ft=()=>{Dt?.view.setRailSide(pa());let i=pa()==="right",d=Hr;if(d){let te=Mo?Mo.getBoundingClientRect().bottom-Pe.getBoundingClientRect().top:0;d.style.top=`calc(${Math.max(0,Math.round(te))}px + ${Ud})`,d.style.width=`${Ml()}px`,d.style.left=i?"":Ud,d.style.right=i?Ud:""}let f=pi,y=ca,w=Sl;if(!f||!y||!w)return;f.style.flex=`0 0 ${El()?Ek:Ml()}px`;let k="1px solid var(--persona-divider,#e5e7eb)";f.style.borderRight=i?"":k,f.style.borderLeft=i?k:"";let q=i?w:f;y.firstElementChild!==q&&y.append(q,i?f:w),Vk(y,i?f:w)};let uC=i=>{if(da&&pi){da.replaceWith(i),da=null,ft();return}let d=v("div","persona-history-rail-shell");d.style.cssText="display:flex;flex-direction:row;flex:1 1 auto;min-height:0";let f=v("div","persona-history-rail-conversation");f.style.cssText="display:flex;flex-direction:column;flex:1 1 auto;min-width:0;min-height:0;position:relative";let y=v("div","persona-history-rail-host");y.style.cssText="display:flex;min-height:0;overflow:hidden",Pe.insertBefore(d,$e.parentNode===Pe?$e:pe);for(let w of Zv())w?.parentNode===Pe&&f.appendChild(w);d.append(y,f),y.appendChild(i),ca=d,pi=y,Sl=f,ft()},$k=()=>{if(ca)return;let i=v("div","persona-history-rail-placeholder");i.style.cssText="flex:1 1 auto;min-height:0",da=i,uC(i),eo()},mC=()=>{da&&(jd(),eo())},zk=i=>{let d=v("div","persona-history-rail-overlay");d.style.cssText=`position:absolute;bottom:${Ud};display:flex;overflow:hidden;z-index:${Ba-1};border-radius:var(--persona-history-overlay-radius,16px);background:var(--persona-history-overlay-bg,var(--persona-container,#f7f7f8));box-shadow:var(--persona-history-overlay-shadow,0 12px 40px rgba(0,0,0,0.25))`,Pe.style.position="relative",Pe.appendChild(d),d.appendChild(i),document.addEventListener("pointermove",$f),Hr=d,ft(),aC()},jd=()=>{Vd?.(),Hr&&(ui&&(Vf=Date.now()+150),document.removeEventListener("pointermove",$f),Hr.remove(),Hr=null);let i=ca;if(i){fa?.();for(let d of Zv())d&&i.contains(d)&&Pe.insertBefore(d,i);i.remove(),ca=null,pi=null,Sl=null,da=null}},fC=i=>{xl=i,i.id=kf,i.style.flex="1 1 auto",i.style.minHeight="0"},Uf=i=>{fC(i),(xt!=="rail"||yn)&&mC(),xt!=="rail"?Tk(i):yn?zk(i):uC(i)},Kd=()=>{if(Pl(),MC(),!mt||!Dt)return;let i=If();if(i===xt)return;let d=document.activeElement,f=d instanceof HTMLElement&&(Dt.element.contains(d)||ho?.contains(d)===!0)?d:null;jd(),Dt.element.remove(),Dt.view.setHeaderPlacement("inline"),xt=i,Dt.view.setPresentation(i),Dt.view.setCollapsed(El()),Dt.requestRender(),Dt.element.isConnected||Uf(Dt.element),f?.isConnected?f.focus():Gd(),xn(),eo(),ps()},gC=(i,d)=>ho?.querySelector(d)??i.querySelector(d),Gd=()=>{let i=Dt?.element??xl;if(!i)return;let d=gC(i,'[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]');if(d){d.focus();return}let f=gC(i,".persona-history-title")??i;f.tabIndex=-1,f.focus()},Ll=async i=>{if(!ar()||mt)return;let d=go;if(!d)return;if(!yn&&ma()&&Of()){Pl();return}Yd();let f=++wl;Bd=i?.returnSurface??"conversation",Mf=i?.invoker??Nn;let y=ma()&&!yn;y&&(qd+=1,Pl(),$k());let w;try{w=await ub()}catch{Nd(Mt.openHistoryLabel),y&&(qd-=1,f===wl&&(mC(),Pl()));return}if(y&&(qd-=1),f!==wl||mt)return;Wd={scope:Lf()},xt=If(),mt=!0;let k=xt==="panel"&&o.layout?.showHeader!==!1&&$e.style.display!=="none"?"external":"inline",q=o.features?.history?.rowAvatar,te=Ff(),Q=te?{hint:te.hint,aria:te.aria}:null,re={provider:d,context:Wd,targetId:qv(),presentation:xt,collapsible:$d(),collapsed:El(),railSide:pa(),renderRailHeader:o.features?.history?.rail?.renderHeader,railBrand:Ik(),onToggleCollapse:nC,...Q?{collapseShortcut:Q}:{},headerPlacement:k,showScopeStatus:o.features?.history?.showScopeStatus!==!1,showDelete:o.features?.history?.showDelete!==!1,showDeleteAll:o.features?.history?.showDeleteAll!==!1,...o.features?.history?.listActions?.length?{listActions:o.features.history.listActions}:{},rowAvatar:q===!1?!1:typeof q=="string"?q:o.launcher?.iconUrl,activeConversationId:N.getActiveConversationId(),...o.features?.history?.grouping?{grouping:o.features.history.grouping}:{},...o.features?.history?.copy?{copy:o.features.history.copy}:{},...o.features?.history?.pageSize!==void 0?{pageSize:o.features.history.pageSize}:{},onSelect:ce=>jf(ce,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:ce=>mi(ce),attachTooltip:In,onStartNew:()=>Kf({focusComposer:!0}),onClose:()=>to(),onRequestDeleteConversation:ce=>AC(ce),onRequestClearHistory:()=>Yk(),...d.resetDevice?{onRequestResetIdentity:()=>Qk()}:{}};Dt=KE({plugins:u,config:o,getPresentation:()=>xt??"panel",getReturnSurface:()=>Bd,close:()=>to(),createView:({slots:ce,renderDom:he,onModelChange:De,railSections:lt})=>(di=w.createHistoryView({...re,railSections:Hk(lt),slots:ce,renderDom:he,onModelChange:De,onAnnounce:Nd}),di),onElementChanged:(ce,he)=>{if(!he?.isConnected)return Uf(ce);fC(ce),he.replaceWith(ce),Hf()}}),Dt.view.setNewConversationRequired(Dd.recovery==="new_conversation_required"),i?.focus!==!1&&(xt!=="rail"||i?.keyboard===!0)&&Gd(),xn(),eo(),ps(),R.emit("history:opened",{presentation:xt,returnSurface:Bd,timestamp:Date.now()})},Yd=()=>{},to=i=>{if(!mt)return;wl+=1;let d=Bd,f=Mf,y=Dt,w=i?.restoreFocus!==!1;mt=!1;let k=!1,q=null,te=()=>{if(!k){if(k=!0,Yd=()=>{},q!==null&&clearTimeout(q),yn=!1,kl(),jd(),y?.dispose(),y?.view.destroy(),y?.element.remove(),Dt===y&&(Dt=null,di=null,xl=null,xt=null,Wd=null,Mf=null),xn(),eo(),ps(),w){let re=f??Nn;re?.isConnected?re.focus():ii()}R.emit("history:closed",{returnSurface:d,timestamp:Date.now()})}},Q=y&&y.element===y.view.element?y.view.playExit():null;if(!Q){te();return}Yd=te,q=setTimeout(te,vk),Q.then(te)},hC=i=>{if(!(i.key!=="Escape"||!mt||!Dt)){if(xt==="rail"){let d=i.target;if(!(d instanceof Node)||!(Dt.element.contains(d)||yn&&Rr?.contains(d)===!0))return}i.preventDefault(),i.stopPropagation(),to()}};Pe.addEventListener("keydown",hC),_e.push(()=>Pe.removeEventListener("keydown",hC));let Qd=null,yC=!1,Il=()=>{if(!Bn)return;let i=o.layout?.header?.titleSource==="conversation",d=i&&Qd?.trim()||null;Bn.textContent=d??o.launcher?.title??"Chat Assistant";let f=Bn.closest(".persona-combo-btn");if(!f)return;let y=!i||N.getActiveConversationId()!==null;f.setAttribute("data-persona-menu-locked",y?"false":"true"),f.setAttribute("aria-haspopup",y?"true":"false"),y||f.setAttribute("aria-expanded","false"),f.style.cursor=y?"pointer":"default";let w=f.querySelector("svg");w&&(w.style.display=y?"":"none")},Uk=i=>{i!==Qd&&(Qd=i,Il())},mi=i=>{yC=i?.starred===!0,Uk(i&&i.title.trim()||null),Il()};Il(),Pe.addEventListener("persona:title-menu-builtin",i=>{let d=i.detail?.actionId,f=N.getActiveConversationId();f&&(d==="delete"?AC(f):d==="star"&&N.canUpdateConversations()&&Gf(f,{starred:!yC}).catch(()=>{}))});let Xd=0,qk=250,Jd=null,Zd=()=>{Jd&&clearTimeout(Jd),Jd=null};_e.push(Zd);let bC=()=>{Zd();let i=ai;i&&(Cl=!0,i.hidden=!1,We.style.display="none",sa())},ep=()=>{Xd+=1,Zd(),ai&&(ai.remove(),ai=null,Cl=!1,We.style.removeProperty("display"),Ao(Qe,!1),sa())},jk=()=>{try{if(window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches)return;We.animate([{opacity:0},{opacity:1}],{duration:150,easing:"ease-out"})}catch{}},qf=(i,d)=>F("div",{className:Gt("persona-conversation-loading-bubble",d&&"persona-conversation-loading-bubble--trailing"),attrs:{"aria-hidden":"true"},style:{width:i}}),vC=()=>F("div",{className:"persona-conversation-loading-body"},qf("58%",!1),qf("72%",!0),qf("44%",!1)),CC=i=>{ai?.remove(),ai=i,i.hidden=!Cl,pe.insertBefore(i,We),Zd(),Cl||(Jd=setTimeout(bC,qk)),Ao(Qe,!0)},Kk=()=>{let i={config:o,streaming:!1,location:"conversation-open",defaultRenderer:vC},d=null,f=u.find(y=>y.renderLoadingIndicator);f?.renderLoadingIndicator&&(d=f.renderLoadingIndicator(i)),d===null&&o.loadingIndicator?.render&&(d=o.loadingIndicator.render(i)),CC(F("div",{className:"persona-conversation-loading",attrs:{role:"status","aria-label":Mt.openConversationLoadingLabel}},d??vC()))},Gk=i=>{let d=()=>{jf(i,{focusComposer:!0}).catch(()=>{})},f=ar()?()=>{ep(),Ll()}:void 0,y=(te,Q)=>{let re=F("button",{className:"persona-conversation-loading-error-action",attrs:{type:"button"},text:te});return re.addEventListener("click",Q),re},w=()=>F("div",{className:"persona-conversation-loading-error-body"},F("p",{className:"persona-conversation-loading-error-title",text:Mt.openConversationErrorTitle}),F("div",{className:"persona-conversation-loading-error-actions"},y(Mt.openConversationRetryLabel,d),f?y(Mt.openConversationBackLabel,f):null)),k=Object.freeze({conversationId:i,config:o,copy:Object.freeze({title:Mt.openConversationErrorTitle,retryLabel:Mt.openConversationRetryLabel,backLabel:Mt.openConversationBackLabel}),retry:d,...f?{back:f}:{},defaultRenderer:w}),q=null;for(let te of u)if(te.renderHistoryOpenError){try{q=te.renderHistoryOpenError(k)}catch(Q){console.warn("[persona] renderHistoryOpenError threw",Q),q=null}if(q)break}CC(F("div",{className:"persona-conversation-loading-error",attrs:{role:"alert"}},q??w())),bC()};R.on("history:closed",()=>{ai&&Ao(Qe,!0)});let jf=async(i,{focusComposer:d=!1}={})=>{let f=la(),y=!!Dt;Dt?.view.setActiveConversationId(i),ep();let w=Xd;Kk(),mt&&(xt==="panel"||yn)&&to({restoreFocus:!1}),Xi=!0;try{await N.openConversation(i,{scope:f})}catch(k){throw w===Xd&&Gk(i),k}finally{Xi=!1}w===Xd&&(ep(),mn.clear(),$o(),Zn(),rf()||Ad(),jk(),Wr(),y||mi(null),R.emit("history:conversationOpened",{conversationId:i,title:Qd,scope:f,timestamp:Date.now()}),d&&ii())},Kf=async({focusComposer:i=!1}={})=>{ep(),await N.startNewConversation({scope:la()}),mi(null),mn.clear(),$o(),Zn(),Ad(),Wr();let d=N.getActiveConversationId();Dt?.view.setActiveConversationId(d),R.emit("history:conversationStarted",{conversationId:d,timestamp:Date.now()}),mt&&(xt==="panel"||yn)&&to({restoreFocus:!1}),i&&ii()},Gf=async(i,d)=>{let f=await N.updateConversation(i,{...d,...d.title!==void 0?{title:d.title.trim()}:{}});return Dt?.view.applyConversationSummary(f),!Dt&&i===N.getActiveConversationId()&&mi(f),f},wC=async i=>{let d=la(),f=N.getActiveConversationId()===i;await N.deleteConversation(i,{scope:d}),Dt?.view.removeConversationSummary(i),f&&(mi(null),mn.clear(),$o(),Zn(),Wr()),R.emit("history:conversationDeleted",{conversationId:i,scope:d,wasActive:f,timestamp:Date.now()})},xC=async i=>{let d=i?.scope??la(),f=i?.allTargets?null:i?.targetId??qv(),y=await N.clearConversationHistory({...f?{targetId:f}:{},scope:d});return mi(null),mn.clear(),$o(),Zn(),Wr(),R.emit("history:cleared",{deleted:y.deleted,scope:d,targetId:f,timestamp:Date.now()}),y},SC=async()=>{if(!go?.resetDevice)throw new Error("[Persona] resetHistoryIdentity() requires a history provider that can reset this device");let i=!1;try{i=(await N.resetHistoryDevice()).remoteRevocationConfirmed}finally{mi(null),N.clearArtifacts(),mn.clear(),Cf=null,o.clearStoredSessionId?.(),o.clearStoredConversationId?.(),L={},se.syncFromMetadata(),x?.clear&&wd(()=>x.clear(),"[AgentWidget] Failed to clear storage adapter:"),$o(),Zn(),Wr(),to({restoreFocus:!1}),ii(),Ae||sn?.launcher.element.focus()}return Nd(i?Mt.identityResetNotice:Mt.identityResetUnconfirmedNotice),R.emit("history:identityReset",{remoteRevocationConfirmed:i,timestamp:Date.now()}),{remoteRevocationConfirmed:i}},Yf=()=>nr?Se:Pe,AC=async i=>await Mm({host:Yf(),title:Mt.deleteConversationConfirmTitle,description:Mt.deleteConversationConfirm,confirmLabel:Mt.deleteConversationConfirmLabel,cancelLabel:Mt.confirmCancelLabel})?(await wC(i),"deleted"):"cancelled",Yk=async()=>{let i=la()==="verified-user";return await Mm({host:Yf(),title:Mt.clearHistoryConfirmTitle,description:i?Mt.clearHistoryVerifiedConfirm:Mt.clearHistoryConfirm,confirmLabel:Mt.clearHistoryConfirmLabel,cancelLabel:Mt.confirmCancelLabel})?(await xC(),"cleared"):"cancelled"},Qk=async()=>{if(!await Mm({host:Yf(),title:Mt.resetIdentityConfirmTitle,description:Mt.resetIdentityConfirm,confirmLabel:Mt.resetIdentityConfirmLabel,cancelLabel:Mt.confirmCancelLabel}))return{outcome:"cancelled"};let{remoteRevocationConfirmed:d}=await SC();return{outcome:"reset",remoteRevocationConfirmed:d}},To=v("button","persona-history-earlier");To.type="button",To.textContent=Mt.showEarlierMessagesLabel,To.setAttribute("data-persona-history-earlier",""),Object.assign(To.style,{alignSelf:"center",minHeight:"44px",padding:"0 16px",borderRadius:"999px",border:"1px solid var(--persona-border, rgba(0,0,0,0.12))",background:"transparent",color:"inherit",font:"inherit",cursor:"pointer",flexShrink:"0"});let Wr=()=>{if(!(ar()&&!!Dd.nextMessageCursor&&!!N.getActiveConversationId())){To.remove();return}To.textContent=Mt.showEarlierMessagesLabel,To.parentNode!==pe&&pe.insertBefore(To,pe.firstChild)};To.addEventListener("click",()=>{let i=N.getActiveConversationId(),d=Dd.nextMessageCursor;if(!i||!d||To.disabled)return;To.disabled=!0;let f=pe.scrollHeight,y=pe.scrollTop;N.loadOlderMessages(i,d,{scope:la()}).then(()=>{pe.scrollTop=y+(pe.scrollHeight-f),eo()}).catch(()=>{}).finally(()=>{To.disabled=!1,Wr()})});let Xk=()=>{let i=ki({ariaLabel:Mt.openHistoryLabel,iconName:"history",wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center",extraClassName:"persona-history-toggle",attrs:{"data-persona-history-toggle":""}});return i.button.addEventListener("click",d=>{if(!(!ar()||Uv())){if(mt){to();return}Ll({invoker:i.button,keyboard:d.detail===0})}}),i},MC=()=>{if(!ar()){ir?.remove(),Nn=null,ir=null;return}if(ir&&!ir.isConnected&&(Nn=null,ir=null),!Nn&&$e){let y=Xk();Nn=y.button,ir=y.wrapper;let w=ot.clearChatButtonWrapper||ot.closeButtonWrapper;w?.parentNode&&$e.contains(w)?w.parentNode.insertBefore(ir,w):$e.appendChild(ir)}if(!Nn||!ir)return;let i=ma()||mt&&xt==="rail";if(ir.style.display=i?"none":"",i){document.activeElement===Nn&&Gd();return}let d=Uv();Nn.disabled=d,Nn.setAttribute("aria-disabled",d?"true":"false");let f=d?Mt.openHistoryBusyLabel:Mt.openHistoryLabel;Nn.setAttribute("aria-label",f),(o.features?.history?.presentation??"panel")==="panel"?(Nn.removeAttribute("aria-expanded"),Nn.removeAttribute("aria-controls")):(Nn.setAttribute("aria-expanded",mt?"true":"false"),Nn.setAttribute("aria-controls",kf))},tp=!1,Jk=()=>{let i=ot.clearChatButton;if(i){if(ar()){tp||(Ef=i.getAttribute("aria-label")??"",tp=!0),i.setAttribute("aria-label",Mt.newConversationLabel),i.removeAttribute("title");return}tp&&(tp=!1,Ef&&i.setAttribute("aria-label",Ef))}},ps=()=>{Mt=nb(o.features?.history?.copy),MC(),Pl(),Jk(),Wr()};pn=ps,_t=i=>{Dd=i,Dt?.view.setNewConversationRequired(i.recovery==="new_conversation_required"),vl(i.sendBlocked||uo),Wr()},Vt=i=>{(i.code==="history_continuity_reset"||i.code==="conversation_deleted_recovered")&&(mn.clear(),$o(),Zn()),Nd(i.message),Dt?.view.refresh()},Yv(),ps(),_e.push(()=>{Od?.(),_d?.(),wl+=1,Yd(),Dt?.dispose(),Dt?.view.destroy(),Dt=null}),o.clientToken&&(o.features?.history?.enabled===!0||o.sessionInit==="mount")&&N.initClientSession().then(()=>{if(ar())return N.reconcileBootConversation({scope:Lf()})}).then(()=>{Wr()}).catch(i=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",i)});let Qf=()=>N.warmClientSession(),TC=i=>{let d=o.sessionInit??"input",f=Et?.input??we,y=i.target;f&&(i.type==="input"?(d==="input"||d==="focus")&&y===f&&i.inputType&&f.value.trim():d==="focus"&&(i.type==="keyup"?y===f&&i.key==="Tab":(Et?.form??Tn)?.contains(y)))&&Qf()},EC=["input","pointerdown","keyup"];EC.forEach(i=>t.addEventListener(i,TC));let kC,Xf,PC=()=>{let i=Xf;Xf=void 0;try{typeof i=="function"&&i()}catch{}},LC=()=>{let i=o.clientToken&&typeof o.sessionInit=="function"?o.sessionInit:void 0;if(i!==kC){PC(),kC=i;try{Xf=i?.({warm:Qf,mount:t})}catch{}}};LC(),_e.push(()=>{EC.forEach(i=>t.removeEventListener(i,TC)),PC()}),(ie||o.onSSEEvent)&&N.setSSEEventCallback((i,d)=>{o.onSSEEvent?.(i,d),qe(i,d)});let IC=()=>{let i=o.resume??(P?Lr.getStoredResumableHandle?.():null);i&&typeof o.reconnectStream=="function"&&N.resumeFromHandle(i)};G?G.then(i=>{if(i){if(i.metadata&&(L=yb(i.metadata),se.syncFromMetadata()),i.messages?.length){Xi=!0;try{N.hydrateMessages(i.messages)}finally{Xi=!1}kd()}i.artifacts?.length&&N.hydrateArtifacts(i.artifacts,i.selectedArtifactId??null),xv(i.draft)}}).catch(i=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",i)}).finally(()=>{uf=!0,V(),IC()}):(xv(ee),IC());let Zk=()=>{!xe()||Ae||!(o.launcher?.composerBar?.expandOnSubmit??!0)||qt(!0,"auto")},eP=(i,d)=>i?d?{refs:[...i.refs,...d.refs],finalize:async()=>{let[f,y]=await Promise.allSettled([i.finalize(),d.finalize()]),w=[];return f.status==="fulfilled"?w.push(f.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",f.reason),y.status==="fulfilled"?w.push(y.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",y.reason),lD(w)}}:i:d,Jf=()=>{let d=we.getInlineMessageFields?.();return d&&d.contentSegments.some(y=>y.kind==="mention")?d.contentSegments:void 0},Br=!1,fi=null,np=()=>{we.value="",we.style.height="auto",Zo(),Hl()},Zf="data-persona-composer-notice",ga=null;function tP(i){nd(i),!(xe()||!pt)&&(pt.hasAttribute(Za)||(pt.setAttribute(Zf,""),pt.setAttribute("role","status"),pt.setAttribute("aria-live","polite"),pt.textContent=i,xi(pt,o.statusIndicator??{},"idle"),ga&&clearTimeout(ga),ga=setTimeout(()=>{if(ga=null,!!pt?.hasAttribute(Zf)&&(pt.removeAttribute(Zf),pt.removeAttribute("role"),pt.removeAttribute("aria-live"),h)){let d=N.getStatus();Qo(pt,_s(d),o.statusIndicator??{},d)}},4e3)))}function nP(){let i=ze.getState().pendingSubmission;i&&(Ui(void 0),we&&(we.value=i.text,we.dispatchEvent(new Event("input",{bubbles:!0})),Zo()),i.options.selectedModelId&&(ze.setSelectedModelId(i.options.selectedModelId),Zr?.repaint()),i.options.activeModeIds?.length&&id(i.options.activeModeIds),i.options.quote&&er(i.options.quote),we?.focus())}let oP=i=>{typeof console<"u"&&console.error("[AgentWidget] composer.onBeforeSend failed; the draft was preserved:",i)},RC=(i={})=>{let d=(i.overrideText??we?.value??"").trim();return i.resolveInlineCommand&&d?(un?.takeInlineCommand(d)??Promise.resolve(null)).then(f=>HC(i,d,f)):HC(i,d,null)},HC=(i,d,f)=>{if(f?.kind==="action"){np(),un?.clear(),zs();return}let y=f?.kind==="server"?f.mentions:null,w=f?.kind==="prompt"?f.sendText:d,k=i.pending?.contentParts,q=(Lt?.hasAttachments()??!1)||(k?.length??0)>0;if(!eA({text:w,hasAttachments:q,attachmentsReady:Lt?.isReady()??!0,hasMentions:un?.hasMentions()??!1,hasServerMentions:!!y,inputDisabled:sr(),sendDisabled:si()}))return;let te=N.isStreaming()?Dm():"block";if(te==="defer-one"&&!i.pending){if(ze.getState().pendingSubmission){tP("One message is already queued. Edit or remove it first.");return}rP({intent:i,sendText:w,serverMentions:y});return}let Q={text:w,mentionRefs:[...un?.getMentionRefs()??[],...y?.refs??[]],contentSegments:f?.kind==="prompt"?void 0:Jf(),options:{...ze.getState().selectedModelId&&{selectedModelId:ze.getState().selectedModelId},...ze.getState().activeModeIds.length>0&&{activeModeIds:[...ze.getState().activeModeIds]},...ze.getState().quote&&{quote:{...ze.getState().quote}}},viaVoice:i.viaVoice};i.pending&&(Q.options={...i.pending.options},Q.contentSegments=i.pending.contentSegments,Q.mentionRefs=[...i.pending.mentionRefs],Q.viaVoice=i.pending.viaVoice);let re=()=>{if(k?.length)return[...k];if(!Lt?.hasAttachments())return;let kt=[...Lt.getContentParts()];return Q.text&&kt.push(fr(Q.text)),kt};Q.contentParts=re();let ce=()=>{Zs(),Zk();let kt=un?.collectForSubmit()??null,no=eP(kt,y),Jt=re();i.consumeDraft!==!1&&np();let rn={selectedModelId:Q.options.selectedModelId,activeModeIds:Q.options.activeModeIds},Vn=te==="interrupt";Vn&&N.cancel(),N.sendMessage(Q.text,{contentParts:Jt,mentions:no??void 0,contentSegments:Q.contentSegments,viaVoice:Q.viaVoice,composerOptions:rn,...Q.options.quote&&{quote:Q.options.quote},...Vn&&{interrupt:!0}}),Lt?.hasAttachments()&&Lt.clearAttachments(),kt&&un?.clear(),zs();let ln=ze.getState().activeModeIds,$t=FS(ln,o.composer?.modes);$t.length!==ln.length&&id($t),ze.getState().quote&&er(void 0),Sd(),Vm.release(),_o()},he=o.composer?.onBeforeSend;if(!he){ce();return}let De=new AbortController;fi=De;let lt=kt=>{if(fi=null,kt.status==="error"){oP(kt.error);return}kt.status==="proceed"&&ce()},It=tA(he,Q,De.signal);if(!(It instanceof Promise)){lt(It);return}return ze.setPreparing(!0),It.then(lt).finally(()=>ze.setPreparing(!1))};function rP(i){let d=ze.getState(),f=Lt?.hasAttachments()??!1,y=f?[...Lt.getContentParts()]:[];f&&i.sendText&&y.push(fr(i.sendText));let w=wh({text:i.sendText,contentParts:y.length?y:void 0,mentionRefs:[...un?.getMentionRefs()??[],...i.serverMentions?.refs??[]],contentSegments:Jf(),options:{...d.selectedModelId&&{selectedModelId:d.selectedModelId},...d.activeModeIds.length>0&&{activeModeIds:[...d.activeModeIds]},...d.quote&&{quote:{...d.quote}}},viaVoice:i.intent.viaVoice});Ui(w),i.intent.consumeDraft!==!1&&np(),f&&Lt.clearAttachments(),un?.clear(),zs(),d.quote&&er(void 0),Sd(),Vm.release(),_o(),nd("Message queued. It sends when the response finishes.")}function sP(){let i=ze.getState().pendingSubmission;i&&(Ui(void 0),rp(i.text,{consumeDraft:!1,pending:i}))}function iP(i){if(o.messageActions?.showEdit!==!0)return;let d=N.getMessages().find(f=>f.id===i);!d||!Yg(d)||Js!==i&&(Zs(),Js=i,os=qS({messageId:i,initialText:d.content,onSave:f=>aP(i,f),onCancel:()=>Zs()}),mn.delete(i),xo(We,N.getMessages(),j),os.focus())}function aP(i,d){let f=os;if(Js=null,os=null,f?.destroy(),mn.delete(i),!N.resubmitFrom(i,{reason:"edit",replacement:{text:d,mentionRefs:[],options:{}}})){xo(We,N.getMessages(),j);return}eo()}function lP(i){if(N.isStreaming())return;let d=Gg(N.getMessages(),i);d&&(Zs(),N.resubmitFrom(d,{reason:"retry"})&&eo())}ad={regenerate:lP,edit:iP,quote:i=>{let f=N.getMessages().find(y=>y.id===i)?.content?.trim();f&&(er({text:f,messageId:i}),we?.focus())}};let Rl=async i=>{if(!Br){Br=!0;try{await RC({resolveInlineCommand:!0,...i})}finally{Br=!1}}};function op(i){si()||(np(),rp(i,{consumeDraft:!1}))}let rp=(i,d)=>{if(Br)return;Br=!0;let f=()=>{Br=!1};try{let y=RC({...d,overrideText:i});y instanceof Promise?y.finally(f):f()}catch(y){throw f(),y}},cP=i=>{if(i.preventDefault(),N.isStreaming()){N.cancel(),Rt?.reset(),Re?.update();return}Br||Rl()},dP=()=>o.features?.composerHistory!==!1,eg={...$h},tg=!1,Hl=()=>{eg={...$h}},pP=()=>N.getMessages().filter(i=>i.role==="user").map(i=>i.content??"").filter(i=>i.length>0),uP=i=>{if(!we)return;tg=!0,we.value=i,we.dispatchEvent(new Event("input",{bubbles:!0})),tg=!1;let d=we.value.length;we.setSelectionRange(d,d)},mP=i=>{tg||(i.isComposing||un?.handleInput(i.inputType??void 0),Hl())},fP=()=>({submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:rc(we)}),gP=i=>{if(we&&!sr()&&!(!i.isComposing&&un?.handleKeydown(i))){if(dP()&&(i.key==="ArrowUp"||i.key==="ArrowDown")&&!i.shiftKey&&!i.metaKey&&!i.ctrlKey&&!i.altKey&&!i.isComposing){let d=we.selectionStart===0&&we.selectionEnd===0,f=QA({direction:i.key==="ArrowUp"?"up":"down",history:pP(),currentValue:we.value,atStart:d,state:eg});if(eg=f.state,f.handled){i.preventDefault(),f.value!==void 0&&uP(f.value);return}}if(wS(i,fP())){if(N.isStreaming()){if(i.preventDefault(),Dm()==="block"||Br||si())return;Hl(),Rl();return}if(Br){i.preventDefault();return}if(si()){i.preventDefault();return}Hl(),i.preventDefault(),Ve.click()}}},WC=i=>{if(!(i.key!=="Escape"||i.isComposing)&&i.composedPath().includes(Pe)){if(fi){fi.abort(),fi=null,i.preventDefault(),i.stopImmediatePropagation();return}N.isStreaming()&&(N.cancel(),Rt?.reset(),Re?.update(),Hl(),i.preventDefault(),i.stopImmediatePropagation())}},hP=async i=>{if(o.attachments?.enabled!==!0||!Lt||sr())return;let d=rD(i.clipboardData);d.length!==0&&(i.preventDefault(),await Lt.handleFiles(d))},Eo=null,lr=!1,ha=null,tn=null,ng=()=>o.voiceRecognition?.completionBehavior==="review";function gi(i){ye?.setAttribute("data-state",i),i==="recording"?bP():ig()}let BC="--persona-voice-level",og=.5,ya=null,rg=-1,sp=0,DC=()=>{let i=[],d=co??ye?.parentElement??null;return d&&i.push(d),Qe&&i.push(Qe),i},sg=i=>{let d=Math.round(Math.max(0,Math.min(1,i))*100)/100;if(d!==rg){rg=d;for(let f of DC())f.style.setProperty(BC,String(d))}},yP=()=>{rg=-1,sp=0;for(let i of DC())i.style.removeProperty(BC)};function bP(){if(ya!==null)return;if(typeof requestAnimationFrame!="function"){sg(h?N.getVoiceLevel()??og:og);return}let i=()=>{ya=requestAnimationFrame(i);let d=h?N.getVoiceLevel():null;if(d===null){sg(og);return}sp+=(d-sp)*.3,sg(sp)};ya=requestAnimationFrame(i)}function ig(){ya!==null&&(cancelAnimationFrame(ya),ya=null),yP()}let OC=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,ip=(i="user")=>{if(lr||N.isStreaming())return;let d=OC();if(!d)return;Eo=new d;let f=o.voiceRecognition??{},y=f.pauseDuration??2e3;Eo.continuous=f.provider?.browser?.continuous??!0,Eo.interimResults=!0,Eo.lang=f.provider?.browser?.language??"en-US";let w=we.value;Eo.onresult=k=>{let q="",te="";for(let re=0;re<k.results.length;re++){let ce=k.results[re],he=ce[0].transcript;ce.isFinal?q+=he+" ":te=he}let Q=w+q+te;we.value=Q,Zo(),ha&&clearTimeout(ha),(q||te)&&(ha=window.setTimeout(()=>{if(we.value.trim()&&Eo&&lr){if(us(),ng())return;Rl({viaVoice:!0})}},y))},Eo.onerror=k=>{k.error!=="no-speech"&&us()},Eo.onend=()=>{if(lr){let k=we.value.trim();!ng()&&k&&k!==w.trim()&&Rl({viaVoice:!0}),us()}};try{if(Eo.start(),lr=!0,wt.active=!0,i!=="system"&&(wt.manuallyDeactivated=!1),kr(i),Vo(),_o(),ye){let k=o.voiceRecognition??{};tn={backgroundColor:ye.style.backgroundColor,color:ye.style.color,borderColor:ye.style.borderColor,iconName:k.iconName??"mic",iconSize:parseFloat(k.iconSize??"")||Un};let q=k.recordingBackgroundColor,te=k.recordingIconColor,Q=k.recordingBorderColor;if(ye.classList.add("persona-voice-recording"),gi("recording"),ye.style.backgroundColor=q??"var(--persona-voice-recording-bg, #ef4444)",ye.style.color=te??"var(--persona-voice-recording-indicator, #ffffff)",te){let re=ye.querySelector("svg");re&&re.setAttribute("stroke",te)}Q&&(ye.style.borderColor=Q),ye.setAttribute("aria-label","Stop voice recognition")}}catch{us("system")}},us=(i="user")=>{if(lr){if(lr=!1,ha&&(clearTimeout(ha),ha=null),Eo){try{Eo.stop()}catch{}Eo=null}if(wt.active=!1,kr(i),Vo(),_o(),ye){if(ye.classList.remove("persona-voice-recording"),gi("idle"),tn){ye.style.backgroundColor=tn.backgroundColor,ye.style.color=tn.color,ye.style.borderColor=tn.borderColor;let d=ye.querySelector("svg");d&&d.setAttribute("stroke",tn.color||"currentColor"),tn=null}ye.setAttribute("aria-label","Start voice recognition")}}},ag=()=>{if(!ye||tn)return;let i=o.voiceRecognition??{};tn={backgroundColor:ye.style.backgroundColor,color:ye.style.color,borderColor:ye.style.borderColor,iconName:i.iconName??"mic",iconSize:parseFloat(i.iconSize??"")||Un}},lg=(i,d)=>{if(!ye)return;let f=ye.querySelector("svg");f&&f.remove();let y=tn?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??"")||Un),w=ke(i,y,d,1.5);w&&ye.appendChild(w)},ap=()=>{ye&&ye.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},ba=()=>{if(!ye)return;ag();let i=o.voiceRecognition??{},d=i.recordingBackgroundColor,f=i.recordingIconColor,y=i.recordingBorderColor;if(ap(),ye.classList.add("persona-voice-recording"),gi("recording"),ye.style.backgroundColor=d??"var(--persona-voice-recording-bg, #ef4444)",ye.style.color=f??"var(--persona-voice-recording-indicator, #ffffff)",f){let w=ye.querySelector("svg");w&&w.setAttribute("stroke",f)}y&&(ye.style.borderColor=y),ye.setAttribute("aria-label","Stop voice recognition")},vP=()=>{if(!ye)return;ag();let i=o.voiceRecognition??{},d=N.getVoiceInterruptionMode(),f=i.processingIconName??"loader",y=i.processingIconColor??tn?.color??"",w=i.processingBackgroundColor??tn?.backgroundColor??"",k=i.processingBorderColor??tn?.borderColor??"";ap(),ye.classList.add("persona-voice-processing"),gi("processing"),ye.style.backgroundColor=w,ye.style.borderColor=k;let q=y||"currentColor";ye.style.color=q,lg(f,q),ye.setAttribute("aria-label","Processing voice input"),d==="none"&&(ye.style.cursor="default")},CP=()=>{if(!ye)return;ag();let i=o.voiceRecognition??{},d=N.getVoiceInterruptionMode(),f=d==="cancel"?"square":d==="barge-in"?"mic":"volume-2",y=i.speakingIconName??f,w=i.speakingIconColor??(d==="barge-in"?i.recordingIconColor??tn?.color??"":tn?.color??""),k=i.speakingBackgroundColor??(d==="barge-in"?i.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":tn?.backgroundColor??""),q=i.speakingBorderColor??(d==="barge-in"?i.recordingBorderColor??"":tn?.borderColor??"");ap(),ye.classList.add("persona-voice-speaking"),gi("speaking"),ye.style.backgroundColor=k,ye.style.borderColor=q;let te=w||"currentColor";ye.style.color=te,lg(y,te);let Q=d==="cancel"?"Stop playback and re-record":d==="barge-in"?"Speak to interrupt":"Agent is speaking";ye.setAttribute("aria-label",Q),d==="none"&&(ye.style.cursor="default"),d==="barge-in"&&ye.classList.add("persona-voice-recording")},Dr=()=>{ye&&(ap(),gi("idle"),tn&&(ye.style.backgroundColor=tn.backgroundColor??"",ye.style.color=tn.color??"",ye.style.borderColor=tn.borderColor??"",lg(tn.iconName,tn.color||"currentColor"),tn=null),ye.style.cursor="",ye.setAttribute("aria-label","Start voice recognition"))},cg=()=>{if(!sr()){if(so(o.voiceRecognition?.provider)){let i=N.getVoiceStatus(),d=N.getVoiceInterruptionMode();if(d==="none"&&(i==="processing"||i==="speaking"))return;if(d==="cancel"&&(i==="processing"||i==="speaking")){N.stopVoicePlayback();return}if(N.isBargeInActive()){N.stopVoicePlayback(),N.deactivateBargeIn().then(()=>{wt.active=!1,wt.manuallyDeactivated=!0,Vo(),kr("user"),Dr()});return}N.toggleVoice().then(()=>{wt.active=N.isVoiceActive(),wt.manuallyDeactivated=!N.isVoiceActive(),Vo(),kr("user"),N.isVoiceActive()?ba():Dr()});return}if(lr){let i=we.value.trim();wt.manuallyDeactivated=!0,Vo(),us("user"),i&&!ng()&&Rl()}else wt.manuallyDeactivated=!1,Vo(),ip("user")}};Om=cg,ye&&_e.push(()=>{so(o.voiceRecognition?.provider)?(N.isVoiceActive()&&N.toggleVoice(),Dr()):us("system")});let wP=R.on("assistant:complete",()=>{ze.getState().pendingSubmission&&setTimeout(()=>{N.isStreaming()||sP()},0)});_e.push(wP);let xP=R.on("assistant:complete",()=>{vv&&(wt.active||wt.manuallyDeactivated||vv==="assistant"&&!wt.lastUserMessageWasVoice||setTimeout(()=>{!wt.active&&!wt.manuallyDeactivated&&(so(o.voiceRecognition?.provider)?N.toggleVoice().then(()=>{wt.active=N.isVoiceActive(),kr("auto"),N.isVoiceActive()&&ba()}):ip("auto"))},600))});_e.push(xP);let SP=R.on("action:resubmit",()=>{setTimeout(()=>{N&&!N.isStreaming()&&N.continueConversation()},100)});_e.push(SP);let _C=()=>{qt(!Ae,"user")},sn=null,Fn=null;if(_&&!xe()){let{instance:i,element:d}=gy({config:o,plugins:u,onToggle:_C});sn=i,i||(Fn=d)}sn?t.appendChild(sn.element):Fn&&t.appendChild(Fn),bl(),Qs(),Id(),yf(),vl(N.isStreaming()),rf()||(po()==="follow"?as(!0):Ad()),$0(),He&&(!_||xe()?setTimeout(()=>ii(),0):Ae&&setTimeout(()=>ii(),200));let ms=null,NC=()=>{ms&&(ms.disconnect(),ms.observe(Qe),ms.observe(Pe),ms.observe(gn))},FC=sl(),Wl=()=>{if(xe()){$s(),bl();return}let i=nn(o),d=o.launcher?.sidebarMode??!1,f=t.ownerDocument.defaultView??window,y=o.launcher?.mobileFullscreen??!0,w=o.launcher?.mobileBreakpoint??640,k=f.innerWidth<=w,q=y&&k&&_;try{if(q){Us(),cl=gd();return}let te=!1;bt&&(bt=!1,Us(),te=!0);let Q=gd();if(!te&&Q!==cl&&(Us(),te=!0),cl=Q,te&&pd(),!_&&!i){Se.style.height="",Se.style.width="";return}if(!d&&!i){let re=Ri(o);Se.style.width=re.width,Se.style.maxWidth=re.maxWidth}fd(),ov()}finally{$s(),sd();let te=sl();if(te!==FC&&(FC=te,sa(),Qs()),bl(),Ae&&_){let re=(t.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),ce=o.launcher?.sidebarMode??!1,he=o.launcher?.mobileFullscreen??!0,De=nn(o)&&he&&re,lt=ce||he&&re&&_||De;if(lt&&!rr){let It=t.getRootNode(),kt=It instanceof ShadowRoot?It.host:t.closest(".persona-host");kt&&!or&&(or=Qh(kt,o.launcher?.zIndex??On)),rr=Xh(t.ownerDocument)}else lt||(or?.(),or=null,rr?.(),rr=null)}}};Wl();let lp=t.ownerDocument.defaultView??window;if(lp.addEventListener("resize",Wl),_e.push(()=>lp.removeEventListener("resize",Wl)),typeof ResizeObserver<"u"){ms=new ResizeObserver(()=>{sd()}),NC(),_e.push(()=>{ms?.disconnect(),ms=null});let i=new ResizeObserver(()=>{Kd()});i.observe(Pe),_e.push(()=>i.disconnect())}lp.addEventListener("resize",Kd),_e.push(()=>lp.removeEventListener("resize",Kd)),fo=pe.scrollTop;let VC=br(pe),$C=()=>{nv();let i=pe.scrollTop,d=br(pe),f=d<VC;if(VC=d,!Jr()){fo=i,xn();return}let{action:y,nextLastScrollTop:w}=zu({following:mo.isFollowing(),currentScrollTop:i,lastScrollTop:fo,nearBottom:jr(pe,Tr),userScrollThreshold:_0,isAutoScrolling:Jn||yd||f,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(fo=w,y==="resume"){Md()||Zn();return}y==="pause"&&na()};if(pe.addEventListener("scroll",$C,{passive:!0}),_e.push(()=>pe.removeEventListener("scroll",$C)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{Y0(),Rg(We)});i.observe(We),i.observe(pe),_e.push(()=>i.disconnect())}let zC=()=>{Jr()&&mo.isFollowing()&&Md()&&na()},UC=pe.ownerDocument;UC.addEventListener("selectionchange",zC),_e.push(()=>{UC.removeEventListener("selectionchange",zC)});let AP=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),qC=i=>{AP.has(i.key)&&(is(),Mb()&&Jr()&&mo.isFollowing()&&na())},jC=i=>{i.target?.closest("a, button, [tabindex], input, textarea, select")&&(is(),Mb()&&Jr()&&mo.isFollowing()&&na())};pe.addEventListener("keydown",qC),pe.addEventListener("focusin",jC),_e.push(()=>{pe.removeEventListener("keydown",qC),pe.removeEventListener("focusin",jC)});let KC=i=>{if(i.deltaY!==0&&is(),!Jr())return;let d=Uu({following:mo.isFollowing(),deltaY:i.deltaY,nearBottom:jr(pe,Tr),resumeWhenNearBottom:!0});d==="pause"?na():d==="resume"&&!Md()&&Zn()};pe.addEventListener("wheel",KC,{passive:!0}),pe.addEventListener("touchmove",is,{passive:!0}),pe.addEventListener("pointerdown",is,{passive:!0}),_e.push(()=>{pe.removeEventListener("touchmove",is),pe.removeEventListener("pointerdown",is)}),_e.push(()=>pe.removeEventListener("wheel",KC)),hn.addEventListener("click",()=>{$o(),pe.scrollTop=pe.scrollHeight,fo=pe.scrollTop,Zn(),as(!0),xn()}),_e.push(()=>hn.remove()),_e.push(()=>{Av(),$o()});let GC=()=>{Ce&&(Gs&&(Ce.removeEventListener("click",Gs),Gs=null),Ne()?(Ce.style.display="",Gs=()=>{qt(!1,"user")},Ce.addEventListener("click",Gs)):Ce.style.display="none")};GC(),(()=>{let{clearChatButton:i}=ot;i&&i.addEventListener("click",()=>{if(ar()){Kf({focusComposer:!0}).catch(f=>{o.debug&&console.warn("[AgentWidget] New conversation failed:",f)});return}N.clearMessages(),o.layout?.topFade&&(pe.scrollTop=0),pe.removeAttribute("data-persona-top-fade"),mn.clear(),Zn(),La(ot.composerOverlay);try{localStorage.removeItem(Ja),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ja}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Ja)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(f){console.error("[AgentWidget] Failed to clear custom localStorage:",f)}let d=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(d),x?.clear&&wd(()=>x.clear(),"[AgentWidget] Failed to clear storage adapter:"),L={},se.syncFromMetadata(),Lt?.clearAttachments(),Sd(),Ui(void 0),er(void 0),Zs(),ct?.clear(),Rt?.reset(),Re?.update()})})();let YC=[["keydown",gP],["input",mP],["input",Zo],["input",zs],["keyup",zs],["paste",hP],["focus",E0]],QC=i=>{if(i)for(let[d,f]of YC)Et?.addListener(i,d,f)},MP=i=>{if(i)for(let[d,f]of YC)Et?.removeListener(i,d,f)},XC=()=>{Et&&(Et.addListener(Et.form,"submit",cP),Et.addListener(Et.footer,"click",zs),QC(we),ye&&Et.addListener(ye,"click",cg))};XC();let JC=()=>{un?.onComposerSwap((i,d)=>{MP(d),we=i,Et&&(Et.input=i),QC(i),Nm(),df(),Zo()})};JC();let dg=!1;function ZC(){if(!dg){dg=!0;try{let i=we?.value??"",d=Qe.ownerDocument??document,f=we?d.activeElement===we:!1;ig(),Et?.destroy(),Et=null,un?.destroy(),un=null;let y=null,w=()=>(y=xe()?Ju({config:o}):Ic({config:o}),y.footer),k=Bb(w)??w();Cn.replaceComposer(k),Qe=Cn.composer.footer;let q=y!==null&&k===y.footer;ji=!q,Ab=q?y.setSendButtonMode:()=>{},Wb(Qe),Ob(Qe),_b(),Nb(),Fb(),JC(),Vb(),Fm(),$b(),XC();let te=Ks.indexOf(Mr);if(Mr.destroy(),Mr=kc(lo),te>=0&&(Ks[te]=Mr),we&&(we.value=i),Zo(),zs(),Id(),Qs(),vl(N.isStreaming()),o.statusIndicator?.mode==="transient"&&!xe()){let Q=N.getStatus();Qo(pt,_s(Q),o.statusIndicator,Q)}wt.active&&gi("recording"),Us(),NC(),$s(),_o(),Pd(),f&&we?.focus()}finally{dg=!1}}}let Bl=t.ownerDocument??document;Bl.addEventListener("keydown",WC,!0);let ew=()=>{ef()},tw=()=>{Bl.visibilityState==="hidden"&&ef()};typeof window<"u"&&(window.addEventListener("pagehide",ew),Bl.addEventListener("visibilitychange",tw),_e.push(()=>{window.removeEventListener("pagehide",ew),Bl.removeEventListener("visibilitychange",tw)}));let nw="persona-attachment-drop-active",Dl=0,pg=()=>{Dl=0,Pe.classList.remove(nw)},va=()=>o.attachments?.enabled===!0&&Lt!==null&&!sr(),ow=i=>{!Tm(i.dataTransfer)||!va()||(Dl++,Dl===1&&Pe.classList.add(nw))},rw=i=>{!Tm(i.dataTransfer)||!va()||(Dl--,Dl<=0&&pg())},sw=i=>{!Tm(i.dataTransfer)||!va()||(i.preventDefault(),i.dataTransfer.dropEffect="copy")},iw=i=>{if(!Tm(i.dataTransfer)||!va())return;i.preventDefault(),i.stopPropagation(),pg();let d=Array.from(i.dataTransfer.files??[]);d.length!==0&&Lt.handleFiles(d)},fs=!0;Pe.addEventListener("dragenter",ow,fs),Pe.addEventListener("dragleave",rw,fs),t.addEventListener("dragover",sw,fs),t.addEventListener("drop",iw,fs);let cp=t.ownerDocument,aw=i=>{va()&&i.preventDefault()},lw=i=>{va()&&i.preventDefault()};cp.addEventListener("dragover",aw),cp.addEventListener("drop",lw),_e.push(()=>{Et?.destroy(),Et=null,ig(),tr?.destroy(),tr=null,Sr?.destroy(),Sr=null,es?.destroy(),es=null,ts?.destroy(),ts=null,Zr=null,Bm=null,ef(),ml.destroy(),ga&&clearTimeout(ga),Zs(),fi?.abort(),fi=null,Lt?.destroy(),Lt=null,ze.destroy(),Bl.removeEventListener("keydown",WC,!0),un?.destroy()}),_e.push(()=>{Pe.removeEventListener("dragenter",ow,fs),Pe.removeEventListener("dragleave",rw,fs),t.removeEventListener("dragover",sw,fs),t.removeEventListener("drop",iw,fs),cp.removeEventListener("dragover",aw),cp.removeEventListener("drop",lw),pg()}),_e.push(()=>{N.cancel()}),sn?_e.push(()=>{sn?.destroy()}):Fn&&_e.push(()=>{Fn?.remove()});let an={update(i){let d=o.future?.v5Defaults===!0,f=o.toolCall,y=o.messageActions,w=o.layout?.messages,k=o.colorScheme,q=o.loadingIndicator,te=o.iterationDisplay,Q=o.features?.showReasoning,re=o.features?.showToolCalls,ce=o.features?.toolCallDisplay,he=o.features?.reasoningDisplay,De=o.features?.streamAnimation?.type,lt=o.features?.history?.enabled===!0,It=o.features?.history?.provider,kt=o.getIdentityProof,no=o.clientToken,Jt=o.contextMentions;o=xE({...o,features:p},i),p=o.features,o=Yy(o),c(),Km(),gc(t,o),Uc(t,o),qc(t,o),ft(),Fo(),o.colorScheme!==k&&rv();let rn=Jy.getForInstance(o.plugins);u.length=0,u.push(...rn),oC(),_=o.launcher?.enabled??!0,Te=o.launcher?.autoExpand??!1,J=o.features?.showReasoning??!0,Y=o.features?.showToolCalls??!0,Me=o.features?.scrollToBottom??{};let Vn=po();Ee=o.features?.scrollBehavior??{},Vn!==po()&&($o(),Zn()),bv(),kb(),xn();let ln=ie;if(ie=o.features?.showEventStreamToggle??!1,ie&&!ln){if(ct||(Tt(),N.setSSEEventCallback((ue,ht)=>{o.onSSEEvent?.(ue,ht),qe(ue,ht)})),!Ht&&$e){let ue=o.features?.eventStream?.classNames,ht="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(ue?.toggleButton?" "+ue.toggleButton:"");Ht=v("button",ht),Ht.style.width="28px",Ht.style.height="28px",Ht.style.color=qn.actionIconColor,Ht.type="button",Ht.setAttribute("aria-label","Event Stream"),Ht.title="Event Stream";let yt=Ge(Xr.Activity,"18px","currentColor",1.5);yt&&Ht.appendChild(yt);let Pt=ot.clearChatButtonWrapper,Yt=ot.closeButtonWrapper,Dn=Pt||Yt;Dn&&Dn.parentNode===$e?$e.insertBefore(Ht,Dn):$e.appendChild(Ht),Ht.addEventListener("click",()=>{nt?qi():_m()})}}else!ie&&ln&&(qi(),Ht&&(Ht.remove(),Ht=null),ct?.clear(),rt?.destroy(),ct=null,rt=null,Rt?.reset(),Rt=null,Z=null);if(o.launcher?.enabled===!1&&sn&&(sn.destroy(),sn=null),o.launcher?.enabled===!1&&Fn&&(Fn.remove(),Fn=null),o.launcher?.enabled!==!1&&!sn&&!Fn){let{instance:ue,element:ht}=gy({config:o,plugins:u,onToggle:_C});sn=ue,ue||(Fn=ht),t.appendChild(ht)}sn&&sn.update(o),Il(),Yn&&o.launcher?.subtitle!==void 0&&(Yn.textContent=o.launcher.subtitle);let $t=o.layout?.header;if($t?.layout!==Wt&&$e){let ue=$t?Qu(o,$t,{showClose:Ne(),onClose:()=>qt(!1,"user")}):Pi({config:o,showClose:Ne(),onClose:()=>qt(!1,"user")});Cn.replaceHeader(ue),$e=Cn.header.element,St=Cn.header.iconHolder,Bn=Cn.header.headerTitle,Yn=Cn.header.headerSubtitle,Ce=Cn.header.closeButton,Wt=$t?.layout,Il()}else if($t){if(St&&(St.style.display=$t.showIcon===!1?"none":""),Bn&&(Bn.style.display=$t.showTitle===!1?"none":""),Yn&&(Yn.style.display=$t.showSubtitle===!1?"none":""),Ce){let ue=Ne()&&$t.showCloseButton!==!1;Ce.style.display=ue?"":"none"}if(ot.clearChatButtonWrapper){let ue=$t.showClearChat;if(ue!==void 0){ot.clearChatButtonWrapper.style.display=ue?"":"none";let{closeButtonWrapper:ht}=ot;ht&&!ht.classList.contains("persona-absolute")&&(ue?ht.classList.remove("persona-ml-auto"):ht.classList.add("persona-ml-auto"))}}}let dr=o.layout?.showHeader!==!1;$e&&($e.style.display=dr?"":"none");let Po=o.layout?.showFooter!==!1;Qe&&(Qe.style.display=Po?"":"none"),$s(),xn(),_!==At?_?qt(Te,"auto"):(Ae=!0,bl()):Te!==ut&&qt(Te,"auto"),ut=Te,At=_,Wl(),GC();let pr=JSON.stringify(o.toolCall)!==JSON.stringify(f),zo=JSON.stringify(o.messageActions)!==JSON.stringify(y),hs=JSON.stringify(o.layout?.messages)!==JSON.stringify(w),Ol=o.loadingIndicator?.render!==q?.render||o.loadingIndicator?.renderIdle!==q?.renderIdle||o.loadingIndicator?.showBubble!==q?.showBubble,hi=o.iterationDisplay!==te,$=(o.features?.showReasoning??!0)!==(Q??!0)||(o.features?.showToolCalls??!0)!==(re??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(ce)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(he);(o.future?.v5Defaults===!0!==d||pr||zo||hs||Ol||hi||$)&&N&&(ei++,xo(We,N.getMessages(),j));let Je=o.features?.streamAnimation?.type;if(Je!==De&&Je&&Je!=="none"){let ue=Qm(Je,o.features?.streamAnimation?.plugins);ue&&xc(ue,t)}let fe=o.launcher??{},zt=fe.headerIconHidden??!1,fn=o.layout?.header?.showIcon,_n=zt||fn===!1,En=fe.headerIconName,jt=fe.headerIconSize??Fl;if(St){let ue=$e,ht=ue?.querySelector(".persona-flex-col");if(_n)St.style.display="none",ue&&ht&&!ue.contains(ht)&&ue.insertBefore(ht,ue.firstChild);else{if(St.style.display="",St.style.height=jt,St.style.width=jt,ue&&ht&&(ue.contains(St)?St.nextSibling!==ht&&(St.remove(),ue.insertBefore(St,ht)):ue.insertBefore(St,ht)),En){let Pt=parseFloat(jt)||24,Yt=ke(En,Pt*.6,"currentColor",1);Yt?(Yt.style.width=`calc(${Pt}px * var(--persona-components-header-iconScale, 0.6))`,Yt.style.height=`calc(${Pt}px * var(--persona-components-header-iconScale, 0.6))`,St.replaceChildren(Yt)):St.textContent=fe.agentIconText??"\u{1F4AC}"}else if(fe.iconUrl){let Pt=St.querySelector("img");if(Pt)Pt.src=fe.iconUrl,Pt.style.height=jt,Pt.style.width=jt;else{let Yt=document.createElement("img");Yt.src=fe.iconUrl,Yt.alt="",Yt.className="persona-rounded-xl persona-object-cover",Yt.style.height=jt,Yt.style.width=jt,St.replaceChildren(Yt)}}else{let Pt=St.querySelector("svg"),Yt=St.querySelector("img");(Pt||Yt)&&St.replaceChildren(),St.textContent=fe.agentIconText??"\u{1F4AC}"}let yt=St.querySelector("img");yt&&(yt.style.height=jt,yt.style.width=jt)}}let cn=o.layout?.header?.showTitle,Sn=o.layout?.header?.showSubtitle;if(Bn&&(Bn.style.display=cn===!1?"none":""),Yn&&(Yn.style.display=Sn===!1?"none":""),Ce){let ue=Ne()&&o.layout?.header?.showCloseButton!==!1;if(Ce.style.display=ue?"":"none",!xe()){let Pn=fe.closeButtonSize??"";Ce.style.height=Pn,Ce.style.width=Pn,Ce.style.minWidth=Pn,Ce.style.minHeight=Pn}let ht=fe.closeButtonPlacement??"inline",{closeButtonWrapper:yt}=ot,Pt=ht==="top-right",Yt=yt?.classList.contains("persona-absolute");if(yt&&Pt!==Yt)if(yt.remove(),Pt){yt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let Pn=Sl??Pe;Pn.style.position="relative",Pn.appendChild(yt)}else{let Pn=fe.clearChat?.placement??"inline",Ln=fe.clearChat?.enabled??!0;yt.className=Ln&&Pn==="inline"?"":"persona-ml-auto",$e&&$e.appendChild(yt)}if(Ce.style.color=fe.closeButtonColor||qn.actionIconColor,fe.closeButtonBackgroundColor?(Ce.style.backgroundColor=fe.closeButtonBackgroundColor,Ce.classList.remove("hover:persona-bg-gray-100")):(Ce.style.backgroundColor="",Ce.classList.add("hover:persona-bg-gray-100")),fe.closeButtonBorderWidth||fe.closeButtonBorderColor){let Pn=fe.closeButtonBorderWidth||"0px",Ln=fe.closeButtonBorderColor||"transparent";Ce.style.border=`${Pn} solid ${Ln}`,Ce.classList.remove("persona-border-none")}else Ce.style.border="",Ce.classList.add("persona-border-none");fe.closeButtonBorderRadius?(Ce.style.borderRadius=fe.closeButtonBorderRadius,Ce.classList.remove("persona-rounded-full")):(Ce.style.borderRadius="",Ce.classList.add("persona-rounded-full")),fe.closeButtonPaddingX?(Ce.style.paddingLeft=fe.closeButtonPaddingX,Ce.style.paddingRight=fe.closeButtonPaddingX):(Ce.style.paddingLeft="",Ce.style.paddingRight=""),fe.closeButtonPaddingY?(Ce.style.paddingTop=fe.closeButtonPaddingY,Ce.style.paddingBottom=fe.closeButtonPaddingY):(Ce.style.paddingTop="",Ce.style.paddingBottom=""),Gu(Ce,fe.closeButtonIconName??"x",{iconSize:xe()?py:void 0,iconText:fe.closeButtonIconText??"\xD7"});let Dn=fe.closeButtonTooltipText??"Close chat",qo=fe.closeButtonShowTooltip??!0;Ce.setAttribute("aria-label",Dn),yt&&In({anchor:Ce,trigger:yt,text:()=>Ce?.getAttribute("aria-label")??Dn,enabled:qo})}let{clearChatButton:Ke,clearChatButtonWrapper:Kt}=ot;if(Ke){let ue=fe.clearChat??{},ht=ue.enabled??!0,yt=o.layout?.header?.showClearChat,Pt=yt!==void 0?yt:ht,Yt=ue.placement??"inline";if(Kt){Kt.style.display=Pt?"":"none";let{closeButtonWrapper:Dn}=ot;!xe()&&Dn&&!Dn.classList.contains("persona-absolute")&&(Pt?Dn.classList.remove("persona-ml-auto"):Dn.classList.add("persona-ml-auto"));let qo=Yt==="top-right",Pn=Kt.classList.contains("persona-absolute");if(!xe()&&qo!==Pn&&Pt){if(Kt.remove(),qo){Kt.className="persona-absolute persona-top-4 persona-z-50",Kt.style.right="48px";let ur=Sl??Pe;ur.style.position="relative",ur.appendChild(Kt)}else{Kt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Kt.style.right="";let ur=ot.closeButtonWrapper;$e&&ur&&ur.parentElement===$e?$e.insertBefore(Kt,ur):$e&&$e.appendChild(Kt)}let Ln=ot.closeButtonWrapper;Ln&&!Ln.classList.contains("persona-absolute")&&(qo?Ln.classList.add("persona-ml-auto"):Ln.classList.remove("persona-ml-auto"))}}if(Pt){if(!xe()){let Ln=ue.size??"";Ke.style.height=Ln,Ke.style.width=Ln,Ke.style.minWidth=Ln,Ke.style.minHeight=Ln}let Dn=ue.iconColor??"";if(Ke.style.color=Dn||qn.actionIconColor,Gu(Ke,ue.iconName??"refresh-cw",{iconSize:xe()?uy:void 0}),ue.backgroundColor?(Ke.style.backgroundColor=ue.backgroundColor,Ke.classList.remove("hover:persona-bg-gray-100")):(Ke.style.backgroundColor="",Ke.classList.add("hover:persona-bg-gray-100")),ue.borderWidth||ue.borderColor){let Ln=ue.borderWidth||"0px",ur=ue.borderColor||"transparent";Ke.style.border=`${Ln} solid ${ur}`,Ke.classList.remove("persona-border-none")}else Ke.style.border="",Ke.classList.add("persona-border-none");ue.borderRadius?(Ke.style.borderRadius=ue.borderRadius,Ke.classList.remove("persona-rounded-full")):(Ke.style.borderRadius="",Ke.classList.add("persona-rounded-full")),ue.paddingX?(Ke.style.paddingLeft=ue.paddingX,Ke.style.paddingRight=ue.paddingX):(Ke.style.paddingLeft="",Ke.style.paddingRight=""),ue.paddingY?(Ke.style.paddingTop=ue.paddingY,Ke.style.paddingBottom=ue.paddingY):(Ke.style.paddingTop="",Ke.style.paddingBottom="");let qo=ue.tooltipText??"Clear chat",Pn=ue.showTooltip??!0;Ke.setAttribute("aria-label",qo),Kt&&In({anchor:Ke,trigger:Kt,text:()=>Ke?.getAttribute("aria-label")??qo,enabled:Pn})}}let et=o.actionParsers&&o.actionParsers.length?o.actionParsers:[eb],An=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[jc.message,jc.messageAndClick];se=tb({parsers:et,handlers:An,getSessionMetadata:le,updateSessionMetadata:de,emit:R.emit,documentRef:typeof document<"u"?document:null}),j=n0(o,se,I),mk(),N.updateConfig(o),LC(),(o.features?.history?.enabled===!0!==lt||o.features?.history?.provider!==It||o.getIdentityProof!==kt||o.clientToken!==no)&&(to({restoreFocus:!1}),Yv()),ps(),Kd(),xo(We,N.getMessages(),j),Qs(),Id(),pk(),vl(N.isStreaming()),Jt!==o.contextMentions&&ZC();let Io=o.voiceRecognition?.enabled===!0,kn=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),Ut=so(o.voiceRecognition?.provider);if(Io&&(kn||Ut))if(!ye||!co){let ue=Da(o);if(ue){ye=ue.button,co=ue.wrapper;let ht=Jo&&Jo.parentElement===ed?Jo:null;ed?ed.insertBefore(co,ht):Tn?.appendChild(co),Et&&(Et.micButton=ye),Et?.addListener(ye,"click",cg),ye.disabled=sr()||N.isStreaming()&&!lf()}}else{let ue=o.voiceRecognition??{},ht=o.sendButton??{},yt=ue.iconName??"mic",Pt=ue.iconSize,Yt=parseFloat(Pt??"")||Un;ye.classList.add(yo),ye.classList.toggle(Go,!Pt),ye.style.width=Pt??"",ye.style.height=Pt??"",ye.style.minWidth=Pt??"",ye.style.minHeight=Pt??"";let Dn=ue.iconColor??ht.textColor;ye.innerHTML="";let qo=ke(yt,Yt,Dn||"currentColor",1.5);qo?ye.appendChild(qo):ye.textContent="\u{1F3A4}";let Pn=ue.backgroundColor??ht.backgroundColor;Pn?ye.style.backgroundColor=Pn:ye.style.backgroundColor="",Dn?ye.style.color=Dn:ye.style.color="var(--persona-text, #111827)",ue.borderWidth?(ye.style.borderWidth=ue.borderWidth,ye.style.borderStyle="solid"):(ye.style.borderWidth="",ye.style.borderStyle=""),ue.borderColor?ye.style.borderColor=ue.borderColor:ye.style.borderColor="",ue.paddingX?(ye.style.paddingLeft=ue.paddingX,ye.style.paddingRight=ue.paddingX):(ye.style.paddingLeft="",ye.style.paddingRight=""),ue.paddingY?(ye.style.paddingTop=ue.paddingY,ye.style.paddingBottom=ue.paddingY):(ye.style.paddingTop="",ye.style.paddingBottom="");let Ln=ue.tooltipText??"Start voice recognition",ur=ue.showTooltip??!1;ye.setAttribute("aria-label",Ln),co&&In({anchor:ye,trigger:co,text:()=>ye?.getAttribute("aria-label")??Ln,enabled:ur}),co.style.display="",ye.disabled=sr()||N.isStreaming()&&!lf()}else ye&&co&&(co.style.display="none",so(o.voiceRecognition?.provider)?N.isVoiceActive()&&N.toggleVoice():lr&&us());if(o.attachments?.enabled===!0){if(!Qn||!on){let ue=o.attachments??{};Xn||(Xn=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Xn.style.display="none",(we.parentElement??Tn).insertBefore(Xn,we)),Xt||(Xt=document.createElement("input"),Xt.type="file",Xt.accept=(ue.allowedTypes??Ur).join(","),Xt.multiple=(ue.maxFiles??4)>1,Xt.style.display="none",Xt.setAttribute("aria-label","Attach files"),(we.parentElement??Tn).insertBefore(Xt,we)),Qn=v("div","persona-send-button-wrapper"),on=v("button",`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${yo} ${Go}`),on.type="button",on.setAttribute("aria-label",ue.buttonTooltipText??"Attach file");let ht=ue.buttonIconName??"paperclip";on.style.fontSize="18px",on.style.lineHeight="1";let yt=ke(ht,Un,"currentColor",1.5);yt?on.appendChild(yt):on.textContent="\u{1F4CE}",on.addEventListener("click",Yt=>{Yt.preventDefault(),Xt?.click()}),Qn.appendChild(on);let Pt=ue.buttonTooltipText??"Attach file";In({anchor:on,trigger:Qn,text:()=>on?.getAttribute("aria-label")??Pt}),Pm?Pm.append(Qn):Tn.appendChild(Qn),Et&&(Et.attachmentButton=on,Et.attachmentInput=Xt??void 0,Et.attachmentPreviews=Xn??void 0),!Lt&&Xt&&Xn&&(Lt=oc.fromConfig(ue,Pb),Lt.setPreviewsContainer(Xn),Et?.addListener(Xt,"change",async()=>{Lt&&Xt?.files&&(await Lt.handleFileSelect(Xt.files),Xt.value="")}))}else{Qn.style.display="";let ue=o.attachments??{};Xt&&(Xt.accept=(ue.allowedTypes??Ur).join(","),Xt.multiple=(ue.maxFiles??4)>1),Lt&&Lt.updateConfig({allowedTypes:ue.allowedTypes,maxFileSize:ue.maxFileSize,maxFiles:ue.maxFiles,adapter:ue.adapter})}if(Pe.querySelector(".persona-attachment-drop-overlay")?.remove(),Pe.appendChild(o0(o.attachments?.dropOverlay)),on){let ue=o.attachments??{},ht=ue.buttonTooltipText??"Attach file";on.setAttribute("aria-label",ht),on.textContent="";let yt=ke(ue.buttonIconName??"paperclip",Un,"currentColor",1.5);yt?on.appendChild(yt):on.textContent="\u{1F4CE}",Qn&&In({anchor:on,trigger:Qn,text:()=>on?.getAttribute("aria-label")??ht})}}else Qn&&(Qn.style.display="none"),Lt&&Lt.clearAttachments(),Pe.querySelector(".persona-attachment-drop-overlay")?.remove();let tt=o.sendButton??{},ys=tt.useIcon??!1,bn=tt.iconText??"\u2191",oo=tt.iconName,Or=tt.tooltipText??"Send message",ug=tt.showTooltip??!1,yi=tt.size,mg=parseFloat(yi??"")||uh,_r=tt.backgroundColor,bi=tt.textColor;if(ys){if(Ve.style.width=yi??"",Ve.style.height=yi??"",Ve.style.minWidth=yi??"",Ve.style.minHeight=yi??"",Ve.style.fontSize="18px",Ve.style.lineHeight="1",bi?Ve.style.color=bi:Ve.style.color="var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))",!N.isStreaming())if(Ve.innerHTML="",oo){let ue=parseFloat(tt.iconSize??"")||Math.round(mg*.5),ht=bi?.trim()||"currentColor",yt=tt.iconStrokeWidth??2,Pt=ke(oo,ue,ht,yt),Yt=ke(tt.stopIconName??"square",ue,ht,yt);Pt&&Yt?Ve.appendChild(mh(Pt,Yt)):Pt?Ve.appendChild(Pt):Ve.textContent=bn}else Ve.textContent=bn;Ve.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${yo}`,_r?(Ve.style.backgroundColor=_r,Ve.classList.remove("persona-bg-persona-primary")):(Ve.style.backgroundColor="",Ve.classList.add("persona-bg-persona-primary"))}else Ve.textContent=o.copy?.sendButtonLabel??"Send",Ve.style.width="",Ve.style.height="",Ve.style.minWidth="",Ve.style.minHeight="",Ve.style.fontSize="",Ve.style.lineHeight="",Ve.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",_r?(Ve.style.backgroundColor=_r,Ve.classList.remove("persona-bg-persona-accent")):Ve.classList.add("persona-bg-persona-accent"),bi?Ve.style.color=bi:Ve.classList.add("persona-text-white");tt.borderWidth?(Ve.style.borderWidth=tt.borderWidth,Ve.style.borderStyle="solid"):(Ve.style.borderWidth="",Ve.style.borderStyle=""),tt.borderColor?Ve.style.borderColor=tt.borderColor:Ve.style.borderColor="",tt.paddingX?(Ve.style.paddingLeft=tt.paddingX,Ve.style.paddingRight=tt.paddingX):(Ve.style.paddingLeft="",Ve.style.paddingRight=""),tt.paddingY?(Ve.style.paddingTop=tt.paddingY,Ve.style.paddingBottom=tt.paddingY):(Ve.style.paddingTop="",Ve.style.paddingBottom=""),N.isStreaming()||Ve.setAttribute("aria-label",Or),Pd(),Jo&&In({anchor:Ve,trigger:Jo,text:()=>Ve.getAttribute("aria-label")??Or,enabled:ug}),zb(),Ym();let cw=hu(ze.getState().activeModeIds,o.composer?.modes);ze.setActiveModeIds(cw),$i().length>0!==!!Sr&&Fm(),Sr?.render(cw,$i());for(let ue of[...zi.keys()])gu(ue,o.composer?.modeGroups)||zi.delete(ue);zi.forEach(ue=>ue.repaint()),Zr?.repaint(),tr?.resolve();let dp=Is(o,xe());if(Gm(),dp){We.style.maxWidth=dp,We.style.marginLeft="auto",We.style.marginRight="auto",We.style.width="100%",z.style.maxWidth=dp,z.style.marginLeft="auto",z.style.marginRight="auto",z.style.width="100%";for(let ue of[Tn,lo,Xn,pt])ue&&(ue.style.maxWidth=dp,ue.style.marginLeft="auto",ue.style.marginRight="auto",ue.style.width="100%")}else{We.style.maxWidth="",We.style.marginLeft="",We.style.marginRight="",We.style.width="",z.style.maxWidth="",z.style.marginLeft="",z.style.marginRight="",z.style.width="";for(let ue of[Tn,lo,Xn,pt])ue&&(ue.style.maxWidth="",ue.style.marginLeft="",ue.style.marginRight="",ue.style.width="")}let Uo=o.statusIndicator??{};if(Eg(pt,Tn,Uo),xi(pt,Uo,N?.getStatus()??"idle"),N){let ue=N.getStatus();Qo(pt,(yt=>yt==="idle"?Uo.idleText??dn.idle:yt==="connecting"?Uo.connectingText??dn.connecting:yt==="connected"?Uo.connectedText??dn.connected:yt==="error"?Uo.errorText??dn.error:yt==="paused"?Uo.pausedText??dn.paused:yt==="resuming"?Uo.resumingText??dn.resuming:dn[yt])(ue),Uo,ue)}pt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let kP=Uo.align==="left"?"persona-text-left":Uo.align==="center"?"persona-text-center":"persona-text-right";pt.classList.add(kP),Nm(),df(),_o(),Mn()},open(){Ne()&&qt(!0,"api")},close(){Ne()&&qt(!1,"api")},toggle(){Ne()&&qt(!Ae,"api")},reconnect(){N.reconnectNow()},clearChat(){Ar=!1,a.clear(),r.clear(),s.clear(),l.clear(),N.clearMessages(),o.layout?.topFade&&(pe.scrollTop=0),pe.removeAttribute("data-persona-top-fade"),mn.clear(),Zn();try{localStorage.removeItem(Ja),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ja}`)}catch(d){console.error("[AgentWidget] Failed to clear default localStorage:",d)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Ja)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(d){console.error("[AgentWidget] Failed to clear custom localStorage:",d)}let i=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(i),x?.clear&&wd(()=>x.clear(),"[AgentWidget] Failed to clear storage adapter:"),L={},se.syncFromMetadata(),Lt?.clearAttachments(),Sd(),Ui(void 0),er(void 0),Zs(),ct?.clear(),Rt?.reset(),Re?.update()},setMessage(i){return!we||N.isStreaming()||sr()?!1:(!Ae&&Ne()&&qt(!0,"system"),we.value=i,we.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(i){if(N.isStreaming()||si())return!1;let d=i?.trim()||we.value.trim();return d?(!Ae&&Ne()&&qt(!0,"system"),we.value="",we.style.height="auto",Zo(),rp(d,{consumeDraft:!1}),!0):!1},getComposerState(){return ze.getState()},setQuote(i){let d=i?.text?.trim();d&&er({...i,text:d})},clearQuote(){er(void 0)},startVoiceRecognition(){return N.isStreaming()?!1:so(o.voiceRecognition?.provider)?(N.isVoiceActive()||N.isBargeInActive()||(!Ae&&Ne()&&qt(!0,"system"),wt.manuallyDeactivated=!1,Vo(),N.toggleVoice().then(()=>{wt.active=N.isVoiceActive(),kr("user"),N.isVoiceActive()&&ba()})),!0):lr?!0:OC()?(!Ae&&Ne()&&qt(!0,"system"),wt.manuallyDeactivated=!1,Vo(),ip("user"),!0):!1},stopVoiceRecognition(){return so(o.voiceRecognition?.provider)?!N.isVoiceActive()&&!N.isBargeInActive()?!1:((N.isBargeInActive()?N.deactivateBargeIn():N.toggleVoice()).then(()=>{wt.active=!1,wt.manuallyDeactivated=!0,Vo(),kr("user"),Dr()}),!0):lr?(wt.manuallyDeactivated=!0,Vo(),us("user"),!0):!1},injectMessage(i){return!Ae&&Ne()&&qt(!0,"system"),N.injectMessage(i)},injectAssistantMessage(i){!Ae&&Ne()&&qt(!0,"system");let d=N.injectAssistantMessage(i);return vt&&(vt=!1,X&&(clearTimeout(X),X=null),setTimeout(()=>{N&&!N.isStreaming()&&N.continueConversation()},100)),d},injectUserMessage(i){return!Ae&&Ne()&&qt(!0,"system"),N.injectUserMessage(i)},injectSystemMessage(i){return!Ae&&Ne()&&qt(!0,"system"),N.injectSystemMessage(i)},injectMessageBatch(i){return!Ae&&Ne()&&qt(!0,"system"),N.injectMessageBatch(i)},injectComponentDirective(i){return!Ae&&Ne()&&qt(!0,"system"),N.injectComponentDirective(i)},injectTestMessage(i){!Ae&&Ne()&&qt(!0,"system"),N.injectTestEvent(i)},async connectStream(i,d){return N.connectStream(i,d)},__pushEventStreamEvent(i){ie&&(Tt(),qe(i.type,i.payload))},showEventStream(){ie&&_m()},hideEventStream(){nt&&qi()},isEventStreamVisible(){return nt},listConversations(i){return N.listConversations(i)},getActiveConversationId(){return N.getActiveConversationId()},openConversation(i,d){return jf(i,{focusComposer:d?.focus===!0})},startNewConversation(i){return Kf({focusComposer:i?.focus===!0})},warmSession(){Qf()},deleteConversation(i){return wC(i)},renameConversation(i,d){return Gf(i,{title:d})},setConversationStarred(i,d){return Gf(i,{starred:d})},clearConversationHistory(i){return xC(i)},resetHistoryIdentity(){return SC()},async getVisitorToken(){let i=So;if(!i)return null;let d=await i.get();return i===So?d:null},getHistoryIdentityStatus(){return go?go.getIdentityStatus():Pf()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory(i){return Ll({...i?.returnSurface?{returnSurface:i.returnSurface}:{},...i?.focus!==void 0?{focus:i.focus}:{}})},hideHistory(i){to(i?.restoreFocus!==void 0?{restoreFocus:i.restoreFocus}:void 0)},isHistoryVisible(){return mt},showArtifacts(){Kn(o)&&(Ar=!1,Ki=!0,Fo(),gt?.setMobileOpen(!0))},hideArtifacts(){Kn(o)&&(Ar=!0,Fo())},upsertArtifact(i){return Kn(o)?(Cs(o.features?.artifacts,{artifactType:i.artifactType,...i.artifactType==="markdown"&&i.file?{file:i.file}:{},...i.presentation?{presentation:i.presentation}:{}})==="panel"&&(Ar=!1,Ki=!0),N.upsertArtifact(i)):null},selectArtifact(i){Kn(o)&&N.selectArtifact(i)},clearArtifacts(){Kn(o)&&N.clearArtifacts()},getArtifacts(){return N?.getArtifacts()??[]},getSelectedArtifactId(){return N?.getSelectedArtifactId()??null},focusInput(){return _&&!Ae&&!xe()||!we?!1:(we.focus(),!0)},async resolveApproval(i,d,f){let w=N.getMessages().find(k=>k.variant==="approval"&&k.approval?.id===i);if(!w?.approval)throw new Error(`Approval not found: ${i}`);if(w.approval.toolType==="webmcp"){N.resolveWebMcpApproval(w.id,d);return}return N.resolveApproval(w.approval,d,f)},setFollowUpSuggestions(i){D0(i)},clearFollowUpSuggestions(){yv()},getMessages(){return N.getMessages()},getStatus(){return N.getStatus()},getPersistentMetadata(){return{...L}},updatePersistentMetadata(i){de(i)},on(i,d){return R.on(i,d)},off(i,d){R.off(i,d)},isOpen(){return Ne()&&Ae},isVoiceActive(){return wt.active},toggleReadAloud(i){N.toggleReadAloud(i)},stopReadAloud(){N.stopSpeaking()},getReadAloudState(i){return N.getReadAloudState(i)},onReadAloudChange(i){return N.onReadAloudChange(i)},getState(){return{open:Ne()&&Ae,launcherEnabled:_,voiceActive:wt.active,streaming:N.isStreaming()}},showCSATFeedback(i){!Ae&&Ne()&&qt(!0,"system");let d=We.querySelector(".persona-feedback-container");d&&d.remove();let f=ZE({onSubmit:async(y,w)=>{N.isClientTokenMode()&&await N.submitCSATFeedback(y,w),i?.onSubmit?.(y,w)},onDismiss:i?.onDismiss,...i});We.appendChild(f),f.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(i){!Ae&&Ne()&&qt(!0,"system");let d=We.querySelector(".persona-feedback-container");d&&d.remove();let f=e0({onSubmit:async(y,w)=>{N.isClientTokenMode()&&await N.submitNPSFeedback(y,w),i?.onSubmit?.(y,w)},onDismiss:i?.onDismiss,...i});We.appendChild(f),f.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(i,d){return N.submitCSATFeedback(i,d)},async submitNPSFeedback(i,d){return N.submitNPSFeedback(i,d)},destroy(){xf(),li!=null&&(clearInterval(li),li=null),a.clear(),r.clear(),s.clear(),l.clear(),_e.forEach(i=>i()),dt.remove(),Nt?.remove(),sn?.destroy(),Fn?.remove(),Gs&&Ce.removeEventListener("click",Gs)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let i=window.AgentWidgetBrowser,d={controller:an,getMessages:an.getMessages,getStatus:an.getStatus,getMetadata:an.getPersistentMetadata,updateMetadata:an.updatePersistentMetadata,clearHistory:()=>an.clearChat(),setVoiceActive:f=>f?an.startVoiceRecognition():an.stopVoiceRecognition()};window.AgentWidgetBrowser=d,_e.push(()=>{window.AgentWidgetBrowser===d&&(window.AgentWidgetBrowser=i)})}if(typeof window<"u"){let i=t.getAttribute("data-persona-instance")||t.id||"persona-"+Math.random().toString(36).slice(2,8),d=re=>{let ce=re.detail;(!ce?.instanceId||ce.instanceId===i)&&an.focusInput()};if(window.addEventListener("persona:focusInput",d),_e.push(()=>{window.removeEventListener("persona:focusInput",d)}),ie){let re=he=>{let De=he.detail;(!De?.instanceId||De.instanceId===i)&&an.showEventStream()},ce=he=>{let De=he.detail;(!De?.instanceId||De.instanceId===i)&&an.hideEventStream()};window.addEventListener("persona:showEventStream",re),window.addEventListener("persona:hideEventStream",ce),_e.push(()=>{window.removeEventListener("persona:showEventStream",re),window.removeEventListener("persona:hideEventStream",ce)})}let f=re=>{let ce=re.detail;(!ce?.instanceId||ce.instanceId===i)&&an.showHistory()},y=re=>{let ce=re.detail;(!ce?.instanceId||ce.instanceId===i)&&an.hideHistory()};window.addEventListener("persona:showHistory",f),window.addEventListener("persona:hideHistory",y),_e.push(()=>{window.removeEventListener("persona:showHistory",f),window.removeEventListener("persona:hideHistory",y)});let w=re=>{let ce=re.detail;(!ce?.instanceId||ce.instanceId===i)&&an.showArtifacts()},k=re=>{let ce=re.detail;(!ce?.instanceId||ce.instanceId===i)&&an.hideArtifacts()},q=re=>{let ce=re.detail;ce?.instanceId&&ce.instanceId!==i||ce?.artifact&&an.upsertArtifact(ce.artifact)},te=re=>{let ce=re.detail;ce?.instanceId&&ce.instanceId!==i||typeof ce?.id=="string"&&an.selectArtifact(ce.id)},Q=re=>{let ce=re.detail;(!ce?.instanceId||ce.instanceId===i)&&an.clearArtifacts()};window.addEventListener("persona:showArtifacts",w),window.addEventListener("persona:hideArtifacts",k),window.addEventListener("persona:upsertArtifact",q),window.addEventListener("persona:selectArtifact",te),window.addEventListener("persona:clearArtifacts",Q),_e.push(()=>{window.removeEventListener("persona:showArtifacts",w),window.removeEventListener("persona:hideArtifacts",k),window.removeEventListener("persona:upsertArtifact",q),window.removeEventListener("persona:selectArtifact",te),window.removeEventListener("persona:clearArtifacts",Q)})}let ko=sD(o.persistState);if(ko&&Ne()){let i=iD(ko.storage),d=`${ko.keyPrefix}widget-open`,f=`${ko.keyPrefix}widget-voice`,y=`${ko.keyPrefix}widget-voice-mode`;if(i){let w=ko.persist?.openState&&i.getItem(d)==="true",k=ko.persist?.voiceState&&i.getItem(f)==="true",q=ko.persist?.voiceState&&i.getItem(y)==="true";if(w&&(sn?.setPanelOpen(!0,"auto"),setTimeout(()=>{an.open(),setTimeout(()=>{if(k||q)an.startVoiceRecognition();else if(ko.persist?.focusInput){let te=t.querySelector("textarea");te&&te.focus()}},100)},0)),ko.persist?.openState&&(R.on("widget:opened",()=>{i.setItem(d,"true")}),R.on("widget:closed",()=>{i.setItem(d,"false")})),ko.persist?.voiceState&&(R.on("voice:state",te=>{i.setItem(f,te.active?"true":"false")}),R.on("user:message",te=>{i.setItem(y,te.viaVoice?"true":"false")})),ko.clearOnChatClear){let te=()=>{i.removeItem(d),i.removeItem(f),i.removeItem(y)},Q=()=>te();window.addEventListener("persona:clear-chat",Q),_e.push(()=>{window.removeEventListener("persona:clear-chat",Q)})}}}if(oe&&Ne()&&(sn?.setPanelOpen(!0,"auto"),setTimeout(()=>{an.open()},0)),oa(),!O0){let i=xa(()=>{N&&(ei++,mn.clear(),xo(We,N.getMessages(),j))});_e.push(i)}H=()=>{N&&(ei++,mn.clear(),xo(We,N.getMessages(),j))},N.getMessages().length>0&&kd(),B=()=>{N&&(ei++,mn.clear(),xo(We,N.getMessages(),j))};let TP=Sw(()=>{N&&(ei++,mn.clear(),xo(We,N.getMessages(),j))});_e.push(TP);let EP=qy(()=>{N&&(ei++,mn.clear(),xo(We,N.getMessages(),j),Gr()?.updateInlineArtifactBlocks(We,wo.artifacts,{suppressTransition:!0}),Fo())});return _e.push(EP),an};ks();var s0=(t,e)=>{let n=t.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(o)return Math.max(0,parseFloat(o[1]));let r=/^(\d+(?:\.\d+)?)%$/i.exec(n);return r?Math.max(0,e*parseFloat(r[1])/100):420},cD=(t,e)=>{if(e===!1){t.style.maxHeight="";return}t.style.maxHeight="100vh",t.style.maxHeight=e},dD=(t,e)=>{e===!1?(t.style.position="relative",t.style.top=""):(t.style.position="sticky",t.style.top="0")},pD=(t,e)=>{let n=t.parentElement;if(!n)return;let o=t.ownerDocument.createElement("div");o.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(o);let r=o.offsetHeight>0;o.style.height="100%";let s=o.offsetHeight>0;o.remove(),!(!r||s)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(e.maxHeight===!1?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${e.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},i0=(t,e)=>{let n=e?.launcher?.enabled??!0;t.className="persona-host",t.style.height=n?"":"100%",t.style.display=n?"":"flex",t.style.flexDirection=n?"":"column",t.style.flex=n?"":"1 1 auto",t.style.minHeight=n?"":"0",t.style.minWidth=n?"":"0"},wb=t=>{t.style.position="",t.style.top="",t.style.bottom="",t.style.left="",t.style.right="",t.style.zIndex="",t.style.transform="",t.style.pointerEvents=""},a0=t=>{t.style.inset="",t.style.width="",t.style.height="",t.style.maxWidth="",t.style.maxHeight="",t.style.minWidth="",wb(t)},bb=t=>{t.style.transition=""},vb=t=>{t.style.display="",t.style.flexDirection="",t.style.flex="",t.style.minHeight="",t.style.minWidth="",t.style.width="",t.style.height="",t.style.alignItems="",t.style.transition="",t.style.transform="",t.style.marginLeft=""},Cb=t=>{t.style.width="",t.style.maxWidth="",t.style.minWidth="",t.style.flex="1 1 auto"},Em=(t,e)=>{t.style.width="",t.style.minWidth="0",t.style.maxWidth="",t.style.boxSizing="",e.style.alignItems=""},uD=(t,e,n,o,r)=>{r?n.parentElement!==e&&(t.replaceChildren(),e.replaceChildren(n,o),t.appendChild(e)):n.parentElement===e&&(e.replaceChildren(),t.appendChild(n),t.appendChild(o))},mD=(t,e,n,o,r,s)=>{let a=s?e:t;r==="left"?a.firstElementChild!==o&&a.replaceChildren(o,n):a.lastElementChild!==o&&a.replaceChildren(n,o)},fD=t=>{let e=qr(t),n=e.components?.panel,o=(r,s)=>r==null||r===""?s:Hn(e,r)??r;return{inset:o(n?.inset,Wu),canvasBackground:o(n?.canvasBackground,Bu)}},l0=(t,e,n,o)=>{if(!e){t.style.padding="",t.style.background="",t.style.boxSizing="";return}t.style.boxSizing="border-box",t.style.padding=n,t.style.background=o},gD=(t,e,n,o,r,s,a,l)=>{let c=Do(s),p=c.reveal==="push",u=l!=null,m=l?.inset??"",g=l?.canvasBackground??"";uD(t,e,n,o,p),mD(t,e,n,o,c.side,p),t.dataset.personaHostLayout="docked",t.dataset.personaDockSide=c.side,t.dataset.personaDockOpen=a?"true":"false",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0",t.style.height="100%",t.style.minHeight="0",t.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let h=t.ownerDocument.defaultView,b=s?.launcher?.mobileFullscreen??!0,C=s?.launcher?.mobileBreakpoint??640,M=h!=null?h.innerWidth<=C:!1;if(b&&M&&a){t.dataset.personaDockMobileFullscreen="true",t.removeAttribute("data-persona-dock-reveal"),vb(e),bb(o),a0(o),Cb(n),Em(r,o),l0(o,!1,"",""),t.style.display="flex",t.style.flexDirection="column",t.style.alignItems="stretch",t.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String(s?.launcher?.zIndex??On),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",p&&(e.style.display="flex",e.style.flexDirection="column",e.style.width="100%",e.style.height="100%",e.style.minHeight="0",e.style.minWidth="0",e.style.flex="1 1 auto",e.style.alignItems="stretch",e.style.transform="none",e.style.marginLeft="0",e.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(t.removeAttribute("data-persona-dock-mobile-fullscreen"),a0(o),cD(o,c.maxHeight),l0(o,u&&a,m,g),c.reveal==="overlay"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="overlay",vb(e),bb(o),Cb(n),Em(r,o);let T=c.animate?"transform 180ms ease":"none",H=c.side==="right"?"translateX(100%)":"translateX(-100%)",A=a?"translateX(0)":H;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=c.width,o.style.maxWidth=c.width,o.style.minWidth=c.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=T,o.style.transform=A,o.style.pointerEvents=a?"auto":"none",o.style.zIndex="2",c.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(c.reveal==="push"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="push",bb(o),wb(o),Em(r,o);let T=s0(c.width,t.clientWidth),H=Math.max(0,t.clientWidth),A=c.animate?"margin-left 180ms ease":"none",D=c.side==="right"?a?-T:0:a?0:-T;e.style.display="flex",e.style.flexDirection="row",e.style.flex="0 0 auto",e.style.minHeight="0",e.style.minWidth="0",e.style.alignItems="stretch",e.style.height="100%",e.style.width=`${H+T}px`,e.style.transition=A,e.style.marginLeft=`${D}px`,e.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${H}px`,n.style.maxWidth=`${H}px`,n.style.minWidth=`${H}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=c.width,o.style.minWidth=c.width,o.style.maxWidth=c.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=a?"auto":"none"}else{t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="",vb(e),wb(o),Cb(n),Em(r,o);let T=c.reveal==="emerge";T?t.dataset.personaDockReveal="emerge":t.removeAttribute("data-persona-dock-reveal");let H=a?c.width:"0px",A=c.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${u?", padding 180ms ease":""}`:"none",D=!a;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${H}`,o.style.width=H,o.style.maxWidth=H,o.style.minWidth=H,o.style.minHeight="0",dD(o,c.maxHeight),o.style.overflow=T||D?"hidden":"visible",o.style.transition=A,T){o.style.alignItems=c.side==="right"?"flex-start":"flex-end";let W=u?`calc(${s0(c.width,t.clientWidth)}px - (2 * ${m}))`:c.width;r.style.width=W,r.style.minWidth=W,r.style.maxWidth=W,r.style.boxSizing="border-box"}}},hD=(t,e)=>{let n=t.ownerDocument.createElement("div");return i0(n,e),t.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){i0(n,o)},destroy(){n.remove()}}},yD=(t,e)=>{let{ownerDocument:n}=t,o=t.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=t.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=t.nextSibling,a=n.createElement("div"),l=n.createElement("div"),c=n.createElement("div"),p=n.createElement("aside"),u=n.createElement("div"),m=e?.launcher?.enabled??!0?e?.launcher?.autoExpand??!1:!0;l.dataset.personaDockRole="push-track",c.dataset.personaDockRole="content",p.dataset.personaDockRole="panel",u.dataset.personaDockRole="host",p.appendChild(u),o.insertBefore(a,t),c.appendChild(t);let g=null,h=()=>{g?.disconnect(),g=null},b=null,C=()=>{b=e?.launcher?.detachedPanel===!0?fD(e):null};C();let M=()=>{gD(a,l,c,p,u,e,m,b)},E=null,T=()=>{E?.(),E=null,!(e?.launcher?.detachedPanel!==!0||e?.colorScheme!=="auto")&&(E=Du(()=>{C(),M()}))},H=()=>{h(),Do(e).reveal==="push"&&(typeof ResizeObserver>"u"||(g=new ResizeObserver(()=>{M()}),g.observe(a)))},A=!1,D=()=>{M(),H(),m&&!A&&a.dataset.personaDockMobileFullscreen!=="true"&&(A=!0,pD(a,Do(e)))},W=a.ownerDocument.defaultView,U=()=>{D()};return W?.addEventListener("resize",U),Do(e).reveal==="push"?(l.appendChild(c),l.appendChild(p),a.appendChild(l)):(a.appendChild(c),a.appendChild(p)),D(),T(),{mode:"docked",host:u,shell:a,syncWidgetState(B){let O=B.launcherEnabled?B.open:!0;m!==O&&(m=O,D())},updateConfig(B){e=B,(e?.launcher?.enabled??!0)===!1&&(m=!0),C(),D(),T()},destroy(){W?.removeEventListener("resize",U),E?.(),E=null,h(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(t,s):o.appendChild(t)),a.remove()}}},c0=(t,e)=>nn(e)?yD(t,e):hD(t,e);var Jc={desktop:{w:1280,h:800},mobile:{w:390,h:844}},d0=.15,p0=1.5,xb="persona-preview-shell-theme",bD={load:()=>null,save:()=>{},clear:()=>{}},vD=["How do I get started?","Pricing & plans","Talk to support"];function Sb(t){return t.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function CD(t){return t==="dark"?{pageBg:"linear-gradient(180deg, #0f172a 0%, #020617 100%)",chromeBg:"#111827",chromeBorder:"#1f2937",dot:"#475569",skeleton:"#334155",cardBg:"#1e293b",cardBorder:"rgba(148, 163, 184, 0.16)"}:{pageBg:"linear-gradient(180deg, #ffffff 0%, #f8fafc 100%)",chromeBg:"#ffffff",chromeBorder:"#e5e7eb",dot:"#cbd5e1",skeleton:"#e2e8f0",cardBg:"#e2e8f0",cardBorder:"rgba(148, 163, 184, 0.18)"}}function u0(t){let e=CD(t);return`* { box-sizing: border-box; }
|
|
1268
|
+
`)}if(!w&&!d){let Ye="max-height: -moz-available !important; max-height: stretch !important;",st=f?"":"padding-top: 1.25em !important;",tt=f?"":`z-index: ${o.launcher?.zIndex??On} !important;`;dt.style.cssText+=Ye+st+tt}Rm(),Io()},Gm=()=>{t.style.setProperty("--persona-content-max-width",Is(o,xe()))},ov=!1;function rv(){o.layout?.topFade&&pe.scrollTop>1?pe.setAttribute("data-persona-top-fade","true"):pe.removeAttribute("data-persona-top-fade")}let Ym=()=>{rv();let i=$h(o,xe());xe()&&o.composer?.placement&&o.debug===!0&&!ov&&(ov=!0,console.warn("[persona] composer.placement is ignored in composer-bar mount mode."));let d=Vs();t.setAttribute("data-persona-composer-placement",i),t.setAttribute("data-persona-conversation-state",od),t.setAttribute("data-persona-welcome-anchor",d.anchor??"bottom"),t.style.setProperty("--persona-composer-anchor-gap",d.composerGap??Ou),sd()},sv=()=>{if(xe())return;let i=nn(o),d=o.launcher?.sidebarMode??!1;if(i||d||(o.launcher?.fullHeight??!1)||!_)return;let y=t.ownerDocument.defaultView??window,w=o.launcher?.mobileFullscreen??!0,k=o.launcher?.mobileBreakpoint??640;if(w&&y.innerWidth<=k)return;let q=Hi(o);Se.style.height=q.height,Se.style.maxHeight=q.maxHeight};Km(),gc(t,o),Uc(t,o),qc(t,o),Gm(),Ym(),Us=()=>{Km(),sv(),gc(t,o),Uc(t,o),qc(t,o),Gm(),Ym(),ld?t.style.setProperty("--persona-artifact-welded-outer-radius",ld):t.style.removeProperty("--persona-artifact-welded-outer-radius"),ft(),Mn()};let Oe=[];Oe.push(()=>{Qb=!0}),Oe.push(()=>{g.forEach(i=>i()),m.destroy()}),Oe.push(()=>{document.removeEventListener("keydown",Zb)}),Oe.push(()=>{rl!==null&&clearTimeout(rl)});let or=null,rr=null;Oe.push(()=>{or?.(),or=null,rr?.(),rr=null}),ll&&Oe.push(()=>{ll?.disconnect(),ll=null}),Oe.push(()=>{pl?.(),pl=null,jm(),en&&(en.remove(),en=null),gt?.element.style.removeProperty("width"),gt?.element.style.removeProperty("maxWidth"),gt?.destroy()}),ie&&Oe.push(()=>{Fe=!0,Z=null,Bt!==null&&(cancelAnimationFrame(Bt),Bt=null),He?.destroy(),He=null,ct?.destroy(),ct=null,rt=null});let js=null,iv=()=>{js&&(js(),js=null),o.colorScheme==="auto"&&(js=Du(()=>{gc(t,o)}))};iv(),Oe.push(()=>{js&&(js(),js=null)}),Oe.push(()=>{T=!0,E?.()}),Oe.push(()=>{W=!0});let av=!1;Oe.push(()=>{av=!0});let Qm=(i,d)=>{let f=vc(i,d);return f||!hM.includes(i)?f:(BM().then(y=>{if(av)return;Ei(y.wipe),Ei(y.glyphCycle);let w=vc(i,d);w&&xc(w,t)}).catch(()=>{}),null)},hd=o.features?.streamAnimation;if(hd?.type&&hd.type!=="none"){let i=Qm(hd.type,hd.plugins);i&&xc(i,t),Oe.push(()=>yM(t))}let Mr=kc(lo),lv=kc(Ns),cv=kc(Xo),Ks=[Mr,lv,cv];Oe.push(()=>{Ks.forEach(i=>i.destroy())});let Gs=null,N,Ys=null,dv=!1,pv=0,uv=null,mv=i=>i.reduce((d,f)=>f.role==="user"?d+1:d,0),fv=i=>{for(let d=i.length-1;d>=0;d--)if(ql(i[d]))return i[d].id??null;return null},gv=!1,q0=()=>{gv||o.debug!==!0||(gv=!0,console.warn('[persona] suggestions.starters.placement is pinned to "welcome" but the welcome surface is hidden (welcome.variant: "none" or copy.showWelcomeCard: false), so no starters render. Use "auto" or "composer".'))},hv=!1,yv=!1,bv=(i,d)=>{hv||o.debug!==!0||!d.enabled||d.expose||dv||yv&&(N.isStreaming()||i.some(ql)||(hv=!0,console.info("[persona] Follow-up suggestions are enabled but the agent has not called suggest_replies. The model needs the tool declared (runtimeTools server-side, suggestions.followUps.expose: true from the widget, or your own backend's tool definition) and benefits from instructions telling it when to offer follow-ups. See the integration paths table in UI-COMPONENTS.md.")))},Qs=i=>{if(!N)return;let d=i??N.getMessages(),f=ye=>{ye.render([],N,we,d)},y=ye=>{Ks.forEach(De=>{De!==ye&&f(De)})};Ys&&(mv(d)>pv||fv(d)!==uv)&&(Ys=null);let w=Ms(o);bv(d,w);let k=w.enabled?Ax(d):null,q=Ys??k,te=Ys?"host":"agent";if(q){let ye=o.suggestions?.followUps,De=ye?.placement??(ye?"auto":"composer"),It=(De==="auto"?xe()?"composer":"after-message":De)==="after-message"?cv:Mr;y(It),It.render(q,N,we,d,o.suggestionChipsConfig,{source:te,surface:"followUp",variant:ye?.variant??"chip",behavior:ye?.behavior??"send",overflow:ye?.overflow??"wrap",maxItems:ye?.maxItems??4,config:o,plugins:u,submitPrompt:op});return}if(d.some(ye=>ye.role==="user")){Ks.forEach(f);return}let Q=o.future?.v5Defaults===!0,re=sl(),ce=o.suggestions?.starters??(Q?{}:void 0);if(ce){let ye=Ua(Vs(),d),De=ce.placement??"auto",lt=De==="auto"?ye?"welcome":"composer":De;if(lt==="welcome"&&!ye){q0(),Ks.forEach(f);return}let It=lt==="welcome"?lv:Mr;y(It),It.render(ce.items??o.suggestionChips,N,we,d,o.suggestionChipsConfig,{surface:"starter",variant:ce.variant??(Q&&!re?"chip":"card"),behavior:ce.behavior??"send",overflow:ce.overflow??"wrap",maxItems:ce.maxItems??(Q&&!re?3:4),config:o,plugins:u,submitPrompt:op});return}y(Mr),Mr.render(o.suggestionChips,N,we,d,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",maxItems:4,config:o,plugins:u,submitPrompt:op})},vv=()=>{Ys&&(Ys=null,Qs())},j0=i=>{let d=Array.isArray(i)?[...i]:[];if(!d.length){vv();return}let f=N?N.getMessages():[];Ys=d,dv=!0,pv=mv(f),uv=fv(f),Qs(f)},uo=!1,mn=lM(),Qi=new Map,Xs=new Map,ns=new Map,Js=null,os=null;function Zs(){if(!Js)return;let i=Js;Js=null,os?.destroy(),os=null,mn.delete(i),Pe.querySelector(`#wrapper-${i}`)?.removeAttribute("data-preserve-runtime"),N&&xo(We,N.getMessages(),j)}let ei=0,K0=Ho()!==null,mo=$u(),fo=0,rs=null,Zn=!1,yd=!1,ss=0,wn=null,ti=null,Xm=!1,Xi=!1,ni=null,ul=!0,bd=!1,Ji=null,vd=!1,is=()=>{vd=!0,X0()},Jm=null,G0=4,Tr=24,Y0=80,Q0=1e3,Er=null,Cv=()=>{t.setAttribute("data-persona-scrollbar",Lm()),Lm()!=="on-scroll"&&(Er!==null&&clearTimeout(Er),Er=null,pe.removeAttribute("data-persona-scrollbar-visible"))},X0=()=>{Lm()==="on-scroll"&&(pe.setAttribute("data-persona-scrollbar-visible",""),Er!==null&&clearTimeout(Er),Er=setTimeout(()=>{Er=null,jr(pe,Tr)&&pe.removeAttribute("data-persona-scrollbar-visible")},Q0))};Cv(),Oe.push(()=>{Er!==null&&clearTimeout(Er)});let Zm=new Map,wt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};_o();let wv=o.voiceRecognition?.autoResume??!1,kr=i=>{H.emit("voice:state",{active:wt.active,source:i,timestamp:Date.now()})},Vo=()=>{de(i=>({...i,voiceState:{active:wt.active,timestamp:Date.now(),manuallyDeactivated:wt.manuallyDeactivated}}))},J0=()=>{if(o.voiceRecognition?.enabled===!1)return;let i=vb(L.voiceState),d=!!i.active,f=Number(i.timestamp??0);wt.manuallyDeactivated=!!i.manuallyDeactivated,d&&Date.now()-f<yD&&setTimeout(()=>{wt.active||(wt.manuallyDeactivated=!1,Un(o.voiceRecognition?.provider)?N.toggleVoice().then(()=>{wt.active=N.isVoiceActive(),kr("restore"),N.isVoiceActive()&&ba()}):ip("restore"))},1e3)},Z0=()=>N?p0(N.getMessages()).filter(i=>!i.__skipPersist):[],Cd=null,xv=(i,d)=>{typeof console<"u"&&console.error(i,d)},wd=(i,d)=>{let f=()=>{try{let q=i();return!q||typeof q.then!="function"?null:Promise.resolve(q).catch(te=>{xv(d,te)})}catch(q){return xv(d,q),null}},y=Cd,w=y?y.then(()=>f()??void 0):f();if(!w)return;let k=w.finally(()=>{Cd===k&&(Cd=null)});Cd=k};function Zi(i){if(!x?.save)return;let d=i?p0(i):N?Z0():[],f=P&&N?.getResumableHandle();f&&(L={...L,durableResume:{executionId:f.executionId,after:f.lastEventId}});let y={messages:d,metadata:L,artifacts:wo.artifacts,selectedArtifactId:wo.selectedId,...oi?{draft:oi}:{}};wd(()=>x.save(y),"[AgentWidget] Failed to persist state:")}let oi,xd=()=>!x?.save||o.persistState===!1?!1:typeof o.persistState=="object"?o.persistState.persist?.draft!==!1:!0,ml=rA({write:()=>{if(!xd())return;let i=ze.getState(),d=nA({text:i.text,mentionRefs:i.mentionRefs,contentSegments:Jf(),selectedModelId:i.selectedModelId,activeModeIds:i.activeModeIds,quote:i.quote});JSON.stringify(d)!==JSON.stringify(oi)&&(oi=d,Zi())}});function Sv(){xd()&&ml.schedule()}function ef(){ml.flush()}function Av(i){if(!xd())return;let d=oA(i,{mentionSourceIds:(o.contextMentions?.sources??[]).map(f=>f.id),modelIds:(o.composer?.models??[]).map(f=>f.id),modes:o.composer?.modes??[]});d&&(oi=i,we&&!we.value&&(we.value=d.text,we.dispatchEvent(new Event("input",{bubbles:!0})),Zo()),d.selectedModelId&&(ze.setSelectedModelId(d.selectedModelId),Zr?.repaint()),id(d.activeModeIds??[]),d.quote&&er(d.quote),ml.cancel())}function Sd(){ml.cancel(),oi&&(oi=void 0,xd()&&Zi())}let ea=null,Mv=()=>dt.querySelector("#persona-scroll-container")||pe,ta=()=>{ea!==null&&(cancelAnimationFrame(ea),ea=null),Zn=!1},Tv=()=>{rs!==null&&(cancelAnimationFrame(rs),rs=null),yd=!1,ta()},ek=()=>uo&&nf()&&(po()!=="anchor-top"||kb()),tf=()=>{let i=tl()||"Jump to latest",d=ek();hn.toggleAttribute("data-persona-scroll-to-bottom-streaming",d),ss>0?(Fs.textContent=String(ss),Fs.style.display="",hn.setAttribute("aria-label",`${i} (${ss} new)`)):(Fs.textContent="",Fs.style.display="none",hn.setAttribute("aria-label",d?`${i} (response streaming below)`:i))},Ev=()=>{ss!==0&&(ss=0,tf())},tk=()=>{let i=wn?.spacerHeight??0;return i<=0?jr(pe,Tr):Ed(i)-pe.scrollTop-pe.clientHeight<=Tr},nf=()=>Jr()?!mo.isFollowing():!tk(),of=()=>!!N&&N.getMessages().length>0,xn=()=>{if(!L0()||ao()){hn.parentNode&&hn.remove(),hn.style.display="none";return}hn.parentNode!==Pe&&Pe.appendChild(hn),$s();let d=br(pe)>0&&nf()&&of();d?tf():Ev(),hn.style.display=d?"":"none"},na=()=>{mo.pause()&&(Tv(),xn())},eo=()=>{mo.resume(),Ev(),xn()},as=(i=!1)=>{Jr()&&of()&&mo.isFollowing()&&(!i&&!uo||(rs!==null&&(cancelAnimationFrame(rs),rs=null),yd=!0,rs=requestAnimationFrame(()=>{rs=null,yd=!1,mo.isFollowing()&&nk(Mv(),i?220:140)})))},kv=(i,d,f,y=()=>!0)=>{let w=i.scrollTop,k=d(),q=k-w;if(ta(),Math.abs(q)<1){Zn=!0,i.scrollTop=k,fo=i.scrollTop,Zn=!1;return}let te=performance.now();Zn=!0;let Q=ce=>1-Math.pow(1-ce,3),re=ce=>{if(!y()){ta();return}let ye=d();ye!==k&&(k=ye,q=k-w);let De=ce-te,lt=Math.min(De/f,1),It=Q(lt),kt=w+q*It;i.scrollTop=kt,fo=i.scrollTop,lt<1?ea=requestAnimationFrame(re):(i.scrollTop=k,fo=i.scrollTop,ea=null,Zn=!1)};ea=requestAnimationFrame(re)},nk=(i,d=500)=>{let f=br(i)-i.scrollTop;if(Math.abs(f)<1){fo=i.scrollTop;return}if(Math.abs(f)>=Y0){ta(),Zn=!0,i.scrollTop=br(i),fo=i.scrollTop,Zn=!1;return}kv(i,()=>br(i),d,()=>mo.isFollowing())},Ad=()=>{if(!of()){xn();return}let i=Mv();Zn=!0,i.scrollTop=br(i),fo=i.scrollTop,Zn=!1,xn()},ri=i=>{let d=0,f=i;for(;f&&f!==pe;)d+=f.offsetTop,f=f.offsetParent;return d},ok=()=>{let i=pe.getRootNode();return(typeof i.getSelection=="function"?i.getSelection():null)??pe.ownerDocument.getSelection()},Md=()=>mM(ok(),pe),rf=()=>{if(I0()!=="last-user-turn")return!1;let i=N?.getMessages()??[];if(i.length<2)return!1;let d=[...i].reverse().find(k=>k.role==="user");if(!d)return!1;let f=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(d.id):d.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),y=pe.querySelector(`[data-message-id="${f}"]`);if(!y)return!1;let w=Math.min(Math.max(0,ri(y)-nl()),br(pe));return Zn=!0,pe.scrollTop=w,fo=pe.scrollTop,Zn=!1,po()==="follow"&&!jr(pe,Tr)&&mo.pause(),xn(),!0},Td=i=>{let d=Math.max(0,Math.round(i));Co.style.height=`${d}px`,Co.style.display=d>0?"":"none",wn&&(wn.spacerHeight=Math.max(0,i))},Ed=i=>{let d=parseFloat(getComputedStyle(pe).paddingBottom)||0,f=0;for(let w of Array.from(pe.children)){if(w===Co||w.offsetHeight===0)continue;let k=ri(w)+w.offsetHeight;k>f&&(f=k)}let y=pe.scrollHeight-i;return f>0?Math.min(f+d,y):y},rk=()=>{if(!wn||wn.spacerHeight<=0)return;let i=Ed(wn.spacerHeight),d=Math.max(0,Math.round(pe.scrollTop)+pe.clientHeight-i+Tr);d<wn.spacerHeight&&(Td(d),xn())},$o=()=>{ti!==null&&(cancelAnimationFrame(ti),ti=null),ta(),wn=null,Co.style.height="0px",Co.style.display="none"},Pv=i=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(i):i.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),sf=i=>pe.querySelector(`[data-message-id="${Pv(i)}"]`),Lv=i=>{ti!==null&&cancelAnimationFrame(ti),ti=requestAnimationFrame(()=>{ti=null;let d=Pv(i),f=pe.querySelector(`[data-message-id="${d}"]`);if(!f)return;let y=ri(f),w=wn?.spacerHeight??0,k=Ed(w),{targetScrollTop:q,spacerHeight:te}=qh({anchorOffsetTop:y,topOffset:nl(),viewportHeight:pe.clientHeight,contentHeight:k,slack:Tr});wn={initialSpacerHeight:te,contentHeightAtAnchor:k,spacerHeight:te},Td(te),kv(pe,()=>f.isConnected?Math.max(0,ri(f)-nl()):q,220)})},to=()=>{if(po()!=="anchor-top"||!wn||!Ji)return;let i=sf(Ji);if(!i)return;ta();let d=wn.spacerHeight,f=Ed(d),{targetScrollTop:y,spacerHeight:w}=qh({anchorOffsetTop:ri(i),topOffset:nl(),viewportHeight:pe.clientHeight,contentHeight:f,slack:Tr});wn={initialSpacerHeight:w,contentHeightAtAnchor:f,spacerHeight:w},Td(w),Zn=!0,pe.scrollTop=y,fo=pe.scrollTop,Zn=!1,xn()},sk=()=>{if(Jr()){if(!mo.isFollowing()||jr(pe,1))return;as(!uo);return}if(wn&&wn.initialSpacerHeight>0){let i=pe.scrollHeight-wn.spacerHeight,d=fM({initialSpacerHeight:wn.initialSpacerHeight,contentHeightAtAnchor:wn.contentHeightAtAnchor,currentContentHeight:i});d!==wn.spacerHeight&&Td(d)}xn()},ik=i=>{let d=po();d==="follow"?(eo(),as(!0)):d==="anchor-top"&&(ul=!1,bd=!0,vd=!1,Ji=i,Lv(i))},ak=()=>{if(po()==="anchor-top"){if(bd){ul=!1;return}ul=!0,$o(),eo(),as(!0)}},lk=96,ck=i=>{if(ni===null)return!0;let d=sf(ni),f=sf(i);if(!d||!f)return!0;let y=ri(f)-ri(d);return nl()+y>pe.clientHeight-lk},dk=i=>{if(po()!=="anchor-top"||!bd||vd||Md())return;let d=ni===null;for(let f of i){if(!d){f.id===ni&&(d=!0);continue}if(uM(f)){if(f.id===Ji||!ck(f.id))return;Ji=f.id,Lv(f.id);return}}},pk=i=>{let d=new Map;i.forEach(f=>{let y=Zm.get(f.id);d.set(f.id,{streaming:f.streaming,role:f.role}),!y&&f.role==="assistant"&&(H.emit("assistant:message",f),!Xi&&(po()!=="anchor-top"||kb())&&nf()&&(ss+=1,tf(),xn(),nd(ss===1?"1 new message below.":`${ss} new messages below.`))),f.role==="assistant"&&y?.streaming&&f.streaming===!1&&H.emit("assistant:complete",f),f.variant==="approval"&&f.approval&&(y?f.approval.status!=="pending"&&H.emit("approval:resolved",{approval:f.approval,decision:f.approval.status}):H.emit("approval:requested",{approval:f.approval,message:f}))}),Zm.clear(),d.forEach((f,y)=>{Zm.set(y,f)})},fl=(i,d)=>{let f=d==="user"?"user":"assistant",y=o.layout?.messages?.[f],w=y?.width??"content",k=y?.maxWidth??(w==="full"?`var(--persona-message-${f}-max-width, 100%)`:void 0);i.classList.add("persona-message-row"),i.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),i.classList.add(`persona-message-row-${d}`,`persona-message-width-${w}`),i.classList.toggle("persona-justify-end",d==="user"),i.setAttribute("data-message-role",d),i.setAttribute("data-message-width",w),k?i.style.setProperty("--persona-message-row-max-width",k):i.style.removeProperty("--persona-message-row-max-width")},Pr=(i,d)=>{let f=document.createElement("div");return f.className="persona-flex",f.id=`wrapper-${i}`,f.setAttribute("data-wrapper-id",i),fl(f,d),f},uk=(i,d,f)=>{let y=new Set;for(let $ of d){let Xe=$.variant==="tool"?"tool":$.variant==="reasoning"?"reasoning":null;if(!Xe||vs(o,Xe)!=="row")continue;let Je=Xe==="tool"?o.features?.toolCallDisplay:o.features?.reasoningDisplay;Je?.expandable!==!1&&(y.add($.id),a.observe($,Xe,Xe==="tool"?r:s,Je))}let w=document.createElement("div"),q=(()=>{let $=u.find(Xe=>Xe.renderLoadingIndicator);if($?.renderLoadingIndicator)return $.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),te=($,Xe)=>Xe==null?!1:typeof Xe=="string"?($.textContent=Xe,!0):($.appendChild(Xe),!0),Q=new Set,re=new Map,ce=new Set,ye=u.some($=>$.renderAskUserQuestion),De=[],lt=[],It=o.enableComponentStreaming!==!1,kt=o.approval!==!1,oo=[],Jt=o.messageActions,rn=Jt?.showRegenerate===!0&&Jt.enabled!==!1&&Ft.current?.isStreaming()!==!0?nS(d):null,Vn=Jt?.showEdit===!0&&Jt.enabled!==!1,ln=Jt?.showQuote===!0&&Jt.enabled!==!1,$t=null,cr=o.features?.reasoningDisplay?.completedVisibility,dr=$=>cr==="removed"?!0:cr==="removed-when-short"?Ex($,o.features?.reasoningDisplay?.shortThinkThreshold):!1,Po=o.features?.toolCallDisplay?.completedVisibility==="removed",Lo=$=>$.variant==="reasoning"&&$.reasoning?.status==="complete"?dr($.reasoning):Po&&$.variant==="tool"&&$.toolCall?.status==="complete";if(d.forEach($=>{if(Lo($))return;if(Q.add($.id),re.set($.id,$.role),Js===$.id&&os){let et=Pr($.id,$.role);et.setAttribute("data-persona-message-edit-stub","true"),et.setAttribute("data-preserve-runtime","true"),w.appendChild(et),$t={messageId:$.id,element:os.element};return}let Xe=ye&&Ai($),Je=kt&&$.variant==="approval"&&!!$.approval,fe=!Xe&&$.role==="assistant"&&!$.variant&&It&&bb($);!Je&&ns.has($.id)&&(i.querySelector(`#wrapper-${$.id}`)?.removeAttribute("data-preserve-runtime"),ns.delete($.id)),!fe&&Xs.has($.id)&&(i.querySelector(`#wrapper-${$.id}`)?.removeAttribute("data-preserve-runtime"),Xs.delete($.id));let zt=Ai($)?`:${$.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${$.agentMetadata?.askUserQuestionAnswers?Object.keys($.agentMetadata.askUserQuestionAnswers).length:0}`:"",fn={canRegenerate:rn===$.id,canEdit:Vn&&Xg($),canQuote:ln&&!$.variant&&($.content?.trim().length??0)>0},_n=`${fn.canRegenerate?"r":""}${fn.canEdit?"e":""}${fn.canQuote?"q":""}`,En=aM($,ei)+zt+`:${_n}`,jt=Xe||Je||fe?null:cM(mn,$.id,En);if(jt){w.appendChild(jt.cloneNode(!0)),Ai($)&&$.toolCall?.id&&$.agentMetadata?.awaitingLocalTool===!0&&!$.agentMetadata?.askUserQuestionAnswered&&(ce.add($.toolCall.id),_p($,o,ot.composerOverlay));return}let cn=null,Sn=u.find(et=>!!($.variant==="reasoning"&&et.renderReasoning||$.variant==="tool"&&et.renderToolCall||!$.variant&&et.renderMessage)),Ke=o.layout?.messages;if(Ai($)&&$.agentMetadata?.askUserQuestionAnswered===!0){Qi.delete($.id),i.querySelector(`#wrapper-${$.id}`)?.removeAttribute("data-preserve-runtime");return}if(ql($)&&Ms(o).enabled)return;if(Ai($)&&o.features?.askUserQuestion?.enabled!==!1){let et=u.find(An=>typeof An.renderAskUserQuestion=="function");if(et&&Ft.current){let An=Qi.get($.id),Io=An!==En,kn=null;if(Io){let{payload:st,complete:tt}=ka($),ys=$.id,bn=()=>Ft.current?.getMessages().find(ro=>ro.id===ys);kn=et.renderAskUserQuestion({message:$,payload:st,complete:tt,resolve:ro=>{let Or=bn();Or&&Ft.current?.resolveAskUserQuestion(Or,ro)},dismiss:()=>{let ro=bn();ro?.agentMetadata?.awaitingLocalTool&&(Ft.current?.markAskUserQuestionResolved(ro),Ft.current?.resolveAskUserQuestion(ro,"(dismissed)"))},config:o})}let Ut=An!=null;if(Io&&kn===null&&!Ut){$.agentMetadata?.awaitingLocalTool===!0&&!$.agentMetadata?.askUserQuestionAnswered&&(ce.add($.toolCall.id),_p($,o,ot.composerOverlay));return}let Ye=Pr($.id,$.role);Ye.setAttribute("data-ask-plugin-stub","true"),Ye.setAttribute("data-preserve-runtime","true"),w.appendChild(Ye),De.push({messageId:$.id,fingerprint:En,bubble:kn});return}else{$.agentMetadata?.awaitingLocalTool===!0&&!$.agentMetadata?.askUserQuestionAnswered&&(ce.add($.toolCall.id),_p($,o,ot.composerOverlay));return}}else if(Je){let et=D();if(!et){w.appendChild(Pr($.id,$.role));return}let An=u.find(Ye=>typeof Ye.renderApproval=="function")??M,kn=ns.get($.id)!==En,Ut=null;if(kn&&An?.renderApproval){let Ye=$.id,st=(tt,ys)=>{let bn=Ft.current?.getMessages().find(ro=>ro.id===Ye);bn?.approval&&(bn.approval.toolType==="webmcp"?Ft.current?.resolveWebMcpApproval(bn.id,tt):Ft.current?.resolveApproval(bn.approval,tt,ys))};Ut=An.renderApproval({message:$,defaultRenderer:()=>et.createApprovalBubble($,o,l),config:o,approve:tt=>st("approved",tt),deny:tt=>st("denied",tt)})}if(kn&&Ut===null)i.querySelector(`#wrapper-${$.id}`)?.removeAttribute("data-preserve-runtime"),ns.delete($.id),cn=et.createApprovalBubble($,o,l);else{let Ye=Pr($.id,$.role);Ye.setAttribute("data-approval-plugin-stub","true"),Ye.setAttribute("data-preserve-runtime","true"),w.appendChild(Ye),oo.push({messageId:$.id,fingerprint:En,bubble:Ut});return}}else if(Sn)if($.variant==="reasoning"&&$.reasoning&&Sn.renderReasoning){if(!J)return;cn=Sn.renderReasoning({message:$,defaultRenderer:()=>vy($,o,s),config:o})}else if($.variant==="tool"&&$.toolCall&&Sn.renderToolCall){if(!Y)return;cn=Sn.renderToolCall({message:$,defaultRenderer:()=>Sy($,o,r),config:o})}else Sn.renderMessage&&(cn=Sn.renderMessage({message:$,defaultRenderer:()=>{let et=ly($,f,Ke,o.messageActions,Yn,{loadingIndicatorRenderer:q,widgetConfig:o,actionEligibility:fn});return $.role!=="user"&&O(et,$,o,N),et},config:o}));if(!cn&&fe){let et=l0($);if(et){let An=Xs.get($.id),Io=An!==En,kn=o.wrapComponentDirectiveInBubble!==!1&&Yo.getOptions(et.component)?.bubbleChrome!==!1,Ut=null;if(Io){let Ye=i0(et,{config:o,message:$,transform:f});if(Ye&&et.component==="PersonaArtifactInline"){let st=Ye.hasAttribute("data-artifact-inline")?Ye:Ye.querySelector("[data-artifact-inline]"),tt=st?.getAttribute("data-artifact-inline")??"",ys=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(tt):tt,bn=tt?i.querySelector(`#wrapper-${$.id}`)?.querySelector(`[data-artifact-inline="${ys}"]`)??null:null;st&&bn&&bn!==st&&Gr()?.hasLiveInlineArtifactBlock(bn)&&(st===Ye?Ye=bn:st.replaceWith(bn))}if(Ye)if(kn){let st=document.createElement("div");if(st.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),st.id=`bubble-${$.id}`,st.setAttribute("data-message-id",$.id),$.content&&$.content.trim()){let tt=document.createElement("div");tt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",tt.innerHTML=f({text:$.content,message:$,streaming:!!$.streaming,raw:$.rawContent}),st.appendChild(tt)}st.appendChild(Ye),Ut=st}else{let st=document.createElement("div");if(st.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",st.id=`bubble-${$.id}`,st.setAttribute("data-message-id",$.id),st.setAttribute("data-persona-component-directive","true"),$.content&&$.content.trim()){let tt=document.createElement("div");tt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",tt.innerHTML=f({text:$.content,message:$,streaming:!!$.streaming,raw:$.rawContent}),st.appendChild(tt)}st.appendChild(Ye),Ut=st}}if(Ut||An!=null){let Ye=Pr($.id,$.role);Ye.setAttribute("data-component-directive-stub","true"),Ye.setAttribute("data-preserve-runtime","true"),w.appendChild(Ye),lt.push({messageId:$.id,fingerprint:En,bubble:Ut});return}}}if(!cn)if($.variant==="reasoning"&&$.reasoning){if(!J)return;cn=vy($,o,s)}else if($.variant==="tool"&&$.toolCall){if(!Y)return;cn=Sy($,o,r)}else if($.variant==="approval"&&$.approval){if(o.approval===!1)return;let et=D();if(!et)return;cn=et.createApprovalBubble($,o,l)}else{let et=o.layout?.messages;et?.renderUserMessage&&$.role==="user"?cn=et.renderUserMessage({message:$,config:o,streaming:!!$.streaming}):et?.renderAssistantMessage&&$.role==="assistant"?cn=et.renderAssistantMessage({message:$,config:o,streaming:!!$.streaming}):cn=ly($,f,et,o.messageActions,Yn,{loadingIndicatorRenderer:q,widgetConfig:o,actionEligibility:fn}),$.role!=="user"&&cn&&O(cn,$,o,N)}let Kt=Pr($.id,$.role);Kt.appendChild(cn),dM(mn,$.id,En,Kt),w.appendChild(Kt)}),ot.composerOverlay&&ot.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Xe=>{let Je=Xe.getAttribute("data-persona-ask-sheet-for");Je&&!ce.has(Je)&&La(ot.composerOverlay,Je)}),o.features?.toolCallDisplay?.grouped){let $=[],Xe=[],Je=o.features.toolCallDisplay.groupedMode==="summary";d.forEach(fe=>{if(fe.variant==="tool"&&fe.toolCall&&Y){if(Po&&fe.toolCall.status==="complete")return;Xe.push(fe);return}fe.variant==="reasoning"&&(!J||fe.reasoning?.status==="complete"&&dr(fe.reasoning))||((Xe.length>1||Je&&Xe.length>0)&&$.push(Xe),Xe=[])}),(Xe.length>1||Je&&Xe.length>0)&&$.push(Xe),$.forEach(fe=>{let zt=fe.map(Ke=>Array.from(w.children).find(Kt=>Kt instanceof HTMLElement&&Kt.getAttribute("data-wrapper-id")===Ke.id)).filter(Ke=>!!Ke);if(zt.length<(Je?1:2))return;let fn=Pr(`tool-group-${fe[0].id}`,"assistant");if(fn.setAttribute("data-persona-tool-group-row","true"),o.features?.toolCallDisplay?.groupedMode==="collapsible"){let Ke=`tool-group-${fe[0].id}`,Kt=fe.some(Ut=>Ut.toolCall?.status!=="complete"),et={...fe[0],id:Ke,toolCall:{id:Ke,name:`${fe.length} tools`,status:Kt?"running":"complete",chunks:fe.flatMap(Ut=>Ut.toolCall?.chunks??[]),success:!fe.some(Ut=>Ut.toolCall?.success===!1)}};y.add(Ke),a.observe(et,"tool",r,o.features.toolCallDisplay);let An=`${Kt?"Using":"Used"} ${fe.length} tools`,Io=o.toolCall?.renderGroupedSummary?.({messages:fe,toolCalls:fe.map(Ut=>Ut.toolCall),defaultSummary:An,config:o}),kn=Ww(et,o,r.has(Ke),Io??An);kn.bubble.classList.add("persona-tool-group"),kn.body.dataset.personaToolGroupStack="true",zt[0].before(fn),fn.appendChild(kn.bubble),zt.forEach((Ut,Ye)=>{Ut.style.setProperty("--persona-message-row-max-width","100%"),Ut.style.setProperty("--persona-activity-stagger",`${Ye*40}ms`),Ut.classList.add("persona-activity-group-child"),kn.body.appendChild(Ut)});return}let _n=document.createElement("div");_n.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",_n.setAttribute("data-persona-tool-group","true");let En=document.createElement("div");En.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",En.id=`tool-group-summary-${fe[0].id}`;let jt=`Called ${fe.length} ${fe.length===1?"tool":"tools"}`,cn=o.toolCall?.renderGroupedSummary?.({messages:fe,toolCalls:fe.map(Ke=>Ke.toolCall).filter(Ke=>!!Ke),defaultSummary:jt,config:o});te(En,cn)||(En.textContent=jt);let Sn=document.createElement("div");Sn.className="persona-tool-group-stack persona-flex persona-flex-col",Sn.id=`tool-group-stack-${fe[0].id}`,Sn.setAttribute("data-persona-tool-group-stack","true"),_n.appendChild(En),Je||_n.appendChild(Sn),fn.appendChild(_n),zt[0].before(fn),zt.forEach((Ke,Kt)=>{if(Je){Ke.remove();return}Ke.style.setProperty("--persona-message-row-max-width","100%");let et=document.createElement("div");et.className="persona-tool-group-item persona-relative",et.setAttribute("data-persona-tool-group-item","true"),Kt<zt.length-1&&et.setAttribute("data-persona-tool-group-connector","true"),et.appendChild(Ke),Sn.appendChild(et)})})}a.prune(y),pM(mn,Q);let gs=$=>$.variant==="tool"&&!Y||$.variant==="reasoning"&&!J||Lo($),pr=d.some($=>$.role==="assistant"&&$.streaming&&!gs($)),zo=d.length-1;for(;zo>=0&&gs(d[zo]);)zo--;let hs=zo>=0?d[zo]:void 0,Ol=zo<d.length-1,hi=hs?.role==="assistant"&&!hs.streaming&&hs.variant!=="approval"&&!Ol;if(uo&&d.some($=>$.role==="user")&&!pr&&!hi){let $={config:o,streaming:!0,location:"standalone",defaultRenderer:Hc},Xe=u.find(fe=>fe.renderLoadingIndicator),Je=null;if(Xe?.renderLoadingIndicator&&(Je=Xe.renderLoadingIndicator($)),Je===null&&o.loadingIndicator?.render&&(Je=o.loadingIndicator.render($)),Je===null&&(Je=Hc()),Je){let fe=document.createElement("div"),zt=o.loadingIndicator?.showBubble!==!1,fn=o.layout?.messages?.layout??"bubble";fe.className=zt?Rc("assistant",fn).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),fe.setAttribute("data-typing-indicator","true"),zt&&(fe.style.color="var(--persona-message-assistant-text, var(--persona-text))",fn!=="flat"&&(fe.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",fe.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),fe.appendChild(Je);let _n=Pr("typing-indicator","assistant");_n.appendChild(fe),w.appendChild(_n)}}if(!uo&&d.length>0){let $=d[d.length-1],Xe={config:o,lastMessage:$,messageCount:d.length},Je=u.find(zt=>zt.renderIdleIndicator),fe=null;if(Je?.renderIdleIndicator&&(fe=Je.renderIdleIndicator(Xe)),fe===null&&o.loadingIndicator?.renderIdle&&(fe=o.loadingIndicator.renderIdle(Xe)),fe){let zt=document.createElement("div"),fn=o.loadingIndicator?.showBubble!==!1;zt.className=fn?["persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),zt.setAttribute("data-idle-indicator","true"),zt.appendChild(fe);let _n=Pr("idle-indicator","assistant");_n.appendChild(zt),w.appendChild(_n)}}if(Qw(w),Vu(i,w),Wg(i),$t){let{messageId:$,element:Xe}=$t,Je=i.querySelector(`#wrapper-${$}`);Je&&Xe.parentElement!==Je&&(fl(Je,re.get($)??"user"),Je.replaceChildren(Xe))}if(De.length>0)for(let{messageId:$,fingerprint:Xe,bubble:Je}of De){let fe=i.querySelector(`#wrapper-${$}`);fe&&(fl(fe,re.get($)??"assistant"),Je!==null&&(fe.replaceChildren(Je),fe.setAttribute("data-bubble-fp",Xe),Qi.set($,Xe)))}if(Qi.size>0)for(let $ of Qi.keys())Q.has($)||Qi.delete($);if(lt.length>0)for(let{messageId:$,fingerprint:Xe,bubble:Je}of lt){let fe=i.querySelector(`#wrapper-${$}`);fe&&(fl(fe,re.get($)??"assistant"),Je!==null&&(fe.replaceChildren(Je),fe.setAttribute("data-bubble-fp",Xe),Xs.set($,Xe)))}if(Xs.size>0)for(let $ of Xs.keys())Q.has($)||Xs.delete($);if(oo.length>0)for(let{messageId:$,fingerprint:Xe,bubble:Je}of oo){let fe=i.querySelector(`#wrapper-${$}`);fe&&(fl(fe,re.get($)??"assistant"),Je!==null&&(fe.replaceChildren(Je),fe.setAttribute("data-bubble-fp",Xe),ns.set($,Xe)))}if(ns.size>0)for(let $ of ns.keys())Q.has($)||ns.delete($)},af=!1,kd=()=>{af||(af=!0,$w().catch(()=>{af=!1}))},xo=(i,d,f)=>{d.length>0&&kd(),uk(i,d,f),Yb()},gl=null,mk=()=>{if(gl)return;let i=f=>{let y=f.composedPath();y.includes(dt)||Nt&&y.includes(Nt)||qt(!1,"user")};gl=i,(t.ownerDocument??document).addEventListener("pointerdown",i,!0)},Iv=()=>{if(!gl)return;(t.ownerDocument??document).removeEventListener("pointerdown",gl,!0),gl=null};Oe.push(()=>Iv());let hl=null,fk=()=>{if(hl)return;let i=f=>{f.key==="Escape"&&(f.isComposing||qt(!1,"user"))};hl=i,(t.ownerDocument??document).addEventListener("keydown",i,!0)},Hv=()=>{if(!hl)return;(t.ownerDocument??document).removeEventListener("keydown",hl,!0),hl=null};Oe.push(()=>Hv());let yl=!1,Rv=new Set,gk=()=>{let i=o.launcher?.composerBar?.peek?.streamAnimation;return i||o.features?.streamAnimation},oa=()=>{if(!xe())return;let i=ot.peekBanner,d=ot.peekTextNode;if(!i||!d)return;if(Ae){i.classList.remove("persona-pill-peek--visible");return}let f=N?.getMessages()??[],y;for(let Jt=f.length-1;Jt>=0;Jt--){let rn=f[Jt];if(rn.role==="assistant"&&rn.content){y=rn;break}}if(!y){i.classList.remove("persona-pill-peek--visible");return}let w=y.content,k=!!y.streaming,q=gk(),te=qu(q),Q=te.type!=="none"?Qm(te.type,q?.plugins):null,re=Q?.isAnimating?.(y)===!0,ce=Q!==null&&(k||re);ce&&Q&&!Rv.has(Q.name)&&(xc(Q,t),Rv.add(Q.name));let ye=ce&&Q?.containerClass?Q.containerClass:null,De=d.dataset.personaPeekStreamClass??null;De&&De!==ye&&(d.classList.remove(De),delete d.dataset.personaPeekStreamClass),ye&&De!==ye&&(d.classList.add(ye),d.dataset.personaPeekStreamClass=ye),ce?(d.style.setProperty("--persona-stream-step",`${te.speed}ms`),d.style.setProperty("--persona-stream-duration",`${te.duration}ms`)):(d.style.removeProperty("--persona-stream-step"),d.style.removeProperty("--persona-stream-duration"));let lt=ce?ju(w,te.buffer,Q,y,k):w;if(ce&&te.placeholder==="skeleton"&&k&&(!lt||!lt.trim())){let Jt=document.createElement("div"),rn=wc();rn.classList.add("persona-pill-peek__skeleton"),Jt.appendChild(rn),Vu(d,Jt)}else{let Jt=Math.max(0,lt.length-100),rn=lt.length>100?lt.slice(-100):lt,Vn=$r(rn);if(!ce||!Q){let ln=lt.length>100?`\u2026${rn}`:rn;d.textContent!==ln&&(d.textContent=ln)}else{let ln=Vn;(Q.wrap==="char"||Q.wrap==="word")&&(ln=Cc(Vn,Q.wrap,`peek-${y.id}`,{skipTags:Q.skipTags,startIndex:Jt}));let $t=document.createElement("div");if($t.innerHTML=ln,Q.useCaret&&rn.length>0){let cr=Ku(),dr=$t.querySelectorAll(".persona-stream-char, .persona-stream-word"),Po=dr[dr.length-1];Po?.parentNode?Po.parentNode.insertBefore(cr,Po.nextSibling):$t.appendChild(cr)}Vu(d,$t),Q.onAfterRender?.({container:d,bubble:i,messageId:y.id,message:y,speed:te.speed,duration:te.duration})}}let oo=uo||yl;i.classList.toggle("persona-pill-peek--visible",oo)};if(xe()){let i=ot.peekBanner;if(i){let y=w=>{w.preventDefault(),w.stopPropagation(),qt(!0,"user")};i.addEventListener("pointerdown",y),Oe.push(()=>{i.removeEventListener("pointerdown",y)})}let d=()=>{yl||(yl=!0,oa())},f=()=>{yl&&(yl=!1,oa())};Se.addEventListener("pointerenter",d),Se.addEventListener("pointerleave",f),Oe.push(()=>{Se.removeEventListener("pointerenter",d),Se.removeEventListener("pointerleave",f)}),Nt&&(Nt.addEventListener("pointerenter",d),Nt.addEventListener("pointerleave",f),Oe.push(()=>{Nt.removeEventListener("pointerenter",d),Nt.removeEventListener("pointerleave",f)}))}let hk=i=>{let d=o.launcher?.composerBar??{},f=d.expandedSize??"anchored",y=d.bottomOffset??"16px",w=d.collapsedMaxWidth,k=d.expandedMaxWidth??"880px",q=d.expandedTopOffset??"5vh",te=d.modalMaxWidth??"880px",Q=d.modalMaxHeight??"min(90vh, 800px)",re="calc(100vw - 32px)",ce="var(--persona-pill-area-height, 80px)",ye=dt.style;if(ye.left="",ye.right="",ye.top="",ye.bottom="",ye.transform="",ye.width="",ye.maxWidth="",ye.height="",ye.maxHeight="",Nt){let De=Nt.style;De.bottom=y,De.width=w??""}if(i&&f!=="fullscreen"){if(f==="modal"){ye.top="50%",ye.left="50%",ye.transform="translate(-50%, -50%)",ye.bottom="auto",ye.right="auto",ye.width=te,ye.maxWidth=re,ye.maxHeight=Q,ye.height=Q;return}ye.left="50%",ye.transform="translateX(-50%)",ye.bottom=`calc(${y} + ${ce})`,ye.top=q,ye.width=k,ye.maxWidth=re}},bl=()=>{if(Ae&&kd(),!Ne())return;if(xe()){let re=(o.launcher?.composerBar??{}).expandedSize??"anchored",ce=Ae?"expanded":"collapsed";dt.dataset.state=ce,dt.dataset.expandedSize=re,Nt&&(Nt.dataset.state=ce,Nt.dataset.expandedSize=re),dt.style.removeProperty("display"),dt.classList.remove("persona-pointer-events-none","persona-opacity-0"),Se.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),hk(Ae),Pe.style.display=Ae?"flex":"none",Us(),Ae?(mk(),fk()):(Iv(),Hv()),oa();return}let i=nn(o),d=t.ownerDocument.defaultView??window,f=o.launcher?.mobileBreakpoint??640,y=o.launcher?.mobileFullscreen??!0,w=d.innerWidth<=f,k=y&&w&&_,q=Do(o).reveal;Ae?(dt.style.removeProperty("display"),dt.style.display=i?"flex":"",dt.classList.remove("persona-pointer-events-none","persona-opacity-0"),Se.classList.remove("persona-scale-95","persona-opacity-0"),Se.classList.add("persona-scale-100","persona-opacity-100"),sn?(sn.setPanelOpen(!0),sn.element.style.display="none"):Fn&&(Fn.style.display="none")):(i?i&&(q==="overlay"||q==="push")&&!k?(dt.style.removeProperty("display"),dt.style.display="flex",dt.classList.remove("persona-pointer-events-none","persona-opacity-0"),Se.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(dt.style.setProperty("display","none","important"),dt.classList.remove("persona-pointer-events-none","persona-opacity-0"),Se.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(dt.style.display="",dt.classList.add("persona-pointer-events-none","persona-opacity-0"),Se.classList.remove("persona-scale-100","persona-opacity-100"),Se.classList.add("persona-scale-95","persona-opacity-0")),sn?(sn.setPanelOpen(!1),sn.element.style.display=i?"none":""):Fn&&(Fn.style.display=i?"none":""))},qt=(i,d="user")=>{if(!Ne()||Ae===i)return;let f=Ae;Ae=i,bl();let y=(()=>{let k=o.launcher?.sidebarMode??!1,q=t.ownerDocument.defaultView??window,te=o.launcher?.mobileFullscreen??!0,Q=o.launcher?.mobileBreakpoint??640,re=q.innerWidth<=Q,ce=nn(o)&&te&&re,ye=xe()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return k||te&&re&&_||ce||ye})();if(Ae&&y){if(!or){let k=t.getRootNode(),q=k instanceof ShadowRoot?k.host:t.closest(".persona-host");q&&(or=Jh(q,o.launcher?.zIndex??On))}rr||(rr=Zh(t.ownerDocument))}else Ae||(or?.(),or=null,rr?.(),rr=null);Ae&&(Wl(),rf()||(po()==="follow"?as(!0):Ad()));let w={open:Ae,source:d,timestamp:Date.now()};Ae&&!f?H.emit("widget:opened",w):!Ae&&f&&H.emit("widget:closed",w),H.emit("widget:state",{open:Ae,launcherEnabled:_,voiceActive:wt.active,streaming:N.isStreaming()})},ls={inputDisabled:!1,sendDisabled:!1},sr=()=>ls.inputDisabled,lf=()=>Un(o.voiceRecognition?.provider)&&!!N&&(N.isBargeInActive()||["listening","processing","speaking"].includes(N.getVoiceStatus())),si=()=>ls.inputDisabled||ls.sendDisabled,yk=()=>(ls.inputDisabled?ls.inputReason:void 0)??(ls.sendDisabled?ls.sendReason:void 0);function cf(){if(!Ve)return;if(ze.getState().phase==="streaming"){Ve.disabled=!1;return}let i=Lt?!Lt.isReady():!1;Ve.disabled=si()||i}function Pd(){if(!Jo)return;let i=ze.getState(),d=o.sendButton?.visibility==="when-text"&&i.phase!=="streaming"&&i.text.trim().length===0&&i.attachments.length===0;Jo.toggleAttribute("data-persona-send-hidden",d)}function bk(){let i=yk();if(xe()){let d=Tn??Qe;i?d.setAttribute("title",i):d.removeAttribute("title"),Qe.toggleAttribute(Za,!!i);return}if(i){pt.setAttribute("role","status"),pt.setAttribute("aria-live","polite"),pt.setAttribute(Za,""),pt.textContent=i,xi(pt,o.statusIndicator??{},"idle");return}if(pt.hasAttribute(Za)&&(pt.removeAttribute("role"),pt.removeAttribute("aria-live"),pt.removeAttribute(Za),h)){let d=N.getStatus();Qo(pt,_s(d),o.statusIndicator??{},d)}}function df(){let i=uh(o.composer?.inputDisabled),d=uh(o.composer?.sendDisabled);ls={inputDisabled:i.disabled,inputReason:i.reason,sendDisabled:d.disabled,sendReason:d.reason},ze.setInputDisabled(i.disabled),ze.setSendDisabled(d.disabled);let f=ze.getState().phase==="streaming",y=i.disabled,w=f||y;we&&(we instanceof HTMLTextAreaElement?we.disabled=y:we.setAttribute("contenteditable",y?"false":"true"),we.setAttribute("aria-disabled",y?"true":"false")),on&&(on.disabled=y),Xt&&(Xt.disabled=y);for(let k of un?.affordanceButtons??[])k.querySelectorAll("button").forEach(q=>{q.disabled=y});he&&(he.disabled=y||f&&!lf()),Ks.forEach(k=>{k.elements.forEach(q=>{q.toggleAttribute("data-disabled",w),q instanceof HTMLButtonElement||q.setAttribute("aria-disabled",w?"true":"false")}),k.buttons.forEach(q=>{q.disabled=w})}),gf.forEach(k=>{k.toggleAttribute("data-disabled",w),k instanceof HTMLButtonElement?k.disabled=w:k.setAttribute("aria-disabled",w?"true":"false"),k.querySelectorAll("button").forEach(q=>{q.disabled=w})}),Qe.dataset.personaComposerStreaming=f?"true":"false",Qe.dataset.personaComposerInputDisabled=y?"true":"false",Qe.dataset.personaComposerSendDisabled=si()?"true":"false",Qe.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(k=>{(k instanceof HTMLButtonElement||k instanceof HTMLInputElement||k instanceof HTMLTextAreaElement||k instanceof HTMLSelectElement)&&(k.disabled=f)}),cf(),bk()}let vl=i=>{ze.setStreaming(i),Tb(i?"stop":"send"),df()},ii=()=>{wt.active||we&&we.focus()};H.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>ii(),200)});let ai=null,Cl=!1,pf=!gn.hidden,cs=null,uf=!G,Ld=null;Oe.push(()=>{Ld?.cancel(),Ld=null});let vk=i=>{let d=nT(i);if(d===od)return;od=d,t.setAttribute("data-persona-conversation-state",d);let f=Hm();sd(),uf&&(Ld?.cancel(),Ld=eT(Qe,d==="active"?f:Hm(),d==="active"?"drop":"rise",Vs().layout==="centered"?320:260)),to()},Wv=null,Bv,Dv=null,ra=null,mf=!1,sa=i=>{let d=Vs(),f=`${d.variant}|${d.layout}|${d.dismiss}|${d.anchor??"bottom"}|${d.align??""}|${d.iconPlacement}|${d.kicker??""}|${d.title}|${d.subtitle}`;(f!==Wv||d.icon!==Bv)&&(Wv=f,Bv=d.icon,tm({host:gn,iconHolder:km,kicker:ge,title:Ue,subtitle:at,starterSuggestions:Ns},d));let y=d.message===void 0?null:`${o.layout?.messages?.layout??"bubble"}|${d.message}`;y!==Dv&&(Dv=y,nm(z,d.message,o));let w=i??(N?N.getMessages():o.initialMessages);vk(w);let k=Cl,q=!k&&Ua(d,w),te=q!==pf;if(pf=q,ra){cs?.cancel(),cs=null,k!==mf&&(mf=k,k?py(pe,gn,null):dy(pe,gn,ra)),za(pe,gn,!k);return}if(te&&!q&&!k&&d.dismiss==="on-first-message"&&uf){cs=ZM(gn,re=>{cs===re&&(cs=null),!pf&&!ra&&(za(pe,gn,!1),to()),re?.cancel()});return}if(cs){if(!q&&!k)return;cs.cancel(),cs=null}let Q=!gn.hidden;za(pe,gn,q),!q&&Q&&to()},ff=[],gf=[],hf=!1,Ov=null,_v,Nv=()=>{gf.length=0;let i=ff.splice(0,ff.length);for(let d of i)try{d()}catch(f){console.warn("[persona] renderWelcome cleanup threw",f)}};Oe.push(Nv);let Ck=(i,d)=>{let f=ty(i,d);if(!f)return o.debug===!0&&console.warn("[persona] renderStarter received a suggestion with no label"),v("span");let y=o.suggestions?.starters,w=ny({item:{...f,behavior:f.behavior??y?.behavior??"send"},index:d,surface:"starter",source:"config",variant:y?.variant??"card",streaming:h?N.isStreaming():!1,config:o,plugins:u,chipsConfig:o.suggestionChipsConfig,session:N,getTextarea:()=>we,eventTarget:gn,submitPrompt:op});return gf.push(w),w},yf=()=>{if(hf)return;hf=!0;let i=Vs();Ov=`${i.variant}|${i.layout}|${i.dismiss}|${i.title}|${i.subtitle}|${i.message??""}`,_v=i.icon;try{Nv(),py(pe,gn,ra),ra=null,mf=!1;let d=N?N.getMessages():o.initialMessages,f=Ua(i,d),y=0,w=null;for(let k of u)if(k.renderWelcome&&(w=k.renderWelcome({config:i,variant:i.variant,visible:f,defaultRenderer:()=>gn,sendMessage:q=>{if(!N||N.isStreaming())return;let te=q.trim();te&&N.sendMessage(te)},requestRender:()=>yf(),renderStarter:q=>Ck(q,y++),storage:b(k.id),onCleanup:q=>{ff.push(q)}}),w))break;w&&w!==gn&&(ra=w,dy(pe,gn,w))}finally{hf=!1}sa()},wk=()=>{let i=Vs();`${i.variant}|${i.layout}|${i.dismiss}|${i.title}|${i.subtitle}|${i.message??""}`===Ov&&i.icon===_v||yf()},Id=()=>{sa(),ji||(we.placeholder=XS(ze.getState().activeModeIds,o.composer?.modes)??o.copy?.inputPlaceholder??"How can I help...",!(o.sendButton?.useIcon??!1)&&!N?.isStreaming()&&(Ve.textContent=o.copy?.sendButtonLabel??"Send")),we.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',we.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},xk=!!o.setStoredConversationId,ia=i=>de(d=>{let f={...d};return delete f[i],f}),Hd=i=>{let d=L[i];return typeof d=="string"?d:null},Fv=()=>{let i=L.durableResume;if(!i||typeof i!="object")return null;let d=i;return typeof d.executionId=="string"&&d.executionId.length>0&&typeof d.after=="string"&&d.after.length>0?{executionId:d.executionId,after:d.after}:null};o.clientToken&&(o={...o,getStoredSessionId:()=>Hd("sessionId"),setStoredSessionId:i=>{de(d=>({...d,sessionId:i}))},clearStoredSessionId:o.clearStoredSessionId??(()=>ia("sessionId")),getStoredConversationId:o.getStoredConversationId??(()=>Hd("conversationId")),setStoredConversationId:o.setStoredConversationId??(i=>{de(d=>({...d,conversationId:i}))}),clearStoredConversationId:o.clearStoredConversationId??(()=>ia("conversationId"))});let Vv=()=>o.clientToken??null,$v=i=>OE(i,_e(),o.persistState===!1),zv=Vv(),So=zv?$v(zv):null,Lr={...So?{visitorStore:So}:{},historyBootstrapReady:K,getStoredMessageCursor:()=>Hd("historyMessageCursor"),setStoredMessageCursor:i=>{if(i===null){ia("historyMessageCursor");return}de(d=>({...d,historyMessageCursor:i}))},getPendingDisplayProjections:()=>{let i=L.pendingDisplayProjections;if(!i||typeof i!="object")return null;let d=i;return typeof d.conversationId!="string"||!Array.isArray(d.messageIds)?null:{conversationId:d.conversationId,messageIds:d.messageIds.filter(f=>typeof f=="string")}},setPendingDisplayProjections:i=>{if(!i){ia("pendingDisplayProjections");return}de(d=>({...d,pendingDisplayProjections:i}))},getStoredResumableHandle:Fv,setStoredResumableHandle:i=>{if(!i){ia("durableResume");return}de(d=>({...d,durableResume:i}))},shouldResumeDurableConversation:()=>P&&Fv()!==null,...xk?{}:{getStoredConversationRevision:()=>Hd("conversationRevision"),setStoredConversationRevision:i=>{if(i===null){ia("conversationRevision");return}de(d=>({...d,conversationRevision:i}))}}};if(P){let i=o.onExecutionState,d=t.ownerDocument.defaultView,f=!1,y=()=>f=!0,w=()=>f=!1;d?.addEventListener("pagehide",y),d?.addEventListener("pageshow",w),Oe.push(()=>{d?.removeEventListener("pagehide",y),d?.removeEventListener("pageshow",w)}),o={...o,reconnectStream:o.reconnectStream??(k=>N.getClient().reconnectClientTokenStream(k)),onExecutionState:k=>{(k||!f)&&Lr.setStoredResumableHandle?.(k?{executionId:k.executionId,after:k.lastEventId}:null),i?.(k)}}}let Sk=()=>{let i=Vv();if(i&&So?.matches(i,_e(),o.persistState===!1)||!i&&!So)return;So?.destroy(),So=i?$v(i):null;let d={...Lr};So?d.visitorStore=So:delete d.visitorStore,Lr=d,N.setHistoryInternals(Lr)},li=null,Ak=()=>{li==null&&(li=setInterval(()=>{let i=We.querySelectorAll("[data-tool-elapsed]");if(i.length===0){clearInterval(li),li=null;return}let d=Date.now();i.forEach(f=>{let y=Number(f.getAttribute("data-tool-elapsed"));y&&(f.textContent=f.closest(".persona-activity-row")?Vl(d-y):Vp(d-y))})},100))},bf=(i,d)=>{if(Object.is(i,d))return!0;if(i===null||d===null||typeof i!="object"||typeof d!="object")return!1;if(Array.isArray(i)||Array.isArray(d))return!Array.isArray(i)||!Array.isArray(d)||i.length!==d.length?!1:i.every((q,te)=>bf(q,d[te]));let f=i,y=d,w=Object.keys(f),k=Object.keys(y);return w.length===k.length&&w.every(q=>Object.prototype.hasOwnProperty.call(y,q)&&bf(f[q],y[q]))},Uv=i=>{let{content:d,rawContent:f,llmContent:y,...w}=i;return w},vf=i=>i.role==="assistant"&&i.streaming===!0&&!i.variant&&!i.toolCall&&!i.tools&&!i.approval&&!i.reasoning&&!i.contentParts&&!i.stopReason&&!bb(i),Mk=(i,d,f)=>{if(i.length!==d.length)return!1;let y=i[f.index],w=d[f.index];return!y||!w||y.id!==f.id||w.id!==f.id?!1:(!Object.is(y.content,w.content)||!Object.is(y.rawContent,w.rawContent)||!Object.is(y.llmContent,w.llmContent))&&vf(y)&&vf(w)&&bf(Uv(y),Uv(w))},Cf=null,aa=null,ci=null,Ir=null,wf=null,Tk=i=>{if(!P)return Zi(i);wf=i,queueMicrotask(()=>{wf===i&&(wf=null,Zi(i))})},Rd=i=>{Cf=i;let d,f;aa=null;for(let w=i.length-1;w>=0;w-=1){let k=i[w];if(!d&&k.role==="user"&&(d=k),!f&&k.role==="assistant"&&(f=k),!aa&&vf(k)&&(aa={index:w,id:k.id}),d&&f&&aa)break}xo(We,i,j),Gr()?.updateInlineArtifactBlocks(We,wo.artifacts,{suppressTransition:uo}),Ak(),sa(i),Qs(i),as(!uo),pk(i),i.length===0&&($o(),ul=!0,bd=!1,Ji=null,vd=!1),!Xm||Xi?(Xm=!0,ni=d?.id??null,Jm=f?.id??null):d&&d.id!==ni?(ni=d.id,ik(d.id)):f&&f.id!==Jm&&ak(),f&&(Jm=f.id),dk(i);let y=wt.lastUserMessageId;d&&d.id!==y&&(wt.lastUserMessageId=d.id,H.emit("user:message",d)),wt.lastUserMessageWasVoice=!!d?.viaVoice,Tk(i),oa()},xf=()=>{Ir!==null&&(cancelAnimationFrame(Ir),Ir=null);let i=ci;ci=null,i&&Rd(i)},qv=()=>{Ir!==null&&cancelAnimationFrame(Ir),Ir=null,ci=null},Ek=i=>{let d=ci??Cf;if(uo&&d&&aa&&Mk(d,i,aa)){ci=i,Ir===null&&(Ir=requestAnimationFrame(()=>{Ir=null;let f=ci;ci=null,f&&Rd(f)}));return}if(i.length===0){qv(),Rd(i);return}xf(),Rd(i)};N=new Jp(o,{onMessagesChanged(i){Ek(i)},onStatusChanged(i){let d=o.statusIndicator??{};Qo(pt,(y=>y==="idle"?d.idleText??dn.idle:y==="connecting"?d.connectingText??dn.connecting:y==="connected"?d.connectedText??dn.connected:y==="error"?d.errorText??dn.error:y==="paused"?d.pausedText??dn.paused:y==="resuming"?d.resumingText??dn.resuming:dn[y])(i),d,i),pn()},onStreamingChanged(i){i||(N?.getMessages().length===0?qv():xf()),uo=i,vl(i),pn(),N&&xo(We,N.getMessages(),j),i||(as(!0),rk(),yv=!0,N&&bv(N.getMessages(),Ms(o))),xn(),nd(i?"Responding\u2026":"Response complete."),oa()},onVoiceStatusChanged(i){if(H.emit("voice:status",{status:i,timestamp:Date.now()}),!(i!=="disconnected"&&!Un(o.voiceRecognition?.provider)))switch(i){case"listening":Dr(),ba();break;case"processing":Dr(),PP();break;case"speaking":Dr(),LP();break;default:i==="idle"&&N.isBargeInActive()?(Dr(),ba(),he?.setAttribute("aria-label","End voice session")):(wt.active=!1,Dr(),kr("system"),Vo());break}},onArtifactsState(i){wo=i,i.artifacts.length===0&&(Ki=!1),Gr()?.updateInlineArtifactBlocks(We,i.artifacts,{suppressTransition:uo}),Fo(),Zi()},onHistoryStateChanged(i){_t(i)},onHistoryNotice(i){Vt(i)},onReconnect(i){let{executionId:d,lastEventId:f}=i.handle;i.phase==="paused"?H.emit("stream:paused",{executionId:d,after:f}):i.phase==="resuming"?H.emit("stream:resuming",{executionId:d,after:f,attempt:i.attempt??1}):H.emit("stream:resumed",{executionId:d,after:f})}},Lr),Ft.current=N,Oe.push(()=>N.cancel()),Oe.push(()=>{N.destroy(),So?.destroy(),So=null});let Sf=null;if(N.onReadAloudChange((i,d)=>{Kb=i,Gb=d,Yb();let f=i??Sf;i&&(Sf=i);let y=f?N.getMessages().find(w=>w.id===f)??null:null;H.emit("message:read-aloud",{messageId:f,message:y,state:d,timestamp:Date.now()}),d==="idle"&&(Sf=null)}),h=!0,Xm=!0,o.voiceRecognition?.enabled===!0&&Un(o.voiceRecognition.provider))try{N.setupVoice()}catch(i){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",i)}let kk=720,Pk=250,Mt=rb(o.features?.history?.copy),go=null,Af=!1,Dt=null,Wd=null,Bd="conversation",Mf=null,Nn=null,ir=null,Dd=N.getHistoryState(),Tf=null,wl=0,Ef=null,Od=null,_d=null,kf=`persona-history-${Math.random().toString(36).slice(2,8)}`,Pf=()=>o.features?.history?.enabled===!0,ar=()=>Pf()&&!!go&&!Af,jv=()=>{let i=N.getStatus();return uo||i==="paused"||i==="resuming"},Lf=()=>{let i=o.features?.history?.scope;if(i)return i;let d=o.getIdentityProof?"verified-user":"browser",f=go?.capabilities.scopes;return!f||f.includes(d)?d:f[0]??d},la=()=>Wd?.scope??Lf(),Kv=()=>N.getClientSession()?.targetId??null,Gv=i=>`${i.state}:${"reason"in i?i.reason:""}`,Lk=i=>{let d=Gv(i);d!==Tf&&(Tf=d,H.emit("history:identityStatusChanged",{status:i,timestamp:Date.now()}))},Nd=i=>{i&&(xr.textContent="",xr.textContent=i)},Yv=null,Qv=null,Ik=()=>{if(!Pf())return null;let i=r0();if(i)return i();let d=o.features?.history?.provider;return d?typeof d!="function"?d:(Yv!==d&&(Yv=d,Qv=d()),Qv):N.isClientTokenMode()?s0({client:N.getClient(),getIdentityProofConfigured:()=>typeof o.getIdentityProof=="function",onActivationCommitted:f=>N.bindActivatedSession(f),getClient:()=>N.getClient()}):null},Xv=()=>{Od?.(),Od=null,_d?.(),_d=null,Af=!1,go=Ik();let i={...Lr};go?i.historyProvider=go:delete i.historyProvider,Lr=i,N.setHistoryInternals(Lr),go&&(Od=go.subscribeAvailability?.(d=>{Af=!d,d||no({restoreFocus:!1}),ps()})??null,_d=go.subscribeIdentityStatus(d=>Lk(d)),Tf=Gv(go.getIdentityStatus()))},If=()=>{let i=o.features?.history?.presentation??"panel";if(i==="panel"||i==="auto"&&!(!_||nn(o)))return"panel";let d=nr??Pe;return(d.getBoundingClientRect().width||d.clientWidth)>=kk?"rail":"panel"},Ao=(i,d)=>{d?(i.setAttribute("aria-hidden","true"),i.setAttribute("inert","")):(i.removeAttribute("aria-hidden"),i.removeAttribute("inert"))},Fd="data-persona-history-suppressed",ho=null,ds=null,di=null,xl=null,Hf=null,Jv="",Zv=()=>$e===Hf?Jv:o.layout?.showHeader===!1?"none":"",Hk=()=>xt==="panel"&&!!di&&xl===di.element&&o.layout?.showHeader!==!1&&Zv()!=="none",Rk=()=>{for(let i of Array.from($e.children))i!==ho&&i.setAttribute(Fd,"")},Wk=()=>{for(let i of Array.from(Pe.querySelectorAll(`[${Fd}]`)))i.removeAttribute(Fd)},Bk=()=>{let i=di;if(!i)return;if(Array.from($e.children).some(y=>y!==ho&&!y.hasAttribute(Fd))){ds&&ds!==$e&&(ds.style.removeProperty("min-height"),ds=null);let y=$e.offsetHeight;y>0&&($e.style.minHeight=`${y}px`,ds=$e)}ho||(ho=v("div","persona-history-header-host")),i.setHeaderPlacement("external");let f=i.getHeaderElement();f.parentNode!==ho&&ho.replaceChildren(f),ho.parentNode!==$e&&$e.appendChild(ho),Rk()},eC=()=>{ds&&(ds.style.removeProperty("min-height"),ds=null),ho&&(di?.setHeaderPlacement("inline"),ho.remove(),ho=null,Wk())},Vd=null,Rf=()=>{if(Vd){if(pe.style.display="none",Ao(pe,!0),Qe.hidden=!0,Ao(Qe,!0),Hk()){Bk(),$e.style.display=Zv(),Ao($e,!1);return}eC(),$e.style.display="none",Ao($e,!0)}};Mn=Rf;let Dk=i=>{let d=pe.style.display,f=Qe.hidden,y=Qe,w=$e,k=$e.style.display;Hf=w,Jv=k,Vd=()=>{Vd=null,eC(),Hf=null,pe.style.display=d,Ao(pe,!1),y.hidden=f,Ao(y,!1),Qe!==y&&(Qe.hidden=!1,Ao(Qe,!1)),w.style.display=k,Ao(w,!1),$e!==w&&($e.style.display=o.layout?.showHeader===!1?"none":"",Ao($e,!1))},Qe.parentNode?.insertBefore(i,Qe),Rf()},ca=null,pi=null,Sl=null,da=null,tC=()=>[$e,ot.closeButtonWrapper,ot.clearChatButtonWrapper,pe,Qe],Ok=52,$d=()=>o.features?.history?.rail?.collapsible!==!1,pa=()=>o.features?.history?.rail?.side==="right"?"right":"left",Wf=200,Bf=400,Df=i=>Math.min(Bf,Math.max(Wf,Math.round(i))),_k=()=>o.features?.history?.rail?.resizable===!0,Al,Nk=()=>{if(Al===void 0&&(Al=null,o.persistState!==!1))try{let i=Number(window.localStorage.getItem(`${_e()}rail-width`));i&&(Al=i)}catch{}return Al},Ml=()=>Df(Nk()??o.features?.history?.rail?.width??260),Fk=i=>{if(Al=i,o.persistState!==!1)try{window.localStorage.setItem(`${_e()}rail-width`,String(i))}catch{}},zd=()=>$d()&&o.features?.history?.rail?.collapsedBehavior==="overlay",yn=!1,nC=i=>{let d=v("img");return d.src=i,d.alt="",d.setAttribute("aria-hidden","true"),d},Vk=()=>{let i=o.features?.history?.rail?.brand;if(!i)return;let d=!1,f;return y=>{if(i.render)try{return i.render({collapsed:y})??null}catch(w){return d||(d=!0,console.warn("[persona] history rail brand threw",w)),null}return f===void 0&&(i.iconUrl?f=nC(i.iconUrl):f=i.icon?ke(i.icon,20):null),f?f.cloneNode(!0):null}},$k=()=>o.features?.history?.rail?.sections?.map(i=>{let d=!1,f=y=>{d||(d=!0,console.warn("[persona] history rail section threw",i.id,y))};return{id:i.id,title:i.title,placement:i.placement??"above-conversations",items:i.items.map(y=>{let w;return{id:y.id,label:y.label,badge:y.badge,iconNode:()=>{if(w!==void 0)return w;try{y.renderIcon?w=y.renderIcon()??null:y.iconUrl?w=nC(y.iconUrl):w=y.icon?ke(y.icon,20):null}catch(k){f(k),w=null}return w},onSelect:()=>{try{y.onSelect()}catch(k){f(k)}}}})}})??[],zk=i=>{let d=$k();for(let f of i)d.some(y=>y.id===f.id)?console.warn("[persona] duplicate history rail section id",f.id):d.push(f);return d.length?d:void 0},Tl=null,oC=()=>`${_e()}rail-collapsed`,Of=()=>{if(Tl===null&&(Tl=o.features?.history?.rail?.defaultCollapsed===!0,o.persistState!==!1))try{let i=window.localStorage.getItem(oC());i&&(Tl=i==="1")}catch{}return Tl},_f=i=>{if(Tl=i,o.persistState!==!1)try{window.localStorage.setItem(oC(),i?"1":"0")}catch{}},El=()=>xt==="rail"&&$d()&&!zd()&&Of(),Nf=()=>{},rC=()=>{if(zd()){Nf();return}_f(!Of()),Dt?.view.setCollapsed(El()),ft(),to()},Ff=()=>{let i=o.features?.history?.rail?.collapseShortcut;return!i||!Nu(i)?null:{combo:i,hint:Fu(i),aria:yc(i)}},sC=()=>{g.forEach(d=>d()),g=[];let i=Ff();i&&g.push(m.register({id:"history-rail-collapse",combo:i.combo,scope:o.features?.history?.rail?.collapseShortcutScope==="page"?"page":"widget",when:()=>mt&&xt==="rail"&&$d()||ma(),run:()=>zd()?Nf():rC()}));for(let d of o.layout?.header?.trailingActions??[])d.shortcut&&g.push(m.register({id:`header-action-${d.id}`,combo:d.shortcut,run:()=>{let f=t.querySelector(`[data-persona-header-action="${d.id}"]`);f?f.click():o.layout?.header?.onAction?.(d.id)}}));for(let d of u)for(let f of d.shortcuts??[])g.push(m.register({...f,id:`${d.id}:${f.id}`}))};sC();let Uk=300,Ud="var(--persona-history-overlay-margin,8px)",Mo=null,Hr=null,qd=0,Rr=null,ua=null,ui=!1,Vf=0,iC=()=>window.matchMedia?.("(pointer: coarse)").matches===!0,ma=()=>ar()&&zd()&&(xt??If())==="rail",qk=()=>mt&&!yn,kl=()=>{ua!==null&&clearTimeout(ua),ua=null},jk=()=>{fb().catch(()=>{})},aC=()=>{kl(),yn&&(ua=setTimeout(()=>{ua=null,!(ui||!yn)&&(Rr?.contains(document.activeElement)||no({restoreFocus:!1}))},Uk))},Kk=(i,d)=>{let f=Rr?.getBoundingClientRect();if(!f)return!1;let y=Mo?.getBoundingClientRect(),w=y?Math.min(y.top,f.top):f.top;return i>=f.left&&i<=f.right&&d>=w&&d<=f.bottom||!!y&&i>=y.left&&i<=y.right&&d>=y.top&&d<=y.bottom},$f=i=>{yn&&(ui=Kk(i.clientX,i.clientY),ui?kl():ua===null&&aC())},lC=i=>{mt||!ma()||(yn=!0,Ll({invoker:Mo,keyboard:i?.keyboard===!0}).then(()=>{mt?!ui&&document.activeElement!==Mo&&no():yn=!1}))},cC=()=>{let i=xl?.querySelector('[data-persona-history-focus="collapse"]');i&&(i.setAttribute("aria-label",yn?Mt.expandLabel:Mt.collapseLabel),i.setAttribute("aria-expanded",yn?"false":"true"))},dC=()=>{_f(!1);let i=Dt;if(!yn||!i){Ll({invoker:Mo});return}let d=document.activeElement===Mo;yn=!1,jd(),i.element.remove(),Uf(i.element),cC(),d&&Gd(),to(),ps()},Gk=()=>{_f(!0),no()};Nf=()=>{!mt||yn?dC():Gk()};let Yk=()=>{let i=Ff(),d=ki({ariaLabel:Mt.expandLabel,iconName:"panel-left",wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center",extraClassName:"persona-rail-trigger",tooltip:!1,attrs:{"data-persona-rail-trigger":"","aria-controls":kf,...i?{"aria-keyshortcuts":i.aria}:{}}}),f=d.button;f.addEventListener("mouseenter",()=>{ui=!0,kl(),!(iC()||Date.now()<Vf)&&lC()}),f.addEventListener("mouseleave",()=>{ui=!1,Vf=0,aC()}),f.addEventListener("focus",()=>{mt||jk()}),f.addEventListener("click",y=>{ar()&&(y.detail!==0&&iC()&&!mt?lC():dC())}),Mo=f,Hr=d.wrapper},Pl=()=>{if(Hr&&!Hr.isConnected&&(Hr=null,Mo=null),!ma()){Hr?.remove(),Hr=null,Mo=null;return}Mo||Yk();let i=Hr,d=Mo;if(!i||!d)return;let f=pa()!=="right"?$e.firstChild:null;(f??$e.lastChild)!==i&&$e.insertBefore(i,f),i.style.display=qk()||qd>0?"none":"",d.setAttribute("aria-label",Mt.expandLabel),d.setAttribute("aria-expanded",mt?"true":"false"),Rr&&ft()},pC=i=>{if(!yn)return;let d=i.target;d instanceof Node&&(Rr?.contains(d)||Hr?.contains(d)||d instanceof Element&&d.closest('.persona-dropdown-menu,[role="alertdialog"]')||no({restoreFocus:!1}))};document.addEventListener("pointerdown",pC,!0),Oe.push(()=>{document.removeEventListener("pointerdown",pC,!0),document.removeEventListener("pointermove",$f),fa?.(),kl()});let zf=null,fa=null,uC=16,mC=i=>{Fk(Df(i)),ft(),to()},Qk=()=>{let i=v("div","persona-rail-resizer");return i.tabIndex=0,i.setAttribute("role","separator"),i.setAttribute("aria-orientation","vertical"),i.setAttribute("aria-valuemin",String(Wf)),i.setAttribute("aria-valuemax",String(Bf)),i.addEventListener("pointerdown",d=>{let f=pi;if(!f||d.button!==0)return;d.preventDefault(),fa?.();let y=d.clientX,w=f.getBoundingClientRect().width||Ml(),k=pa()==="right"?-1:1,q=w,te=t.ownerDocument;f.style.transition="none";let Q=ce=>{q=Df(w+k*(ce.clientX-y)),f.style.flex=`0 0 ${q}px`,i.setAttribute("aria-valuenow",String(q))},re=()=>{fa=null,te.removeEventListener("pointermove",Q),te.removeEventListener("pointerup",re),te.removeEventListener("pointercancel",re),f.style.removeProperty("transition");try{i.releasePointerCapture(d.pointerId)}catch{}mC(q)};fa=re,te.addEventListener("pointermove",Q),te.addEventListener("pointerup",re),te.addEventListener("pointercancel",re);try{i.setPointerCapture(d.pointerId)}catch{}}),i.addEventListener("keydown",d=>{let f=pa()==="right"?-uC:uC,y=Ml(),w=d.key==="ArrowRight"?y+f:d.key==="ArrowLeft"?y-f:d.key==="Home"?Wf:d.key==="End"?Bf:null;w!==null&&(d.preventDefault(),mC(w))}),i},Xk=(i,d)=>{if(!_k()||El()){fa?.(),zf?.remove();return}let f=zf??Qk();zf=f,f.setAttribute("aria-label",Mt.resizeLabel),f.setAttribute("aria-valuenow",String(Ml())),f.nextElementSibling!==d&&i.insertBefore(f,d)};ft=()=>{Dt?.view.setRailSide(pa());let i=pa()==="right",d=Rr;if(d){let te=Mo?Mo.getBoundingClientRect().bottom-Pe.getBoundingClientRect().top:0;d.style.top=`calc(${Math.max(0,Math.round(te))}px + ${Ud})`,d.style.width=`${Ml()}px`,d.style.left=i?"":Ud,d.style.right=i?Ud:""}let f=pi,y=ca,w=Sl;if(!f||!y||!w)return;f.style.flex=`0 0 ${El()?Ok:Ml()}px`;let k="1px solid var(--persona-divider,#e5e7eb)";f.style.borderRight=i?"":k,f.style.borderLeft=i?k:"";let q=i?w:f;y.firstElementChild!==q&&y.append(q,i?f:w),Xk(y,i?f:w)};let fC=i=>{if(da&&pi){da.replaceWith(i),da=null,ft();return}let d=v("div","persona-history-rail-shell");d.style.cssText="display:flex;flex-direction:row;flex:1 1 auto;min-height:0";let f=v("div","persona-history-rail-conversation");f.style.cssText="display:flex;flex-direction:column;flex:1 1 auto;min-width:0;min-height:0;position:relative";let y=v("div","persona-history-rail-host");y.style.cssText="display:flex;min-height:0;overflow:hidden",Pe.insertBefore(d,$e.parentNode===Pe?$e:pe);for(let w of tC())w?.parentNode===Pe&&f.appendChild(w);d.append(y,f),y.appendChild(i),ca=d,pi=y,Sl=f,ft()},Jk=()=>{if(ca)return;let i=v("div","persona-history-rail-placeholder");i.style.cssText="flex:1 1 auto;min-height:0",da=i,fC(i),to()},gC=()=>{da&&(jd(),to())},Zk=i=>{let d=v("div","persona-history-rail-overlay");d.style.cssText=`position:absolute;bottom:${Ud};display:flex;overflow:hidden;z-index:${Ba-1};border-radius:var(--persona-history-overlay-radius,16px);background:var(--persona-history-overlay-bg,var(--persona-container,#f7f7f8));box-shadow:var(--persona-history-overlay-shadow,0 12px 40px rgba(0,0,0,0.25))`,Pe.style.position="relative",Pe.appendChild(d),d.appendChild(i),document.addEventListener("pointermove",$f),Rr=d,ft(),cC()},jd=()=>{Vd?.(),Rr&&(ui&&(Vf=Date.now()+150),document.removeEventListener("pointermove",$f),Rr.remove(),Rr=null);let i=ca;if(i){fa?.();for(let d of tC())d&&i.contains(d)&&Pe.insertBefore(d,i);i.remove(),ca=null,pi=null,Sl=null,da=null}},hC=i=>{xl=i,i.id=kf,i.style.flex="1 1 auto",i.style.minHeight="0"},Uf=i=>{hC(i),(xt!=="rail"||yn)&&gC(),xt!=="rail"?Dk(i):yn?Zk(i):fC(i)},Kd=()=>{if(Pl(),EC(),!mt||!Dt)return;let i=If();if(i===xt)return;let d=document.activeElement,f=d instanceof HTMLElement&&(Dt.element.contains(d)||ho?.contains(d)===!0)?d:null;jd(),Dt.element.remove(),Dt.view.setHeaderPlacement("inline"),xt=i,Dt.view.setPresentation(i),Dt.view.setCollapsed(El()),Dt.requestRender(),Dt.element.isConnected||Uf(Dt.element),f?.isConnected?f.focus():Gd(),xn(),to(),ps()},yC=(i,d)=>ho?.querySelector(d)??i.querySelector(d),Gd=()=>{let i=Dt?.element??xl;if(!i)return;let d=yC(i,'[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]');if(d){d.focus();return}let f=yC(i,".persona-history-title")??i;f.tabIndex=-1,f.focus()},Ll=async i=>{if(!ar()||mt)return;let d=go;if(!d)return;if(!yn&&ma()&&Of()){Pl();return}Yd();let f=++wl;Bd=i?.returnSurface??"conversation",Mf=i?.invoker??Nn;let y=ma()&&!yn;y&&(qd+=1,Pl(),Jk());let w;try{w=await fb()}catch{Nd(Mt.openHistoryLabel),y&&(qd-=1,f===wl&&(gC(),Pl()));return}if(y&&(qd-=1),f!==wl||mt)return;Wd={scope:Lf()},xt=If(),mt=!0;let k=xt==="panel"&&o.layout?.showHeader!==!1&&$e.style.display!=="none"?"external":"inline",q=o.features?.history?.rowAvatar,te=Ff(),Q=te?{hint:te.hint,aria:te.aria}:null,re={provider:d,context:Wd,targetId:Kv(),presentation:xt,collapsible:$d(),collapsed:El(),railSide:pa(),renderRailHeader:o.features?.history?.rail?.renderHeader,railBrand:Vk(),onToggleCollapse:rC,...Q?{collapseShortcut:Q}:{},headerPlacement:k,showScopeStatus:o.features?.history?.showScopeStatus!==!1,showDelete:o.features?.history?.showDelete!==!1,showDeleteAll:o.features?.history?.showDeleteAll!==!1,...o.features?.history?.listActions?.length?{listActions:o.features.history.listActions}:{},rowAvatar:q===!1?!1:typeof q=="string"?q:o.launcher?.iconUrl,activeConversationId:N.getActiveConversationId(),...o.features?.history?.grouping?{grouping:o.features.history.grouping}:{},...o.features?.history?.copy?{copy:o.features.history.copy}:{},...o.features?.history?.pageSize!==void 0?{pageSize:o.features.history.pageSize}:{},onSelect:ce=>jf(ce,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:ce=>mi(ce),attachTooltip:In,onStartNew:()=>Kf({focusComposer:!0}),onClose:()=>no(),onRequestDeleteConversation:ce=>TC(ce),onRequestClearHistory:()=>sP(),...d.resetDevice?{onRequestResetIdentity:()=>iP()}:{}};Dt=o0({plugins:u,config:o,getPresentation:()=>xt??"panel",getReturnSurface:()=>Bd,close:()=>no(),createView:({slots:ce,renderDom:ye,onModelChange:De,railSections:lt})=>(di=w.createHistoryView({...re,railSections:zk(lt),slots:ce,renderDom:ye,onModelChange:De,onAnnounce:Nd}),di),onElementChanged:(ce,ye)=>{if(!ye?.isConnected)return Uf(ce);hC(ce),ye.replaceWith(ce),Rf()}}),Dt.view.setNewConversationRequired(Dd.recovery==="new_conversation_required"),i?.focus!==!1&&(xt!=="rail"||i?.keyboard===!0)&&Gd(),xn(),to(),ps(),H.emit("history:opened",{presentation:xt,returnSurface:Bd,timestamp:Date.now()})},Yd=()=>{},no=i=>{if(!mt)return;wl+=1;let d=Bd,f=Mf,y=Dt,w=i?.restoreFocus!==!1;mt=!1;let k=!1,q=null,te=()=>{if(!k){if(k=!0,Yd=()=>{},q!==null&&clearTimeout(q),yn=!1,kl(),jd(),y?.dispose(),y?.view.destroy(),y?.element.remove(),Dt===y&&(Dt=null,di=null,xl=null,xt=null,Wd=null,Mf=null),xn(),to(),ps(),w){let re=f??Nn;re?.isConnected?re.focus():ii()}H.emit("history:closed",{returnSurface:d,timestamp:Date.now()})}},Q=y&&y.element===y.view.element?y.view.playExit():null;if(!Q){te();return}Yd=te,q=setTimeout(te,Pk),Q.then(te)},bC=i=>{if(!(i.key!=="Escape"||!mt||!Dt)){if(xt==="rail"){let d=i.target;if(!(d instanceof Node)||!(Dt.element.contains(d)||yn&&Hr?.contains(d)===!0))return}i.preventDefault(),i.stopPropagation(),no()}};Pe.addEventListener("keydown",bC),Oe.push(()=>Pe.removeEventListener("keydown",bC));let Qd=null,vC=!1,Il=()=>{if(!Bn)return;let i=o.layout?.header?.titleSource==="conversation",d=i&&Qd?.trim()||null;Bn.textContent=d??o.launcher?.title??"Chat Assistant";let f=Bn.closest(".persona-combo-btn");if(!f)return;let y=!i||N.getActiveConversationId()!==null;f.setAttribute("data-persona-menu-locked",y?"false":"true"),f.setAttribute("aria-haspopup",y?"true":"false"),y||f.setAttribute("aria-expanded","false"),f.style.cursor=y?"pointer":"default";let w=f.querySelector("svg");w&&(w.style.display=y?"":"none")},eP=i=>{i!==Qd&&(Qd=i,Il())},mi=i=>{vC=i?.starred===!0,eP(i&&i.title.trim()||null),Il()};Il(),Pe.addEventListener("persona:title-menu-builtin",i=>{let d=i.detail?.actionId,f=N.getActiveConversationId();f&&(d==="delete"?TC(f):d==="star"&&N.canUpdateConversations()&&Gf(f,{starred:!vC}).catch(()=>{}))});let Xd=0,tP=250,Jd=null,Zd=()=>{Jd&&clearTimeout(Jd),Jd=null};Oe.push(Zd);let CC=()=>{Zd();let i=ai;i&&(Cl=!0,i.hidden=!1,We.style.display="none",sa())},ep=()=>{Xd+=1,Zd(),ai&&(ai.remove(),ai=null,Cl=!1,We.style.removeProperty("display"),Ao(Qe,!1),sa())},nP=()=>{try{if(window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches)return;We.animate([{opacity:0},{opacity:1}],{duration:150,easing:"ease-out"})}catch{}},qf=(i,d)=>F("div",{className:Gt("persona-conversation-loading-bubble",d&&"persona-conversation-loading-bubble--trailing"),attrs:{"aria-hidden":"true"},style:{width:i}}),wC=()=>F("div",{className:"persona-conversation-loading-body"},qf("58%",!1),qf("72%",!0),qf("44%",!1)),xC=i=>{ai?.remove(),ai=i,i.hidden=!Cl,pe.insertBefore(i,We),Zd(),Cl||(Jd=setTimeout(CC,tP)),Ao(Qe,!0)},oP=()=>{let i={config:o,streaming:!1,location:"conversation-open",defaultRenderer:wC},d=null,f=u.find(y=>y.renderLoadingIndicator);f?.renderLoadingIndicator&&(d=f.renderLoadingIndicator(i)),d===null&&o.loadingIndicator?.render&&(d=o.loadingIndicator.render(i)),xC(F("div",{className:"persona-conversation-loading",attrs:{role:"status","aria-label":Mt.openConversationLoadingLabel}},d??wC()))},rP=i=>{let d=()=>{jf(i,{focusComposer:!0}).catch(()=>{})},f=ar()?()=>{ep(),Ll()}:void 0,y=(te,Q)=>{let re=F("button",{className:"persona-conversation-loading-error-action",attrs:{type:"button"},text:te});return re.addEventListener("click",Q),re},w=()=>F("div",{className:"persona-conversation-loading-error-body"},F("p",{className:"persona-conversation-loading-error-title",text:Mt.openConversationErrorTitle}),F("div",{className:"persona-conversation-loading-error-actions"},y(Mt.openConversationRetryLabel,d),f?y(Mt.openConversationBackLabel,f):null)),k=Object.freeze({conversationId:i,config:o,copy:Object.freeze({title:Mt.openConversationErrorTitle,retryLabel:Mt.openConversationRetryLabel,backLabel:Mt.openConversationBackLabel}),retry:d,...f?{back:f}:{},defaultRenderer:w}),q=null;for(let te of u)if(te.renderHistoryOpenError){try{q=te.renderHistoryOpenError(k)}catch(Q){console.warn("[persona] renderHistoryOpenError threw",Q),q=null}if(q)break}xC(F("div",{className:"persona-conversation-loading-error",attrs:{role:"alert"}},q??w())),CC()};H.on("history:closed",()=>{ai&&Ao(Qe,!0)});let jf=async(i,{focusComposer:d=!1}={})=>{let f=la(),y=!!Dt;Dt?.view.setActiveConversationId(i),ep();let w=Xd;oP(),mt&&(xt==="panel"||yn)&&no({restoreFocus:!1}),Xi=!0;try{await N.openConversation(i,{scope:f})}catch(k){throw w===Xd&&rP(i),k}finally{Xi=!1}w===Xd&&(ep(),mn.clear(),$o(),eo(),rf()||Ad(),nP(),Wr(),y||mi(null),H.emit("history:conversationOpened",{conversationId:i,title:Qd,scope:f,timestamp:Date.now()}),d&&ii())},Kf=async({focusComposer:i=!1}={})=>{ep(),await N.startNewConversation({scope:la()}),mi(null),mn.clear(),$o(),eo(),Ad(),Wr();let d=N.getActiveConversationId();Dt?.view.setActiveConversationId(d),H.emit("history:conversationStarted",{conversationId:d,timestamp:Date.now()}),mt&&(xt==="panel"||yn)&&no({restoreFocus:!1}),i&&ii()},Gf=async(i,d)=>{let f=await N.updateConversation(i,{...d,...d.title!==void 0?{title:d.title.trim()}:{}});return Dt?.view.applyConversationSummary(f),!Dt&&i===N.getActiveConversationId()&&mi(f),f},SC=async i=>{let d=la(),f=N.getActiveConversationId()===i;await N.deleteConversation(i,{scope:d}),Dt?.view.removeConversationSummary(i),f&&(mi(null),mn.clear(),$o(),eo(),Wr()),H.emit("history:conversationDeleted",{conversationId:i,scope:d,wasActive:f,timestamp:Date.now()})},AC=async i=>{let d=i?.scope??la(),f=i?.allTargets?null:i?.targetId??Kv(),y=await N.clearConversationHistory({...f?{targetId:f}:{},scope:d});return mi(null),mn.clear(),$o(),eo(),Wr(),H.emit("history:cleared",{deleted:y.deleted,scope:d,targetId:f,timestamp:Date.now()}),y},MC=async()=>{if(!go?.resetDevice)throw new Error("[Persona] resetHistoryIdentity() requires a history provider that can reset this device");let i=!1;try{i=(await N.resetHistoryDevice()).remoteRevocationConfirmed}finally{mi(null),N.clearArtifacts(),mn.clear(),Cf=null,o.clearStoredSessionId?.(),o.clearStoredConversationId?.(),L={},se.syncFromMetadata(),x?.clear&&wd(()=>x.clear(),"[AgentWidget] Failed to clear storage adapter:"),$o(),eo(),Wr(),no({restoreFocus:!1}),ii(),Ae||sn?.launcher.element.focus()}return Nd(i?Mt.identityResetNotice:Mt.identityResetUnconfirmedNotice),H.emit("history:identityReset",{remoteRevocationConfirmed:i,timestamp:Date.now()}),{remoteRevocationConfirmed:i}},Yf=()=>nr?Se:Pe,TC=async i=>await Mm({host:Yf(),title:Mt.deleteConversationConfirmTitle,description:Mt.deleteConversationConfirm,confirmLabel:Mt.deleteConversationConfirmLabel,cancelLabel:Mt.confirmCancelLabel})?(await SC(i),"deleted"):"cancelled",sP=async()=>{let i=la()==="verified-user";return await Mm({host:Yf(),title:Mt.clearHistoryConfirmTitle,description:i?Mt.clearHistoryVerifiedConfirm:Mt.clearHistoryConfirm,confirmLabel:Mt.clearHistoryConfirmLabel,cancelLabel:Mt.confirmCancelLabel})?(await AC(),"cleared"):"cancelled"},iP=async()=>{if(!await Mm({host:Yf(),title:Mt.resetIdentityConfirmTitle,description:Mt.resetIdentityConfirm,confirmLabel:Mt.resetIdentityConfirmLabel,cancelLabel:Mt.confirmCancelLabel}))return{outcome:"cancelled"};let{remoteRevocationConfirmed:d}=await MC();return{outcome:"reset",remoteRevocationConfirmed:d}},To=v("button","persona-history-earlier");To.type="button",To.textContent=Mt.showEarlierMessagesLabel,To.setAttribute("data-persona-history-earlier",""),Object.assign(To.style,{alignSelf:"center",minHeight:"44px",padding:"0 16px",borderRadius:"999px",border:"1px solid var(--persona-border, rgba(0,0,0,0.12))",background:"transparent",color:"inherit",font:"inherit",cursor:"pointer",flexShrink:"0"});let Wr=()=>{if(!(ar()&&!!Dd.nextMessageCursor&&!!N.getActiveConversationId())){To.remove();return}To.textContent=Mt.showEarlierMessagesLabel,To.parentNode!==pe&&pe.insertBefore(To,pe.firstChild)};To.addEventListener("click",()=>{let i=N.getActiveConversationId(),d=Dd.nextMessageCursor;if(!i||!d||To.disabled)return;To.disabled=!0;let f=pe.scrollHeight,y=pe.scrollTop;N.loadOlderMessages(i,d,{scope:la()}).then(()=>{pe.scrollTop=y+(pe.scrollHeight-f),to()}).catch(()=>{}).finally(()=>{To.disabled=!1,Wr()})});let aP=()=>{let i=ki({ariaLabel:Mt.openHistoryLabel,iconName:"history",wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center",extraClassName:"persona-history-toggle",attrs:{"data-persona-history-toggle":""}});return i.button.addEventListener("click",d=>{if(!(!ar()||jv())){if(mt){no();return}Ll({invoker:i.button,keyboard:d.detail===0})}}),i},EC=()=>{if(!ar()){ir?.remove(),Nn=null,ir=null;return}if(ir&&!ir.isConnected&&(Nn=null,ir=null),!Nn&&$e){let y=aP();Nn=y.button,ir=y.wrapper;let w=ot.clearChatButtonWrapper||ot.closeButtonWrapper;w?.parentNode&&$e.contains(w)?w.parentNode.insertBefore(ir,w):$e.appendChild(ir)}if(!Nn||!ir)return;let i=ma()||mt&&xt==="rail";if(ir.style.display=i?"none":"",i){document.activeElement===Nn&&Gd();return}let d=jv();Nn.disabled=d,Nn.setAttribute("aria-disabled",d?"true":"false");let f=d?Mt.openHistoryBusyLabel:Mt.openHistoryLabel;Nn.setAttribute("aria-label",f),(o.features?.history?.presentation??"panel")==="panel"?(Nn.removeAttribute("aria-expanded"),Nn.removeAttribute("aria-controls")):(Nn.setAttribute("aria-expanded",mt?"true":"false"),Nn.setAttribute("aria-controls",kf))},tp=!1,lP=()=>{let i=ot.clearChatButton;if(i){if(ar()){tp||(Ef=i.getAttribute("aria-label")??"",tp=!0),i.setAttribute("aria-label",Mt.newConversationLabel),i.removeAttribute("title");return}tp&&(tp=!1,Ef&&i.setAttribute("aria-label",Ef))}},ps=()=>{Mt=rb(o.features?.history?.copy),EC(),Pl(),lP(),Wr()};pn=ps,_t=i=>{Dd=i,Dt?.view.setNewConversationRequired(i.recovery==="new_conversation_required"),vl(i.sendBlocked||uo),Wr()},Vt=i=>{(i.code==="history_continuity_reset"||i.code==="conversation_deleted_recovered")&&(mn.clear(),$o(),eo()),Nd(i.message),Dt?.view.refresh()},Xv(),ps(),Oe.push(()=>{Od?.(),_d?.(),wl+=1,Yd(),Dt?.dispose(),Dt?.view.destroy(),Dt=null}),o.clientToken&&(o.features?.history?.enabled===!0||o.sessionInit==="mount")&&N.initClientSession().then(()=>{if(ar())return N.reconcileBootConversation({scope:Lf()})}).then(()=>{Wr()}).catch(i=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",i)});let Qf=()=>N.warmClientSession(),kC=i=>{let d=o.sessionInit??"input",f=Et?.input??we,y=i.target;f&&(i.type==="input"?(d==="input"||d==="focus")&&y===f&&i.inputType&&f.value.trim():d==="focus"&&(i.type==="keyup"?y===f&&i.key==="Tab":(Et?.form??Tn)?.contains(y)))&&Qf()},PC=["input","pointerdown","keyup"];PC.forEach(i=>t.addEventListener(i,kC));let LC,Xf,IC=()=>{let i=Xf;Xf=void 0;try{typeof i=="function"&&i()}catch{}},HC=()=>{let i=o.clientToken&&typeof o.sessionInit=="function"?o.sessionInit:void 0;if(i!==LC){IC(),LC=i;try{Xf=i?.({warm:Qf,mount:t})}catch{}}};HC(),Oe.push(()=>{PC.forEach(i=>t.removeEventListener(i,kC)),IC()}),(ie||o.onSSEEvent)&&N.setSSEEventCallback((i,d)=>{o.onSSEEvent?.(i,d),qe(i,d)});let RC=()=>{let i=o.resume??(P?Lr.getStoredResumableHandle?.():null);i&&typeof o.reconnectStream=="function"&&N.resumeFromHandle(i)};G?G.then(i=>{if(i){if(i.metadata&&(L=vb(i.metadata),se.syncFromMetadata()),i.messages?.length){Xi=!0;try{N.hydrateMessages(i.messages)}finally{Xi=!1}kd()}i.artifacts?.length&&N.hydrateArtifacts(i.artifacts,i.selectedArtifactId??null),Av(i.draft)}}).catch(i=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",i)}).finally(()=>{uf=!0,V(),RC()}):(Av(ee),RC());let cP=()=>{!xe()||Ae||!(o.launcher?.composerBar?.expandOnSubmit??!0)||qt(!0,"auto")},dP=(i,d)=>i?d?{refs:[...i.refs,...d.refs],finalize:async()=>{let[f,y]=await Promise.allSettled([i.finalize(),d.finalize()]),w=[];return f.status==="fulfilled"?w.push(f.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",f.reason),y.status==="fulfilled"?w.push(y.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",y.reason),AD(w)}}:i:d,Jf=()=>{let d=we.getInlineMessageFields?.();return d&&d.contentSegments.some(y=>y.kind==="mention")?d.contentSegments:void 0},Br=!1,fi=null,np=()=>{we.value="",we.style.height="auto",Zo(),Rl()},Zf="data-persona-composer-notice",ga=null;function pP(i){nd(i),!(xe()||!pt)&&(pt.hasAttribute(Za)||(pt.setAttribute(Zf,""),pt.setAttribute("role","status"),pt.setAttribute("aria-live","polite"),pt.textContent=i,xi(pt,o.statusIndicator??{},"idle"),ga&&clearTimeout(ga),ga=setTimeout(()=>{if(ga=null,!!pt?.hasAttribute(Zf)&&(pt.removeAttribute(Zf),pt.removeAttribute("role"),pt.removeAttribute("aria-live"),h)){let d=N.getStatus();Qo(pt,_s(d),o.statusIndicator??{},d)}},4e3)))}function uP(){let i=ze.getState().pendingSubmission;i&&(Ui(void 0),we&&(we.value=i.text,we.dispatchEvent(new Event("input",{bubbles:!0})),Zo()),i.options.selectedModelId&&(ze.setSelectedModelId(i.options.selectedModelId),Zr?.repaint()),i.options.activeModeIds?.length&&id(i.options.activeModeIds),i.options.quote&&er(i.options.quote),we?.focus())}let mP=i=>{typeof console<"u"&&console.error("[AgentWidget] composer.onBeforeSend failed; the draft was preserved:",i)},WC=(i={})=>{let d=(i.overrideText??we?.value??"").trim();return i.resolveInlineCommand&&d?(un?.takeInlineCommand(d)??Promise.resolve(null)).then(f=>BC(i,d,f)):BC(i,d,null)},BC=(i,d,f)=>{if(f?.kind==="action"){np(),un?.clear(),zs();return}let y=f?.kind==="server"?f.mentions:null,w=f?.kind==="prompt"?f.sendText:d,k=i.pending?.contentParts,q=(Lt?.hasAttachments()??!1)||(k?.length??0)>0;if(!dA({text:w,hasAttachments:q,attachmentsReady:Lt?.isReady()??!0,hasMentions:un?.hasMentions()??!1,hasServerMentions:!!y,inputDisabled:sr(),sendDisabled:si()}))return;let te=N.isStreaming()?Dm():"block";if(te==="defer-one"&&!i.pending){if(ze.getState().pendingSubmission){pP("One message is already queued. Edit or remove it first.");return}fP({intent:i,sendText:w,serverMentions:y});return}let Q={text:w,mentionRefs:[...un?.getMentionRefs()??[],...y?.refs??[]],contentSegments:f?.kind==="prompt"?void 0:Jf(),options:{...ze.getState().selectedModelId&&{selectedModelId:ze.getState().selectedModelId},...ze.getState().activeModeIds.length>0&&{activeModeIds:[...ze.getState().activeModeIds]},...ze.getState().quote&&{quote:{...ze.getState().quote}}},viaVoice:i.viaVoice};i.pending&&(Q.options={...i.pending.options},Q.contentSegments=i.pending.contentSegments,Q.mentionRefs=[...i.pending.mentionRefs],Q.viaVoice=i.pending.viaVoice);let re=()=>{if(k?.length)return[...k];if(!Lt?.hasAttachments())return;let kt=[...Lt.getContentParts()];return Q.text&&kt.push(fr(Q.text)),kt};Q.contentParts=re();let ce=()=>{Zs(),cP();let kt=un?.collectForSubmit()??null,oo=dP(kt,y),Jt=re();i.consumeDraft!==!1&&np();let rn={selectedModelId:Q.options.selectedModelId,activeModeIds:Q.options.activeModeIds},Vn=te==="interrupt";Vn&&N.cancel(),N.sendMessage(Q.text,{contentParts:Jt,mentions:oo??void 0,contentSegments:Q.contentSegments,viaVoice:Q.viaVoice,composerOptions:rn,...Q.options.quote&&{quote:Q.options.quote},...Vn&&{interrupt:!0}}),Lt?.hasAttachments()&&Lt.clearAttachments(),kt&&un?.clear(),zs();let ln=ze.getState().activeModeIds,$t=QS(ln,o.composer?.modes);$t.length!==ln.length&&id($t),ze.getState().quote&&er(void 0),Sd(),Vm.release(),_o()},ye=o.composer?.onBeforeSend;if(!ye){ce();return}let De=new AbortController;fi=De;let lt=kt=>{if(fi=null,kt.status==="error"){mP(kt.error);return}kt.status==="proceed"&&ce()},It=pA(ye,Q,De.signal);if(!(It instanceof Promise)){lt(It);return}return ze.setPreparing(!0),It.then(lt).finally(()=>ze.setPreparing(!1))};function fP(i){let d=ze.getState(),f=Lt?.hasAttachments()??!1,y=f?[...Lt.getContentParts()]:[];f&&i.sendText&&y.push(fr(i.sendText));let w=Sh({text:i.sendText,contentParts:y.length?y:void 0,mentionRefs:[...un?.getMentionRefs()??[],...i.serverMentions?.refs??[]],contentSegments:Jf(),options:{...d.selectedModelId&&{selectedModelId:d.selectedModelId},...d.activeModeIds.length>0&&{activeModeIds:[...d.activeModeIds]},...d.quote&&{quote:{...d.quote}}},viaVoice:i.intent.viaVoice});Ui(w),i.intent.consumeDraft!==!1&&np(),f&&Lt.clearAttachments(),un?.clear(),zs(),d.quote&&er(void 0),Sd(),Vm.release(),_o(),nd("Message queued. It sends when the response finishes.")}function gP(){let i=ze.getState().pendingSubmission;i&&(Ui(void 0),rp(i.text,{consumeDraft:!1,pending:i}))}function hP(i){if(o.messageActions?.showEdit!==!0)return;let d=N.getMessages().find(f=>f.id===i);!d||!Xg(d)||Js!==i&&(Zs(),Js=i,os=tA({messageId:i,initialText:d.content,onSave:f=>yP(i,f),onCancel:()=>Zs()}),mn.delete(i),xo(We,N.getMessages(),j),os.focus())}function yP(i,d){let f=os;if(Js=null,os=null,f?.destroy(),mn.delete(i),!N.resubmitFrom(i,{reason:"edit",replacement:{text:d,mentionRefs:[],options:{}}})){xo(We,N.getMessages(),j);return}to()}function bP(i){if(N.isStreaming())return;let d=Qg(N.getMessages(),i);d&&(Zs(),N.resubmitFrom(d,{reason:"retry"})&&to())}ad={regenerate:bP,edit:hP,quote:i=>{let f=N.getMessages().find(y=>y.id===i)?.content?.trim();f&&(er({text:f,messageId:i}),we?.focus())}};let Hl=async i=>{if(!Br){Br=!0;try{await WC({resolveInlineCommand:!0,...i})}finally{Br=!1}}};function op(i){si()||(np(),rp(i,{consumeDraft:!1}))}let rp=(i,d)=>{if(Br)return;Br=!0;let f=()=>{Br=!1};try{let y=WC({...d,overrideText:i});y instanceof Promise?y.finally(f):f()}catch(y){throw f(),y}},vP=i=>{if(i.preventDefault(),N.isStreaming()){N.cancel(),Ht?.reset(),He?.update();return}Br||Hl()},CP=()=>o.features?.composerHistory!==!1,eg={...Uh},tg=!1,Rl=()=>{eg={...Uh}},wP=()=>N.getMessages().filter(i=>i.role==="user").map(i=>i.content??"").filter(i=>i.length>0),xP=i=>{if(!we)return;tg=!0,we.value=i,we.dispatchEvent(new Event("input",{bubbles:!0})),tg=!1;let d=we.value.length;we.setSelectionRange(d,d)},SP=i=>{tg||(i.isComposing||un?.handleInput(i.inputType??void 0),Rl())},AP=()=>({submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:rc(we)}),MP=i=>{if(we&&!sr()&&!(!i.isComposing&&un?.handleKeydown(i))){if(CP()&&(i.key==="ArrowUp"||i.key==="ArrowDown")&&!i.shiftKey&&!i.metaKey&&!i.ctrlKey&&!i.altKey&&!i.isComposing){let d=we.selectionStart===0&&we.selectionEnd===0,f=iM({direction:i.key==="ArrowUp"?"up":"down",history:wP(),currentValue:we.value,atStart:d,state:eg});if(eg=f.state,f.handled){i.preventDefault(),f.value!==void 0&&xP(f.value);return}}if(IS(i,AP())){if(N.isStreaming()){if(i.preventDefault(),Dm()==="block"||Br||si())return;Rl(),Hl();return}if(Br){i.preventDefault();return}if(si()){i.preventDefault();return}Rl(),i.preventDefault(),Ve.click()}}},DC=i=>{if(!(i.key!=="Escape"||i.isComposing)&&i.composedPath().includes(Pe)){if(fi){fi.abort(),fi=null,i.preventDefault(),i.stopImmediatePropagation();return}N.isStreaming()&&(N.cancel(),Ht?.reset(),He?.update(),Rl(),i.preventDefault(),i.stopImmediatePropagation())}},TP=async i=>{if(o.attachments?.enabled!==!0||!Lt||sr())return;let d=CD(i.clipboardData);d.length!==0&&(i.preventDefault(),await Lt.handleFiles(d))},Eo=null,lr=!1,ha=null,tn=null,ng=()=>o.voiceRecognition?.completionBehavior==="review";function gi(i){he?.setAttribute("data-state",i),i==="recording"?kP():ig()}let OC="--persona-voice-level",og=.5,ya=null,rg=-1,sp=0,_C=()=>{let i=[],d=co??he?.parentElement??null;return d&&i.push(d),Qe&&i.push(Qe),i},sg=i=>{let d=Math.round(Math.max(0,Math.min(1,i))*100)/100;if(d!==rg){rg=d;for(let f of _C())f.style.setProperty(OC,String(d))}},EP=()=>{rg=-1,sp=0;for(let i of _C())i.style.removeProperty(OC)};function kP(){if(ya!==null)return;if(typeof requestAnimationFrame!="function"){sg(h?N.getVoiceLevel()??og:og);return}let i=()=>{ya=requestAnimationFrame(i);let d=h?N.getVoiceLevel():null;if(d===null){sg(og);return}sp+=(d-sp)*.3,sg(sp)};ya=requestAnimationFrame(i)}function ig(){ya!==null&&(cancelAnimationFrame(ya),ya=null),EP()}let NC=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,ip=(i="user")=>{if(lr||N.isStreaming())return;let d=NC();if(!d)return;Eo=new d;let f=o.voiceRecognition??{},y=f.pauseDuration??2e3;Eo.continuous=f.provider?.browser?.continuous??!0,Eo.interimResults=!0,Eo.lang=f.provider?.browser?.language??"en-US";let w=we.value;Eo.onresult=k=>{let q="",te="";for(let re=0;re<k.results.length;re++){let ce=k.results[re],ye=ce[0].transcript;ce.isFinal?q+=ye+" ":te=ye}let Q=w+q+te;we.value=Q,Zo(),ha&&clearTimeout(ha),(q||te)&&(ha=window.setTimeout(()=>{if(we.value.trim()&&Eo&&lr){if(us(),ng())return;Hl({viaVoice:!0})}},y))},Eo.onerror=k=>{k.error!=="no-speech"&&us()},Eo.onend=()=>{if(lr){let k=we.value.trim();!ng()&&k&&k!==w.trim()&&Hl({viaVoice:!0}),us()}};try{if(Eo.start(),lr=!0,wt.active=!0,i!=="system"&&(wt.manuallyDeactivated=!1),kr(i),Vo(),_o(),he){let k=o.voiceRecognition??{};tn={backgroundColor:he.style.backgroundColor,color:he.style.color,borderColor:he.style.borderColor,iconName:k.iconName??"mic",iconSize:parseFloat(k.iconSize??"")||qn};let q=k.recordingBackgroundColor,te=k.recordingIconColor,Q=k.recordingBorderColor;if(he.classList.add("persona-voice-recording"),gi("recording"),he.style.backgroundColor=q??"var(--persona-voice-recording-bg, #ef4444)",he.style.color=te??"var(--persona-voice-recording-indicator, #ffffff)",te){let re=he.querySelector("svg");re&&re.setAttribute("stroke",te)}Q&&(he.style.borderColor=Q),he.setAttribute("aria-label","Stop voice recognition")}}catch{us("system")}},us=(i="user")=>{if(lr){if(lr=!1,ha&&(clearTimeout(ha),ha=null),Eo){try{Eo.stop()}catch{}Eo=null}if(wt.active=!1,kr(i),Vo(),_o(),he){if(he.classList.remove("persona-voice-recording"),gi("idle"),tn){he.style.backgroundColor=tn.backgroundColor,he.style.color=tn.color,he.style.borderColor=tn.borderColor;let d=he.querySelector("svg");d&&d.setAttribute("stroke",tn.color||"currentColor"),tn=null}he.setAttribute("aria-label","Start voice recognition")}}},ag=()=>{if(!he||tn)return;let i=o.voiceRecognition??{};tn={backgroundColor:he.style.backgroundColor,color:he.style.color,borderColor:he.style.borderColor,iconName:i.iconName??"mic",iconSize:parseFloat(i.iconSize??"")||qn}},lg=(i,d)=>{if(!he)return;let f=he.querySelector("svg");f&&f.remove();let y=tn?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??"")||qn),w=ke(i,y,d,1.5);w&&he.appendChild(w)},ap=()=>{he&&he.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},ba=()=>{if(!he)return;ag();let i=o.voiceRecognition??{},d=i.recordingBackgroundColor,f=i.recordingIconColor,y=i.recordingBorderColor;if(ap(),he.classList.add("persona-voice-recording"),gi("recording"),he.style.backgroundColor=d??"var(--persona-voice-recording-bg, #ef4444)",he.style.color=f??"var(--persona-voice-recording-indicator, #ffffff)",f){let w=he.querySelector("svg");w&&w.setAttribute("stroke",f)}y&&(he.style.borderColor=y),he.setAttribute("aria-label","Stop voice recognition")},PP=()=>{if(!he)return;ag();let i=o.voiceRecognition??{},d=N.getVoiceInterruptionMode(),f=i.processingIconName??"loader",y=i.processingIconColor??tn?.color??"",w=i.processingBackgroundColor??tn?.backgroundColor??"",k=i.processingBorderColor??tn?.borderColor??"";ap(),he.classList.add("persona-voice-processing"),gi("processing"),he.style.backgroundColor=w,he.style.borderColor=k;let q=y||"currentColor";he.style.color=q,lg(f,q),he.setAttribute("aria-label","Processing voice input"),d==="none"&&(he.style.cursor="default")},LP=()=>{if(!he)return;ag();let i=o.voiceRecognition??{},d=N.getVoiceInterruptionMode(),f=d==="cancel"?"square":d==="barge-in"?"mic":"volume-2",y=i.speakingIconName??f,w=i.speakingIconColor??(d==="barge-in"?i.recordingIconColor??tn?.color??"":tn?.color??""),k=i.speakingBackgroundColor??(d==="barge-in"?i.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":tn?.backgroundColor??""),q=i.speakingBorderColor??(d==="barge-in"?i.recordingBorderColor??"":tn?.borderColor??"");ap(),he.classList.add("persona-voice-speaking"),gi("speaking"),he.style.backgroundColor=k,he.style.borderColor=q;let te=w||"currentColor";he.style.color=te,lg(y,te);let Q=d==="cancel"?"Stop playback and re-record":d==="barge-in"?"Speak to interrupt":"Agent is speaking";he.setAttribute("aria-label",Q),d==="none"&&(he.style.cursor="default"),d==="barge-in"&&he.classList.add("persona-voice-recording")},Dr=()=>{he&&(ap(),gi("idle"),tn&&(he.style.backgroundColor=tn.backgroundColor??"",he.style.color=tn.color??"",he.style.borderColor=tn.borderColor??"",lg(tn.iconName,tn.color||"currentColor"),tn=null),he.style.cursor="",he.setAttribute("aria-label","Start voice recognition"))},cg=()=>{if(!sr()){if(Un(o.voiceRecognition?.provider)){let i=N.getVoiceStatus(),d=N.getVoiceInterruptionMode();if(d==="none"&&(i==="processing"||i==="speaking"))return;if(d==="cancel"&&(i==="processing"||i==="speaking")){N.stopVoicePlayback();return}if(N.isBargeInActive()){N.stopVoicePlayback(),N.deactivateBargeIn().then(()=>{wt.active=!1,wt.manuallyDeactivated=!0,Vo(),kr("user"),Dr()});return}N.toggleVoice().then(()=>{wt.active=N.isVoiceActive(),wt.manuallyDeactivated=!N.isVoiceActive(),Vo(),kr("user"),N.isVoiceActive()?ba():Dr()});return}if(lr){let i=we.value.trim();wt.manuallyDeactivated=!0,Vo(),us("user"),i&&!ng()&&Hl()}else wt.manuallyDeactivated=!1,Vo(),ip("user")}};Om=cg;let FC=()=>N.prewarmVoice(),VC=()=>{let i=o.voiceRecognition;return i?.enabled!==!0?!1:i.prewarm??(o.clientToken?"hover":!1)},$C=i=>{VC()==="hover"&&he?.contains(i.target)&&FC()},zC=["pointerover","pointerdown","focusin"];zC.forEach(i=>t.addEventListener(i,$C));let UC,qC=null,dg,jC=()=>{let i=dg;dg=void 0;try{typeof i=="function"&&i()}catch{}},pg=()=>{let i=VC(),d=typeof i=="function"&&he?i:void 0,f=d?he:null;if(!(d===UC&&f===qC)&&(jC(),UC=d,qC=f,!(!d||!f)))try{dg=d({warm:FC,micButton:f,mount:t})}catch{}};pg(),Oe.push(()=>{zC.forEach(i=>t.removeEventListener(i,$C)),jC()}),he&&Oe.push(()=>{Un(o.voiceRecognition?.provider)?(N.isVoiceActive()&&N.toggleVoice(),Dr()):us("system")});let IP=H.on("assistant:complete",()=>{ze.getState().pendingSubmission&&setTimeout(()=>{N.isStreaming()||gP()},0)});Oe.push(IP);let HP=H.on("assistant:complete",()=>{wv&&(wt.active||wt.manuallyDeactivated||wv==="assistant"&&!wt.lastUserMessageWasVoice||setTimeout(()=>{!wt.active&&!wt.manuallyDeactivated&&(Un(o.voiceRecognition?.provider)?N.toggleVoice().then(()=>{wt.active=N.isVoiceActive(),kr("auto"),N.isVoiceActive()&&ba()}):ip("auto"))},600))});Oe.push(HP);let RP=H.on("action:resubmit",()=>{setTimeout(()=>{N&&!N.isStreaming()&&N.continueConversation()},100)});Oe.push(RP);let KC=()=>{qt(!Ae,"user")},sn=null,Fn=null;if(_&&!xe()){let{instance:i,element:d}=yy({config:o,plugins:u,onToggle:KC});sn=i,i||(Fn=d)}sn?t.appendChild(sn.element):Fn&&t.appendChild(Fn),bl(),Qs(),Id(),yf(),vl(N.isStreaming()),rf()||(po()==="follow"?as(!0):Ad()),J0(),Re&&(!_||xe()?setTimeout(()=>ii(),0):Ae&&setTimeout(()=>ii(),200));let ms=null,GC=()=>{ms&&(ms.disconnect(),ms.observe(Qe),ms.observe(Pe),ms.observe(gn))},YC=sl(),Wl=()=>{if(xe()){$s(),bl();return}let i=nn(o),d=o.launcher?.sidebarMode??!1,f=t.ownerDocument.defaultView??window,y=o.launcher?.mobileFullscreen??!0,w=o.launcher?.mobileBreakpoint??640,k=f.innerWidth<=w,q=y&&k&&_;try{if(q){Us(),cl=gd();return}let te=!1;bt&&(bt=!1,Us(),te=!0);let Q=gd();if(!te&&Q!==cl&&(Us(),te=!0),cl=Q,te&&pd(),!_&&!i){Se.style.height="",Se.style.width="";return}if(!d&&!i){let re=Hi(o);Se.style.width=re.width,Se.style.maxWidth=re.maxWidth}fd(),sv()}finally{$s(),sd();let te=sl();if(te!==YC&&(YC=te,sa(),Qs()),bl(),Ae&&_){let re=(t.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),ce=o.launcher?.sidebarMode??!1,ye=o.launcher?.mobileFullscreen??!0,De=nn(o)&&ye&&re,lt=ce||ye&&re&&_||De;if(lt&&!rr){let It=t.getRootNode(),kt=It instanceof ShadowRoot?It.host:t.closest(".persona-host");kt&&!or&&(or=Jh(kt,o.launcher?.zIndex??On)),rr=Zh(t.ownerDocument)}else lt||(or?.(),or=null,rr?.(),rr=null)}}};Wl();let lp=t.ownerDocument.defaultView??window;if(lp.addEventListener("resize",Wl),Oe.push(()=>lp.removeEventListener("resize",Wl)),typeof ResizeObserver<"u"){ms=new ResizeObserver(()=>{sd()}),GC(),Oe.push(()=>{ms?.disconnect(),ms=null});let i=new ResizeObserver(()=>{Kd()});i.observe(Pe),Oe.push(()=>i.disconnect())}lp.addEventListener("resize",Kd),Oe.push(()=>lp.removeEventListener("resize",Kd)),fo=pe.scrollTop;let QC=br(pe),XC=()=>{rv();let i=pe.scrollTop,d=br(pe),f=d<QC;if(QC=d,!Jr()){fo=i,xn();return}let{action:y,nextLastScrollTop:w}=zu({following:mo.isFollowing(),currentScrollTop:i,lastScrollTop:fo,nearBottom:jr(pe,Tr),userScrollThreshold:G0,isAutoScrolling:Zn||yd||f,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(fo=w,y==="resume"){Md()||eo();return}y==="pause"&&na()};if(pe.addEventListener("scroll",XC,{passive:!0}),Oe.push(()=>pe.removeEventListener("scroll",XC)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{sk(),Wg(We)});i.observe(We),i.observe(pe),Oe.push(()=>i.disconnect())}let JC=()=>{Jr()&&mo.isFollowing()&&Md()&&na()},ZC=pe.ownerDocument;ZC.addEventListener("selectionchange",JC),Oe.push(()=>{ZC.removeEventListener("selectionchange",JC)});let WP=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),ew=i=>{WP.has(i.key)&&(is(),Eb()&&Jr()&&mo.isFollowing()&&na())},tw=i=>{i.target?.closest("a, button, [tabindex], input, textarea, select")&&(is(),Eb()&&Jr()&&mo.isFollowing()&&na())};pe.addEventListener("keydown",ew),pe.addEventListener("focusin",tw),Oe.push(()=>{pe.removeEventListener("keydown",ew),pe.removeEventListener("focusin",tw)});let nw=i=>{if(i.deltaY!==0&&is(),!Jr())return;let d=Uu({following:mo.isFollowing(),deltaY:i.deltaY,nearBottom:jr(pe,Tr),resumeWhenNearBottom:!0});d==="pause"?na():d==="resume"&&!Md()&&eo()};pe.addEventListener("wheel",nw,{passive:!0}),pe.addEventListener("touchmove",is,{passive:!0}),pe.addEventListener("pointerdown",is,{passive:!0}),Oe.push(()=>{pe.removeEventListener("touchmove",is),pe.removeEventListener("pointerdown",is)}),Oe.push(()=>pe.removeEventListener("wheel",nw)),hn.addEventListener("click",()=>{$o(),pe.scrollTop=pe.scrollHeight,fo=pe.scrollTop,eo(),as(!0),xn()}),Oe.push(()=>hn.remove()),Oe.push(()=>{Tv(),$o()});let ow=()=>{Ce&&(Gs&&(Ce.removeEventListener("click",Gs),Gs=null),Ne()?(Ce.style.display="",Gs=()=>{qt(!1,"user")},Ce.addEventListener("click",Gs)):Ce.style.display="none")};ow(),(()=>{let{clearChatButton:i}=ot;i&&i.addEventListener("click",()=>{if(ar()){Kf({focusComposer:!0}).catch(f=>{o.debug&&console.warn("[AgentWidget] New conversation failed:",f)});return}N.clearMessages(),o.layout?.topFade&&(pe.scrollTop=0),pe.removeAttribute("data-persona-top-fade"),mn.clear(),eo(),La(ot.composerOverlay);try{localStorage.removeItem(Ja),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ja}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Ja)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(f){console.error("[AgentWidget] Failed to clear custom localStorage:",f)}let d=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(d),x?.clear&&wd(()=>x.clear(),"[AgentWidget] Failed to clear storage adapter:"),L={},se.syncFromMetadata(),Lt?.clearAttachments(),Sd(),Ui(void 0),er(void 0),Zs(),ct?.clear(),Ht?.reset(),He?.update()})})();let rw=[["keydown",MP],["input",SP],["input",Zo],["input",zs],["keyup",zs],["paste",TP],["focus",O0]],sw=i=>{if(i)for(let[d,f]of rw)Et?.addListener(i,d,f)},BP=i=>{if(i)for(let[d,f]of rw)Et?.removeListener(i,d,f)},iw=()=>{Et&&(Et.addListener(Et.form,"submit",vP),Et.addListener(Et.footer,"click",zs),sw(we),he&&Et.addListener(he,"click",cg),pg())};iw();let aw=()=>{un?.onComposerSwap((i,d)=>{BP(d),we=i,Et&&(Et.input=i),sw(i),Nm(),df(),Zo()})};aw();let ug=!1;function lw(){if(!ug){ug=!0;try{let i=we?.value??"",d=Qe.ownerDocument??document,f=we?d.activeElement===we:!1;ig(),Et?.destroy(),Et=null,un?.destroy(),un=null;let y=null,w=()=>(y=xe()?Ju({config:o}):Ic({config:o}),y.footer),k=Ob(w)??w();Cn.replaceComposer(k),Qe=Cn.composer.footer;let q=y!==null&&k===y.footer;ji=!q,Tb=q?y.setSendButtonMode:()=>{},Db(Qe),Nb(Qe),Fb(),Vb(),$b(),aw(),zb(),Fm(),Ub(),iw();let te=Ks.indexOf(Mr);if(Mr.destroy(),Mr=kc(lo),te>=0&&(Ks[te]=Mr),we&&(we.value=i),Zo(),zs(),Id(),Qs(),vl(N.isStreaming()),o.statusIndicator?.mode==="transient"&&!xe()){let Q=N.getStatus();Qo(pt,_s(Q),o.statusIndicator,Q)}wt.active&&gi("recording"),Us(),GC(),$s(),_o(),Pd(),f&&we?.focus()}finally{ug=!1}}}let Bl=t.ownerDocument??document;Bl.addEventListener("keydown",DC,!0);let cw=()=>{ef()},dw=()=>{Bl.visibilityState==="hidden"&&ef()};typeof window<"u"&&(window.addEventListener("pagehide",cw),Bl.addEventListener("visibilitychange",dw),Oe.push(()=>{window.removeEventListener("pagehide",cw),Bl.removeEventListener("visibilitychange",dw)}));let pw="persona-attachment-drop-active",Dl=0,mg=()=>{Dl=0,Pe.classList.remove(pw)},va=()=>o.attachments?.enabled===!0&&Lt!==null&&!sr(),uw=i=>{!Tm(i.dataTransfer)||!va()||(Dl++,Dl===1&&Pe.classList.add(pw))},mw=i=>{!Tm(i.dataTransfer)||!va()||(Dl--,Dl<=0&&mg())},fw=i=>{!Tm(i.dataTransfer)||!va()||(i.preventDefault(),i.dataTransfer.dropEffect="copy")},gw=i=>{if(!Tm(i.dataTransfer)||!va())return;i.preventDefault(),i.stopPropagation(),mg();let d=Array.from(i.dataTransfer.files??[]);d.length!==0&&Lt.handleFiles(d)},fs=!0;Pe.addEventListener("dragenter",uw,fs),Pe.addEventListener("dragleave",mw,fs),t.addEventListener("dragover",fw,fs),t.addEventListener("drop",gw,fs);let cp=t.ownerDocument,hw=i=>{va()&&i.preventDefault()},yw=i=>{va()&&i.preventDefault()};cp.addEventListener("dragover",hw),cp.addEventListener("drop",yw),Oe.push(()=>{Et?.destroy(),Et=null,ig(),tr?.destroy(),tr=null,Sr?.destroy(),Sr=null,es?.destroy(),es=null,ts?.destroy(),ts=null,Zr=null,Bm=null,ef(),ml.destroy(),ga&&clearTimeout(ga),Zs(),fi?.abort(),fi=null,Lt?.destroy(),Lt=null,ze.destroy(),Bl.removeEventListener("keydown",DC,!0),un?.destroy()}),Oe.push(()=>{Pe.removeEventListener("dragenter",uw,fs),Pe.removeEventListener("dragleave",mw,fs),t.removeEventListener("dragover",fw,fs),t.removeEventListener("drop",gw,fs),cp.removeEventListener("dragover",hw),cp.removeEventListener("drop",yw),mg()}),Oe.push(()=>{N.cancel()}),sn?Oe.push(()=>{sn?.destroy()}):Fn&&Oe.push(()=>{Fn?.remove()});let an={update(i){let d=o.future?.v5Defaults===!0,f=o.toolCall,y=o.messageActions,w=o.layout?.messages,k=o.colorScheme,q=o.loadingIndicator,te=o.iterationDisplay,Q=o.features?.showReasoning,re=o.features?.showToolCalls,ce=o.features?.toolCallDisplay,ye=o.features?.reasoningDisplay,De=o.features?.streamAnimation?.type,lt=o.features?.history?.enabled===!0,It=o.features?.history?.provider,kt=o.getIdentityProof,oo=o.clientToken,Jt=o.contextMentions;o=HE({...o,features:p},i),p=o.features,o=Xy(o),c(),Km(),gc(t,o),Uc(t,o),qc(t,o),ft(),Fo(),o.colorScheme!==k&&iv();let rn=eb.getForInstance(o.plugins);u.length=0,u.push(...rn),sC(),_=o.launcher?.enabled??!0,Te=o.launcher?.autoExpand??!1,J=o.features?.showReasoning??!0,Y=o.features?.showToolCalls??!0,Me=o.features?.scrollToBottom??{};let Vn=po();Ee=o.features?.scrollBehavior??{},Vn!==po()&&($o(),eo()),Cv(),Lb(),xn();let ln=ie;if(ie=o.features?.showEventStreamToggle??!1,ie&&!ln){if(ct||(Tt(),N.setSSEEventCallback((ue,ht)=>{o.onSSEEvent?.(ue,ht),qe(ue,ht)})),!Rt&&$e){let ue=o.features?.eventStream?.classNames,ht="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(ue?.toggleButton?" "+ue.toggleButton:"");Rt=v("button",ht),Rt.style.width="28px",Rt.style.height="28px",Rt.style.color=jn.actionIconColor,Rt.type="button",Rt.setAttribute("aria-label","Event Stream"),Rt.title="Event Stream";let yt=Ge(Xr.Activity,"18px","currentColor",1.5);yt&&Rt.appendChild(yt);let Pt=ot.clearChatButtonWrapper,Yt=ot.closeButtonWrapper,Dn=Pt||Yt;Dn&&Dn.parentNode===$e?$e.insertBefore(Rt,Dn):$e.appendChild(Rt),Rt.addEventListener("click",()=>{nt?qi():_m()})}}else!ie&&ln&&(qi(),Rt&&(Rt.remove(),Rt=null),ct?.clear(),rt?.destroy(),ct=null,rt=null,Ht?.reset(),Ht=null,Z=null);if(o.launcher?.enabled===!1&&sn&&(sn.destroy(),sn=null),o.launcher?.enabled===!1&&Fn&&(Fn.remove(),Fn=null),o.launcher?.enabled!==!1&&!sn&&!Fn){let{instance:ue,element:ht}=yy({config:o,plugins:u,onToggle:KC});sn=ue,ue||(Fn=ht),t.appendChild(ht)}sn&&sn.update(o),Il(),Qn&&o.launcher?.subtitle!==void 0&&(Qn.textContent=o.launcher.subtitle);let $t=o.layout?.header;if($t?.layout!==Wt&&$e){let ue=$t?Qu(o,$t,{showClose:Ne(),onClose:()=>qt(!1,"user")}):Pi({config:o,showClose:Ne(),onClose:()=>qt(!1,"user")});Cn.replaceHeader(ue),$e=Cn.header.element,St=Cn.header.iconHolder,Bn=Cn.header.headerTitle,Qn=Cn.header.headerSubtitle,Ce=Cn.header.closeButton,Wt=$t?.layout,Il()}else if($t){if(St&&(St.style.display=$t.showIcon===!1?"none":""),Bn&&(Bn.style.display=$t.showTitle===!1?"none":""),Qn&&(Qn.style.display=$t.showSubtitle===!1?"none":""),Ce){let ue=Ne()&&$t.showCloseButton!==!1;Ce.style.display=ue?"":"none"}if(ot.clearChatButtonWrapper){let ue=$t.showClearChat;if(ue!==void 0){ot.clearChatButtonWrapper.style.display=ue?"":"none";let{closeButtonWrapper:ht}=ot;ht&&!ht.classList.contains("persona-absolute")&&(ue?ht.classList.remove("persona-ml-auto"):ht.classList.add("persona-ml-auto"))}}}let dr=o.layout?.showHeader!==!1;$e&&($e.style.display=dr?"":"none");let Po=o.layout?.showFooter!==!1;Qe&&(Qe.style.display=Po?"":"none"),$s(),xn(),_!==At?_?qt(Te,"auto"):(Ae=!0,bl()):Te!==ut&&qt(Te,"auto"),ut=Te,At=_,Wl(),ow();let pr=JSON.stringify(o.toolCall)!==JSON.stringify(f),zo=JSON.stringify(o.messageActions)!==JSON.stringify(y),hs=JSON.stringify(o.layout?.messages)!==JSON.stringify(w),Ol=o.loadingIndicator?.render!==q?.render||o.loadingIndicator?.renderIdle!==q?.renderIdle||o.loadingIndicator?.showBubble!==q?.showBubble,hi=o.iterationDisplay!==te,$=(o.features?.showReasoning??!0)!==(Q??!0)||(o.features?.showToolCalls??!0)!==(re??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(ce)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(ye);(o.future?.v5Defaults===!0!==d||pr||zo||hs||Ol||hi||$)&&N&&(ei++,xo(We,N.getMessages(),j));let Je=o.features?.streamAnimation?.type;if(Je!==De&&Je&&Je!=="none"){let ue=Qm(Je,o.features?.streamAnimation?.plugins);ue&&xc(ue,t)}let fe=o.launcher??{},zt=fe.headerIconHidden??!1,fn=o.layout?.header?.showIcon,_n=zt||fn===!1,En=fe.headerIconName,jt=fe.headerIconSize??Fl;if(St){let ue=$e,ht=ue?.querySelector(".persona-flex-col");if(_n)St.style.display="none",ue&&ht&&!ue.contains(ht)&&ue.insertBefore(ht,ue.firstChild);else{if(St.style.display="",St.style.height=jt,St.style.width=jt,ue&&ht&&(ue.contains(St)?St.nextSibling!==ht&&(St.remove(),ue.insertBefore(St,ht)):ue.insertBefore(St,ht)),En){let Pt=parseFloat(jt)||24,Yt=ke(En,Pt*.6,"currentColor",1);Yt?(Yt.style.width=`calc(${Pt}px * var(--persona-components-header-iconScale, 0.6))`,Yt.style.height=`calc(${Pt}px * var(--persona-components-header-iconScale, 0.6))`,St.replaceChildren(Yt)):St.textContent=fe.agentIconText??"\u{1F4AC}"}else if(fe.iconUrl){let Pt=St.querySelector("img");if(Pt)Pt.src=fe.iconUrl,Pt.style.height=jt,Pt.style.width=jt;else{let Yt=document.createElement("img");Yt.src=fe.iconUrl,Yt.alt="",Yt.className="persona-rounded-xl persona-object-cover",Yt.style.height=jt,Yt.style.width=jt,St.replaceChildren(Yt)}}else{let Pt=St.querySelector("svg"),Yt=St.querySelector("img");(Pt||Yt)&&St.replaceChildren(),St.textContent=fe.agentIconText??"\u{1F4AC}"}let yt=St.querySelector("img");yt&&(yt.style.height=jt,yt.style.width=jt)}}let cn=o.layout?.header?.showTitle,Sn=o.layout?.header?.showSubtitle;if(Bn&&(Bn.style.display=cn===!1?"none":""),Qn&&(Qn.style.display=Sn===!1?"none":""),Ce){let ue=Ne()&&o.layout?.header?.showCloseButton!==!1;if(Ce.style.display=ue?"":"none",!xe()){let Pn=fe.closeButtonSize??"";Ce.style.height=Pn,Ce.style.width=Pn,Ce.style.minWidth=Pn,Ce.style.minHeight=Pn}let ht=fe.closeButtonPlacement??"inline",{closeButtonWrapper:yt}=ot,Pt=ht==="top-right",Yt=yt?.classList.contains("persona-absolute");if(yt&&Pt!==Yt)if(yt.remove(),Pt){yt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let Pn=Sl??Pe;Pn.style.position="relative",Pn.appendChild(yt)}else{let Pn=fe.clearChat?.placement??"inline",Ln=fe.clearChat?.enabled??!0;yt.className=Ln&&Pn==="inline"?"":"persona-ml-auto",$e&&$e.appendChild(yt)}if(Ce.style.color=fe.closeButtonColor||jn.actionIconColor,fe.closeButtonBackgroundColor?(Ce.style.backgroundColor=fe.closeButtonBackgroundColor,Ce.classList.remove("hover:persona-bg-gray-100")):(Ce.style.backgroundColor="",Ce.classList.add("hover:persona-bg-gray-100")),fe.closeButtonBorderWidth||fe.closeButtonBorderColor){let Pn=fe.closeButtonBorderWidth||"0px",Ln=fe.closeButtonBorderColor||"transparent";Ce.style.border=`${Pn} solid ${Ln}`,Ce.classList.remove("persona-border-none")}else Ce.style.border="",Ce.classList.add("persona-border-none");fe.closeButtonBorderRadius?(Ce.style.borderRadius=fe.closeButtonBorderRadius,Ce.classList.remove("persona-rounded-full")):(Ce.style.borderRadius="",Ce.classList.add("persona-rounded-full")),fe.closeButtonPaddingX?(Ce.style.paddingLeft=fe.closeButtonPaddingX,Ce.style.paddingRight=fe.closeButtonPaddingX):(Ce.style.paddingLeft="",Ce.style.paddingRight=""),fe.closeButtonPaddingY?(Ce.style.paddingTop=fe.closeButtonPaddingY,Ce.style.paddingBottom=fe.closeButtonPaddingY):(Ce.style.paddingTop="",Ce.style.paddingBottom=""),Gu(Ce,fe.closeButtonIconName??"x",{iconSize:xe()?my:void 0,iconText:fe.closeButtonIconText??"\xD7"});let Dn=fe.closeButtonTooltipText??"Close chat",qo=fe.closeButtonShowTooltip??!0;Ce.setAttribute("aria-label",Dn),yt&&In({anchor:Ce,trigger:yt,text:()=>Ce?.getAttribute("aria-label")??Dn,enabled:qo})}let{clearChatButton:Ke,clearChatButtonWrapper:Kt}=ot;if(Ke){let ue=fe.clearChat??{},ht=ue.enabled??!0,yt=o.layout?.header?.showClearChat,Pt=yt!==void 0?yt:ht,Yt=ue.placement??"inline";if(Kt){Kt.style.display=Pt?"":"none";let{closeButtonWrapper:Dn}=ot;!xe()&&Dn&&!Dn.classList.contains("persona-absolute")&&(Pt?Dn.classList.remove("persona-ml-auto"):Dn.classList.add("persona-ml-auto"));let qo=Yt==="top-right",Pn=Kt.classList.contains("persona-absolute");if(!xe()&&qo!==Pn&&Pt){if(Kt.remove(),qo){Kt.className="persona-absolute persona-top-4 persona-z-50",Kt.style.right="48px";let ur=Sl??Pe;ur.style.position="relative",ur.appendChild(Kt)}else{Kt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Kt.style.right="";let ur=ot.closeButtonWrapper;$e&&ur&&ur.parentElement===$e?$e.insertBefore(Kt,ur):$e&&$e.appendChild(Kt)}let Ln=ot.closeButtonWrapper;Ln&&!Ln.classList.contains("persona-absolute")&&(qo?Ln.classList.add("persona-ml-auto"):Ln.classList.remove("persona-ml-auto"))}}if(Pt){if(!xe()){let Ln=ue.size??"";Ke.style.height=Ln,Ke.style.width=Ln,Ke.style.minWidth=Ln,Ke.style.minHeight=Ln}let Dn=ue.iconColor??"";if(Ke.style.color=Dn||jn.actionIconColor,Gu(Ke,ue.iconName??"refresh-cw",{iconSize:xe()?fy:void 0}),ue.backgroundColor?(Ke.style.backgroundColor=ue.backgroundColor,Ke.classList.remove("hover:persona-bg-gray-100")):(Ke.style.backgroundColor="",Ke.classList.add("hover:persona-bg-gray-100")),ue.borderWidth||ue.borderColor){let Ln=ue.borderWidth||"0px",ur=ue.borderColor||"transparent";Ke.style.border=`${Ln} solid ${ur}`,Ke.classList.remove("persona-border-none")}else Ke.style.border="",Ke.classList.add("persona-border-none");ue.borderRadius?(Ke.style.borderRadius=ue.borderRadius,Ke.classList.remove("persona-rounded-full")):(Ke.style.borderRadius="",Ke.classList.add("persona-rounded-full")),ue.paddingX?(Ke.style.paddingLeft=ue.paddingX,Ke.style.paddingRight=ue.paddingX):(Ke.style.paddingLeft="",Ke.style.paddingRight=""),ue.paddingY?(Ke.style.paddingTop=ue.paddingY,Ke.style.paddingBottom=ue.paddingY):(Ke.style.paddingTop="",Ke.style.paddingBottom="");let qo=ue.tooltipText??"Clear chat",Pn=ue.showTooltip??!0;Ke.setAttribute("aria-label",qo),Kt&&In({anchor:Ke,trigger:Kt,text:()=>Ke?.getAttribute("aria-label")??qo,enabled:Pn})}}let et=o.actionParsers&&o.actionParsers.length?o.actionParsers:[nb],An=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[jc.message,jc.messageAndClick];se=ob({parsers:et,handlers:An,getSessionMetadata:le,updateSessionMetadata:de,emit:H.emit,documentRef:typeof document<"u"?document:null}),j=u0(o,se,I),Sk(),N.updateConfig(o),HC(),(o.features?.history?.enabled===!0!==lt||o.features?.history?.provider!==It||o.getIdentityProof!==kt||o.clientToken!==oo)&&(no({restoreFocus:!1}),Xv()),ps(),Kd(),xo(We,N.getMessages(),j),Qs(),Id(),wk(),vl(N.isStreaming()),Jt!==o.contextMentions&&lw();let Io=o.voiceRecognition?.enabled===!0,kn=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),Ut=Un(o.voiceRecognition?.provider);if(Io&&(kn||Ut))if(!he||!co){let ue=Da(o);if(ue){he=ue.button,co=ue.wrapper;let ht=Jo&&Jo.parentElement===ed?Jo:null;ed?ed.insertBefore(co,ht):Tn?.appendChild(co),Et&&(Et.micButton=he),Et?.addListener(he,"click",cg),he.disabled=sr()||N.isStreaming()&&!lf()}}else{let ue=o.voiceRecognition??{},ht=o.sendButton??{},yt=ue.iconName??"mic",Pt=ue.iconSize,Yt=parseFloat(Pt??"")||qn;he.classList.add(yo),he.classList.toggle(Go,!Pt),he.style.width=Pt??"",he.style.height=Pt??"",he.style.minWidth=Pt??"",he.style.minHeight=Pt??"";let Dn=ue.iconColor??ht.textColor;he.innerHTML="";let qo=ke(yt,Yt,Dn||"currentColor",1.5);qo?he.appendChild(qo):he.textContent="\u{1F3A4}";let Pn=ue.backgroundColor??ht.backgroundColor;Pn?he.style.backgroundColor=Pn:he.style.backgroundColor="",Dn?he.style.color=Dn:he.style.color="var(--persona-text, #111827)",ue.borderWidth?(he.style.borderWidth=ue.borderWidth,he.style.borderStyle="solid"):(he.style.borderWidth="",he.style.borderStyle=""),ue.borderColor?he.style.borderColor=ue.borderColor:he.style.borderColor="",ue.paddingX?(he.style.paddingLeft=ue.paddingX,he.style.paddingRight=ue.paddingX):(he.style.paddingLeft="",he.style.paddingRight=""),ue.paddingY?(he.style.paddingTop=ue.paddingY,he.style.paddingBottom=ue.paddingY):(he.style.paddingTop="",he.style.paddingBottom="");let Ln=ue.tooltipText??"Start voice recognition",ur=ue.showTooltip??!1;he.setAttribute("aria-label",Ln),co&&In({anchor:he,trigger:co,text:()=>he?.getAttribute("aria-label")??Ln,enabled:ur}),co.style.display="",he.disabled=sr()||N.isStreaming()&&!lf()}else he&&co&&(co.style.display="none",Un(o.voiceRecognition?.provider)?N.isVoiceActive()&&N.toggleVoice():lr&&us());if(pg(),o.attachments?.enabled===!0){if(!Xn||!on){let ue=o.attachments??{};Jn||(Jn=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Jn.style.display="none",(we.parentElement??Tn).insertBefore(Jn,we)),Xt||(Xt=document.createElement("input"),Xt.type="file",Xt.accept=(ue.allowedTypes??Ur).join(","),Xt.multiple=(ue.maxFiles??4)>1,Xt.style.display="none",Xt.setAttribute("aria-label","Attach files"),(we.parentElement??Tn).insertBefore(Xt,we)),Xn=v("div","persona-send-button-wrapper"),on=v("button",`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${yo} ${Go}`),on.type="button",on.setAttribute("aria-label",ue.buttonTooltipText??"Attach file");let ht=ue.buttonIconName??"paperclip";on.style.fontSize="18px",on.style.lineHeight="1";let yt=ke(ht,qn,"currentColor",1.5);yt?on.appendChild(yt):on.textContent="\u{1F4CE}",on.addEventListener("click",Yt=>{Yt.preventDefault(),Xt?.click()}),Xn.appendChild(on);let Pt=ue.buttonTooltipText??"Attach file";In({anchor:on,trigger:Xn,text:()=>on?.getAttribute("aria-label")??Pt}),Pm?Pm.append(Xn):Tn.appendChild(Xn),Et&&(Et.attachmentButton=on,Et.attachmentInput=Xt??void 0,Et.attachmentPreviews=Jn??void 0),!Lt&&Xt&&Jn&&(Lt=oc.fromConfig(ue,Ib),Lt.setPreviewsContainer(Jn),Et?.addListener(Xt,"change",async()=>{Lt&&Xt?.files&&(await Lt.handleFileSelect(Xt.files),Xt.value="")}))}else{Xn.style.display="";let ue=o.attachments??{};Xt&&(Xt.accept=(ue.allowedTypes??Ur).join(","),Xt.multiple=(ue.maxFiles??4)>1),Lt&&Lt.updateConfig({allowedTypes:ue.allowedTypes,maxFileSize:ue.maxFileSize,maxFiles:ue.maxFiles,adapter:ue.adapter})}if(Pe.querySelector(".persona-attachment-drop-overlay")?.remove(),Pe.appendChild(m0(o.attachments?.dropOverlay)),on){let ue=o.attachments??{},ht=ue.buttonTooltipText??"Attach file";on.setAttribute("aria-label",ht),on.textContent="";let yt=ke(ue.buttonIconName??"paperclip",qn,"currentColor",1.5);yt?on.appendChild(yt):on.textContent="\u{1F4CE}",Xn&&In({anchor:on,trigger:Xn,text:()=>on?.getAttribute("aria-label")??ht})}}else Xn&&(Xn.style.display="none"),Lt&&Lt.clearAttachments(),Pe.querySelector(".persona-attachment-drop-overlay")?.remove();let tt=o.sendButton??{},ys=tt.useIcon??!1,bn=tt.iconText??"\u2191",ro=tt.iconName,Or=tt.tooltipText??"Send message",fg=tt.showTooltip??!1,yi=tt.size,gg=parseFloat(yi??"")||fh,_r=tt.backgroundColor,bi=tt.textColor;if(ys){if(Ve.style.width=yi??"",Ve.style.height=yi??"",Ve.style.minWidth=yi??"",Ve.style.minHeight=yi??"",Ve.style.fontSize="18px",Ve.style.lineHeight="1",bi?Ve.style.color=bi:Ve.style.color="var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))",!N.isStreaming())if(Ve.innerHTML="",ro){let ue=parseFloat(tt.iconSize??"")||Math.round(gg*.5),ht=bi?.trim()||"currentColor",yt=tt.iconStrokeWidth??2,Pt=ke(ro,ue,ht,yt),Yt=ke(tt.stopIconName??"square",ue,ht,yt);Pt&&Yt?Ve.appendChild(gh(Pt,Yt)):Pt?Ve.appendChild(Pt):Ve.textContent=bn}else Ve.textContent=bn;Ve.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${yo}`,_r?(Ve.style.backgroundColor=_r,Ve.classList.remove("persona-bg-persona-primary")):(Ve.style.backgroundColor="",Ve.classList.add("persona-bg-persona-primary"))}else Ve.textContent=o.copy?.sendButtonLabel??"Send",Ve.style.width="",Ve.style.height="",Ve.style.minWidth="",Ve.style.minHeight="",Ve.style.fontSize="",Ve.style.lineHeight="",Ve.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",_r?(Ve.style.backgroundColor=_r,Ve.classList.remove("persona-bg-persona-accent")):Ve.classList.add("persona-bg-persona-accent"),bi?Ve.style.color=bi:Ve.classList.add("persona-text-white");tt.borderWidth?(Ve.style.borderWidth=tt.borderWidth,Ve.style.borderStyle="solid"):(Ve.style.borderWidth="",Ve.style.borderStyle=""),tt.borderColor?Ve.style.borderColor=tt.borderColor:Ve.style.borderColor="",tt.paddingX?(Ve.style.paddingLeft=tt.paddingX,Ve.style.paddingRight=tt.paddingX):(Ve.style.paddingLeft="",Ve.style.paddingRight=""),tt.paddingY?(Ve.style.paddingTop=tt.paddingY,Ve.style.paddingBottom=tt.paddingY):(Ve.style.paddingTop="",Ve.style.paddingBottom=""),N.isStreaming()||Ve.setAttribute("aria-label",Or),Pd(),Jo&&In({anchor:Ve,trigger:Jo,text:()=>Ve.getAttribute("aria-label")??Or,enabled:fg}),qb(),Ym();let bw=hu(ze.getState().activeModeIds,o.composer?.modes);ze.setActiveModeIds(bw),$i().length>0!==!!Sr&&Fm(),Sr?.render(bw,$i());for(let ue of[...zi.keys()])gu(ue,o.composer?.modeGroups)||zi.delete(ue);zi.forEach(ue=>ue.repaint()),Zr?.repaint(),tr?.resolve();let dp=Is(o,xe());if(Gm(),dp){We.style.maxWidth=dp,We.style.marginLeft="auto",We.style.marginRight="auto",We.style.width="100%",z.style.maxWidth=dp,z.style.marginLeft="auto",z.style.marginRight="auto",z.style.width="100%";for(let ue of[Tn,lo,Jn,pt])ue&&(ue.style.maxWidth=dp,ue.style.marginLeft="auto",ue.style.marginRight="auto",ue.style.width="100%")}else{We.style.maxWidth="",We.style.marginLeft="",We.style.marginRight="",We.style.width="",z.style.maxWidth="",z.style.marginLeft="",z.style.marginRight="",z.style.width="";for(let ue of[Tn,lo,Jn,pt])ue&&(ue.style.maxWidth="",ue.style.marginLeft="",ue.style.marginRight="",ue.style.width="")}let Uo=o.statusIndicator??{};if(Pg(pt,Tn,Uo),xi(pt,Uo,N?.getStatus()??"idle"),N){let ue=N.getStatus();Qo(pt,(yt=>yt==="idle"?Uo.idleText??dn.idle:yt==="connecting"?Uo.connectingText??dn.connecting:yt==="connected"?Uo.connectedText??dn.connected:yt==="error"?Uo.errorText??dn.error:yt==="paused"?Uo.pausedText??dn.paused:yt==="resuming"?Uo.resumingText??dn.resuming:dn[yt])(ue),Uo,ue)}pt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let _P=Uo.align==="left"?"persona-text-left":Uo.align==="center"?"persona-text-center":"persona-text-right";pt.classList.add(_P),Nm(),df(),_o(),Mn()},open(){Ne()&&qt(!0,"api")},close(){Ne()&&qt(!1,"api")},toggle(){Ne()&&qt(!Ae,"api")},reconnect(){N.reconnectNow()},clearChat(){Ar=!1,a.clear(),r.clear(),s.clear(),l.clear(),N.clearMessages(),o.layout?.topFade&&(pe.scrollTop=0),pe.removeAttribute("data-persona-top-fade"),mn.clear(),eo();try{localStorage.removeItem(Ja),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ja}`)}catch(d){console.error("[AgentWidget] Failed to clear default localStorage:",d)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Ja)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(d){console.error("[AgentWidget] Failed to clear custom localStorage:",d)}let i=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(i),x?.clear&&wd(()=>x.clear(),"[AgentWidget] Failed to clear storage adapter:"),L={},se.syncFromMetadata(),Lt?.clearAttachments(),Sd(),Ui(void 0),er(void 0),Zs(),ct?.clear(),Ht?.reset(),He?.update()},setMessage(i){return!we||N.isStreaming()||sr()?!1:(!Ae&&Ne()&&qt(!0,"system"),we.value=i,we.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(i){if(N.isStreaming()||si())return!1;let d=i?.trim()||we.value.trim();return d?(!Ae&&Ne()&&qt(!0,"system"),we.value="",we.style.height="auto",Zo(),rp(d,{consumeDraft:!1}),!0):!1},getComposerState(){return ze.getState()},setQuote(i){let d=i?.text?.trim();d&&er({...i,text:d})},clearQuote(){er(void 0)},startVoiceRecognition(){return N.isStreaming()?!1:Un(o.voiceRecognition?.provider)?(N.isVoiceActive()||N.isBargeInActive()||(!Ae&&Ne()&&qt(!0,"system"),wt.manuallyDeactivated=!1,Vo(),N.toggleVoice().then(()=>{wt.active=N.isVoiceActive(),kr("user"),N.isVoiceActive()&&ba()})),!0):lr?!0:NC()?(!Ae&&Ne()&&qt(!0,"system"),wt.manuallyDeactivated=!1,Vo(),ip("user"),!0):!1},stopVoiceRecognition(){return Un(o.voiceRecognition?.provider)?!N.isVoiceActive()&&!N.isBargeInActive()?!1:((N.isBargeInActive()?N.deactivateBargeIn():N.toggleVoice()).then(()=>{wt.active=!1,wt.manuallyDeactivated=!0,Vo(),kr("user"),Dr()}),!0):lr?(wt.manuallyDeactivated=!0,Vo(),us("user"),!0):!1},injectMessage(i){return!Ae&&Ne()&&qt(!0,"system"),N.injectMessage(i)},injectAssistantMessage(i){!Ae&&Ne()&&qt(!0,"system");let d=N.injectAssistantMessage(i);return vt&&(vt=!1,X&&(clearTimeout(X),X=null),setTimeout(()=>{N&&!N.isStreaming()&&N.continueConversation()},100)),d},injectUserMessage(i){return!Ae&&Ne()&&qt(!0,"system"),N.injectUserMessage(i)},injectSystemMessage(i){return!Ae&&Ne()&&qt(!0,"system"),N.injectSystemMessage(i)},injectMessageBatch(i){return!Ae&&Ne()&&qt(!0,"system"),N.injectMessageBatch(i)},injectComponentDirective(i){return!Ae&&Ne()&&qt(!0,"system"),N.injectComponentDirective(i)},injectTestMessage(i){!Ae&&Ne()&&qt(!0,"system"),N.injectTestEvent(i)},async connectStream(i,d){return N.connectStream(i,d)},__pushEventStreamEvent(i){ie&&(Tt(),qe(i.type,i.payload))},showEventStream(){ie&&_m()},hideEventStream(){nt&&qi()},isEventStreamVisible(){return nt},listConversations(i){return N.listConversations(i)},getActiveConversationId(){return N.getActiveConversationId()},openConversation(i,d){return jf(i,{focusComposer:d?.focus===!0})},startNewConversation(i){return Kf({focusComposer:i?.focus===!0})},warmSession(){Qf()},deleteConversation(i){return SC(i)},renameConversation(i,d){return Gf(i,{title:d})},setConversationStarred(i,d){return Gf(i,{starred:d})},clearConversationHistory(i){return AC(i)},resetHistoryIdentity(){return MC()},async getVisitorToken(){let i=So;if(!i)return null;let d=await i.get();return i===So?d:null},getHistoryIdentityStatus(){return go?go.getIdentityStatus():Pf()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory(i){return Ll({...i?.returnSurface?{returnSurface:i.returnSurface}:{},...i?.focus!==void 0?{focus:i.focus}:{}})},hideHistory(i){no(i?.restoreFocus!==void 0?{restoreFocus:i.restoreFocus}:void 0)},isHistoryVisible(){return mt},showArtifacts(){Gn(o)&&(Ar=!1,Ki=!0,Fo(),gt?.setMobileOpen(!0))},hideArtifacts(){Gn(o)&&(Ar=!0,Fo())},upsertArtifact(i){return Gn(o)?(Cs(o.features?.artifacts,{artifactType:i.artifactType,...i.artifactType==="markdown"&&i.file?{file:i.file}:{},...i.presentation?{presentation:i.presentation}:{}})==="panel"&&(Ar=!1,Ki=!0),N.upsertArtifact(i)):null},selectArtifact(i){Gn(o)&&N.selectArtifact(i)},clearArtifacts(){Gn(o)&&N.clearArtifacts()},getArtifacts(){return N?.getArtifacts()??[]},getSelectedArtifactId(){return N?.getSelectedArtifactId()??null},focusInput(){return _&&!Ae&&!xe()||!we?!1:(we.focus(),!0)},async resolveApproval(i,d,f){let w=N.getMessages().find(k=>k.variant==="approval"&&k.approval?.id===i);if(!w?.approval)throw new Error(`Approval not found: ${i}`);if(w.approval.toolType==="webmcp"){N.resolveWebMcpApproval(w.id,d);return}return N.resolveApproval(w.approval,d,f)},setFollowUpSuggestions(i){j0(i)},clearFollowUpSuggestions(){vv()},getMessages(){return N.getMessages()},getStatus(){return N.getStatus()},getPersistentMetadata(){return{...L}},updatePersistentMetadata(i){de(i)},on(i,d){return H.on(i,d)},off(i,d){H.off(i,d)},isOpen(){return Ne()&&Ae},isVoiceActive(){return wt.active},toggleReadAloud(i){N.toggleReadAloud(i)},stopReadAloud(){N.stopSpeaking()},getReadAloudState(i){return N.getReadAloudState(i)},onReadAloudChange(i){return N.onReadAloudChange(i)},getState(){return{open:Ne()&&Ae,launcherEnabled:_,voiceActive:wt.active,streaming:N.isStreaming()}},showCSATFeedback(i){!Ae&&Ne()&&qt(!0,"system");let d=We.querySelector(".persona-feedback-container");d&&d.remove();let f=c0({onSubmit:async(y,w)=>{N.isClientTokenMode()&&await N.submitCSATFeedback(y,w),i?.onSubmit?.(y,w)},onDismiss:i?.onDismiss,...i});We.appendChild(f),f.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(i){!Ae&&Ne()&&qt(!0,"system");let d=We.querySelector(".persona-feedback-container");d&&d.remove();let f=d0({onSubmit:async(y,w)=>{N.isClientTokenMode()&&await N.submitNPSFeedback(y,w),i?.onSubmit?.(y,w)},onDismiss:i?.onDismiss,...i});We.appendChild(f),f.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(i,d){return N.submitCSATFeedback(i,d)},async submitNPSFeedback(i,d){return N.submitNPSFeedback(i,d)},destroy(){xf(),li!=null&&(clearInterval(li),li=null),a.clear(),r.clear(),s.clear(),l.clear(),Oe.forEach(i=>i()),dt.remove(),Nt?.remove(),sn?.destroy(),Fn?.remove(),Gs&&Ce.removeEventListener("click",Gs)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let i=window.AgentWidgetBrowser,d={controller:an,getMessages:an.getMessages,getStatus:an.getStatus,getMetadata:an.getPersistentMetadata,updateMetadata:an.updatePersistentMetadata,clearHistory:()=>an.clearChat(),setVoiceActive:f=>f?an.startVoiceRecognition():an.stopVoiceRecognition()};window.AgentWidgetBrowser=d,Oe.push(()=>{window.AgentWidgetBrowser===d&&(window.AgentWidgetBrowser=i)})}if(typeof window<"u"){let i=t.getAttribute("data-persona-instance")||t.id||"persona-"+Math.random().toString(36).slice(2,8),d=re=>{let ce=re.detail;(!ce?.instanceId||ce.instanceId===i)&&an.focusInput()};if(window.addEventListener("persona:focusInput",d),Oe.push(()=>{window.removeEventListener("persona:focusInput",d)}),ie){let re=ye=>{let De=ye.detail;(!De?.instanceId||De.instanceId===i)&&an.showEventStream()},ce=ye=>{let De=ye.detail;(!De?.instanceId||De.instanceId===i)&&an.hideEventStream()};window.addEventListener("persona:showEventStream",re),window.addEventListener("persona:hideEventStream",ce),Oe.push(()=>{window.removeEventListener("persona:showEventStream",re),window.removeEventListener("persona:hideEventStream",ce)})}let f=re=>{let ce=re.detail;(!ce?.instanceId||ce.instanceId===i)&&an.showHistory()},y=re=>{let ce=re.detail;(!ce?.instanceId||ce.instanceId===i)&&an.hideHistory()};window.addEventListener("persona:showHistory",f),window.addEventListener("persona:hideHistory",y),Oe.push(()=>{window.removeEventListener("persona:showHistory",f),window.removeEventListener("persona:hideHistory",y)});let w=re=>{let ce=re.detail;(!ce?.instanceId||ce.instanceId===i)&&an.showArtifacts()},k=re=>{let ce=re.detail;(!ce?.instanceId||ce.instanceId===i)&&an.hideArtifacts()},q=re=>{let ce=re.detail;ce?.instanceId&&ce.instanceId!==i||ce?.artifact&&an.upsertArtifact(ce.artifact)},te=re=>{let ce=re.detail;ce?.instanceId&&ce.instanceId!==i||typeof ce?.id=="string"&&an.selectArtifact(ce.id)},Q=re=>{let ce=re.detail;(!ce?.instanceId||ce.instanceId===i)&&an.clearArtifacts()};window.addEventListener("persona:showArtifacts",w),window.addEventListener("persona:hideArtifacts",k),window.addEventListener("persona:upsertArtifact",q),window.addEventListener("persona:selectArtifact",te),window.addEventListener("persona:clearArtifacts",Q),Oe.push(()=>{window.removeEventListener("persona:showArtifacts",w),window.removeEventListener("persona:hideArtifacts",k),window.removeEventListener("persona:upsertArtifact",q),window.removeEventListener("persona:selectArtifact",te),window.removeEventListener("persona:clearArtifacts",Q)})}let ko=wD(o.persistState);if(ko&&Ne()){let i=xD(ko.storage),d=`${ko.keyPrefix}widget-open`,f=`${ko.keyPrefix}widget-voice`,y=`${ko.keyPrefix}widget-voice-mode`;if(i){let w=ko.persist?.openState&&i.getItem(d)==="true",k=ko.persist?.voiceState&&i.getItem(f)==="true",q=ko.persist?.voiceState&&i.getItem(y)==="true";if(w&&(sn?.setPanelOpen(!0,"auto"),setTimeout(()=>{an.open(),setTimeout(()=>{if(k||q)an.startVoiceRecognition();else if(ko.persist?.focusInput){let te=t.querySelector("textarea");te&&te.focus()}},100)},0)),ko.persist?.openState&&(H.on("widget:opened",()=>{i.setItem(d,"true")}),H.on("widget:closed",()=>{i.setItem(d,"false")})),ko.persist?.voiceState&&(H.on("voice:state",te=>{i.setItem(f,te.active?"true":"false")}),H.on("user:message",te=>{i.setItem(y,te.viaVoice?"true":"false")})),ko.clearOnChatClear){let te=()=>{i.removeItem(d),i.removeItem(f),i.removeItem(y)},Q=()=>te();window.addEventListener("persona:clear-chat",Q),Oe.push(()=>{window.removeEventListener("persona:clear-chat",Q)})}}}if(oe&&Ne()&&(sn?.setPanelOpen(!0,"auto"),setTimeout(()=>{an.open()},0)),oa(),!K0){let i=xa(()=>{N&&(ei++,mn.clear(),xo(We,N.getMessages(),j))});Oe.push(i)}R=()=>{N&&(ei++,mn.clear(),xo(We,N.getMessages(),j))},N.getMessages().length>0&&kd(),B=()=>{N&&(ei++,mn.clear(),xo(We,N.getMessages(),j))};let DP=Hw(()=>{N&&(ei++,mn.clear(),xo(We,N.getMessages(),j))});Oe.push(DP);let OP=Ky(()=>{N&&(ei++,mn.clear(),xo(We,N.getMessages(),j),Gr()?.updateInlineArtifactBlocks(We,wo.artifacts,{suppressTransition:!0}),Fo())});return Oe.push(OP),an};ks();var g0=(t,e)=>{let n=t.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(o)return Math.max(0,parseFloat(o[1]));let r=/^(\d+(?:\.\d+)?)%$/i.exec(n);return r?Math.max(0,e*parseFloat(r[1])/100):420},MD=(t,e)=>{if(e===!1){t.style.maxHeight="";return}t.style.maxHeight="100vh",t.style.maxHeight=e},TD=(t,e)=>{e===!1?(t.style.position="relative",t.style.top=""):(t.style.position="sticky",t.style.top="0")},ED=(t,e)=>{let n=t.parentElement;if(!n)return;let o=t.ownerDocument.createElement("div");o.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(o);let r=o.offsetHeight>0;o.style.height="100%";let s=o.offsetHeight>0;o.remove(),!(!r||s)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(e.maxHeight===!1?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${e.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},h0=(t,e)=>{let n=e?.launcher?.enabled??!0;t.className="persona-host",t.style.height=n?"":"100%",t.style.display=n?"":"flex",t.style.flexDirection=n?"":"column",t.style.flex=n?"":"1 1 auto",t.style.minHeight=n?"":"0",t.style.minWidth=n?"":"0"},Sb=t=>{t.style.position="",t.style.top="",t.style.bottom="",t.style.left="",t.style.right="",t.style.zIndex="",t.style.transform="",t.style.pointerEvents=""},y0=t=>{t.style.inset="",t.style.width="",t.style.height="",t.style.maxWidth="",t.style.maxHeight="",t.style.minWidth="",Sb(t)},Cb=t=>{t.style.transition=""},wb=t=>{t.style.display="",t.style.flexDirection="",t.style.flex="",t.style.minHeight="",t.style.minWidth="",t.style.width="",t.style.height="",t.style.alignItems="",t.style.transition="",t.style.transform="",t.style.marginLeft=""},xb=t=>{t.style.width="",t.style.maxWidth="",t.style.minWidth="",t.style.flex="1 1 auto"},Em=(t,e)=>{t.style.width="",t.style.minWidth="0",t.style.maxWidth="",t.style.boxSizing="",e.style.alignItems=""},kD=(t,e,n,o,r)=>{r?n.parentElement!==e&&(t.replaceChildren(),e.replaceChildren(n,o),t.appendChild(e)):n.parentElement===e&&(e.replaceChildren(),t.appendChild(n),t.appendChild(o))},PD=(t,e,n,o,r,s)=>{let a=s?e:t;r==="left"?a.firstElementChild!==o&&a.replaceChildren(o,n):a.lastElementChild!==o&&a.replaceChildren(n,o)},LD=t=>{let e=qr(t),n=e.components?.panel,o=(r,s)=>r==null||r===""?s:Rn(e,r)??r;return{inset:o(n?.inset,Wu),canvasBackground:o(n?.canvasBackground,Bu)}},b0=(t,e,n,o)=>{if(!e){t.style.padding="",t.style.background="",t.style.boxSizing="";return}t.style.boxSizing="border-box",t.style.padding=n,t.style.background=o},ID=(t,e,n,o,r,s,a,l)=>{let c=Do(s),p=c.reveal==="push",u=l!=null,m=l?.inset??"",g=l?.canvasBackground??"";kD(t,e,n,o,p),PD(t,e,n,o,c.side,p),t.dataset.personaHostLayout="docked",t.dataset.personaDockSide=c.side,t.dataset.personaDockOpen=a?"true":"false",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0",t.style.height="100%",t.style.minHeight="0",t.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let h=t.ownerDocument.defaultView,b=s?.launcher?.mobileFullscreen??!0,C=s?.launcher?.mobileBreakpoint??640,M=h!=null?h.innerWidth<=C:!1;if(b&&M&&a){t.dataset.personaDockMobileFullscreen="true",t.removeAttribute("data-persona-dock-reveal"),wb(e),Cb(o),y0(o),xb(n),Em(r,o),b0(o,!1,"",""),t.style.display="flex",t.style.flexDirection="column",t.style.alignItems="stretch",t.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String(s?.launcher?.zIndex??On),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",p&&(e.style.display="flex",e.style.flexDirection="column",e.style.width="100%",e.style.height="100%",e.style.minHeight="0",e.style.minWidth="0",e.style.flex="1 1 auto",e.style.alignItems="stretch",e.style.transform="none",e.style.marginLeft="0",e.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(t.removeAttribute("data-persona-dock-mobile-fullscreen"),y0(o),MD(o,c.maxHeight),b0(o,u&&a,m,g),c.reveal==="overlay"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="overlay",wb(e),Cb(o),xb(n),Em(r,o);let T=c.animate?"transform 180ms ease":"none",R=c.side==="right"?"translateX(100%)":"translateX(-100%)",A=a?"translateX(0)":R;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=c.width,o.style.maxWidth=c.width,o.style.minWidth=c.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=T,o.style.transform=A,o.style.pointerEvents=a?"auto":"none",o.style.zIndex="2",c.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(c.reveal==="push"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="push",Cb(o),Sb(o),Em(r,o);let T=g0(c.width,t.clientWidth),R=Math.max(0,t.clientWidth),A=c.animate?"margin-left 180ms ease":"none",D=c.side==="right"?a?-T:0:a?0:-T;e.style.display="flex",e.style.flexDirection="row",e.style.flex="0 0 auto",e.style.minHeight="0",e.style.minWidth="0",e.style.alignItems="stretch",e.style.height="100%",e.style.width=`${R+T}px`,e.style.transition=A,e.style.marginLeft=`${D}px`,e.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${R}px`,n.style.maxWidth=`${R}px`,n.style.minWidth=`${R}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=c.width,o.style.minWidth=c.width,o.style.maxWidth=c.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=a?"auto":"none"}else{t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="",wb(e),Sb(o),xb(n),Em(r,o);let T=c.reveal==="emerge";T?t.dataset.personaDockReveal="emerge":t.removeAttribute("data-persona-dock-reveal");let R=a?c.width:"0px",A=c.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${u?", padding 180ms ease":""}`:"none",D=!a;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${R}`,o.style.width=R,o.style.maxWidth=R,o.style.minWidth=R,o.style.minHeight="0",TD(o,c.maxHeight),o.style.overflow=T||D?"hidden":"visible",o.style.transition=A,T){o.style.alignItems=c.side==="right"?"flex-start":"flex-end";let W=u?`calc(${g0(c.width,t.clientWidth)}px - (2 * ${m}))`:c.width;r.style.width=W,r.style.minWidth=W,r.style.maxWidth=W,r.style.boxSizing="border-box"}}},HD=(t,e)=>{let n=t.ownerDocument.createElement("div");return h0(n,e),t.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){h0(n,o)},destroy(){n.remove()}}},RD=(t,e)=>{let{ownerDocument:n}=t,o=t.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=t.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=t.nextSibling,a=n.createElement("div"),l=n.createElement("div"),c=n.createElement("div"),p=n.createElement("aside"),u=n.createElement("div"),m=e?.launcher?.enabled??!0?e?.launcher?.autoExpand??!1:!0;l.dataset.personaDockRole="push-track",c.dataset.personaDockRole="content",p.dataset.personaDockRole="panel",u.dataset.personaDockRole="host",p.appendChild(u),o.insertBefore(a,t),c.appendChild(t);let g=null,h=()=>{g?.disconnect(),g=null},b=null,C=()=>{b=e?.launcher?.detachedPanel===!0?LD(e):null};C();let M=()=>{ID(a,l,c,p,u,e,m,b)},E=null,T=()=>{E?.(),E=null,!(e?.launcher?.detachedPanel!==!0||e?.colorScheme!=="auto")&&(E=Du(()=>{C(),M()}))},R=()=>{h(),Do(e).reveal==="push"&&(typeof ResizeObserver>"u"||(g=new ResizeObserver(()=>{M()}),g.observe(a)))},A=!1,D=()=>{M(),R(),m&&!A&&a.dataset.personaDockMobileFullscreen!=="true"&&(A=!0,ED(a,Do(e)))},W=a.ownerDocument.defaultView,U=()=>{D()};return W?.addEventListener("resize",U),Do(e).reveal==="push"?(l.appendChild(c),l.appendChild(p),a.appendChild(l)):(a.appendChild(c),a.appendChild(p)),D(),T(),{mode:"docked",host:u,shell:a,syncWidgetState(B){let O=B.launcherEnabled?B.open:!0;m!==O&&(m=O,D())},updateConfig(B){e=B,(e?.launcher?.enabled??!0)===!1&&(m=!0),C(),D(),T()},destroy(){W?.removeEventListener("resize",U),E?.(),E=null,h(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(t,s):o.appendChild(t)),a.remove()}}},v0=(t,e)=>nn(e)?RD(t,e):HD(t,e);var Jc={desktop:{w:1280,h:800},mobile:{w:390,h:844}},C0=.15,w0=1.5,Ab="persona-preview-shell-theme",WD={load:()=>null,save:()=>{},clear:()=>{}},BD=["How do I get started?","Pricing & plans","Talk to support"];function Mb(t){return t.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function DD(t){return t==="dark"?{pageBg:"linear-gradient(180deg, #0f172a 0%, #020617 100%)",chromeBg:"#111827",chromeBorder:"#1f2937",dot:"#475569",skeleton:"#334155",cardBg:"#1e293b",cardBorder:"rgba(148, 163, 184, 0.16)"}:{pageBg:"linear-gradient(180deg, #ffffff 0%, #f8fafc 100%)",chromeBg:"#ffffff",chromeBorder:"#e5e7eb",dot:"#cbd5e1",skeleton:"#e2e8f0",cardBg:"#e2e8f0",cardBorder:"rgba(148, 163, 184, 0.18)"}}function x0(t){let e=DD(t);return`* { box-sizing: border-box; }
|
|
1269
1269
|
html, body { margin: 0; padding: 0; height: 100%; overflow: hidden; }
|
|
1270
1270
|
html { color-scheme: ${t}; }
|
|
1271
1271
|
body { font-family: system-ui, sans-serif; background: ${e.pageBg}; }
|
|
@@ -1289,7 +1289,7 @@ _Details: ${n.message}_`:o}var sh=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
1289
1289
|
.preview-workspace-content-shell { position: relative; z-index: 1; flex: 1 1 auto; min-height: 100%; padding: 24px; }
|
|
1290
1290
|
.preview-workspace-row { display: flex; gap: 16px; margin-top: 20px; }
|
|
1291
1291
|
.preview-workspace-card { flex: 1; min-width: 0; height: 168px; border-radius: 18px; background: ${e.cardBg}; box-shadow: inset 0 0 0 1px ${e.cardBorder}; }
|
|
1292
|
-
.preview-workspace-card.short { height: 96px; }`}function
|
|
1292
|
+
.preview-workspace-card.short { height: 96px; }`}function S0(t,e){let n=t.contentDocument;if(!n?.documentElement)return;let o=n.getElementById(Ab);o||(o=n.createElement("style"),o.id=Ab,n.head.appendChild(o)),o.textContent=x0(e)}var OD=`
|
|
1293
1293
|
<div class="preview-iframe-mock" aria-hidden="true">
|
|
1294
1294
|
<div class="preview-iframe-chrome">
|
|
1295
1295
|
<span class="preview-iframe-dot"></span>
|
|
@@ -1308,7 +1308,7 @@ _Details: ${n.message}_`:o}var sh=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
1308
1308
|
<div class="preview-iframe-line body"></div>
|
|
1309
1309
|
<div class="preview-iframe-line body"></div>
|
|
1310
1310
|
</div>
|
|
1311
|
-
</div>`,
|
|
1311
|
+
</div>`,_D=`
|
|
1312
1312
|
<div class="preview-workspace-content-shell" aria-hidden="true">
|
|
1313
1313
|
<div class="preview-iframe-line hero"></div>
|
|
1314
1314
|
<div class="preview-iframe-line body"></div>
|
|
@@ -1321,8 +1321,8 @@ _Details: ${n.message}_`:o}var sh=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
1321
1321
|
<div class="preview-workspace-card short"></div>
|
|
1322
1322
|
<div class="preview-workspace-card short"></div>
|
|
1323
1323
|
</div>
|
|
1324
|
-
</div>`;function
|
|
1325
|
-
${
|
|
1324
|
+
</div>`;function A0(t,e,n,o){let r=`
|
|
1325
|
+
${OD}
|
|
1326
1326
|
<div style="position:fixed;inset:0;z-index:9999;"><div id="${t}" data-mount-id="${t}"></div></div>`,s=`
|
|
1327
1327
|
<div class="preview-workspace-shell">
|
|
1328
1328
|
<div class="preview-workspace-topbar">
|
|
@@ -1334,7 +1334,7 @@ _Details: ${n.message}_`:o}var sh=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
1334
1334
|
</div>
|
|
1335
1335
|
<div class="preview-workspace-body">
|
|
1336
1336
|
<div id="preview-content-${t}" class="preview-workspace-content" data-mount-id="${t}">
|
|
1337
|
-
${
|
|
1337
|
+
${_D}
|
|
1338
1338
|
</div>
|
|
1339
1339
|
</div>
|
|
1340
1340
|
</div>`;return`<!DOCTYPE html>
|
|
@@ -1342,16 +1342,16 @@ _Details: ${n.message}_`:o}var sh=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
1342
1342
|
<head>
|
|
1343
1343
|
<meta charset="UTF-8">
|
|
1344
1344
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
1345
|
-
<link rel="stylesheet" href="${
|
|
1346
|
-
<style id="${
|
|
1345
|
+
<link rel="stylesheet" href="${Mb(o)}">
|
|
1346
|
+
<style id="${Ab}">${x0(e)}</style>
|
|
1347
1347
|
</head>
|
|
1348
1348
|
<body>
|
|
1349
1349
|
${n?s:r}
|
|
1350
1350
|
</body>
|
|
1351
|
-
</html>`}var
|
|
1352
|
-
${D?`<div class="preview-frame-meta"><span class="preview-frame-label">${
|
|
1351
|
+
</html>`}var ND=()=>[{id:"preview-adv-1",role:"user",content:"Can you create the product and gather the docs?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-adv-2",role:"assistant",content:"",createdAt:new Date(Date.now()-15e4).toISOString(),streaming:!0,variant:"reasoning",reasoning:{id:"preview-reasoning",status:"streaming",chunks:["Now let me get the Persona embed documentation and builtin tools catalog."]}},{id:"preview-adv-3",role:"assistant",content:"",createdAt:new Date(Date.now()-12e4).toISOString(),streaming:!0,variant:"tool",toolCall:{id:"preview-tool-1",name:"Load tools",status:"running",chunks:["Loaded tools, used Runtype integration"]}},{id:"preview-adv-4",role:"assistant",content:"",createdAt:new Date(Date.now()-9e4).toISOString(),streaming:!0,variant:"tool",toolCall:{id:"preview-tool-2",name:"Get platform documentation",status:"running",chunks:["Get platform documentation"]}},{id:"preview-adv-5",role:"assistant",content:"I loaded the tools and fetched the docs. Next I can assemble the product details.",createdAt:new Date(Date.now()-3e4).toISOString()}],FD=t=>!!(t?.features?.toolCallDisplay?.activePreview||t?.features?.toolCallDisplay?.grouped||t?.features?.toolCallDisplay?.collapsedMode&&t.features.toolCallDisplay.collapsedMode!=="tool-call"||t?.features?.reasoningDisplay?.activePreview);function VD(t,e,n=[]){if(t==="follow-ups"){let o=Date.now();return[{id:"preview-follow-up-user",role:"user",content:"What can Persona help me build?",createdAt:new Date(o-12e4).toISOString()},{id:"preview-follow-up-assistant",role:"assistant",content:"Persona gives you a themeable streaming chat interface with flexible integrations and interaction patterns. Where would you like to go next?",createdAt:new Date(o-6e4).toISOString()},{id:"preview-follow-up-suggestions",role:"assistant",content:"",createdAt:new Date(o-59e3).toISOString(),streaming:!1,variant:"tool",toolCall:{id:"preview-follow-up-suggestions",name:"suggest_replies",status:"complete",args:{suggestions:[{id:"preview-implementation",label:"Show me an implementation",prompt:"Show me a practical implementation",description:"See a complete integration example",icon:"code-2",emphasis:"primary"},{id:"preview-theming",label:"Explore theming",prompt:"Tell me how theming works",description:"Customize colors, type, and component styles",icon:"palette"},{id:"preview-security",label:"Review security",prompt:"Explain the security model",description:"Learn about isolation and safe rendering",icon:"shield-check"},{id:"preview-support",label:"Talk to support",prompt:"Help me contact support",description:"Get help choosing the right approach",icon:"messages-square"}]},chunks:[]}},...n]}return t==="home"?[]:t==="minimized"?[{id:"preview-min-1",role:"assistant",content:"We are here whenever you are ready.",createdAt:new Date().toISOString()}]:t==="artifact"?[{id:"preview-art-1",role:"user",content:"Can you draft a quick overview of the project?",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-art-2",role:"assistant",content:"Here\u2019s a project overview document for you.",createdAt:new Date(Date.now()-6e4).toISOString()}]:t==="conversation"&&FD(e)?[...ND(),...n]:[{id:"preview-conv-1",role:"assistant",content:"Hello! How can I help you today?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-conv-2",role:"user",content:"I want to customize the theme editor preview.",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-conv-3",role:"assistant",content:"Absolutely. Check out the [getting started guide](https://example.com) to see what\u2019s possible, then adjust colors and tokens to match your brand.",createdAt:new Date(Date.now()-6e4).toISOString()},...n]}function $D(t,e,n=[]){let o={...t.launcher,enabled:!0,autoExpand:e!=="minimized"},r={...t,launcher:o,suggestionChips:e==="home"?t.suggestionChips?.length?t.suggestionChips:BD:t.suggestionChips,initialMessages:VD(e,t,n),storageAdapter:WD};return e==="artifact"&&(r.features={...r.features,artifacts:{...r.features?.artifacts,enabled:!0}}),e==="messages"&&(r.features={...r.features,history:{presentation:"panel",...r.features?.history,enabled:!0}}),r}function zD(t,e){let n=fp(t.config),o=t.config?.future,r=t.theme?Na(t.theme,{validate:!1,future:o}):Na(void 0,{future:o});return{...n,...t.config,theme:r,darkTheme:t.darkTheme,colorScheme:e??t.config?.colorScheme??"light"}}function el(t,e){let n=t.scene??"conversation";return $D(zD(t,e),n,t.appendedMessages??[])}function M0(t){let e=t.compareMode??"off",n=t.shellMode??"light";if(e==="themes")return[{mountId:"preview-light",label:"Light",config:el(t,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:el(t,"dark"),shellMode:"dark"}];if(e==="baseline"&&(t.baselineConfig||t.baselineTheme)){let o={...t,config:t.baselineConfig??t.config,theme:t.baselineTheme??t.theme,darkTheme:t.baselineDarkTheme??t.darkTheme};return[{mountId:"preview-baseline",label:"Baseline",config:el(o,n),shellMode:n},{mountId:"preview-current",label:"Current",config:el(t,n),shellMode:n}]}return[{mountId:"preview-current",label:"Current",config:el(t,n),shellMode:n}]}function T0(t,e){let n={...e},o=[],r=[],s=null,a=!1,l=1,c=1,p=0;function u(){return n.device??"desktop"}function m(){return n.zoom??l}function g(){let T=getComputedStyle(t),R=parseFloat(T.paddingLeft)+parseFloat(T.paddingRight),A=parseFloat(T.paddingTop)+parseFloat(T.paddingBottom),D=40,W=(n.compareMode??"off")!=="off",U=(t.clientWidth-R-D)/(W?2:1),B=t.clientHeight-A-D;if(U<=0||B<=0)return 1;let O=Jc[u()]??Jc.desktop;return Math.min(U/O.w,B/O.h,1)}function h(){l=g();let T=Math.max(C0,Math.min(w0,m()));c=T;let R=Array.from(t.querySelectorAll(".preview-iframe-wrapper"));for(let A of R){let D=A.dataset.device??"desktop",W=Jc[D]??Jc.desktop;A.style.width=`${W.w*T}px`,A.style.height=`${W.h*T}px`,D==="mobile"&&(A.style.borderRadius=`${32*T}px`);let U=A.querySelector("iframe");U&&(U.style.width=`${W.w}px`,U.style.height=`${W.h}px`,U.style.transformOrigin="top left",U.style.transition="none",U.style.transform=`scale(${T})`)}n.onScaleChange?.(T)}function b(){n.onBeforeDestroy?.();for(let T of o)T.destroy();for(let T of r)T();o=[],r=[]}function C(){return Array.from(t.querySelectorAll("iframe[data-mount-id]"))}function M(){if(a)return;b();let T=++p,R=M0(n),A=u(),D=(n.compareMode??"off")!=="off",W=(n.scene??"conversation")==="minimized",U=n.widgetCssPath??"/widget-dist/widget.css",B=n.buildSrcdoc??A0,O=A==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",H=V=>`<div class="${O}" data-mount-id="${V.mountId}" data-device="${A}" data-shell-mode="${V.shellMode}">
|
|
1352
|
+
${D?`<div class="preview-frame-meta"><span class="preview-frame-label">${Mb(V.label)}</span></div>`:""}
|
|
1353
1353
|
<iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${V.mountId}"></iframe>
|
|
1354
|
-
</div>`,S=D?`<div class="preview-compare-grid">${
|
|
1354
|
+
</div>`,S=D?`<div class="preview-compare-grid">${R.map(V=>`<div class="preview-compare-cell">${H(V)}</div>`).join("")}</div>`:`<div class="preview-single">${H(R[0])}</div>`;n.morphContainer?n.morphContainer(t,S):t.innerHTML=S,h();let x=C(),P=0,L=x.length,G=()=>{if(a||T!==p)return;for(let K of x){let ee=K.dataset.mountId;if(!ee||!K.contentDocument)continue;let oe=R.find(Le=>Le.mountId===ee);if(!oe)continue;let ne=()=>{},le=nn(oe.config),de=le?(()=>{let Le=K.contentDocument?.getElementById(`preview-content-${ee}`);if(!Le)return null;let se=v0(Le,oe.config),_=K.contentDocument.createElement("div");_.id=ee,_.style.height="100%",_.style.display="flex",_.style.flexDirection="column",_.style.flex="1",_.style.minHeight="0",se.host.appendChild(_);let Te=()=>se.syncWidgetState(ve.getState()),Re=ne;return ne=()=>{se.destroy(),Re()},_.__syncDock=Te,_.__hostLayout=se,_})():K.contentDocument.getElementById(ee);if(!de)continue;let ve=f0(de,oe.config);if(o.push(ve),le&&de.__syncDock){let Le=de.__syncDock,se=ve.on("widget:opened",Le),_=ve.on("widget:closed",Le),Te=ne;ne=()=>{se(),_(),Te()},Le()}r.push(ne),W&&ve.close()}let V=n.scene??"conversation";if(V==="messages")for(let K of o)K.showHistory({focus:!1});if(V==="artifact"||n.config?.features?.artifacts?.enabled)for(let K of o)K.upsertArtifact({id:"preview-sample",artifactType:"markdown",title:"Sample Document",content:`# Sample Artifact
|
|
1355
1355
|
|
|
1356
1356
|
This is a preview of the artifact sidebar.
|
|
1357
1357
|
|
|
@@ -1359,4 +1359,4 @@ This is a preview of the artifact sidebar.
|
|
|
1359
1359
|
|
|
1360
1360
|
- Markdown rendering
|
|
1361
1361
|
- Document toolbar
|
|
1362
|
-
- Resizable panes`,transcript:!1});n.onAfterMount?.({iframes:x,controllers:[...o]})};for(let V of x){let K=V.dataset.mountId;if(!K)continue;let ee=
|
|
1362
|
+
- Resizable panes`,transcript:!1});n.onAfterMount?.({iframes:x,controllers:[...o]})};for(let V of x){let K=V.dataset.mountId;if(!K)continue;let ee=R.find(oe=>oe.mountId===K);ee&&(V.addEventListener("load",()=>{P++,P>=L&&G()},{once:!0}),V.srcdoc=B(K,ee.shellMode,nn(ee.config),U))}L===0&&G()}function E(){if(a)return;let T=M0(n);if(o.length!==T.length){M();return}if(T.some(A=>{let D=t.querySelector(`.preview-iframe-wrapper[data-mount-id="${A.mountId}"]`);return!D||D.dataset.shellMode!==A.shellMode})){M();return}o.forEach((A,D)=>{A.update(T[D].config),(n.scene??"conversation")==="minimized"&&A.close()});for(let A of T){let D=t.querySelector(`iframe[data-mount-id="${A.mountId}"]`);D&&S0(D,A.shellMode)}n.onAfterUpdate?.({iframes:C(),controllers:[...o]})}return typeof ResizeObserver<"u"&&(s=new ResizeObserver(()=>{a||h()}),s.observe(t)),M(),{update(T){if(a)return;let R=T.device!==void 0&&T.device!==n.device||T.scene!==void 0&&T.scene!==n.scene||T.compareMode!==void 0&&T.compareMode!==n.compareMode||T.widgetCssPath!==void 0&&T.widgetCssPath!==n.widgetCssPath;n={...n,...T},R?M():E()},destroy(){a||(a=!0,b(),s?.disconnect(),t.innerHTML="")},getControllers(){return[...o]},fitToContainer(){a||(n={...n,zoom:void 0},h())},getIframes(){return C()},getScale(){return c},setZoom(T){a||(n={...n,zoom:T},h())}}}0&&(module.exports={createThemePreview});
|