@runtypelabs/persona 4.26.1 → 4.27.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 +5 -0
- package/dist/approval-ui.d.ts +5 -0
- package/dist/artifacts-ui.d.cts +5 -0
- package/dist/artifacts-ui.d.ts +5 -0
- package/dist/chunk-3255TNY7.js +1 -0
- package/dist/{client-history-GOZWBDA5.js → client-history-HTRKHBAF.js} +1 -1
- package/dist/client-history.js +1 -1
- package/dist/client-stream-N22JHTLE.js +4 -0
- package/dist/client-stream.js +3 -3
- package/dist/codegen.cjs +1 -1
- package/dist/codegen.js +1 -1
- package/dist/context-mentions.d.cts +5 -0
- package/dist/context-mentions.d.ts +5 -0
- package/dist/event-stream-view.d.cts +5 -0
- package/dist/event-stream-view.d.ts +5 -0
- package/dist/forms-ui.d.cts +7 -0
- package/dist/forms-ui.d.ts +7 -0
- package/dist/index.cjs +57 -57
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +7 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.global.js +1 -1
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +58 -58
- package/dist/index.js.map +1 -1
- package/dist/session-reconnect.d.cts +5 -0
- package/dist/session-reconnect.d.ts +5 -0
- package/dist/smart-dom-reader.d.cts +5 -0
- package/dist/smart-dom-reader.d.ts +5 -0
- package/dist/theme-editor-preview.cjs +59 -59
- package/dist/theme-editor-preview.d.cts +5 -0
- package/dist/theme-editor-preview.d.ts +5 -0
- package/dist/theme-editor-preview.js +31 -31
- package/dist/theme-editor.d.cts +5 -0
- package/dist/theme-editor.d.ts +5 -0
- package/dist/voice-runtime-RHRX4F3T.js +17 -0
- package/dist/voice-runtime.cjs +8 -8
- package/dist/voice-runtime.d.cts +9 -0
- package/dist/voice-runtime.d.ts +9 -0
- package/dist/voice-runtime.js +8 -8
- package/package.json +1 -1
- package/src/client-stream.ts +10 -3
- package/src/client.test.ts +20 -0
- package/src/session.ts +5 -0
- package/src/session.voice.test.ts +59 -3
- package/src/types.ts +5 -0
- package/src/ui.composer-defer-one.test.ts +17 -0
- package/src/ui.ts +49 -12
- package/src/voice/__fixtures__/voice-wire/server/session_end-provider-error.json +6 -0
- package/src/voice/__fixtures__/voice-wire/server/session_end-unknown-reason.json +4 -0
- package/src/voice/__fixtures__/voice-wire/server/session_end.json +5 -0
- package/src/voice/runtype-voice-provider.ts +112 -10
- package/src/voice/voice-delegation.ts +26 -10
- package/src/voice/voice.test.ts +176 -0
- package/dist/chunk-GKPCIQPB.js +0 -1
- package/dist/client-stream-42FOI3EC.js +0 -4
- package/dist/voice-runtime-XLU6YK2N.js +0 -17
package/dist/index.cjs
CHANGED
|
@@ -1,33 +1,33 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),ya=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},
|
|
1
|
+
"use strict";var _M=Object.create;var yd=Object.defineProperty;var BM=Object.getOwnPropertyDescriptor;var DM=Object.getOwnPropertyNames;var NM=Object.getPrototypeOf,FM=Object.prototype.hasOwnProperty;var Ve=(e,t)=>()=>(e&&(t=e(e=0)),t);var ys=(e,t)=>{for(var n in t)yd(e,n,{get:t[n],enumerable:!0})},nv=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of DM(t))!FM.call(e,r)&&r!==n&&yd(e,r,{get:()=>t[r],enumerable:!(o=BM(t,r))||o.enumerable});return e};var Bn=(e,t,n)=>(n=e!=null?_M(NM(e)):{},nv(t||!e||!e.__esModule?yd(n,"default",{value:e,enumerable:!0}):n,e)),$M=e=>nv(yd({},"__esModule",{value:!0}),e);var lt,dn=Ve(()=>{"use strict";lt=e=>{let{fallbackImport:t,resetOnSetLoader:n=!1}=e,o=null,r=null,s=null;return{setLoader:d=>{o=d,n&&(r=null,s=null)},load:()=>r?Promise.resolve(r):s||(s=(o??t)().then(g=>(r=g,g)).catch(g=>{throw s=null,g}),s),provide:d=>{r=d},getSync:()=>r}}});var sv={};ys(sv,{DOMPurify:()=>rv.default,Marked:()=>ov.Marked});var ov,rv,iv=Ve(()=>{"use strict";ov=require("marked"),rv=Bn(require("dompurify"),1)});var Nt,Lr=Ve(()=>{"use strict";Nt=(e,t=24,n="currentColor",o=2)=>{if(!Array.isArray(e))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(t)),r.setAttribute("height",String(t)),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"),e.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let i=s[0],l=s[1];if(!l)return;let c=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(l).forEach(([p,d])=>{p!=="stroke"&&c.setAttribute(p,String(d))}),r.appendChild(c)}),r}});var JI,jM,Cd,tf=Ve(()=>{"use strict";dn();({setLoader:JI,load:jM}=lt({fallbackImport:()=>import("@runtypelabs/persona/icons-extra")})),Cd=jM});var ee,qM,zM,di,ga,fa,wd,of,uv,rf,gv,fv,nf,KM,GM,ge,kt=Ve(()=>{"use strict";Lr();tf();ee=require("lucide"),qM={activity:ee.Activity,"arrow-down":ee.ArrowDown,"arrow-up":ee.ArrowUp,"arrow-up-right":ee.ArrowUpRight,bot:ee.Bot,"chevron-down":ee.ChevronDown,"chevron-up":ee.ChevronUp,"chevron-right":ee.ChevronRight,"chevron-left":ee.ChevronLeft,check:ee.Check,clipboard:ee.Clipboard,"clipboard-copy":ee.ClipboardCopy,"code-xml":ee.CodeXml,copy:ee.Copy,file:ee.File,"file-code":ee.FileCode,"file-spreadsheet":ee.FileSpreadsheet,"file-text":ee.FileText,"image-plus":ee.ImagePlus,loader:ee.Loader,"loader-circle":ee.LoaderCircle,mic:ee.Mic,paperclip:ee.Paperclip,quote:ee.Quote,"refresh-cw":ee.RefreshCw,search:ee.Search,send:ee.Send,"shield-alert":ee.ShieldAlert,"shield-check":ee.ShieldCheck,"shield-x":ee.ShieldX,square:ee.Square,"thumbs-down":ee.ThumbsDown,"thumbs-up":ee.ThumbsUp,upload:ee.Upload,"volume-2":ee.Volume2,x:ee.X,"at-sign":ee.AtSign,"arrow-left":ee.ArrowLeft,"arrow-right":ee.ArrowRight,"external-link":ee.ExternalLink,ellipsis:ee.Ellipsis,"ellipsis-vertical":ee.EllipsisVertical,menu:ee.Menu,"panel-left":ee.PanelLeft,plus:ee.Plus,minus:ee.Minus,pencil:ee.Pencil,trash:ee.Trash,"trash-2":ee.Trash2,download:ee.Download,maximize:ee.Maximize,minimize:ee.Minimize,"message-square":ee.MessageSquare,star:ee.Star,eye:ee.Eye,history:ee.History},zM=["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"],di=new Map(Object.entries(qM)),ga=new Set,fa=!1,wd=new Set,of=e=>{let t=[...wd];e&&wd.clear();for(let n of t)try{n()}catch{}},uv=e=>fa?()=>{}:(wd.add(e),()=>{wd.delete(e)}),rf=()=>{let e=0;for(let t of[...ga]){let n=di.get(t.name);if(!n)continue;ga.delete(t),e++;let o=Nt(n,t.size,t.color,t.strokeWidth);if(o)for(t.el.removeAttribute("data-persona-icon-pending");o.firstChild;)t.el.appendChild(o.firstChild)}return e},gv=e=>{for(let[t,n]of Object.entries(e))di.set(t,n);rf()>0&&!fa&&of(!1)},fv=e=>{if(!fa){for(let[t,n]of Object.entries(e))di.has(t)||di.set(t,n);fa=!0,rf(),of(!0)}},nf=!1,KM=()=>{Cd().then(e=>{if(!fa){for(let[t,n]of Object.entries(e.EXTRA_LUCIDE_ICONS))di.has(t)||di.set(t,n);fa=!0,rf(),of(!0)}}).catch(e=>{nf=!0,console.warn("[Persona] Failed to load the icons-extra chunk",e)})},GM=(e,t,n)=>{let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(e)),o.setAttribute("height",String(e)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",t),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},ge=(e,t=24,n="currentColor",o=2)=>{let r=di.get(e);if(r)return Nt(r,t,n,o);if(zM.includes(e)){nf&&(nf=!1);let s=GM(t,n,o);if(ga.size>=500){let i=ga.values().next().value;i&&ga.delete(i)}return ga.add({el:s,name:e,size:t,color:n,strokeWidth:o}),KM(),s}return console.warn(`Lucide icon "${e}" 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}});function yv(e){if(e.length===0)return"0:empty";let t=e.map(n=>[n.name,n.description??"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",n.origin??"",n.annotations?JSON.stringify(n.annotations):""].join("")).sort();return`${e.length}:${YM(t.join(""))}`}function hv(e,t){let n=3735928559^t,o=1103547991^t;for(let r=0;r<e.length;r++){let s=e.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 YM(e){let t=hv(e,0).toString(36),n=hv(e,2654435761).toString(36);return`${t}.${n}`}var El,sf,Sd,ma,mv,af,bs,Ad,pi=Ve(()=>{"use strict";El="webmcp:",sf=new Map,Sd=e=>{sf.clear();for(let t of e){let n=t.title?.trim();n&&sf.set(t.name,n)}},ma=e=>sf.get(af(e)),mv=null;af=e=>e.startsWith(El)?e.slice(El.length):e,bs=e=>e.startsWith(El),Ad=()=>mv?mv():import("@mcp-b/webmcp-polyfill")});function Yn(e){return e==="card"?"collapsed":e}function vs(e){return e.split(";",1)[0].trim().toLowerCase()}function XM(e,t){if(!e)return;let n=Object.entries(e);for(let[r,s]of n)if(vs(r)===t)return{mode:Yn(s),selector:vs(r)};let o=`${t.split("/",1)[0]}/*`;for(let[r,s]of n)if(vs(r)===o)return{mode:Yn(s),selector:o}}function lf(e,t){let n=e?.display,o=typeof n=="string"?{default:n}:n??{};if(t.file&&o.files){if(typeof o.files=="string")return{mode:Yn(o.files),matchedBy:{type:"files"}};let l=t.file.mimeType?vs(t.file.mimeType):void 0,c=l?XM(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:Yn(o.files.default),matchedBy:{type:"files"}}}let r=o.byKind?.[t.artifactType];if(r)return{mode:Yn(r),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let s=o.byType?.[t.artifactType];if(s)return{mode:Yn(s),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let i=t.presentation?.preferredMode;return i?{mode:Yn(i),matchedBy:{type:"preferredMode"}}:o.default?{mode:Yn(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function or(e,t){return lf(e,t).mode}function Ml(e,t){return JSON.stringify({component:e==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:t.artifactId,title:t.title,artifactType:t.artifactType,status:t.status,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...e==="inline"&&t.component?{component:t.component}:{},...e==="inline"&&t.componentProps?{componentProps:t.componentProps}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}})}var ha=Ve(()=>{"use strict"});var Hr,xd,ya,QM,bv,JM,ZM,vv,eT,Cv,Ed,Pl,Md,cf,Td,Tl,tT,kl,Pd,kd,Ld,wv,Hd,Cs=Ve(()=>{"use strict";Hr=require("partial-json"),xd=e=>e.replace(/\\n/g,`
|
|
2
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),ya=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},QM=e=>{let t=e.completedAt??Date.now(),n=e.startedAt??t,r=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},bv=e=>e.status==="complete"?QM(e):e.status==="pending"?"Waiting":"",JM=15e3,ZM=1200,vv=(e,t)=>{let n=t?.durationMs??JM,o=t?.chars??ZM;return typeof e.durationMs=="number"?e.durationMs<n:(e.chunks??[]).join("").length<o},eT=e=>{let n=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.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`},Cv=e=>e.status==="complete"?eT(e):"Using tool...",Ed=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Pl=e=>{let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return Ed(t)},Md=e=>{let t=e.durationMs!==void 0?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return Ed(t)},cf=(e,t,n)=>{if(!t)return n;let o=e.name?.trim()||"tool",r=Pl(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},Td=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,i;for(;(i=r.exec(n))!==null;)i.index>s&&Tl(o,n.slice(s,i.index),[]),i[1]!==void 0?Tl(o,i[1],["bold"]):i[2]!==void 0?Tl(o,i[2],["italic"]):i[3]!==void 0&&Tl(o,i[3],["dim"]),s=i.index+i[0].length;return s<n.length&&Tl(o,n.slice(s),[]),o},Tl=(e,t,n)=>{let o=t.split("{duration}");for(let r=0;r<o.length;r++)o[r]&&e.push({text:o[r],styles:n}),r<o.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},tT=()=>{let e=null,t=0,n=o=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=o.match(r);if(s&&s[1])try{return s[1].replace(/\\n/g,`
|
|
3
3
|
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let i=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,l=o.match(i);if(l&&l[1])try{return l[1].replace(/\\n/g,`
|
|
4
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(e=s),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},kl=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Ed=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Td=()=>{let e=XE();return{processChunk:async t=>{let n=t.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:e.close?.bind(e)}},Pd=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let r=(0,Hr.parse)(n,Hr.STR|Hr.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?Sd(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=Sd(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},yv=e=>{let t=null,n=0,r=e||(s=>{if(!s||typeof s!="object")return null;let i=l=>typeof l=="string"?Sd(l):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Sd(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return i(s.on_load_text)||i(s.text)||null;case"message":case"message_and_click":case"checkout":return i(s.text)||null;default:return i(s.text)||i(s.display_text)||i(s.message)||null}return i(s.text)||i(s.display_text)||i(s.message)||i(s.content)||null});return{getExtractedText:()=>t,processChunk:s=>{let i=s.trim();if(!i.startsWith("{")&&!i.startsWith("["))return null;if(s.length<=n)return t!==null?{text:t,raw:s}:null;try{let l=(0,Hr.parse)(s,Hr.STR|Hr.OBJ),c=r(l);c!==null&&(t=c)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},kd=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let o=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(e=o[1],{text:e,raw:t}):null},getExtractedText:()=>e}}});var x,Q,_n,Je=Ve(()=>{"use strict";x=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Q=(e,t={},...n)=>{let o=document.createElement(e);if(t.className&&(o.className=t.className),t.text!==void 0&&(o.textContent=t.text),t.attrs)for(let[s,i]of Object.entries(t.attrs))o.setAttribute(s,i);if(t.style){let s=o.style,i=t.style;for(let l of Object.keys(i)){let c=i[l];c!=null&&(s[l]=c)}}let r=n.filter(s=>s!=null);return r.length>0&&o.append(...r),o},_n=(...e)=>e.filter(Boolean).join(" ")});var ws,Hl,Ll,ba,QE,JE,vv,Cv,ZE,eT,tT,nT,oT,af,lf,wv,cf,Sv,rT,sT,bv,Av,Ir,Ld,Rr,Il,iT,aT,xv,Mv,lT,cT,dT,Ev,pT,uT,ui,Tv,Co,gT,va,Ss,fT,mT,Hd,Pv,kv,df,hT,yT,Lv,Id,Wr,pf,As,Rd,Rl=Ve(()=>{"use strict";ws=require("partial-json");Je();Hl="ask_user_question",Ll=8,ba="data-persona-ask-sheet-for",QE="Other",JE="Other\u2026",vv="Type your own answer here",Cv="Send",ZE="Next",eT="Back",tT="Submit all",nT="Skip",oT=3,af="data-ask-current-index",lf="data-ask-question-count",wv="data-ask-answers",cf="data-ask-grouped",Sv="data-ask-layout",rT=e=>e.layout==="pills"?"pills":"rows",sT=e=>e.getAttribute(Sv)==="pills"?"pills":"rows",bv=!1,Av=e=>e.replace(/["\\]/g,"\\$&"),Ir=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Hl,Ld=e=>e?.features?.askUserQuestion??{},Rr=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let o=t.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}},Il=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>Ll&&!bv&&(bv=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Ll}.`)),t.slice(0,Ll)},iT=e=>Il(e)[0]??null,aT=(e,t)=>Il(e)[t]??null,xv=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},Mv=(e,t,n)=>{if(e!=="rows")return null;let o=x("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=x("span","persona-ask-row-check");o.appendChild(r)}else{let r=x("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},lT=(e,t,n,o)=>{let s=x("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(t)),s.setAttribute("data-option-label",e.label),n==="rows"){let i=x("span","persona-ask-row-content"),l=x("span","persona-ask-row-label");if(l.textContent=e.label,i.appendChild(l),e.description){let p=x("span","persona-ask-row-description");p.textContent=e.description,i.appendChild(p)}s.appendChild(i);let c=Mv(n,o,t);c&&s.appendChild(c)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},cT=e=>{let n=x("span",e==="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},dT=(e,t,n,o)=>{let s=x("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 i=!!e?.multiSelect,c=(Array.isArray(e?.options)?e.options:[]).filter(d=>d&&typeof d.label=="string"&&d.label.length>0);if(c.length===0&&!n){for(let d=0;d<oT;d++)s.appendChild(cT(o));return s}if(c.forEach((d,g)=>{s.appendChild(lT(d,g,o,i))}),e?.allowFreeText!==!1){let d=o==="rows"?QE:JE;if(o==="rows"){let g=x("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");g.setAttribute("data-ask-user-action","focus-free-text"),g.setAttribute("data-option-index",String(c.length)),g.setAttribute("data-ask-other-row","true");let f=x("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=t.freeTextPlaceholder??vv,h.setAttribute("data-ask-free-text-input","true"),h.setAttribute("aria-label",t.freeTextLabel??d),f.appendChild(h),g.appendChild(f);let y=Mv(o,i,c.length);y&&g.appendChild(y),s.appendChild(g)}else{let g=x("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");g.type="button",g.setAttribute("data-ask-user-action","open-free-text"),g.textContent=t.freeTextLabel??d,s.appendChild(g)}}return s},Ev=(e,t)=>{let o=x("div",t==="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=e.freeTextPlaceholder??vv,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let s=x("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=e.submitLabel??Cv,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},pT=e=>{let t=x("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=x("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=e.submitLabel??Cv,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},uT=(e,t,n)=>{let o=x("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=x("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??eT,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let s=x("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),i=x("button","persona-ask-nav-skip persona-pointer-events-auto");i.type="button",i.textContent=n.skipLabel??nT,i.setAttribute("data-ask-user-action","skip"),s.appendChild(i);let l=x("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let c=e===t-1;return l.textContent=c?n.submitAllLabel??tT:n.nextLabel??ZE,l.setAttribute("data-ask-user-action",c?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},ui=e=>{let t=e.getAttribute(wv);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Tv=(e,t)=>{e.setAttribute(wv,JSON.stringify(t))},Co=e=>{let t=Number(e.getAttribute(af)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},gT=(e,t)=>{e.setAttribute(af,String(Math.max(0,Math.floor(t))))},va=e=>{let t=Number(e.getAttribute(lf)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},Ss=e=>e.getAttribute(cf)==="true",fT=(e,t)=>{let n=e.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return t.forEach((r,s)=>{let i=typeof r?.question=="string"?r.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let l=n[i];(typeof l=="string"||Array.isArray(l))&&(o[s]=l)}}),o},mT=(e,t)=>{let n=e.agentMetadata?.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},Hd=(e,t)=>{let{payload:n}=Rr(t),o=Il(n),r=ui(e),s={},i=new Set;return o.forEach((l,c)=>{let p=typeof l?.question=="string"?l.question:"";p&&(i.has(p)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${p}"; later answer wins.`),i.add(p),Object.prototype.hasOwnProperty.call(r,c)&&(s[p]=r[c]))}),s},Pv=e=>{let t=ui(e),n=Co(e),o=t[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(c=>r.add(c));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(c=>{let p=c.getAttribute("data-option-label")??"",d=r.has(p);c.setAttribute("aria-pressed",d?"true":"false"),c.classList.toggle("persona-ask-pill-selected",d)});let i=new Set(Array.from(s).map(c=>c.getAttribute("data-option-label")??"")),l=e.querySelector('[data-ask-free-text-input="true"]');l&&(typeof o=="string"&&o.length>0&&!i.has(o)?(l.value=o,l.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):l.value="")},kv=e=>{if(!Ss(e))return;let t=ui(e),n=Co(e),o=t[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);let i=e.querySelector('[data-ask-user-action="submit-multi"]');if(i){let l=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));i.disabled=l.length===0}},df=(e,t,n)=>{let o=Ld(n),r=sT(e),{payload:s,complete:i}=Rr(t),l=Ss(e),c=Co(e),p=va(e),d=l?aT(s,c):iT(s),g=!!d?.multiSelect,f=e.querySelector('[data-ask-step-inline="true"]');f&&(f.textContent=l?`${c+1}/${p}`:"");let h=e.querySelector('[data-ask-stepper="true"]');h&&h.remove();let y=e.querySelector('[data-ask-question="true"]');if(y){let L=typeof d?.question=="string"?d.question:"";y.textContent=L,y.classList.toggle("persona-ask-question-skeleton",!L&&!i)}let v=e.querySelector('[data-ask-pill-list="true"]');if(v){let L=dT(d,o,i,r);v.replaceWith(L)}if(r!=="rows"){let L=e.querySelector('[data-ask-free-text-row="true"]');L&&L.replaceWith(Ev(o,r))}let C=e.querySelector('[data-ask-multi-actions="true"]');!l&&g&&!C?e.appendChild(pT(o)):(!g||l)&&C&&C.remove(),e.setAttribute("data-multi-select",g?"true":"false");let A=e.querySelector('[data-ask-nav-row="true"]');if(l){let L=uT(c,p,o);A?A.replaceWith(L):e.appendChild(L)}else A&&A.remove();Pv(e),kv(e)},hT=(e,t,n)=>{let o=Ld(t),r=rT(o),s=e.toolCall.id,i=Il(n),l=Math.max(1,i.length),c=l>1,p=fT(e,i),d=c?mT(e,l):0,g=x("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));g.setAttribute(ba,s),g.setAttribute("data-tool-call-id",s),g.setAttribute("data-message-id",e.id),g.setAttribute(lf,String(l)),g.setAttribute(af,String(d)),g.setAttribute(cf,c?"true":"false"),g.setAttribute(Sv,r),Tv(g,p),g.setAttribute("role","group"),g.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&g.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),xv(g,o);let f=x("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),h=x("div","persona-ask-sheet-question persona-flex-1");h.setAttribute("data-ask-question","true"),h.textContent="",f.appendChild(h);let y=x("span","persona-ask-sheet-step-inline");y.setAttribute("data-ask-step-inline","true"),y.textContent="",f.appendChild(y),g.appendChild(f);let C=x("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 C.setAttribute("data-ask-pill-list","true"),C.setAttribute("role","group"),g.appendChild(C),r!=="rows"&&g.appendChild(Ev(o,r)),df(g,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>g.classList.remove("persona-ask-sheet-enter"))}),g},yT=(e,t,n)=>{let{payload:o}=Rr(t),r=Math.max(1,Il(o).length);r>va(e)&&(e.setAttribute(lf,String(r)),r>1&&!Ss(e)&&e.setAttribute(cf,"true")),df(e,t,n)},Lv=(e,t)=>{let n=x("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),n.setAttribute("data-bubble-type","ask-user-question");let o=Ld(t);xv(n,o);let r=x("span","persona-ask-stub-label"),{complete:s}=Rr(e);return r.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(r),n},Id=(e,t,n)=>{if(!n||!Ir(e)||Ld(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${ba}]`).forEach(p=>{p.getAttribute(ba)!==r&&p.remove()});let i=n.querySelector(`[${ba}="${Av(r)}"]`);if(i){yT(i,e,t);return}let{payload:l}=Rr(e),c=hT(e,t,l);n.appendChild(c)},Wr=(e,t)=>{if(!e)return;let n=t?`[${ba}="${Av(t)}"]`:`[${ba}]`;e.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)})},pf=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),As=(e,t)=>{let n=ui(e),o=Co(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,Tv(e,n),Pv(e),kv(e)},Rd=(e,t,n,o)=>{let r=va(e),s=Math.max(0,Math.min(r-1,o));gT(e,s),df(e,t,n)}});var Oo,uf,Wd,Iv,gi,gf,Od,Hv,bT,xs,Ca=Ve(()=>{"use strict";Oo="suggest_replies",uf={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},Wd={name:Oo,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:uf,origin:"sdk",annotations:{readOnlyHint:!0}},Iv=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),gi=e=>e.variant==="tool"&&e.toolCall?.name===Oo,gf=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t?.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 i={label:s.label.trim()};return typeof s.prompt=="string"&&s.prompt.trim()&&(i.prompt=s.prompt.trim()),typeof s.description=="string"&&s.description.trim()&&(i.description=s.description.trim()),[i]});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},Od=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!gi(n))continue;let o=gf(n.toolCall?.args);return o.length>0?o:null}return null},Hv=new Set,bT=(e,t,n)=>{let o=`${e}:${t}:${n}`;Hv.has(o)||(Hv.add(o),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},xs=e=>{let t=e?.suggestions?.followUps,n=e?.features?.suggestReplies,o=i=>{let l=t?.[i],c=n?.[i];l===void 0||c===void 0||l!==c&&bT(i,c,l)};e&&(o("enabled"),o("expose"));let r=t?.enabled??n?.enabled??!0,s=r?t?.expose??n?.expose??!1:!1;return{enabled:r,expose:s}}});var ff,mf,fi,Bd=Ve(()=>{"use strict";Rl();Ca();ff={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Ll,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},mf={name:Hl,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:ff,origin:"sdk",annotations:{readOnlyHint:!0}},fi=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(mf),xs(e).expose&&t.push(Wd),t}});var Yt,kn,wa,_d,Bo=Ve(()=>{"use strict";Yt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},kn=1e5,wa=kn+1,_d="https://api.runtype.com"});async function Rv(e,t,n){let o={"Content-Type":"application/json",...e.headers};e.getHeaders&&Object.assign(o,await e.getHeaders());let r={executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0},s=(p,d)=>fetch(`${e.clientApiBase()}${p}`,{method:"POST",headers:o,body:JSON.stringify({...d,...r})}),i=`/v1/agents/${t.agentId}/approve`;if(!e.isClientTokenMode())return s(i);let{sessionId:l}=await e.initSession(),c=await s("/v1/client/approve",{sessionId:l});if(c.status===404){let p=await c.clone().json().catch(()=>null);if(!p||p.error==="Not Found")return s(i)}return c}async function Wv(e,t,n,o){let r=e.isClientTokenMode(),s=r?e.getClientApiUrl("resume"):`${e.config.apiUrl?.replace(/\/+$/,"")||_d}/resume`,i,l=null;if(r){let d=await e.initSession();i=d.sessionId,d.durableRecovery?.enabled===!0&&(l=await e.readVisitorToken())}let c={"Content-Type":"application/json",...l?{"X-Visitor-Token":l}:{},...e.headers};e.getHeaders&&Object.assign(c,await e.getHeaders());let p={executionId:t,toolOutputs:n,streamResponse:o?.streamResponse??!0,...o?.after?{after:o.after}:{}};if(i&&(p.sessionId=i),r&&i){let d=[...fi(e.config),...await(await e.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:g,commit:f}=await e.sendWithClientToolsDiff(i,d,h=>{let y={...p,...h};return e.debug&&console.debug("[AgentWidgetClient] client token resume",y),fetch(s,{method:"POST",headers:c,body:JSON.stringify(y),signal:o?.signal})},{emptyMeansReplace:!0});return g.ok&&f(),g}return fetch(s,{method:"POST",headers:c,body:JSON.stringify(p),signal:o?.signal})}var Ov=Ve(()=>{"use strict";Bd();Bo()});var Dd={};ys(Dd,{preferFinalStructuredContent:()=>_v,resolveApproval:()=>Rv,resumeFlow:()=>Wv,streamResponse:()=>wT});function vT(e){let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;let r=t.indexOf("/");if(r>0){let s=t.slice(r+1).split(";")[0]?.trim()??"";if(s&&s!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(s))return`attachment.${s}`}return"attachment"}function _v(e,t){if(!e)return t;let n=e.trim(),o=t.trim();if(n.length===0)return t;if(o.length===0)return e;let r=Bv(n);if(!Bv(o))return e;if(!r||o===n||o.startsWith(n))return t;let i=kl(e);return kl(t)!==null&&i===null?t:e}async function CT(e,t,n,o,r,s,i){if(!e.parseSSEEvent)return!1;try{let l=await e.parseSSEEvent(t);if(l===null)return!1;let c=d=>{let g={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...d!==void 0&&{partId:d}};return o.current=g,r(g),g},p=d=>o.current?o.current:c(d);if(l.text!==void 0){l.partId!==void 0&&i.current!==null&&l.partId!==i.current&&(o.current&&(o.current.streaming=!1,r(o.current)),c(l.partId)),l.partId!==void 0&&(i.current=l.partId);let d=p(l.partId);l.partId!==void 0&&!d.partId&&(d.partId=l.partId),d.content+=l.text,r(d)}return l.done&&(o.current&&(o.current.streaming=!1,r(o.current)),i.current=null,n({type:"status",status:"idle"})),l.error&&(i.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 function wT(e,t,n,o,r){let s=t.getReader(),i=new TextDecoder,l="",c=Date.now(),p=0,d=()=>c+p++,g=D=>{let S=D.reasoning?{...D.reasoning,chunks:[...D.reasoning.chunks]}:void 0,F=D.toolCall?{...D.toolCall,chunks:D.toolCall.chunks?[...D.toolCall.chunks]:void 0}:void 0,z=D.tools?D.tools.map(K=>({...K,chunks:K.chunks?[...K.chunks]:void 0})):void 0;return{...D,reasoning:S,toolCall:F,tools:z}},f=D=>{if(D.role!=="assistant"||D.variant)return!0;let S=Array.isArray(D.contentParts)&&D.contentParts.length>0,F=typeof D.rawContent=="string"&&D.rawContent.trim()!=="";return typeof D.content=="string"&&D.content.trim()!==""||S||F||!!D.stopReason},h=D=>{f(D)&&n({type:"message",message:g(D)})},y=null,v=null,C={current:null},A={current:null},L=null,I="",H=new Map,_=new Map,V=new Map,oe=new Map,W=new Map,j=o,X=!1,E=()=>{if(y)return y;let D,S="",F=L;return!X&&j?(D=j,X=!0,S=r??""):j&&F?D=`${j}_${F}`:D=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,y={id:D,role:"assistant",content:S,createdAt:new Date().toISOString(),streaming:!0,sequence:d()},h(y),y},T=D=>{let S=oe.get(D);if(S)return S;let F={id:`reason-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:d(),reasoning:{id:D,status:"streaming",chunks:[]}};return oe.set(D,F),h(F),F},B=new Set,P=new Map,J=new Set,U=new Map,ue=D=>{if(!D)return!1;let S=D.replace(/_+/g,"_").replace(/^_|_$/g,"");return S==="emit_artifact_markdown"||S==="emit_artifact_component"},fe=D=>{let S=W.get(D);if(S)return S;let F={id:`tool-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:d(),toolCall:{id:D,status:"pending"}};return W.set(D,F),h(F),F},me=D=>{if(typeof D=="number"&&Number.isFinite(D))return D;if(typeof D=="string"){let S=Number(D);if(!Number.isNaN(S)&&Number.isFinite(S))return S;let F=Date.parse(D);if(!Number.isNaN(F))return F}return Date.now()},He=D=>{if(typeof D=="string")return D;if(D==null)return"";try{return JSON.stringify(D)}catch{return String(D)}},Ee=new Map,Ie=new Map,yt=(D,S)=>{let F=He(S),z=Ie.get(D.id),K=_v(z,F);D.rawContent=K;let te=Ee.get(D.id),ve=De=>{let Xe=D.content??"";De.trim()!==""&&(Xe.trim().length===0||De.startsWith(Xe)||De.trimStart().startsWith(Xe.trim()))&&(D.content=De)},Ce=()=>{if(te){let De=te.close?.();De instanceof Promise&&De.catch(()=>{})}Ee.delete(D.id),Ie.delete(D.id),D.streaming=!1,h(D)};if(!te){ve(F),Ce();return}let Me=kl(K);if(Me!==null&&Me.trim()!==""){ve(Me),Ce();return}let ot=De=>{let Xe=typeof De=="string"?De:De?.text??null;if(Xe!==null&&Xe.trim()!=="")return Xe;let pn=te.getExtractedText();return pn!==null&&pn.trim()!==""?pn:F},Ct;try{Ct=te.processChunk(K)}catch{ve(F),Ce();return}if(Ct instanceof Promise){Ct.then(De=>{ve(ot(De)),Ce()}).catch(()=>{ve(F),Ce()});return}ve(ot(Ct)),Ce()},qe=null,Oe=(D,S,F,z)=>{D.rawContent=S,Ee.has(D.id)||Ee.set(D.id,e.createStreamParser());let K=Ee.get(D.id),te=S.trim().startsWith("{")||S.trim().startsWith("[");if(te&&Ie.set(D.id,S),K.__isPlainTextParser===!0){D.content=z!==void 0?S:D.content+F,Ie.delete(D.id),Ee.delete(D.id),D.rawContent=void 0,h(D);return}let Ce=K.processChunk(S);if(Ce instanceof Promise)Ce.then(Me=>{let ot=typeof Me=="string"?Me:Me?.text??null;ot!==null&&ot.trim()!==""?(D.content=ot,h(D)):!te&&!S.trim().startsWith("<")&&(D.content=z!==void 0?S:D.content+F,Ie.delete(D.id),Ee.delete(D.id),D.rawContent=void 0,h(D))}).catch(()=>{D.content=z!==void 0?S:D.content+F,Ie.delete(D.id),Ee.delete(D.id),D.rawContent=void 0,h(D)});else{let Me=typeof Ce=="string"?Ce:Ce?.text??null;Me!==null&&Me.trim()!==""?(D.content=Me,h(D)):!te&&!S.trim().startsWith("<")&&(D.content=z!==void 0?S:D.content+F,Ie.delete(D.id),Ee.delete(D.id),D.rawContent=void 0,h(D))}},$=(D,S)=>{let F=S??D.content;if(F==null||F===""){D.streaming=!1,h(D);return}let K=Ie.get(D.id)??He(F);D.rawContent=K;let te=Ee.get(D.id),ve=null,Ce=!1;if(te&&(ve=te.getExtractedText(),ve===null&&(ve=kl(K)),ve===null)){let Me=te.processChunk(K);Me instanceof Promise?(Ce=!0,Me.then(ot=>{let Ct=typeof ot=="string"?ot:ot?.text??null;Ct!==null&&(D.content=Ct,D.streaming=!1,Ee.delete(D.id),Ie.delete(D.id),h(D))}).catch(()=>{})):ve=typeof Me=="string"?Me:Me?.text??null}if(!Ce){ve!==null&&ve.trim()!==""?D.content=ve:Ie.has(D.id)||(D.content=He(F));let Me=Ee.get(D.id);if(Me){let ot=Me.close?.();ot instanceof Promise&&ot.catch(()=>{}),Ee.delete(D.id)}Ie.delete(D.id),D.streaming=!1,h(D)}},Be=(D,S,F)=>{let z=_.get(D);if(z)return z;let K={id:`nested-${S}-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),...F?{variant:F}:{},...F==="reasoning"?{reasoning:{id:D,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:S}};return _.set(D,K),h(K),K},ye=[],ut,Zt=new Map,xt=0,xe="agent",Wt=!1,vt=null,Le=null,Ye=e.config().iterationDisplay??"separate";for(ut=()=>{for(let D=0;D<ye.length;D++){let S=ye[D];if(!Wt&&xe!=="flow"&&typeof S.stepType=="string"&&(xe="flow"),S.type==="reasoning_start"){let F=typeof S.id=="string"?S.id:null,z=typeof S.parentToolCallId=="string"&&S.parentToolCallId?S.parentToolCallId:null;if(F&&z){H.set(F,z),Be(F,z,"reasoning");continue}let K=S.id,te=T(K);te.reasoning=te.reasoning??{id:K,status:"streaming",chunks:[]},te.reasoning.startedAt=te.reasoning.startedAt??Date.now(),te.reasoning.completedAt=void 0,te.reasoning.durationMs=void 0,(S.scope==="loop"||S.scope==="turn")&&(te.reasoning.scope=S.scope),te.streaming=!0,te.reasoning.status="streaming",h(te)}else if(S.type==="reasoning_delta"){let F=typeof S.id=="string"?S.id:null;if(F&&H.has(F)&&_.has(F)){let te=_.get(F),ve=S.delta;ve&&te.reasoning&&(te.reasoning.chunks.push(String(ve)),h(te));continue}let z=S.id,K=T(z);K.reasoning=K.reasoning??{id:z,status:"streaming",chunks:[]},K.reasoning.startedAt=K.reasoning.startedAt??Date.now(),S.delta&&K.reasoning.chunks.push(S.delta),K.reasoning.status="streaming",K.streaming=!0,h(K)}else if(S.type==="reasoning_complete"){let F=typeof S.id=="string"?S.id:null;if(F&&H.has(F)&&_.has(F)){let ve=_.get(F);if(ve.reasoning){let Ce=typeof S.text=="string"?S.text:"";Ce&&ve.reasoning.chunks.length===0&&ve.reasoning.chunks.push(Ce),ve.reasoning.status="complete",ve.streaming=!1,h(ve)}H.delete(F),_.delete(F);continue}let z=S.id,K=typeof S.text=="string"?S.text:"";!oe.get(z)&&(K||S.scope==="loop")&&T(z);let te=oe.get(z);if(te?.reasoning){(S.scope==="loop"||S.scope==="turn")&&(te.reasoning.scope=S.scope),K&&te.reasoning.chunks.length===0&&te.reasoning.chunks.push(K),te.reasoning.status="complete",te.reasoning.completedAt=Date.now();let ve=te.reasoning.startedAt??Date.now();te.reasoning.durationMs=Math.max(0,(te.reasoning.completedAt??Date.now())-ve),te.streaming=!1,h(te)}}else if(S.type==="tool_start"){y&&(y.streaming=!1,h(y),y=null),typeof S.iteration=="number"&&(xt=S.iteration);let F=S.toolCallId,z=S.toolName;if(ue(z)){B.add(F);continue}let K=fe(F),te=K.toolCall??{id:F,status:"pending"};te.name=z??te.name,te.status="running",te.success=void 0,te.error=void 0,te.duration=void 0,S.parameters!==void 0&&(te.args=S.parameters),te.startedAt=te.startedAt??me(S.startedAt),te.completedAt=void 0,te.durationMs=void 0,K.toolCall=te,K.streaming=!0,S.executionId&&(K.agentMetadata={executionId:S.executionId,iteration:S.iteration}),h(K)}else if(S.type==="tool_output_delta"){let F=S.toolCallId;if(B.has(F))continue;let z=fe(F),K=z.toolCall??{id:F,status:"running"};K.startedAt=K.startedAt??Date.now();let te=S.delta;te&&(K.chunks=K.chunks??[],K.chunks.push(String(te))),K.status="running",z.toolCall=K,z.streaming=!0,S.executionId&&(z.agentMetadata=z.agentMetadata??{executionId:S.executionId,iteration:xt}),h(z)}else if(S.type==="tool_complete"){let F=S.toolCallId;if(B.has(F)){B.delete(F);continue}let z=fe(F),K=z.toolCall??{id:F,status:"running"};K.status="complete",S.result!==void 0&&(K.result=S.result),K.name=S.toolName??K.name,K.success=S.success,K.error=S.error,K.completedAt=Date.now();let te=S.executionTime;if(typeof te=="number")K.durationMs=te,K.duration=te;else{let ve=K.startedAt??Date.now();K.durationMs=Math.max(0,(K.completedAt??Date.now())-ve)}z.toolCall=K,z.streaming=!1,S.executionId&&(z.agentMetadata=z.agentMetadata??{executionId:S.executionId,iteration:S.iteration??xt}),h(z)}else if(S.type==="await"&&S.toolName){let F=typeof S.toolCallId=="string"&&S.toolCallId.length>0?S.toolCallId:void 0,z=F??S.toolId??`local-${d()}`,K=fe(z),te=S.toolName,ve=S.origin==="webmcp"&&!bs(te)?`webmcp:${te}`:te,Ce=bs(ve),Me=K.toolCall??{id:z,status:"pending"};Me.name=ve,Me.args=S.parameters,Me.status=Ce?"running":"complete",Me.chunks=Me.chunks??[],Me.startedAt=Me.startedAt??me(S.awaitedAt),Ce?(Me.completedAt=void 0,Me.duration=void 0,Me.durationMs=void 0):Me.completedAt=Me.completedAt??Me.startedAt,K.toolCall=Me,K.streaming=!1,K.agentMetadata={...K.agentMetadata,executionId:S.executionId??K.agentMetadata?.executionId,awaitingLocalTool:!0,...F?{webMcpToolCallId:F}:{}},h(K)}else if(S.type==="text_start"){let F=typeof S.id=="string"?S.id:null,z=typeof S.parentToolCallId=="string"&&S.parentToolCallId?S.parentToolCallId:null;if(F&&z){H.set(F,z);continue}let K=y;K&&(xe==="flow"?($(K),qe=K):(K.streaming=!1,h(K)),y=null),L=typeof S.id=="string"?S.id:L,I=""}else if(S.type==="text_delta"){let F=typeof S.id=="string"?S.id:null,z=F?H.get(F):void 0;if(F&&z){let ve=typeof S.delta=="string"?S.delta:"",Ce=(V.get(F)??"")+ve;if(V.set(F,Ce),Ce.trim()==="")continue;let Me=Be(F,z);Me.agentMetadata={...Me.agentMetadata,executionId:S.executionId,parentToolId:z},Oe(Me,Ce,ve,void 0);continue}if(L=typeof S.id=="string"?S.id:L,xe==="flow"){let ve=typeof S.delta=="string"?S.delta:"";if(I+=ve,I.trim()==="")continue;let Ce=E();Ce.agentMetadata={executionId:S.executionId,iteration:xt},Oe(Ce,I,ve,void 0),v=Ce;continue}let K=typeof S.delta=="string"?S.delta:"";I+=K;let te=E();te.agentMetadata={executionId:S.executionId,iteration:xt,turnId:vt??void 0,agentName:Le?.agentName},Oe(te,I,K,void 0),v=te}else if(S.type==="text_complete"){let F=typeof S.id=="string"?S.id:null;if(F&&H.has(F)){let K=_.get(F);K&&$(K),H.delete(F),V.delete(F),_.delete(F);continue}let z=y;z&&(xe==="flow"?($(z),qe=z):((z.content??"")===""&&typeof S.text=="string"&&(z.content=S.text),z.streaming=!1,h(z)),y=null),L=null,I=""}else if(S.type==="step_complete"){if(S.stepType==="tool")continue;if(S.success===!1){let F=S.error||"Step failed";n({type:"error",error:new Error(F)});let z=y;z&&z.streaming&&(z.streaming=!1,h(z)),n({type:"status",status:"idle"});continue}{let F=qe;qe=null;let z=S.stopReason,te=(S.result&&typeof S.result=="object"?S.result:null)?.response;if(F)z&&(F.stopReason=z),te!=null?yt(F,te):F.streaming!==!1&&(Ee.delete(F.id),Ie.delete(F.id),F.streaming=!1,h(F));else{let ve=te!=null&&te!=="";if(ve||z){let Ce=E();z&&(Ce.stopReason=z),ve?$(Ce,te):(Ce.streaming=!1,h(Ce))}}continue}}else if(S.type==="execution_start")xe=S.kind==="flow"?"flow":"agent",Wt=!0,xe==="agent"&&(Le={executionId:S.executionId,agentId:S.agentId??"virtual",agentName:S.agentName??""});else if(S.type==="turn_start"){let F=typeof S.iteration=="number"?S.iteration:xt;if(F!==xt){if(Ye==="separate"&&F>1){let z=y;z&&(z.streaming=!1,h(z),y=null)}xt=F}vt=typeof S.id=="string"?S.id:null,v=null}else if(S.type==="tool_input_delta"){let F=S.toolCallId;if(F){let z=W.get(F);z?.toolCall&&(z.toolCall.chunks=z.toolCall.chunks??[],z.toolCall.chunks.push(S.delta??""),h(z))}}else if(S.type==="tool_input_complete"){if(B.has(S.toolCallId))continue;let F=fe(S.toolCallId),z=F.toolCall;z.args=S.parameters,z.name=S.toolName??z.name,h(F)}else if(S.type==="turn_complete"){let F=S.stopReason,z=y??v;if(F&&z!==null){let K=S.id;(!K||z.agentMetadata?.turnId===K)&&(z.stopReason=F,h(z))}vt===S.id&&(vt=null)}else if(S.type==="media_start"){let F=String(S.id);Zt.set(F,{mediaType:typeof S.mediaType=="string"?S.mediaType:void 0,toolCallId:S.toolCallId,parts:[]})}else if(S.type==="media_delta"){let F=Zt.get(String(S.id));F&&typeof S.delta=="string"&&F.parts.push(S.delta)}else if(S.type==="media_complete"){let F=String(S.id),z=Zt.get(F);Zt.delete(F);let K=(typeof S.mediaType=="string"?S.mediaType:void 0)??z?.mediaType??"application/octet-stream",te=typeof S.data=="string"?S.data:void 0,ve=typeof S.url=="string"?S.url:z&&z.parts.length>0?z.parts.join(""):void 0,Ce=null;if(te)Ce={type:"media",data:te,mediaType:K};else if(ve){let De=K.toLowerCase();Ce={type:De==="image"||De.startsWith("image/")?"image-url":"file-url",url:ve,mediaType:K}}let Me=S.toolCallId??z?.toolCallId,ot=Ce?[Ce]:[],Ct=[];for(let De of ot){if(!De||typeof De!="object")continue;let Xe=De,pn=typeof Xe.type=="string"?Xe.type:void 0,xo=typeof Xe.mediaType=="string"?Xe.mediaType.toLowerCase():"",ft=null,bt="";if(pn==="media"){let Ft=typeof Xe.data=="string"?Xe.data:void 0;if(!Ft)continue;bt=xo.length>0?xo:"application/octet-stream",ft=`data:${bt};base64,${Ft}`}else if(pn==="image-url"){let Ft=typeof Xe.url=="string"?Xe.url:void 0;if(!Ft)continue;bt=xo,ft=Ft}else if(pn==="file-url"){let Ft=typeof Xe.url=="string"?Xe.url:void 0;if(!Ft)continue;bt=xo,ft=Ft}else continue;if(ft)if(pn==="image-url"||bt.startsWith("image/"))Ct.push({type:"image",image:ft,...bt.includes("/")?{mimeType:bt}:{}});else if(bt.startsWith("audio/"))Ct.push({type:"audio",audio:ft,mimeType:bt});else if(bt.startsWith("video/"))Ct.push({type:"video",video:ft,mimeType:bt});else{let Ft=bt||"application/octet-stream";Ct.push({type:"file",data:ft,mimeType:Ft,filename:vT(Ft)})}}if(Ct.length>0){let De=d(),Xe=Me,xo={id:`agent-media-${typeof Xe=="string"&&Xe.length>0?`${Xe}-${De}`:String(De)}`,role:"assistant",content:"",contentParts:Ct,createdAt:new Date().toISOString(),streaming:!1,sequence:De,agentMetadata:{executionId:S.executionId,iteration:xt}};h(xo);let ft=y;ft&&(ft.streaming=!1,h(ft)),y=null,C.current=null}}else if(S.type==="execution_complete"){let F=y;F&&(S.kind==="flow"&&F.streaming!==!1?$(F):(F.streaming=!1,h(F)),y=null),L=null,I="",qe=null,n({type:"status",status:"idle",terminal:!0})}else if(S.type==="execution_error"){let F=typeof S.error=="string"?S.error:S.error?.message??"Execution error";n({type:"error",error:new Error(F)})}else if(S.type!=="ping"){if(S.type==="approval_start"){let F=S.approvalId??`approval-${d()}`,z={id:`approval-${F}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:F,status:"pending",agentId:Le?.agentId??"virtual",executionId:S.executionId??Le?.executionId??"",toolName:S.toolName??"",toolType:S.toolType,description:S.description??`Execute ${S.toolName??"tool"}`,...typeof S.reason=="string"&&S.reason?{reason:S.reason}:{},parameters:S.parameters,...typeof S.toolCallId=="string"&&S.toolCallId?{toolCallId:S.toolCallId}:{}}};h(z)}else if(S.type==="approval_complete"){let F=S.approvalId;if(F){let K={id:`approval-${F}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:F,status:S.decision??"approved",agentId:Le?.agentId??"virtual",executionId:S.executionId??Le?.executionId??"",toolName:"",description:"",resolvedAt:Date.now()}};h(K)}}else if(S.type==="artifact_start"||S.type==="artifact_delta"||S.type==="artifact_update"||S.type==="artifact_complete"){if(S.type==="artifact_start"){let F=S.artifactType,z=String(S.id),K=typeof S.title=="string"?S.title:void 0,te=S.file,ve;if(te&&typeof te=="object"&&!Array.isArray(te)&&typeof te.path=="string"&&typeof te.mimeType=="string"&&(ve={path:te.path,mimeType:te.mimeType,...typeof te.language=="string"?{language:te.language}:{}}),n({type:"artifact_start",id:z,artifactType:F,title:K,component:typeof S.component=="string"?S.component:void 0,...ve?{file:ve}:{}}),U.set(z,{markdown:"",title:K,file:ve}),!J.has(z)){J.add(z);let Ce=or(e.config().features?.artifacts,{artifactType:F,...ve?{file:ve}:{}}),Me=typeof S.component=="string"?S.component:void 0,ot={id:`artifact-ref-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),rawContent:El(Ce,{artifactId:z,title:K,artifactType:F,status:"streaming",...ve?{file:ve}:{},...Me?{component:Me}:{}})};P.set(z,ot),h(ot)}}else if(S.type==="artifact_delta"){let F=String(S.id),z=typeof S.delta=="string"?S.delta:String(S.delta??"");n({type:"artifact_delta",id:F,artDelta:z});let K=U.get(F);K&&(K.markdown+=z)}else if(S.type==="artifact_update"){let F=S.props&&typeof S.props=="object"&&!Array.isArray(S.props)?S.props:{};n({type:"artifact_update",id:String(S.id),props:F,component:typeof S.component=="string"?S.component:void 0});let z=U.get(String(S.id));z&&(z.props={...z.props??{},...F})}else if(S.type==="artifact_complete"){let F=String(S.id);n({type:"artifact_complete",id:F});let z=P.get(F);if(z){z.streaming=!1;try{let K=JSON.parse(z.rawContent??"{}");if(K.props){K.props.status="complete";let te=U.get(F);te?.markdown&&(K.props.markdown=te.markdown),te?.file&&(K.props.file=te.file),K.component==="PersonaArtifactInline"&&te?.props&&Object.keys(te.props).length>0&&(K.props.componentProps=te.props)}z.rawContent=JSON.stringify(K)}catch{}U.delete(F),h(z),P.delete(F)}}}else if(S.type==="error"&&S.recoverable===!1&&S.error!=null&&S.error!==""){let F=typeof S.error=="string"?S.error:S.error?.message!=null?String(S.error.message):"Execution error";n({type:"error",error:new Error(F)});let z=y;z&&z.streaming&&(z.streaming=!1,h(z)),n({type:"status",status:"idle"})}}}ye.length=0};;){let{done:D,value:S}=await s.read();if(D)break;l+=i.decode(S,{stream:!0});let F=l.split(`
|
|
4
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(e=s),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},kl=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Pd=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},kd=()=>{let e=tT();return{processChunk:async t=>{let n=t.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:e.close?.bind(e)}},Ld=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let r=(0,Hr.parse)(n,Hr.STR|Hr.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?xd(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=xd(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},wv=e=>{let t=null,n=0,r=e||(s=>{if(!s||typeof s!="object")return null;let i=l=>typeof l=="string"?xd(l):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?xd(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return i(s.on_load_text)||i(s.text)||null;case"message":case"message_and_click":case"checkout":return i(s.text)||null;default:return i(s.text)||i(s.display_text)||i(s.message)||null}return i(s.text)||i(s.display_text)||i(s.message)||i(s.content)||null});return{getExtractedText:()=>t,processChunk:s=>{let i=s.trim();if(!i.startsWith("{")&&!i.startsWith("["))return null;if(s.length<=n)return t!==null?{text:t,raw:s}:null;try{let l=(0,Hr.parse)(s,Hr.STR|Hr.OBJ),c=r(l);c!==null&&(t=c)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},Hd=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let o=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(e=o[1],{text:e,raw:t}):null},getExtractedText:()=>e}}});var x,Q,Dn,Ze=Ve(()=>{"use strict";x=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Q=(e,t={},...n)=>{let o=document.createElement(e);if(t.className&&(o.className=t.className),t.text!==void 0&&(o.textContent=t.text),t.attrs)for(let[s,i]of Object.entries(t.attrs))o.setAttribute(s,i);if(t.style){let s=o.style,i=t.style;for(let l of Object.keys(i)){let c=i[l];c!=null&&(s[l]=c)}}let r=n.filter(s=>s!=null);return r.length>0&&o.append(...r),o},Dn=(...e)=>e.filter(Boolean).join(" ")});var ws,Hl,Ll,ba,nT,oT,Av,xv,rT,sT,iT,aT,lT,df,pf,Ev,uf,Mv,cT,dT,Sv,Tv,Ir,Id,Rr,Il,pT,uT,Pv,kv,gT,fT,mT,Lv,hT,yT,ui,Hv,wo,bT,va,Ss,vT,CT,Rd,Iv,Rv,gf,wT,ST,Wv,Wd,Wr,ff,As,Od,Rl=Ve(()=>{"use strict";ws=require("partial-json");Ze();Hl="ask_user_question",Ll=8,ba="data-persona-ask-sheet-for",nT="Other",oT="Other\u2026",Av="Type your own answer here",xv="Send",rT="Next",sT="Back",iT="Submit all",aT="Skip",lT=3,df="data-ask-current-index",pf="data-ask-question-count",Ev="data-ask-answers",uf="data-ask-grouped",Mv="data-ask-layout",cT=e=>e.layout==="pills"?"pills":"rows",dT=e=>e.getAttribute(Mv)==="pills"?"pills":"rows",Sv=!1,Tv=e=>e.replace(/["\\]/g,"\\$&"),Ir=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Hl,Id=e=>e?.features?.askUserQuestion??{},Rr=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let o=t.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}},Il=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>Ll&&!Sv&&(Sv=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Ll}.`)),t.slice(0,Ll)},pT=e=>Il(e)[0]??null,uT=(e,t)=>Il(e)[t]??null,Pv=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},kv=(e,t,n)=>{if(e!=="rows")return null;let o=x("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=x("span","persona-ask-row-check");o.appendChild(r)}else{let r=x("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},gT=(e,t,n,o)=>{let s=x("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(t)),s.setAttribute("data-option-label",e.label),n==="rows"){let i=x("span","persona-ask-row-content"),l=x("span","persona-ask-row-label");if(l.textContent=e.label,i.appendChild(l),e.description){let p=x("span","persona-ask-row-description");p.textContent=e.description,i.appendChild(p)}s.appendChild(i);let c=kv(n,o,t);c&&s.appendChild(c)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},fT=e=>{let n=x("span",e==="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},mT=(e,t,n,o)=>{let s=x("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 i=!!e?.multiSelect,c=(Array.isArray(e?.options)?e.options:[]).filter(d=>d&&typeof d.label=="string"&&d.label.length>0);if(c.length===0&&!n){for(let d=0;d<lT;d++)s.appendChild(fT(o));return s}if(c.forEach((d,g)=>{s.appendChild(gT(d,g,o,i))}),e?.allowFreeText!==!1){let d=o==="rows"?nT:oT;if(o==="rows"){let g=x("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");g.setAttribute("data-ask-user-action","focus-free-text"),g.setAttribute("data-option-index",String(c.length)),g.setAttribute("data-ask-other-row","true");let f=x("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=t.freeTextPlaceholder??Av,h.setAttribute("data-ask-free-text-input","true"),h.setAttribute("aria-label",t.freeTextLabel??d),f.appendChild(h),g.appendChild(f);let y=kv(o,i,c.length);y&&g.appendChild(y),s.appendChild(g)}else{let g=x("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");g.type="button",g.setAttribute("data-ask-user-action","open-free-text"),g.textContent=t.freeTextLabel??d,s.appendChild(g)}}return s},Lv=(e,t)=>{let o=x("div",t==="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=e.freeTextPlaceholder??Av,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let s=x("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=e.submitLabel??xv,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},hT=e=>{let t=x("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=x("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=e.submitLabel??xv,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},yT=(e,t,n)=>{let o=x("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=x("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??sT,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let s=x("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),i=x("button","persona-ask-nav-skip persona-pointer-events-auto");i.type="button",i.textContent=n.skipLabel??aT,i.setAttribute("data-ask-user-action","skip"),s.appendChild(i);let l=x("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let c=e===t-1;return l.textContent=c?n.submitAllLabel??iT:n.nextLabel??rT,l.setAttribute("data-ask-user-action",c?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},ui=e=>{let t=e.getAttribute(Ev);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Hv=(e,t)=>{e.setAttribute(Ev,JSON.stringify(t))},wo=e=>{let t=Number(e.getAttribute(df)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},bT=(e,t)=>{e.setAttribute(df,String(Math.max(0,Math.floor(t))))},va=e=>{let t=Number(e.getAttribute(pf)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},Ss=e=>e.getAttribute(uf)==="true",vT=(e,t)=>{let n=e.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return t.forEach((r,s)=>{let i=typeof r?.question=="string"?r.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let l=n[i];(typeof l=="string"||Array.isArray(l))&&(o[s]=l)}}),o},CT=(e,t)=>{let n=e.agentMetadata?.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},Rd=(e,t)=>{let{payload:n}=Rr(t),o=Il(n),r=ui(e),s={},i=new Set;return o.forEach((l,c)=>{let p=typeof l?.question=="string"?l.question:"";p&&(i.has(p)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${p}"; later answer wins.`),i.add(p),Object.prototype.hasOwnProperty.call(r,c)&&(s[p]=r[c]))}),s},Iv=e=>{let t=ui(e),n=wo(e),o=t[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(c=>r.add(c));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(c=>{let p=c.getAttribute("data-option-label")??"",d=r.has(p);c.setAttribute("aria-pressed",d?"true":"false"),c.classList.toggle("persona-ask-pill-selected",d)});let i=new Set(Array.from(s).map(c=>c.getAttribute("data-option-label")??"")),l=e.querySelector('[data-ask-free-text-input="true"]');l&&(typeof o=="string"&&o.length>0&&!i.has(o)?(l.value=o,l.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):l.value="")},Rv=e=>{if(!Ss(e))return;let t=ui(e),n=wo(e),o=t[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);let i=e.querySelector('[data-ask-user-action="submit-multi"]');if(i){let l=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));i.disabled=l.length===0}},gf=(e,t,n)=>{let o=Id(n),r=dT(e),{payload:s,complete:i}=Rr(t),l=Ss(e),c=wo(e),p=va(e),d=l?uT(s,c):pT(s),g=!!d?.multiSelect,f=e.querySelector('[data-ask-step-inline="true"]');f&&(f.textContent=l?`${c+1}/${p}`:"");let h=e.querySelector('[data-ask-stepper="true"]');h&&h.remove();let y=e.querySelector('[data-ask-question="true"]');if(y){let L=typeof d?.question=="string"?d.question:"";y.textContent=L,y.classList.toggle("persona-ask-question-skeleton",!L&&!i)}let v=e.querySelector('[data-ask-pill-list="true"]');if(v){let L=mT(d,o,i,r);v.replaceWith(L)}if(r!=="rows"){let L=e.querySelector('[data-ask-free-text-row="true"]');L&&L.replaceWith(Lv(o,r))}let C=e.querySelector('[data-ask-multi-actions="true"]');!l&&g&&!C?e.appendChild(hT(o)):(!g||l)&&C&&C.remove(),e.setAttribute("data-multi-select",g?"true":"false");let A=e.querySelector('[data-ask-nav-row="true"]');if(l){let L=yT(c,p,o);A?A.replaceWith(L):e.appendChild(L)}else A&&A.remove();Iv(e),Rv(e)},wT=(e,t,n)=>{let o=Id(t),r=cT(o),s=e.toolCall.id,i=Il(n),l=Math.max(1,i.length),c=l>1,p=vT(e,i),d=c?CT(e,l):0,g=x("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));g.setAttribute(ba,s),g.setAttribute("data-tool-call-id",s),g.setAttribute("data-message-id",e.id),g.setAttribute(pf,String(l)),g.setAttribute(df,String(d)),g.setAttribute(uf,c?"true":"false"),g.setAttribute(Mv,r),Hv(g,p),g.setAttribute("role","group"),g.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&g.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),Pv(g,o);let f=x("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),h=x("div","persona-ask-sheet-question persona-flex-1");h.setAttribute("data-ask-question","true"),h.textContent="",f.appendChild(h);let y=x("span","persona-ask-sheet-step-inline");y.setAttribute("data-ask-step-inline","true"),y.textContent="",f.appendChild(y),g.appendChild(f);let C=x("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 C.setAttribute("data-ask-pill-list","true"),C.setAttribute("role","group"),g.appendChild(C),r!=="rows"&&g.appendChild(Lv(o,r)),gf(g,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>g.classList.remove("persona-ask-sheet-enter"))}),g},ST=(e,t,n)=>{let{payload:o}=Rr(t),r=Math.max(1,Il(o).length);r>va(e)&&(e.setAttribute(pf,String(r)),r>1&&!Ss(e)&&e.setAttribute(uf,"true")),gf(e,t,n)},Wv=(e,t)=>{let n=x("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),n.setAttribute("data-bubble-type","ask-user-question");let o=Id(t);Pv(n,o);let r=x("span","persona-ask-stub-label"),{complete:s}=Rr(e);return r.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(r),n},Wd=(e,t,n)=>{if(!n||!Ir(e)||Id(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${ba}]`).forEach(p=>{p.getAttribute(ba)!==r&&p.remove()});let i=n.querySelector(`[${ba}="${Tv(r)}"]`);if(i){ST(i,e,t);return}let{payload:l}=Rr(e),c=wT(e,t,l);n.appendChild(c)},Wr=(e,t)=>{if(!e)return;let n=t?`[${ba}="${Tv(t)}"]`:`[${ba}]`;e.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)})},ff=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),As=(e,t)=>{let n=ui(e),o=wo(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,Hv(e,n),Iv(e),Rv(e)},Od=(e,t,n,o)=>{let r=va(e),s=Math.max(0,Math.min(r-1,o));bT(e,s),gf(e,t,n)}});var Oo,mf,_d,_v,gi,hf,Bd,Ov,AT,xs,Ca=Ve(()=>{"use strict";Oo="suggest_replies",mf={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},_d={name:Oo,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:mf,origin:"sdk",annotations:{readOnlyHint:!0}},_v=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),gi=e=>e.variant==="tool"&&e.toolCall?.name===Oo,hf=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t?.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 i={label:s.label.trim()};return typeof s.prompt=="string"&&s.prompt.trim()&&(i.prompt=s.prompt.trim()),typeof s.description=="string"&&s.description.trim()&&(i.description=s.description.trim()),[i]});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},Bd=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!gi(n))continue;let o=hf(n.toolCall?.args);return o.length>0?o:null}return null},Ov=new Set,AT=(e,t,n)=>{let o=`${e}:${t}:${n}`;Ov.has(o)||(Ov.add(o),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},xs=e=>{let t=e?.suggestions?.followUps,n=e?.features?.suggestReplies,o=i=>{let l=t?.[i],c=n?.[i];l===void 0||c===void 0||l!==c&&AT(i,c,l)};e&&(o("enabled"),o("expose"));let r=t?.enabled??n?.enabled??!0,s=r?t?.expose??n?.expose??!1:!1;return{enabled:r,expose:s}}});var yf,bf,fi,Dd=Ve(()=>{"use strict";Rl();Ca();yf={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Ll,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},bf={name:Hl,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:yf,origin:"sdk",annotations:{readOnlyHint:!0}},fi=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(bf),xs(e).expose&&t.push(_d),t}});var Yt,kn,wa,Nd,_o=Ve(()=>{"use strict";Yt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},kn=1e5,wa=kn+1,Nd="https://api.runtype.com"});async function Bv(e,t,n){let o={"Content-Type":"application/json",...e.headers};e.getHeaders&&Object.assign(o,await e.getHeaders());let r={executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0},s=(p,d)=>fetch(`${e.clientApiBase()}${p}`,{method:"POST",headers:o,body:JSON.stringify({...d,...r})}),i=`/v1/agents/${t.agentId}/approve`;if(!e.isClientTokenMode())return s(i);let{sessionId:l}=await e.initSession(),c=await s("/v1/client/approve",{sessionId:l});if(c.status===404){let p=await c.clone().json().catch(()=>null);if(!p||p.error==="Not Found")return s(i)}return c}async function Dv(e,t,n,o){let r=e.isClientTokenMode(),s=r?e.getClientApiUrl("resume"):`${e.config.apiUrl?.replace(/\/+$/,"")||Nd}/resume`,i,l=null;if(r){let d=await e.initSession();i=d.sessionId,d.durableRecovery?.enabled===!0&&(l=await e.readVisitorToken())}let c={"Content-Type":"application/json",...l?{"X-Visitor-Token":l}:{},...e.headers};e.getHeaders&&Object.assign(c,await e.getHeaders());let p={executionId:t,toolOutputs:n,streamResponse:o?.streamResponse??!0,...o?.after?{after:o.after}:{}};if(i&&(p.sessionId=i),r&&i){let d=[...fi(e.config),...await(await e.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:g,commit:f}=await e.sendWithClientToolsDiff(i,d,h=>{let y={...p,...h};return e.debug&&console.debug("[AgentWidgetClient] client token resume",y),fetch(s,{method:"POST",headers:c,body:JSON.stringify(y),signal:o?.signal})},{emptyMeansReplace:!0});return g.ok&&f(),g}return fetch(s,{method:"POST",headers:c,body:JSON.stringify(p),signal:o?.signal})}var Nv=Ve(()=>{"use strict";Dd();_o()});var Fd={};ys(Fd,{preferFinalStructuredContent:()=>$v,resolveApproval:()=>Bv,resumeFlow:()=>Dv,streamResponse:()=>MT});function xT(e){let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;let r=t.indexOf("/");if(r>0){let s=t.slice(r+1).split(";")[0]?.trim()??"";if(s&&s!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(s))return`attachment.${s}`}return"attachment"}function $v(e,t){if(!e)return t;let n=e.trim(),o=t.trim();if(n.length===0)return t;if(o.length===0)return e;let r=Fv(n);if(!Fv(o))return e;if(!r||o===n||o.startsWith(n))return t;let i=kl(e);return kl(t)!==null&&i===null?t:e}async function ET(e,t,n,o,r,s,i){if(!e.parseSSEEvent)return!1;try{let l=await e.parseSSEEvent(t);if(l===null)return!1;let c=d=>{let g={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...d!==void 0&&{partId:d}};return o.current=g,r(g),g},p=d=>o.current?o.current:c(d);if(l.text!==void 0){l.partId!==void 0&&i.current!==null&&l.partId!==i.current&&(o.current&&(o.current.streaming=!1,r(o.current)),c(l.partId)),l.partId!==void 0&&(i.current=l.partId);let d=p(l.partId);l.partId!==void 0&&!d.partId&&(d.partId=l.partId),d.content+=l.text,r(d)}return l.done&&(o.current&&(o.current.streaming=!1,r(o.current)),i.current=null,n({type:"status",status:"idle"})),l.error&&(i.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 function MT(e,t,n,o,r){let s=t.getReader(),i=new TextDecoder,l="",c=Date.now(),p=0,d=()=>c+p++,g=D=>{let S=D.reasoning?{...D.reasoning,chunks:[...D.reasoning.chunks]}:void 0,F=D.toolCall?{...D.toolCall,chunks:D.toolCall.chunks?[...D.toolCall.chunks]:void 0}:void 0,q=D.tools?D.tools.map(K=>({...K,chunks:K.chunks?[...K.chunks]:void 0})):void 0;return{...D,reasoning:S,toolCall:F,tools:q}},f=D=>{if(D.role!=="assistant"||D.variant)return!0;let S=Array.isArray(D.contentParts)&&D.contentParts.length>0,F=typeof D.rawContent=="string"&&D.rawContent.trim()!=="";return typeof D.content=="string"&&D.content.trim()!==""||S||F||!!D.stopReason},h=D=>{f(D)&&n({type:"message",message:g(D)})},y=null,v=null,C={current:null},A={current:null},L=null,I="",H=new Map,B=new Map,V=new Map,oe=new Map,W=new Map,j=o,X=!1,M=()=>{if(y)return y;let D,S="",F=L;return!X&&j?(D=j,X=!0,S=r??""):j&&F?D=`${j}_${F}`:D=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,y={id:D,role:"assistant",content:S,createdAt:new Date().toISOString(),streaming:!0,sequence:d()},h(y),y},T=D=>{let S=oe.get(D);if(S)return S;let F={id:`reason-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:d(),reasoning:{id:D,status:"streaming",chunks:[]}};return oe.set(D,F),h(F),F},_=new Set,P=new Map,J=new Set,U=new Map,ue=D=>{if(!D)return!1;let S=D.replace(/_+/g,"_").replace(/^_|_$/g,"");return S==="emit_artifact_markdown"||S==="emit_artifact_component"},fe=D=>{let S=W.get(D);if(S)return S;let F={id:`tool-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:d(),toolCall:{id:D,status:"pending"}};return W.set(D,F),h(F),F},me=D=>{if(typeof D=="number"&&Number.isFinite(D))return D;if(typeof D=="string"){let S=Number(D);if(!Number.isNaN(S)&&Number.isFinite(S))return S;let F=Date.parse(D);if(!Number.isNaN(F))return F}return Date.now()},He=D=>{if(typeof D=="string")return D;if(D==null)return"";try{return JSON.stringify(D)}catch{return String(D)}},Ee=new Map,Ie=new Map,yt=(D,S)=>{let F=He(S),q=Ie.get(D.id),K=$v(q,F);D.rawContent=K;let te=Ee.get(D.id),ve=De=>{let Qe=D.content??"";De.trim()!==""&&(Qe.trim().length===0||De.startsWith(Qe)||De.trimStart().startsWith(Qe.trim()))&&(D.content=De)},Me=()=>{if(te){let De=te.close?.();De instanceof Promise&&De.catch(()=>{})}Ee.delete(D.id),Ie.delete(D.id),D.streaming=!1,h(D)};if(!te){ve(F),Me();return}let Ce=kl(K);if(Ce!==null&&Ce.trim()!==""){ve(Ce),Me();return}let st=De=>{let Qe=typeof De=="string"?De:De?.text??null;if(Qe!==null&&Qe.trim()!=="")return Qe;let pn=te.getExtractedText();return pn!==null&&pn.trim()!==""?pn:F},Ct;try{Ct=te.processChunk(K)}catch{ve(F),Me();return}if(Ct instanceof Promise){Ct.then(De=>{ve(st(De)),Me()}).catch(()=>{ve(F),Me()});return}ve(st(Ct)),Me()},qe=null,Oe=(D,S,F,q)=>{D.rawContent=S,Ee.has(D.id)||Ee.set(D.id,e.createStreamParser());let K=Ee.get(D.id),te=S.trim().startsWith("{")||S.trim().startsWith("[");if(te&&Ie.set(D.id,S),K.__isPlainTextParser===!0){D.content=q!==void 0?S:D.content+F,Ie.delete(D.id),Ee.delete(D.id),D.rawContent=void 0,h(D);return}let Me=K.processChunk(S);if(Me instanceof Promise)Me.then(Ce=>{let st=typeof Ce=="string"?Ce:Ce?.text??null;st!==null&&st.trim()!==""?(D.content=st,h(D)):!te&&!S.trim().startsWith("<")&&(D.content=q!==void 0?S:D.content+F,Ie.delete(D.id),Ee.delete(D.id),D.rawContent=void 0,h(D))}).catch(()=>{D.content=q!==void 0?S:D.content+F,Ie.delete(D.id),Ee.delete(D.id),D.rawContent=void 0,h(D)});else{let Ce=typeof Me=="string"?Me:Me?.text??null;Ce!==null&&Ce.trim()!==""?(D.content=Ce,h(D)):!te&&!S.trim().startsWith("<")&&(D.content=q!==void 0?S:D.content+F,Ie.delete(D.id),Ee.delete(D.id),D.rawContent=void 0,h(D))}},$=(D,S)=>{let F=S??D.content;if(F==null||F===""){D.streaming=!1,h(D);return}let K=Ie.get(D.id)??He(F);D.rawContent=K;let te=Ee.get(D.id),ve=null,Me=!1;if(te&&(ve=te.getExtractedText(),ve===null&&(ve=kl(K)),ve===null)){let Ce=te.processChunk(K);Ce instanceof Promise?(Me=!0,Ce.then(st=>{let Ct=typeof st=="string"?st:st?.text??null;Ct!==null&&(D.content=Ct,D.streaming=!1,Ee.delete(D.id),Ie.delete(D.id),h(D))}).catch(()=>{})):ve=typeof Ce=="string"?Ce:Ce?.text??null}if(!Me){ve!==null&&ve.trim()!==""?D.content=ve:Ie.has(D.id)||(D.content=He(F));let Ce=Ee.get(D.id);if(Ce){let st=Ce.close?.();st instanceof Promise&&st.catch(()=>{}),Ee.delete(D.id)}Ie.delete(D.id),D.streaming=!1,h(D)}},_e=(D,S,F)=>{let q=B.get(D);if(q)return q;let K={id:`nested-${S}-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),...F?{variant:F}:{},...F==="reasoning"?{reasoning:{id:D,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:S}};return B.set(D,K),h(K),K},ye=[],ut,Zt=new Map,xt=0,xe="agent",Wt=!1,vt=null,Le=null,Xe=e.config().iterationDisplay??"separate";for(ut=()=>{for(let D=0;D<ye.length;D++){let S=ye[D];if(!Wt&&xe!=="flow"&&typeof S.stepType=="string"&&(xe="flow"),S.type==="reasoning_start"){let F=typeof S.id=="string"?S.id:null,q=typeof S.parentToolCallId=="string"&&S.parentToolCallId?S.parentToolCallId:null;if(F&&q){H.set(F,q),_e(F,q,"reasoning");continue}let K=S.id,te=T(K);te.reasoning=te.reasoning??{id:K,status:"streaming",chunks:[]},te.reasoning.startedAt=te.reasoning.startedAt??Date.now(),te.reasoning.completedAt=void 0,te.reasoning.durationMs=void 0,(S.scope==="loop"||S.scope==="turn")&&(te.reasoning.scope=S.scope),te.streaming=!0,te.reasoning.status="streaming",h(te)}else if(S.type==="reasoning_delta"){let F=typeof S.id=="string"?S.id:null;if(F&&H.has(F)&&B.has(F)){let te=B.get(F),ve=S.delta;ve&&te.reasoning&&(te.reasoning.chunks.push(String(ve)),h(te));continue}let q=S.id,K=T(q);K.reasoning=K.reasoning??{id:q,status:"streaming",chunks:[]},K.reasoning.startedAt=K.reasoning.startedAt??Date.now(),S.delta&&K.reasoning.chunks.push(S.delta),K.reasoning.status="streaming",K.streaming=!0,h(K)}else if(S.type==="reasoning_complete"){let F=typeof S.id=="string"?S.id:null;if(F&&H.has(F)&&B.has(F)){let ve=B.get(F);if(ve.reasoning){let Me=typeof S.text=="string"?S.text:"";Me&&ve.reasoning.chunks.length===0&&ve.reasoning.chunks.push(Me),ve.reasoning.status="complete",ve.streaming=!1,h(ve)}H.delete(F),B.delete(F);continue}let q=S.id,K=typeof S.text=="string"?S.text:"";!oe.get(q)&&(K||S.scope==="loop")&&T(q);let te=oe.get(q);if(te?.reasoning){(S.scope==="loop"||S.scope==="turn")&&(te.reasoning.scope=S.scope),K&&te.reasoning.chunks.length===0&&te.reasoning.chunks.push(K),te.reasoning.status="complete",te.reasoning.completedAt=Date.now();let ve=te.reasoning.startedAt??Date.now();te.reasoning.durationMs=Math.max(0,(te.reasoning.completedAt??Date.now())-ve),te.streaming=!1,h(te)}}else if(S.type==="tool_start"){y&&(y.streaming=!1,h(y),y=null),typeof S.iteration=="number"&&(xt=S.iteration);let F=S.toolCallId,q=S.toolName;if(ue(q)){_.add(F);continue}let K=fe(F),te=K.toolCall??{id:F,status:"pending"};te.name=q??te.name,te.status="running",te.success=void 0,te.error=void 0,te.duration=void 0,S.parameters!==void 0&&(te.args=S.parameters),te.startedAt=te.startedAt??me(S.startedAt),te.completedAt=void 0,te.durationMs=void 0,K.toolCall=te,K.streaming=!0,S.executionId&&(K.agentMetadata={executionId:S.executionId,iteration:S.iteration}),h(K)}else if(S.type==="tool_output_delta"){let F=S.toolCallId;if(_.has(F))continue;let q=fe(F),K=q.toolCall??{id:F,status:"running"};K.startedAt=K.startedAt??Date.now();let te=S.delta;te&&(K.chunks=K.chunks??[],K.chunks.push(String(te))),K.status="running",q.toolCall=K,q.streaming=!0,S.executionId&&(q.agentMetadata=q.agentMetadata??{executionId:S.executionId,iteration:xt}),h(q)}else if(S.type==="tool_complete"){let F=S.toolCallId;if(_.has(F)){_.delete(F);continue}let q=fe(F),K=q.toolCall??{id:F,status:"running"};K.status="complete",S.result!==void 0&&(K.result=S.result),K.name=S.toolName??K.name,K.success=S.success,K.error=S.error,K.completedAt=Date.now();let te=S.executionTime;if(typeof te=="number")K.durationMs=te,K.duration=te;else{let ve=K.startedAt??Date.now();K.durationMs=Math.max(0,(K.completedAt??Date.now())-ve)}q.toolCall=K,q.streaming=!1,S.executionId&&(q.agentMetadata=q.agentMetadata??{executionId:S.executionId,iteration:S.iteration??xt}),h(q)}else if(S.type==="await"&&S.toolName){let F=typeof S.toolCallId=="string"&&S.toolCallId.length>0?S.toolCallId:void 0,q=F??S.toolId??`local-${d()}`,K=fe(q),te=S.toolName,ve=S.origin==="webmcp"&&!bs(te)?`webmcp:${te}`:te,Me=bs(ve),Ce=K.toolCall??{id:q,status:"pending"};Ce.name=ve,Ce.args=S.parameters,Ce.status=Me?"running":"complete",Ce.chunks=Ce.chunks??[],Ce.startedAt=Ce.startedAt??me(S.awaitedAt),Me?(Ce.completedAt=void 0,Ce.duration=void 0,Ce.durationMs=void 0):Ce.completedAt=Ce.completedAt??Ce.startedAt,K.toolCall=Ce,K.streaming=!1,K.agentMetadata={...K.agentMetadata,executionId:S.executionId??K.agentMetadata?.executionId,awaitingLocalTool:!0,...F?{webMcpToolCallId:F}:{}},h(K)}else if(S.type==="text_start"){let F=typeof S.id=="string"?S.id:null,q=typeof S.parentToolCallId=="string"&&S.parentToolCallId?S.parentToolCallId:null;if(F&&q){H.set(F,q);continue}let K=y;K&&(xe==="flow"?($(K),qe=K):(K.streaming=!1,h(K)),y=null),L=typeof S.id=="string"?S.id:L,I=""}else if(S.type==="text_delta"){let F=typeof S.id=="string"?S.id:null,q=F?H.get(F):void 0;if(F&&q){let ve=typeof S.delta=="string"?S.delta:"",Me=(V.get(F)??"")+ve;if(V.set(F,Me),Me.trim()==="")continue;let Ce=_e(F,q);Ce.agentMetadata={...Ce.agentMetadata,executionId:S.executionId,parentToolId:q},Oe(Ce,Me,ve,void 0);continue}if(L=typeof S.id=="string"?S.id:L,xe==="flow"){let ve=typeof S.delta=="string"?S.delta:"";if(I+=ve,I.trim()==="")continue;let Me=M();Me.agentMetadata={executionId:S.executionId,iteration:xt},Oe(Me,I,ve,void 0),v=Me;continue}let K=typeof S.delta=="string"?S.delta:"";I+=K;let te=M();te.agentMetadata={executionId:S.executionId,iteration:xt,turnId:vt??void 0,agentName:Le?.agentName},Oe(te,I,K,void 0),v=te}else if(S.type==="text_complete"){let F=typeof S.id=="string"?S.id:null;if(F&&H.has(F)){let K=B.get(F);K&&$(K),H.delete(F),V.delete(F),B.delete(F);continue}let q=y;q&&(xe==="flow"?($(q),qe=q):((q.content??"")===""&&typeof S.text=="string"&&(q.content=S.text),q.streaming=!1,h(q)),y=null),L=null,I=""}else if(S.type==="step_complete"){if(S.stepType==="tool")continue;if(S.success===!1){let F=S.error||"Step failed";n({type:"error",error:new Error(F)});let q=y;q&&q.streaming&&(q.streaming=!1,h(q)),n({type:"status",status:"idle"});continue}{let F=qe;qe=null;let q=S.stopReason,te=(S.result&&typeof S.result=="object"?S.result:null)?.response;if(F)q&&(F.stopReason=q),te!=null?yt(F,te):F.streaming!==!1&&(Ee.delete(F.id),Ie.delete(F.id),F.streaming=!1,h(F));else{let ve=te!=null&&te!=="";if(ve||!!q&&q!=="end_turn"&&q!=="unknown"){let Ce=M();q&&(Ce.stopReason=q),ve?$(Ce,te):(Ce.streaming=!1,h(Ce))}}continue}}else if(S.type==="execution_start")xe=S.kind==="flow"?"flow":"agent",Wt=!0,xe==="agent"&&(Le={executionId:S.executionId,agentId:S.agentId??"virtual",agentName:S.agentName??""});else if(S.type==="turn_start"){let F=typeof S.iteration=="number"?S.iteration:xt;if(F!==xt){if(Xe==="separate"&&F>1){let q=y;q&&(q.streaming=!1,h(q),y=null)}xt=F}vt=typeof S.id=="string"?S.id:null,v=null}else if(S.type==="tool_input_delta"){let F=S.toolCallId;if(F){let q=W.get(F);q?.toolCall&&(q.toolCall.chunks=q.toolCall.chunks??[],q.toolCall.chunks.push(S.delta??""),h(q))}}else if(S.type==="tool_input_complete"){if(_.has(S.toolCallId))continue;let F=fe(S.toolCallId),q=F.toolCall;q.args=S.parameters,q.name=S.toolName??q.name,h(F)}else if(S.type==="turn_complete"){let F=S.stopReason,q=y??v;if(F&&q!==null){let K=S.id;(!K||q.agentMetadata?.turnId===K)&&(q.stopReason=F,h(q))}vt===S.id&&(vt=null)}else if(S.type==="media_start"){let F=String(S.id);Zt.set(F,{mediaType:typeof S.mediaType=="string"?S.mediaType:void 0,toolCallId:S.toolCallId,parts:[]})}else if(S.type==="media_delta"){let F=Zt.get(String(S.id));F&&typeof S.delta=="string"&&F.parts.push(S.delta)}else if(S.type==="media_complete"){let F=String(S.id),q=Zt.get(F);Zt.delete(F);let K=(typeof S.mediaType=="string"?S.mediaType:void 0)??q?.mediaType??"application/octet-stream",te=typeof S.data=="string"?S.data:void 0,ve=typeof S.url=="string"?S.url:q&&q.parts.length>0?q.parts.join(""):void 0,Me=null;if(te)Me={type:"media",data:te,mediaType:K};else if(ve){let De=K.toLowerCase();Me={type:De==="image"||De.startsWith("image/")?"image-url":"file-url",url:ve,mediaType:K}}let Ce=S.toolCallId??q?.toolCallId,st=Me?[Me]:[],Ct=[];for(let De of st){if(!De||typeof De!="object")continue;let Qe=De,pn=typeof Qe.type=="string"?Qe.type:void 0,Eo=typeof Qe.mediaType=="string"?Qe.mediaType.toLowerCase():"",ft=null,bt="";if(pn==="media"){let Ft=typeof Qe.data=="string"?Qe.data:void 0;if(!Ft)continue;bt=Eo.length>0?Eo:"application/octet-stream",ft=`data:${bt};base64,${Ft}`}else if(pn==="image-url"){let Ft=typeof Qe.url=="string"?Qe.url:void 0;if(!Ft)continue;bt=Eo,ft=Ft}else if(pn==="file-url"){let Ft=typeof Qe.url=="string"?Qe.url:void 0;if(!Ft)continue;bt=Eo,ft=Ft}else continue;if(ft)if(pn==="image-url"||bt.startsWith("image/"))Ct.push({type:"image",image:ft,...bt.includes("/")?{mimeType:bt}:{}});else if(bt.startsWith("audio/"))Ct.push({type:"audio",audio:ft,mimeType:bt});else if(bt.startsWith("video/"))Ct.push({type:"video",video:ft,mimeType:bt});else{let Ft=bt||"application/octet-stream";Ct.push({type:"file",data:ft,mimeType:Ft,filename:xT(Ft)})}}if(Ct.length>0){let De=d(),Qe=Ce,Eo={id:`agent-media-${typeof Qe=="string"&&Qe.length>0?`${Qe}-${De}`:String(De)}`,role:"assistant",content:"",contentParts:Ct,createdAt:new Date().toISOString(),streaming:!1,sequence:De,agentMetadata:{executionId:S.executionId,iteration:xt}};h(Eo);let ft=y;ft&&(ft.streaming=!1,h(ft)),y=null,C.current=null}}else if(S.type==="execution_complete"){let F=y;F&&(S.kind==="flow"&&F.streaming!==!1?$(F):(F.streaming=!1,h(F)),y=null),L=null,I="",qe=null,n({type:"status",status:"idle",terminal:!0})}else if(S.type==="execution_error"){let F=typeof S.error=="string"?S.error:S.error?.message??"Execution error";n({type:"error",error:new Error(F)})}else if(S.type!=="ping"){if(S.type==="approval_start"){let F=S.approvalId??`approval-${d()}`,q={id:`approval-${F}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:F,status:"pending",agentId:Le?.agentId??"virtual",executionId:S.executionId??Le?.executionId??"",toolName:S.toolName??"",toolType:S.toolType,description:S.description??`Execute ${S.toolName??"tool"}`,...typeof S.reason=="string"&&S.reason?{reason:S.reason}:{},parameters:S.parameters,...typeof S.toolCallId=="string"&&S.toolCallId?{toolCallId:S.toolCallId}:{}}};h(q)}else if(S.type==="approval_complete"){let F=S.approvalId;if(F){let K={id:`approval-${F}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:F,status:S.decision??"approved",agentId:Le?.agentId??"virtual",executionId:S.executionId??Le?.executionId??"",toolName:"",description:"",resolvedAt:Date.now()}};h(K)}}else if(S.type==="artifact_start"||S.type==="artifact_delta"||S.type==="artifact_update"||S.type==="artifact_complete"){if(S.type==="artifact_start"){let F=S.artifactType,q=String(S.id),K=typeof S.title=="string"?S.title:void 0,te=S.file,ve;if(te&&typeof te=="object"&&!Array.isArray(te)&&typeof te.path=="string"&&typeof te.mimeType=="string"&&(ve={path:te.path,mimeType:te.mimeType,...typeof te.language=="string"?{language:te.language}:{}}),n({type:"artifact_start",id:q,artifactType:F,title:K,component:typeof S.component=="string"?S.component:void 0,...ve?{file:ve}:{}}),U.set(q,{markdown:"",title:K,file:ve}),!J.has(q)){J.add(q);let Me=or(e.config().features?.artifacts,{artifactType:F,...ve?{file:ve}:{}}),Ce=typeof S.component=="string"?S.component:void 0,st={id:`artifact-ref-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),rawContent:Ml(Me,{artifactId:q,title:K,artifactType:F,status:"streaming",...ve?{file:ve}:{},...Ce?{component:Ce}:{}})};P.set(q,st),h(st)}}else if(S.type==="artifact_delta"){let F=String(S.id),q=typeof S.delta=="string"?S.delta:String(S.delta??"");n({type:"artifact_delta",id:F,artDelta:q});let K=U.get(F);K&&(K.markdown+=q)}else if(S.type==="artifact_update"){let F=S.props&&typeof S.props=="object"&&!Array.isArray(S.props)?S.props:{};n({type:"artifact_update",id:String(S.id),props:F,component:typeof S.component=="string"?S.component:void 0});let q=U.get(String(S.id));q&&(q.props={...q.props??{},...F})}else if(S.type==="artifact_complete"){let F=String(S.id);n({type:"artifact_complete",id:F});let q=P.get(F);if(q){q.streaming=!1;try{let K=JSON.parse(q.rawContent??"{}");if(K.props){K.props.status="complete";let te=U.get(F);te?.markdown&&(K.props.markdown=te.markdown),te?.file&&(K.props.file=te.file),K.component==="PersonaArtifactInline"&&te?.props&&Object.keys(te.props).length>0&&(K.props.componentProps=te.props)}q.rawContent=JSON.stringify(K)}catch{}U.delete(F),h(q),P.delete(F)}}}else if(S.type==="error"&&S.recoverable===!1&&S.error!=null&&S.error!==""){let F=typeof S.error=="string"?S.error:S.error?.message!=null?String(S.error.message):"Execution error";n({type:"error",error:new Error(F)});let q=y;q&&q.streaming&&(q.streaming=!1,h(q)),n({type:"status",status:"idle"})}}}ye.length=0};;){let{done:D,value:S}=await s.read();if(D)break;l+=i.decode(S,{stream:!0});let F=l.split(`
|
|
5
5
|
|
|
6
|
-
`);l=F.pop()??"";for(let
|
|
7
|
-
`),te="message",ve="",Ce=null;for(let Xe of K)Xe.startsWith("event:")?te=Xe.replace("event:","").trim():Xe.startsWith("data:")?ve+=Xe.replace("data:","").trim():Xe.startsWith("id:")&&(Ce=Xe.slice(3).trim());let Me=()=>{Ce!==null&&Ce!==""&&n({type:"cursor",id:Ce})};if(!ve){Me();continue}let ot;try{ot=JSON.parse(ve)}catch(Xe){n({type:"error",error:Xe instanceof Error?Xe:new Error("Failed to parse chat stream payload")});continue}let Ct=ot!==null&&typeof ot=="object"&&!Array.isArray(ot)?ot:null,De=te!=="message"?te:typeof Ct?.type=="string"?Ct.type:"message";if(e.onSSEEvent?.(De,ot),e.parseSSEEvent){C.current=y;let Xe=await CT(e,ot,n,C,h,d,A);if(C.current&&C.current!==y&&(y=C.current),Xe){Me();continue}}Ct&&(ye.push({...Ct,type:De}),ut()),Me()}}ut()}var Bv,hf=Ve(()=>{"use strict";pi();ha();Cs();Ov();Bv=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<")});var $v,Fv=Ve(()=>{$v="4.26.1"});var Yn,Sa=Ve(()=>{"use strict";Fv();Yn=$v});var Nd={};ys(Nd,{deleteAllConversations:()=>OT,deleteConversation:()=>WT,finalizeDisplayProjections:()=>RT,getConversation:()=>IT,historyErrorFor:()=>Yv,listConversations:()=>HT,readErrorCode:()=>bf,recoverFromUnauthorized:()=>Gv,resetVisitor:()=>BT});function ET(e,t,n){let o=new URLSearchParams;for(let[s,i]of Object.entries(n))i===void 0||i===""||o.set(s,String(i));let r=o.toString();return`${e.clientApiBase()}/v1/client/${t}${r?`?${r}`:""}`}function TT(e,t){if(t)return t;let n=e.config.features?.history?.scope;return n||(e.config.getIdentityProof?"verified-user":"browser")}async function PT(e,t,n){let o=e.config.getIdentityProof;if(!o)return n&&e.setHistoryIdentityStatus(e.browserOnlyStatus()),null;n&&e.setHistoryIdentityStatus({state:"verifying"});let r;try{r=await o()??null}catch{throw n&&e.setHistoryIdentityStatus({state:"identity_provider_failed"}),new e.HistoryClientError("identity_provider_failed","The identity proof provider failed")}if(r)return r;if(t.visitor?.endUserId!=null)throw n&&e.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new e.HistoryClientError("authentication_required","This browser is bound to a signed-in user and needs a fresh identity proof");return n&&e.setHistoryIdentityStatus({state:"browser_only",reason:"proof_unavailable_before_binding"}),null}async function kT(e,t,n,o){if(t.visitor?.endUserId!=null)return t;let r=await e.reinitWithProof(n);if(!(r.visitor?.identityStatus==="admitted"&&r.visitor?.endUserId!=null))throw o&&e.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new e.HistoryClientError("proof_not_admitted",jv);return r}async function bf(e,t){let n=await t.json().catch(()=>({}));return typeof n.error=="string"?n.error:typeof n.message=="string"?n.message:""}async function Gv(e,t,n,o){let r=t.toLowerCase();if(r.includes("invalid_identity_proof"))throw o&&e.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new e.HistoryClientError("invalid_identity_proof",qv);if(r.includes("visitor token required"))throw new e.HistoryClientError("visitor_token_missing",zv);if(r.includes("visitor_identity_mismatch")){if(!n)throw o&&e.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new e.HistoryClientError("visitor_identity_mismatch",Kv);return e.reinitWithProof(n)}if(r.includes("expired")||r.includes("not found"))return e.clearClientSession(),e.initSession();throw new e.HistoryClientError("unauthorized",t||"History request was not authorized")}async function Yv(e,t,n){let o=await bf(e,t);if(t.status===404)return new e.HistoryClientError("not_found","Conversation not found");if(t.status===429){let r=Number.parseInt(t.headers.get("Retry-After")??"",10);return new e.HistoryClientError("rate_limited","Too many history requests",{...Number.isFinite(r)?{retryAfterSeconds:r}:{}})}if(t.status===503&&o.includes("identity_proof_not_admitted"))return n&&e.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new e.HistoryClientError("proof_not_admitted",jv);if(t.status===401){let r=o.toLowerCase();return r.includes("invalid_identity_proof")?(n&&e.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new e.HistoryClientError("invalid_identity_proof",qv)):r.includes("visitor token required")?new e.HistoryClientError("visitor_token_missing",zv):r.includes("visitor_identity_mismatch")?new e.HistoryClientError("visitor_identity_mismatch",Kv):new e.HistoryClientError("unauthorized",o||"History request was not authorized")}return new e.HistoryClientError("request_failed",o||`History request failed (${t.status})`)}function LT(e,t,n,o){let r=t?.toLowerCase()??null;if(n){if(r==="admitted"){o&&e.setHistoryIdentityStatus({state:"verified"});return}throw o&&e.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),r==="ignored"?new e.HistoryClientError("identity_contract_violation","Server reported an ignored identity proof on a success response"):new e.HistoryClientError("proof_not_admitted","The response did not acknowledge the identity proof this request sent")}if(r==="admitted")throw new e.HistoryClientError("identity_contract_violation","Server admitted an identity proof that was never sent");o&&e.setHistoryIdentityStatus(e.browserOnlyStatus())}async function Aa(e,t,n){vf(e);let o=n.trackIdentity!==!1,r=await e.initSession(),s=null;TT(e,n.scope)==="verified-user"&&(s=await PT(e,r,o),s&&(r=await kT(e,r,s,o)));let i=e.historyInternals.visitorStore,l=!1;for(;;){let c=i?.revision()??0,p=await e.readVisitorToken();if(!p&&!n.visitorTokenOptional)throw new e.HistoryClientError("visitor_token_missing","No visitor credential is stored for this browser");let d=await fetch(ET(e,t,{...n.query,sessionId:r.sessionId}),{method:n.method,headers:{"X-Persona-Version":Yn,...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(d.status===401&&!l){l=!0,r=await Gv(e,await bf(e,d),s,o);continue}if(!d.ok)throw await Yv(e,d,o);let g=d.headers.get("X-History-Identity-Status"),f=await d.json().catch(()=>{});if(i&&i.revision()!==c)throw new e.HistoryClientError("credential_changed","The visitor credential changed while the request was in flight");return LT(e,g,s!==null,o),f}}function vf(e){if(!e.isClientTokenMode())throw new Error("Conversation history is only available in client token mode");if(!e.isHistoryCapable())throw new e.HistoryClientError("history_disabled","Visitor history is disabled for this surface")}async function HT(e,t){let n=await Aa(e,"conversations",{method:"GET",query:{...t?.cursor?{cursor:t.cursor}:{},...t?.limit!==void 0?{limit:t.limit}:{},...t?.targetId?{targetId:t.targetId}:{}},...t?.scope?{scope:t.scope}:{}});return{data:(Array.isArray(n?.data)?n.data:[]).map(Vv),nextCursor:typeof n?.nextCursor=="string"?n.nextCursor:null}}async function IT(e,t,n){let o=await Aa(e,`conversations/${encodeURIComponent(t)}`,{method:"GET",query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}});return{summary:Vv(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 function RT(e,t,n){vf(e);let o=0;for(let c of n){let p=c.displayContent.length;if(p>Uv)throw new e.HistoryClientError("payload_too_large",`displayContent exceeds the ${Uv} character limit`);o+=p}if(o>yf)throw new e.HistoryClientError("payload_too_large",`Display projection batch exceeds the ${yf} character limit`);await e.initSession();let r=e.historyInternals.visitorStore,s=r?.revision()??0,i=await Aa(e,`conversations/${encodeURIComponent(t)}/display-projections`,{method:"PATCH",body:{messages:n},scope:"browser",keepalive:o<=yf,trackIdentity:!1}),l=typeof i?.conversationRevision=="string"?i.conversationRevision:null;return l&&e.clientSession?.conversationId===t&&(r?.revision()??0)===s&&e.historyInternals.setStoredConversationRevision?.(l),{conversationRevision:l}}async function WT(e,t,n){let o=await Aa(e,`conversations/${encodeURIComponent(t)}`,{method:"DELETE",...n?.scope?{scope:n.scope}:{}});return{deleted:typeof o?.deleted=="number"?o.deleted:0}}async function OT(e,t){let n=await Aa(e,"conversations",{method:"DELETE",query:{...t?.targetId!==void 0?{targetId:t.targetId}:{}},...t?.scope?{scope:t.scope}:{}});return{deleted:typeof n?.deleted=="number"?n.deleted:0}}async function BT(e){vf(e),e.setHistoryIdentityStatus({state:"resetting"});try{await Aa(e,"visitor/reset",{method:"POST",scope:"browser",visitorTokenOptional:!0})}finally{await e.historyInternals.visitorStore?.clear(),e.setHistoryIdentityStatus(e.derivedBrowserOnly())}return{reset:!0}}var Uv,yf,Vv,jv,qv,zv,Kv,Cf=Ve(()=>{"use strict";Sa();Uv=32768,yf=49152,Vv=e=>{let t=e??{},n=typeof t.targetId=="string"?t.targetId:null;return{id:typeof t.id=="string"?t.id:"",title:typeof t.title=="string"?t.title:"",targetId:n,preview:typeof t.preview=="string"?t.preview:null,messageCount:typeof t.messageCount=="number"?t.messageCount:0,createdAt:typeof t.createdAt=="string"?t.createdAt:"",updatedAt:typeof t.updatedAt=="string"?t.updatedAt:""}},jv="The identity proof was not admitted; account history is unavailable",qv="The identity proof was rejected",zv="The request carried no visitor credential",Kv="The stored visitor belongs to a different signed-in user"});var Qv,Jv=Ve(()=>{"use strict";Rl();Qv=e=>{let{mount:t,overlay:n,sessionRef:o}=e,r=(d,g,f)=>{let h=g.trim();if(!h||!o.current)return;let y=d.getAttribute("data-tool-call-id")??"",v=f.source==="free-text";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:y,answer:h,answers:f.structured,values:f.values??(f.source==="multi"?h.split(", "):[h]),isFreeText:v,source:f.source},bubbles:!0,composed:!0})),Wr(n,y);let C=o.current.getMessages().find(A=>A.toolCall?.id===y);C?.agentMetadata?.awaitingLocalTool?o.current.resolveAskUserQuestion(C,f.structured??h):o.current.sendMessage(h)},s=d=>{let g=o.current;if(!g)return;let f=d.getAttribute("data-tool-call-id")??"",h=g.getMessages().find(y=>y.toolCall?.id===f);h&&g.persistAskUserQuestionProgress(h,{answers:Hd(d,h),currentIndex:Co(d)})},i=d=>Object.entries(d).map(([g,f])=>`${g}: ${Array.isArray(f)?f.join(", "):f}`).join(" | "),l=d=>{if(e.config().features?.askUserQuestion?.groupedAutoAdvance===!1)return;let g=Co(d),f=va(d);if(g>=f-1)return;let h=o.current?.getMessages().find(y=>y.toolCall?.id===d.getAttribute("data-tool-call-id"));h&&(Rd(d,h,e.config(),g+1),s(d))};return{click:d=>{let f=d.target.closest("[data-ask-user-action]");if(!f)return;let h=f.closest("[data-persona-ask-sheet-for]");if(!h)return;let y=f.getAttribute("data-ask-user-action");if(d.preventDefault(),d.stopPropagation(),y==="dismiss"){let v=h.getAttribute("data-tool-call-id")??"";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:v},bubbles:!0,composed:!0})),Wr(n,v);let C=o.current?.getMessages().find(A=>A.toolCall?.id===v);C?.agentMetadata?.awaitingLocalTool&&(o.current?.markAskUserQuestionResolved(C),o.current?.resolveAskUserQuestion(C,"(dismissed)"));return}if(y==="pick"){let v=f.getAttribute("data-option-label");if(!v)return;let C=h.getAttribute("data-multi-select")==="true",A=Ss(h);if(A&&C){let L=ui(h)[Co(h)],I=new Set(Array.isArray(L)?L:[]);I.has(v)?I.delete(v):I.add(v),As(h,Array.from(I)),s(h);return}if(A){As(h,v),s(h),l(h);return}if(C){let L=f.getAttribute("aria-pressed")==="true";f.setAttribute("aria-pressed",L?"false":"true"),f.classList.toggle("persona-ask-pill-selected",!L);let I=h.querySelector('[data-ask-user-action="submit-multi"]');I&&(I.disabled=pf(h).length===0);return}r(h,v,{source:"pick",values:[v]});return}if(y==="submit-multi"){let v=pf(h);if(v.length===0)return;r(h,v.join(", "),{source:"multi",values:v});return}if(y==="open-free-text"){let v=h.querySelector('[data-ask-free-text-row="true"]');v&&(v.classList.remove("persona-hidden"),v.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(y==="focus-free-text"){h.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(y==="submit-free-text"){let C=h.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!C.trim())return;if(Ss(h)){As(h,C.trim()),s(h),l(h);return}r(h,C,{source:"free-text"});return}if(y==="next"||y==="back"){if(!o.current)return;let v=h.getAttribute("data-tool-call-id")??"",C=o.current.getMessages().find(_=>_.toolCall?.id===v);if(!C)return;let L=h.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(L){let _=ui(h)[Co(h)];(typeof _!="string"||_!==L)&&As(h,L)}let I=y==="next"?1:-1,H=Co(h)+I;Rd(h,C,e.config(),H),s(h);return}if(y==="submit-all"){if(!o.current)return;let v=h.getAttribute("data-tool-call-id")??"",C=o.current.getMessages().find(_=>_.toolCall?.id===v);if(!C)return;let L=h.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";L&&As(h,L);let I=Hd(h,C);o.current.persistAskUserQuestionProgress(C,{answers:I,currentIndex:Co(h)});let H=i(I);r(h,H||"(submitted)",{source:"submit-all",structured:I});return}if(y==="skip"){if(!o.current)return;let v=h.getAttribute("data-tool-call-id")??"",C=o.current.getMessages().find(V=>V.toolCall?.id===v);if(!C)return;let A=Ss(h),L=Co(h),I=va(h),H=L>=I-1;if(!A){t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:v},bubbles:!0,composed:!0})),Wr(n,v),C.agentMetadata?.awaitingLocalTool&&(o.current.markAskUserQuestionResolved(C),o.current.resolveAskUserQuestion(C,"(dismissed)"));return}As(h,"");let _=h.querySelector('[data-ask-free-text-input="true"]');if(_&&(_.value=""),H){let V=Hd(h,C),oe=i(V);r(h,oe||"(skipped)",{source:"submit-all",structured:V});return}Rd(h,C,e.config(),L+1),s(h);return}},keydown:d=>{if(d.key!=="Enter")return;let f=d.target;if(!f.matches?.('[data-ask-free-text-input="true"]'))return;let h=f.closest("[data-persona-ask-sheet-for]");if(!h)return;d.preventDefault();let y=f.value;if(y.trim()){if(Ss(h)){As(h,y.trim()),s(h),l(h);return}r(h,y,{source:"free-text"})}}}}});function NT(e,t,n){if(n==="input-start")return t===0;let o=t>0?e[t-1]:"";return n==="line-start"?o===""||o===`
|
|
8
|
-
`:o===""||
|
|
9
|
-
`||i==="\uFFFC"||!r&&Zv.test(i))return null;s--}return null}function eC(e,t,n){for(let o of n){let r=FT(e,t,o.trigger,o.position??"anywhere",o.allowSpaces??!1);if(r)return{channel:o,match:r}}return null}function tC(e){return e?e!=="insertFromPaste"&&e!=="insertFromDrop":!0}var Zv,nC=Ve(()=>{"use strict";Zv=/\s/});function oC(e){let t={trigger:e.trigger??"@",position:e.triggerPosition??"anywhere",allowSpaces:!1,sources:Array.isArray(e.sources)?e.sources:[],searchPlaceholder:e.searchPlaceholder,showButton:e.showButton!==!1,buttonIconName:e.buttonIconName,buttonTooltipText:e.buttonTooltipText},n=(e.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[t,...n]}var rC=Ve(()=>{"use strict"});var Fd=Ve(()=>{"use strict"});function lC(e){e.delayMs!==void 0&&(sC=Ud(e.delayMs)),e.skipDelayMs!==void 0&&(iC=Ud(e.skipDelayMs))}function cC(e){$d.get(e)?.hide()}function vn(e){$d.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:o,hint:r,enabled:s=!0,gap:i=$T,viewportPadding:l=UT}=e,c=()=>t.ownerDocument,p=()=>c().defaultView??window,d=null,g=null,f=null,h=null,y,v=!1,C=!1,A=!1,L=()=>(typeof o=="function"?o():o).trim(),I=()=>(typeof r=="function"?r():r??"").trim(),H=()=>Ud(e.delayMs??sC),_=()=>Ud(e.skipDelayMs??iC),V=()=>{y!==void 0&&(p().clearTimeout(y),y=void 0)},oe=()=>{V();let me=d!==null;h?.(),h=null,d?.remove(),d=null,g=null,f=null,me&&jT(_())},W=()=>{if(!d)return;let me=c(),He=p(),Ee=t.getBoundingClientRect(),Ie=d.getBoundingClientRect(),yt=me.documentElement.clientWidth||He.innerWidth,qe=me.documentElement.clientHeight||He.innerHeight,Oe=yt-l-Ie.width,$=Ee.left+Ee.width/2-Ie.width/2,Be=Sf($,l,Oe),ye=Ee.top-l,ut=qe-l-Ee.bottom,Zt=Ie.height+i,xt=ye>=Zt||ye>=ut?"top":"bottom",xe=xt==="top"?Ee.top-i-Ie.height:Ee.bottom+i,Wt=qe-l-Ie.height,vt=Sf(xe,l,Wt),Le=Ee.left+Ee.width/2,Ye=Math.max(wf,Ie.width-wf),D=Sf(Le-Be,wf,Ye);d.dataset.placement=xt,d.style.left=`${Be}px`,d.style.top=`${vt}px`,d.style.setProperty("--persona-tooltip-arrow-x",`${D}px`)},j=()=>{if(A||!s||d||!t.isConnected||qT(t))return;let me=L(),He=zT(t);if(!me||!He)return;let Ee=c(),Ie=p();d=Ee.createElement("div"),d.className="persona-control-tooltip",d.setAttribute("role","tooltip"),d.dataset.state="measuring",d.style.zIndex=String(wa);let yt=Ie.getComputedStyle?.(t);if(yt){for(let Zt of KT){let xt=yt.getPropertyValue(Zt).trim();xt&&d.style.setProperty(Zt,xt)}yt.fontFamily&&(d.style.fontFamily=yt.fontFamily)}g=Ee.createElement("span"),g.className="persona-control-tooltip__label",g.textContent=me,d.appendChild(g);let qe=I();qe&&(f=Ee.createElement("span"),f.className="persona-control-tooltip__hint",f.textContent=qe,d.appendChild(f));let Oe=Ee.createElement("span");Oe.className="persona-control-tooltip__arrow",d.appendChild(Oe),He.appendChild(d),W(),d.dataset.state="open";let $=()=>{if(!t.isConnected){oe();return}g&&(g.textContent=L()),f&&(f.textContent=I()),W()};Ie.addEventListener("scroll",$,!0),Ie.addEventListener("resize",$);let Be=t.getRootNode(),ye=dC(Be)?Be:Ee.documentElement,ut=typeof MutationObserver>"u"?null:new MutationObserver(()=>{t.isConnected||oe()});ut?.observe(ye,{childList:!0,subtree:!0}),h=()=>{Ie.removeEventListener("scroll",$,!0),Ie.removeEventListener("resize",$),ut?.disconnect()}},X=me=>{if(!(A||d)){if(V(),me||H()<=0||VT()){j();return}y=p().setTimeout(()=>{y=void 0,j()},H())}},E=()=>{v||C?X(C):oe()},T=()=>{let me=p();(!me.matchMedia||!me.matchMedia("(hover: none)").matches)&&(v=!0,E())},B=()=>{v=!1,E()},P=()=>{try{C=t.matches(":focus-visible")}catch{C=!0}E()},J=()=>{C=!1,E()},U=()=>{v=!1,C=!1,oe()},ue=me=>{me.key==="Escape"&&U()};n.addEventListener("mouseenter",T),n.addEventListener("mouseleave",B),t.addEventListener("focus",P),t.addEventListener("blur",J),t.addEventListener("keydown",ue),t.addEventListener("click",U);let fe={get isOpen(){return d!==null},show:j,hide:oe,reposition:W,destroy:()=>{A||(A=!0,oe(),n.removeEventListener("mouseenter",T),n.removeEventListener("mouseleave",B),t.removeEventListener("focus",P),t.removeEventListener("blur",J),t.removeEventListener("keydown",ue),t.removeEventListener("click",U),$d.delete(t))}};return $d.set(t,fe),fe}var $T,UT,wf,sC,iC,aC,Ud,VT,jT,$d,Af,qT,dC,zT,Sf,KT,xa=Ve(()=>{"use strict";Bo();Fd();$T=8,UT=8,wf=10,sC=200,iC=300,aC=0,Ud=e=>Math.max(0,e);VT=()=>Date.now()<aC,jT=e=>{aC=e>0?Date.now()+e:0},$d=new WeakMap,Af="data-persona-tooltip-suppressed",qT=e=>typeof e.closest=="function"&&e.closest(`[${Af}]`)!==null;dC=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,zT=e=>{let t=e.getRootNode?.();return dC(t)?t:e.ownerDocument.body},Sf=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n)),KT=[...["background","foreground","hint-fg","radius","font-size","padding","max-width","shadow","arrow-display"].map(e=>`--persona-tooltip-${e}`),"--persona-font-family","--persona-radius-sm"]});var GT,hi,xf,Mf=Ve(()=>{"use strict";GT=(e,t)=>e.visible!==!1&&(e.mode!=="transient"||t==="connecting"||t==="paused"||t==="resuming"||t==="error"),hi=(e,t,n)=>{let o=t.mode==="transient",r=e.hasAttribute("data-persona-composer-reason")||e.hasAttribute("data-persona-composer-notice");e.style.display=GT(t,n)||o&&r&&t.visible!==!1?"":"none",e.classList.toggle("persona-mt-2",!o),e.classList.toggle("persona-mb-2",o)},xf=(e,t,n)=>{!t.parentElement||e.parentElement!==t.parentElement||(n.mode==="transient"?e.nextElementSibling!==t&&t.before(e):t.nextElementSibling!==e&&t.after(e))}});function _o(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];pC(s)&&pC(r)?n[o]=_o(s,r):n[o]=r}return n}var pC,Vd=Ve(()=>{"use strict";pC=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});function jd(e,t=""){return Object.entries(e).flatMap(([n,o])=>{let r=t?`${t}.${n}`:n;return Tf(o)?jd(o,r):[r]})}function uC(e,t){for(let n of t.split(".")){if(!Tf(e)||!Object.prototype.hasOwnProperty.call(e,n))return"absent";if(e=e[n],e===void 0)return"clear"}return"explicit"}function gC(e,t){return e?.[Ef]??t.filter(n=>uC(e,n)==="explicit")}function Pf(e,t){return Object.defineProperty(e,Ef,{value:t,enumerable:!0,configurable:!0}),e}function kf(e,t,n){return Pf(e,gC(t,jd(n)))}function fC(e,t,n){let o=t[Ef];if(o)return o;let r=new Set(gC(e,n));for(let s of n){let i=uC(t,s);i==="clear"&&r.delete(s),i==="explicit"&&r.add(s)}return[...r]}function mC(e,t,n){let o={...e};for(let r of t){if(n.includes(r))continue;let s=r.split("."),i=o;for(let l of s.slice(0,-1)){let c=i[l];if(!Tf(c)){i=void 0;break}i[l]={...c},i=i[l]}i&&delete i[s[s.length-1]]}return o}var Ef,Tf,Lf=Ve(()=>{"use strict";Ef=Symbol("persona.defaultsProvenance"),Tf=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});var hC,Hf,yi,qd,YT,Br,If,Rf,yC,Ma=Ve(()=>{"use strict";hC="var(--persona-components-panel-width)",Hf=Symbol("persona.panelAliasProvenance"),yi=(e,t)=>e!=null&&Object.prototype.hasOwnProperty.call(e,t),qd=(e,t)=>yi(e,t)&&e[t]!==void 0,YT=e=>({launcherWidth:qd(e?.launcher,"width"),legacyLauncherWidth:qd(e,"launcherWidth"),sidebarWidth:qd(e?.launcher,"sidebarWidth"),dockWidth:qd(e?.launcher?.dock,"width")}),Br=e=>{let t=e?.[Hf];return t?{...t}:YT(e)},If=(e,t)=>(Object.defineProperty(e,Hf,{value:t,enumerable:!0,configurable:!0}),e),Rf=(e,t)=>If(e,Br(t)),yC=(e,t)=>{let n=t[Hf];if(n)return{...n};let o=Br(e);return yi(t,"launcherWidth")&&(o.legacyLauncherWidth=t.launcherWidth!==void 0),yi(t,"launcher")&&t.launcher===void 0?(o.launcherWidth=!1,o.sidebarWidth=!1,o.dockWidth=!1,o):(yi(t.launcher,"width")&&(o.launcherWidth=t.launcher?.width!==void 0),yi(t.launcher,"sidebarWidth")&&(o.sidebarWidth=t.launcher?.sidebarWidth!==void 0),yi(t.launcher,"dock")&&t.launcher?.dock===void 0?o.dockWidth=!1:yi(t.launcher?.dock,"width")&&(o.dockWidth=t.launcher?.dock?.width!==void 0),o)}});function Ms(e){return e?.future?.v5Defaults===!0?"v5":"v4"}function CC(e){let t=Ms(e)==="v5"?bi:JT;return _o(QT,t)}function bC(e,t){if(!(!e&&!t))return e?t?_o(e,t):e:t}function Ea(e){let t=CC(e);return e?kf(Rf({...t,...e,theme:bC(t.theme,e.theme),darkTheme:bC(t.darkTheme,e.darkTheme),launcher:{...t.launcher,...e.launcher,dock:{...t.launcher?.dock,...e.launcher?.dock},clearChat:{...t.launcher?.clearChat,...e.launcher?.clearChat}},...t.composer||e.composer?{composer:{...t.composer,...e.composer}}:{},tooltip:{...t.tooltip,...e.tooltip},copy:{...t.copy,...e.copy},sendButton:{...t.sendButton,...e.sendButton},statusIndicator:{...t.statusIndicator,...e.statusIndicator},voiceRecognition:{...t.voiceRecognition,...e.voiceRecognition},features:(()=>{let n=t.features?.artifacts,o=e.features?.artifacts,r=t.features?.scrollToBottom,s=e.features?.scrollToBottom,i=t.features?.scrollBehavior,l=e.features?.scrollBehavior,c=t.features?.streamAnimation,p=e.features?.streamAnimation,d=t.features?.askUserQuestion,g=e.features?.askUserQuestion,f=t.features?.history,h=e.features?.history,y=n===void 0&&o===void 0?void 0:{...n,...o,layout:{...n?.layout,...o?.layout}},v=r===void 0&&s===void 0?void 0:{...r,...s},C=i===void 0&&l===void 0?void 0:{...i,...l},A=c===void 0&&p===void 0?void 0:{...c,...p},L=d===void 0&&g===void 0?void 0:{...d,...g,styles:{...d?.styles,...g?.styles}},I=f===void 0&&h===void 0?void 0:{...f,...h,copy:{...f?.copy,...h?.copy}};return{...t.features,...e.features,toolCallDisplay:{...t.features?.toolCallDisplay,...e.features?.toolCallDisplay},reasoningDisplay:{...t.features?.reasoningDisplay,...e.features?.reasoningDisplay},...v!==void 0?{scrollToBottom:v}:{},...C!==void 0?{scrollBehavior:C}:{},...y!==void 0?{artifacts:y}:{},...A!==void 0?{streamAnimation:A}:{},...L!==void 0?{askUserQuestion:L}:{},...I!==void 0?{history:I}:{}}})(),suggestionChips:e.suggestionChips??t.suggestionChips,suggestionChipsConfig:{...t.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...t.layout,...e.layout,header:{...t.layout?.header,...e.layout?.header},messages:{...t.layout?.messages,...e.layout?.messages,...t.layout?.messages?.user||e.layout?.messages?.user?{user:{...t.layout?.messages?.user,...e.layout?.messages?.user}}:{},...t.layout?.messages?.assistant||e.layout?.messages?.assistant?{assistant:{...t.layout?.messages?.assistant,...e.layout?.messages?.assistant}}:{},avatar:{...t.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...t.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...t.layout?.slots,...e.layout?.slots}},markdown:{...t.markdown,...e.markdown,options:{...t.markdown?.options,...e.markdown?.options}},messageActions:{...t.messageActions,...e.messageActions}},e),e,bi):kf(Rf(t),void 0,bi)}var vi,vC,Bl,Wf,_r,Ci,XT,QT,JT,ZT,bi,wC,wo=Ve(()=>{"use strict";Vd();Lf();Ma();Fd();vi="min(440px, calc(100vw - 24px))",vC="440px",Bl="40px",Wf="How can I help...",_r={collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",previewMaxLines:3,expandable:!0,loadingAnimation:"none"},Ci={activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},XT={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:vi,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:Bl,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)"},QT={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:XT,copy:{inputPlaceholder:Wf,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:_r,reasoningDisplay:Ci,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},JT={},ZT={variant:"circle",width:"min(400px, calc(100vw - 24px))",headerIconSize:"20px"},bi={launcher:ZT,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"}}}};wC=CC()});function SC(e){return typeof e=="string"?[{type:"text",text:e}]:e}function zd(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Pa(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function AC(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function So(e){return{type:"text",text:e}}function Kd(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function xC(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;t({type:"image",image:r,mimeType:e.type,alt:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function MC(e,t=["image/png","image/jpeg","image/gif","image/webp"],n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}function tP(e){return EC.includes(e)||e.startsWith("image/")}function Gd(e){return tP(e.type)}function TC(e,t,n){return{type:"file",data:e,mimeType:t,filename:n}}async function PC(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;Gd(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function kC(e,t=Dr,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function nP(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function LC(e,t){let n=nP(t).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"}[e]||n||"FILE"}var Ta,EC,eP,Dr,Nr=Ve(()=>{"use strict";Ta="[Image]";EC=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],eP=["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"],Dr=[...EC,...eP]});function Of(e){let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return 20;let n=t.getComputedStyle(e).lineHeight;if(!n||!n.trim().endsWith("px"))return 20;let o=parseFloat(n);return Number.isFinite(o)&&o>0?o:20}function Yd(e,t){return typeof e!="number"||!Number.isFinite(e)?t:e>0?e:t}function HC(e,t){e.style.maxHeight=`${t*Of(e)}px`,e.style.overflowY="auto"}function _l(e){let t=e?.ownerDocument?.defaultView??(typeof window<"u"?window:null);if(!t||typeof t.matchMedia!="function")return!1;try{return t.matchMedia("(pointer: coarse)").matches===!0}catch{return!1}}function IC(e){return e.insertNewlineOnTouchEnter===!0&&e.coarsePointer===!0}function RC(e,t){if(e.key!=="Enter"||e.shiftKey||e.isComposing)return!1;let n=e.metaKey===!0||e.ctrlKey===!0,o=t.submitKey??"enter";return o==="none"?!1:o==="mod-enter"?n:n||!IC(t)}function oP(e){return(e.submitKey??"enter")!=="enter"||IC(e)?"enter":"send"}function Xd(e,t){e.setAttribute("enterkeyhint",oP(t))}function Qd(e,t){let n=t?.autocomplete;e.setAttribute("autocomplete",typeof n=="string"&&n?n:"off");let o=(r,s)=>{s===void 0?e.removeAttribute(r):e.setAttribute(r,s)};o("autocapitalize",typeof t?.autocapitalize=="string"?t.autocapitalize:void 0),o("spellcheck",typeof t?.spellcheck=="boolean"?String(t.spellcheck):void 0),o("inputmode",typeof t?.inputmode=="string"&&t.inputmode?t.inputmode:void 0),o("aria-label",typeof t?.ariaLabel=="string"&&t.ariaLabel?t.ariaLabel:void 0)}function Bf(e){return e===!0?{disabled:!0}:!e||typeof e!="object"?{disabled:!1}:{disabled:!0,reason:typeof e.reason=="string"&&e.reason?e.reason:void 0}}var Jd=Ve(()=>{"use strict"});var ro,Do,Df,Xn,Zd,ep,sP,Nf,tp,ka,np,op,rp,Es=Ve(()=>{"use strict";Mf();Je();kt();wo();Nr();xa();Jd();ro="persona-composer-control",Do="persona-composer-control--glyph",Df=40,Xn=24,Zd=(e,t,n)=>{let o=e.ownerDocument?.defaultView;if(!o)return;let r=o.getComputedStyle(e);for(let s of n){let i=r.getPropertyValue(s).trim();i?t.style.setProperty(s,i):t.style.removeProperty(s)}},ep=(e,t)=>{let n=x("textarea");n.setAttribute("data-persona-composer-input",""),n.placeholder=e?.copy?.inputPlaceholder??Wf,n.dir="auto",Xd(n,{submitKey:e?.composer?.submitKey,insertNewlineOnTouchEnter:e?.composer?.insertNewlineOnTouchEnter,coarsePointer:_l(n)}),Qd(n,e?.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=Yd(e?.composer?.maxLines,t?.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*Of(n);return r=`${c}px`,n.style.maxHeight=r,c},i=()=>{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:i}},sP="[data-persona-glyph-stack]",Nf=(e,t,n="send")=>{let o=Q("span",{className:"persona-composer-glyph-stack",attrs:{"data-mode":n,"data-persona-glyph-stack":""}});return e.setAttribute("data-glyph","send"),t.setAttribute("data-glyph","stop"),o.append(e,t),o},tp=e=>{let t=e?.sendButton??{},n=t.useIcon??!1,o=t.iconText??"\u2191",r=t.iconName,s=t.stopIconName??"square",i=t.tooltipText??"Send message",l=t.stopTooltipText??"Stop generating",c=e?.copy?.sendButtonLabel??"Send",p=e?.copy?.stopButtonLabel??"Stop",d=t.showTooltip??!1,g=t.size,f=parseFloat(g??"")||Df,h=t.backgroundColor,y=t.textColor,v=x("div","persona-send-button-wrapper"),C=Q("button",{className:_n("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?`persona-flex persona-items-center persona-justify-center ${ro}`:"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!h&&"persona-bg-persona-primary",!n&&!y&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":"","data-persona-send-mode":"send"},style:{width:n?g:void 0,height:n?g:void 0,minWidth:n?g:void 0,minHeight:n?g:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?y||"var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))":y||void 0,backgroundColor:n&&h||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:n?"0":t.paddingX||void 0,paddingRight:n?"0":t.paddingX||void 0,paddingTop:n?"0":t.paddingY||void 0,paddingBottom:n?"0":t.paddingY||void 0}}),A=null,L=null,I=null;if(n){let V=parseFloat(t.iconSize??"")||Math.round(f*.5),oe=t.iconStrokeWidth??2,W=y?.trim()||"currentColor";if(r&&(A=ge(r,V,W,oe)),L=ge(s,V,W,oe),!t.iconSize)for(let j of[A,L])j&&(j.style.width=`var(--persona-components-composer-sendIconSize, ${V}px)`,j.style.height=`var(--persona-components-composer-sendIconSize, ${V}px)`);A&&L?(I=Nf(A,L),C.appendChild(I)):A?C.appendChild(A):(C.textContent=o,L=null)}else C.textContent=c;C.setAttribute("aria-label",i),v.appendChild(C),vn({anchor:C,trigger:v,text:()=>C.getAttribute("aria-label")??"",enabled:d});let H="send";return{button:C,wrapper:v,setMode:V=>{if(V===H)return;H=V;let oe=V==="stop"?l:i;C.setAttribute("aria-label",oe),C.setAttribute("data-persona-send-mode",V),n?(C.querySelector(sP)??I)?.setAttribute("data-mode",V):C.textContent=V==="stop"?p:c},glyphStack:I}},ka=e=>{let t=e?.voiceRecognition??{};if(!(t.enabled===!0))return null;let o=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),r=t.provider?.type==="runtype",s=t.provider?.type==="custom";if(!(o||r||s))return null;let l=t.iconName??"mic",c=t.iconSize,p=parseFloat(c??"")||Xn,d=t.backgroundColor??e?.sendButton?.backgroundColor,g=t.iconColor??e?.sendButton?.textColor,f=x("div","persona-send-button-wrapper"),h=Q("button",{className:_n("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",ro,!c&&Do),attrs:{type:"button","data-persona-composer-mic":"","data-state":"idle","aria-label":t.tooltipText??"Start voice recognition"},style:{width:c,height:c,minWidth:c,minHeight:c,fontSize:"18px",lineHeight:"1",color:g||"var(--persona-text, #111827)",backgroundColor:d||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),v=ge(l,p,g||"currentColor",1.5);v?h.appendChild(v):h.textContent="\u{1F3A4}",f.appendChild(h);let C=t.tooltipText??"Start voice recognition",A=t.showTooltip??!1;return vn({anchor:h,trigger:f,text:()=>h.getAttribute("aria-label")??C,enabled:A}),{button:h,wrapper:f}},np=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=x("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=x("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=(t.allowedTypes??Dr).join(","),o.multiple=(t.maxFiles??4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let r=t.buttonIconName??"paperclip",s=x("div","persona-send-button-wrapper"),i=Q("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${ro} ${Do}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),l=ge(r,Xn,"currentColor",1.5);l?i.appendChild(l):i.textContent="\u{1F4CE}",i.addEventListener("click",p=>{p.preventDefault(),o.click()}),s.appendChild(i);let c=t.buttonTooltipText??"Attach file";return vn({anchor:i,trigger:s,text:()=>i.getAttribute("aria-label")??c}),{button:i,wrapper:s,input:o,previewsContainer:n}},op=e=>{let t=e?.statusIndicator??{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=x("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status",""),hi(o,t,"idle");let r=t.idleText??"Online";if(t.idleLink){let s=x("a");s.href=t.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},rp=()=>Q("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}})});function sp(e){let{config:t,onOpen:n}=e,o=t.buttonIconName??"plus",r=t.buttonTooltipText??"Add context",s=x("div","persona-send-button-wrapper"),i=Q("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${ro} ${Do}`,attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":r,"aria-haspopup":"listbox","aria-expanded":"false"},style:{fontSize:"18px",lineHeight:"1"}}),l=ge(o,Xn,"currentColor",1.5);return l?i.appendChild(l):i.textContent="+",i.addEventListener("click",c=>{c.preventDefault(),c.stopPropagation(),n()}),s.appendChild(i),vn({anchor:i,trigger:s,text:()=>i.getAttribute("aria-label")??r}),{button:i,wrapper:s}}var Ff=Ve(()=>{"use strict";Je();kt();xa();Es()});var iW,iP,ip,$f=Ve(()=>{"use strict";dn();({setLoader:iW,load:iP}=lt({fallbackImport:()=>import("@runtypelabs/persona/context-mentions")})),ip=iP});var cW,aP,ap,Uf=Ve(()=>{"use strict";dn();({setLoader:cW,load:aP}=lt({fallbackImport:()=>import("@runtypelabs/persona/context-mentions-inline"),resetOnSetLoader:!0})),ap=aP});function Dl(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=Q("span",{className:_n("persona-mention-token",t.readonly&&"persona-mention-token-readonly"),attrs:{"data-mention-source":e.sourceId,title:e.label,role:"img","aria-label":`${e.label} mention`}});e.color&&n.style.setProperty("--persona-mention-token-accent",e.color);let o=ge(e.iconName??"at-sign",13,"currentColor",2);if(o){let r=x("span","persona-mention-token-icon");r.appendChild(o),n.appendChild(r)}return n.appendChild(Q("span",{className:"persona-mention-token-label",text:`@${e.label}`})),n}var Vf=Ve(()=>{"use strict";Je();kt()});function WC(e){let{loadContextMentions:t,loadContextMentionsInline:n,renderLucideIcon:o,createMentionButton:r}=e.deps??lP,s=e.config.contextMentions;if(!s?.enabled)return null;let i=oC(s).filter(W=>W.sources.length>0);if(i.length===0)return typeof console<"u"&&console.warn("[Persona] contextMentions.enabled is true but no sources were provided; mentions are disabled."),null;let l=i.filter(W=>W.sources.some(j=>typeof j.matchCommand=="function")),c=W=>l.some(j=>j.trigger?j.position==="line-start"?W.split(`
|
|
10
|
-
`).some(
|
|
11
|
-
`)[0]).startsWith(j.trigger):!1),p=(W,j)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${W}`,{detail:j}))}catch{}},d=!e.chipRow,g=e.chipRow??Q("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),f=null,h=null,y=e.textarea,v=null,C=null,A=null,L=null,I=()=>{if(f)return Promise.resolve(f);if(h)return h;let W=t().then(j=>(j.setMentionIconRenderer(o),f=j.mountContextMentions({mentionConfig:s,textarea:e.textarea,composerInput:v??void 0,anchor:e.anchor,contextRow:g,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:oe,emit:p}),f)).catch(j=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",j),h===W&&(h=null),null));return h=W,W},H=()=>{n().then(W=>{let j=W.mountInlineComposer({textarea:e.textarea,renderToken:E=>Dl(E,{render:s.renderMentionToken}),onMentionRemoved:E=>f?.untrackMention(E)});v=j.input,C=j.destroy;let X=y;X.replaceWith(j.element),y=j.element,L={next:j.element,prev:X},A?.(j.element,X),f?f.rebindComposer(j.input):h&&h.then(E=>E?.rebindComposer(j.input))}).catch(W=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",W)})};s.display==="inline"&&H();let _=[],V=new Map;for(let W of i){if(!W.showButton)continue;let j=r({config:{...s,buttonIconName:W.buttonIconName,buttonTooltipText:W.buttonTooltipText},onOpen:()=>{I().then(X=>X?.openMenu(W.trigger))}});_.push(j),V.set(W.trigger,j.button)}let oe=(W,j,X)=>{let E=V.get(j);E&&(E.setAttribute("aria-expanded",W?"true":"false"),W?E.setAttribute("aria-controls",X):E.removeAttribute("aria-controls"))};return{affordanceButtons:_.map(W=>W.wrapper),contextRow:g,handleInput:W=>{if(f){f.handleInput();return}if(!tC(W))return;let j=y,X=j.selectionStart??0;eC(j.value,X,i)&&I().then(E=>E?.handleInput())},handleKeydown:W=>{if(f?.isMenuOpen())return f.handleKeydown(W);if(W.key==="Backspace"&&f?.hasMentions()&&!L){let j=y,X=j.selectionStart===0&&j.selectionEnd===0;if((j.value.length===0||X)&&f.removeLastChip())return W.preventDefault(),!0}return!1},isMenuOpen:()=>f?.isMenuOpen()??!1,hasMentions:()=>f?.hasMentions()??!1,getMentionRefs:()=>f?.getMentionRefs()??[],collectForSubmit:()=>f?.collectForSubmit()??null,takeInlineCommand:async W=>c(W)?(f??await I())?.dispatchInlineCommand(W)??null:null,clear:()=>f?.clear(),prefetch:()=>{t().catch(()=>{})},onComposerSwap:W=>{A=W,L&&W(L.next,L.prev)},destroy:()=>{f?.destroy(),C?.();for(let W of _)W.wrapper.remove();d&&g.remove()}}}var lP,OC=Ve(()=>{"use strict";Je();nC();rC();Ff();$f();kt();Uf();Vf();lP={loadContextMentions:()=>ip(),loadContextMentionsInline:()=>ap(),renderLucideIcon:(...e)=>ge(...e),createMentionButton:(...e)=>sp(...e)}});var lp={};ys(lp,{createAskUserSheetHandlers:()=>Qv,createContextMentionOrchestrator:()=>WC});var jf=Ve(()=>{"use strict";Jv();OC()});var pp={};ys(pp,{resolveApproval:()=>gP,resolveAskUserQuestion:()=>fP,resolveWebMcpToolCall:()=>yP,resolveWebMcpToolCallBatch:()=>DC});async function gP(e,t,n,o){let r=`approval-${t.id}`,s=`approval-error-${t.id}`,i={};e.s.approvalTokens.set(r,i);let l={...t,status:n,resolvedAt:Date.now()},c=e.s.messages.find(f=>f.id===r),p={id:r,role:"assistant",content:"",createdAt:c?.createdAt??new Date().toISOString(),...c?.sequence!==void 0?{sequence:c.sequence}:{},streaming:!1,variant:"approval",approval:l};e.s.upsertMessage(p),e.s.abortController?.abort(),e.s.abortController=new AbortController,e.setStreaming(!0);let d=e.s.config.approval,g=d&&typeof d=="object"?d.onDecision:void 0;try{let f;if(g?f=await g({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,o):f=await e.s.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),f){let h=null;if(f instanceof Response){if(!f.ok){let y=await f.json().catch(()=>null),v=y?.message??y?.error??`Approval request failed: ${f.status}`,C=y?.code==="APPROVAL_ALREADY_RESOLVED"||f.status===404&&/no paused execution/i.test(String(y?.error)),A=e.s.messages.find(L=>L.id===r);throw e.s.approvalTokens.get(r)===i&&A?.approval?.resolvedAt===l.resolvedAt&&(e.s.upsertMessage({...p,approval:C?{...l,status:"timeout"}:t}),C&&e.settleApprovalPausedToolCall(r),e.s.upsertMessage({id:s,role:"assistant",content:v,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()})),new Error(v)}h=f.body}else f instanceof ReadableStream&&(h=f);e.s.approvalTokens.get(r)===i&&e.s.messages.some(y=>y.id===s)&&(e.s.messages=e.s.messages.filter(y=>y.id!==s),e.s.callbacks.onMessagesChanged([...e.s.messages])),h?await e.s.connectStream(h,{allowReentry:!0}):(n==="denied"&&(e.settleApprovalPausedToolCall(r),e.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()})),e.setStreaming(!1),e.s.abortController=null)}else e.setStreaming(!1),e.s.abortController=null}catch(f){let h=f instanceof Error&&(f.name==="AbortError"||f.message.includes("aborted")||f.message.includes("abort"));e.setStreaming(!1),e.s.abortController=null,h||e.s.callbacks.onError?.(f instanceof Error?f:new Error(String(f)))}finally{e.s.approvalTokens.get(r)===i&&e.s.approvalTokens.delete(r)}}async function fP(e,t,n){if(e.s.messages.find(d=>d.id===t.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=t.agentMetadata?.executionId,s=t.toolCall?.name;if(!r||!s){e.s.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let i=typeof n=="string"?void 0:n;if(i===void 0&&typeof n=="string"){let d=t.toolCall?.args,g=Array.isArray(d?.questions)?d.questions:[];if(g.length===1){let f=typeof g[0]?.question=="string"?g[0].question:"";f&&(i={[f]:n})}}e.s.markAskUserQuestionResolved(t,i),e.s.abortController?.abort(),e.s.abortController=new AbortController,e.setStreaming(!0);let l=t.toolCall.id,c=t.toolCall?.args,p=Array.isArray(c?.questions)?c.questions:[];if(p.length===0){let d=typeof n=="string"?n:Object.entries(n).map(([g,f])=>`${g}: ${Array.isArray(f)?f.join(", "):f}`).join(" | ");e.appendMessage({id:`ask-user-answer-${l}`,role:"user",content:d,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()})}else{let d=i??{};p.forEach((g,f)=>{let h=typeof g?.question=="string"?g.question:"";if(!h)return;let y=d[h],v=Array.isArray(y)?y.join(", "):typeof y=="string"?y:"";e.appendMessage({id:`ask-user-q-${l}-${f}`,role:"assistant",content:h,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()}),e.appendMessage({id:`ask-user-a-${l}-${f}`,role:"user",content:v||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()})})}try{let d=await e.s.client.resumeFlow(r,{[s]:n},{after:e.resumeAfter(r)});if(!d.ok){let g=await d.json().catch(()=>null);throw new Error(g?.error??`Resume failed: ${d.status}`)}d.body?await e.s.connectStream(d.body,{allowReentry:!0}):(e.setStreaming(!1),e.s.abortController=null)}catch(d){let g=d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"));e.setStreaming(!1),e.s.abortController=null,g||e.s.callbacks.onError?.(d instanceof Error?d:new Error(String(d)))}}function mP(e,t){let o=[e.s.messages.find(r=>r.id===t.id)?.toolCall?.startedAt,t.toolCall?.startedAt];for(let r of o)if(typeof r=="number"&&Number.isFinite(r))return r;return Date.now()}function _C(e,t){return t.toolCall?.name!==Oo?!1:(e.s.messages.find(o=>o.id===t.id)??t).agentMetadata?.suggestRepliesResolved===!0}function hP(e,t){let n=mP(e,t);return e.s.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}function dp(e,t,n,o,r=Date.now(),s){e.s.messages.some(i=>i.id===t.id)&&e.s.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...s},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:o,completedAt:r,duration:void 0,durationMs:Math.max(0,r-o)}:t.toolCall})}async function DC(e,t,n){let o=[],r=new AbortController;e.s.webMcpResolveControllers.add(r),e.setStreaming(!0);let s=async c=>{let p=c.toolCall?.name,d=c.toolCall?.id;if(!p||!d)return null;let g=`${t}:${d}`;if(e.s.webMcpInflightKeys.has(g)||e.s.webMcpResolvedKeys.has(g)||_C(e,c))return null;e.s.webMcpInflightKeys.add(g),o.push(g);let f=hP(e,c),h=c.agentMetadata?.webMcpToolCallId??p;if(p===Oo)return{dedupeKey:g,resumeKey:h,output:Iv(),toolMessage:c,startedAt:f,completedAt:Date.now()};let y=e.s.client.executeWebMcpToolCall(p,c.toolCall?.args,r.signal),v;if(!y)v={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{v=await y}catch(C){let A=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));return A||e.s.callbacks.onError?.(C instanceof Error?C:new Error(String(C))),dp(e,c,zf(A?"Aborted by cancel()":uP(C)),f),e.s.webMcpInflightKeys.delete(g),null}return r.signal.aborted?(dp(e,c,zf("Aborted by cancel()"),f),e.s.webMcpInflightKeys.delete(g),null):{dedupeKey:g,resumeKey:h,output:v,toolMessage:c,startedAt:f,completedAt:Date.now()}},i;if(e.s.config.webmcp?.execution==="sequential"){i=[];for(let c of n)i.push(await s(c))}else i=await Promise.all(n.map(s));let l=[];try{if(l=i.filter(g=>g!==null),l.length===0)return;let c={};for(let g of l)c[g.resumeKey]=g.output;let p=await e.s.client.resumeFlow(t,c,{signal:r.signal,after:e.resumeAfter(t)});if(!p.ok){let g=await p.json().catch(()=>null);throw new Error(g?.error??`Resume failed: ${p.status}`)}let d=l[0].dedupeKey;for(let g of l){e.s.webMcpResolvedKeys.add(g.dedupeKey);let f=g.toolMessage.toolCall?.name,h=g.toolMessage.agentMetadata?.webMcpToolCallId;dp(e,g.toolMessage,g.output,g.startedAt,g.completedAt,{...f===Oo?{suggestRepliesResolved:!0}:{},...f&&h?{clientToolAnswer:{toolCallId:h,toolName:f,args:g.toolMessage.toolCall?.args,result:g.output,batch:d}}:{}})}p.body&&await e.s.connectStream(p.body,{allowReentry:!0})}catch(c){if(!(c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"))))e.s.callbacks.onError?.(c instanceof Error?c:new Error(String(c)));else for(let d of l)dp(e,d.toolMessage,zf("Aborted by cancel()"),d.startedAt)}finally{for(let c of o)e.s.webMcpInflightKeys.delete(c);e.s.webMcpResolveControllers.delete(r),e.s.webMcpResolveControllers.size===0&&!e.s.abortController&&e.setStreaming(!1)}}async function yP(e,t){let n=t.agentMetadata?.executionId,o=t.toolCall?.name,r=t.toolCall?.id;if(!n){e.s.callbacks.onError?.(new Error("WebMCP await missing executionId: dispatch left paused."));return}if(!o)return;if(!r){let i=`${n}:__no_tool_id__:${o}`;if(e.s.webMcpInflightKeys.has(i)||e.s.webMcpResolvedKeys.has(i))return;e.s.webMcpInflightKeys.add(i);try{await bP(e,n,o,{isError:!0,content:[{type:"text",text:"WebMCP await missing toolCall.id: cannot execute the page tool."}]}),e.s.webMcpResolvedKeys.add(i)}catch(l){e.s.callbacks.onError?.(l instanceof Error?l:new Error(String(l)))}finally{e.s.webMcpInflightKeys.delete(i)}return}let s=`${n}:${r}`;if(!(e.s.webMcpInflightKeys.has(s)||e.s.webMcpResolvedKeys.has(s)||_C(e,t)))return DC(e,n,[t])}async function bP(e,t,n,o,r){let s=await e.s.client.resumeFlow(t,{[n]:o},{signal:r?.signal,after:e.resumeAfter(t)});if(!s.ok){let i=await s.json().catch(()=>null);throw new Error(i?.error??`Resume failed: ${s.status}`)}r?.onHttpOk?.(),s.body?await e.s.connectStream(s.body,{allowReentry:!0}):e.s.webMcpResolveControllers.size===0&&(e.setStreaming(!1),e.s.abortController=null)}var zf,uP,Kf=Ve(()=>{"use strict";Ca();zf=e=>({isError:!0,content:[{type:"text",text:e}]}),uP=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t});function Yf(e){if(!e)return $C;let t={...$C};for(let n of SP){let o=e[n];typeof o=="string"&&o.length>0&&(t[n]=o)}return t}var SP,$C,UC=Ve(()=>{"use strict";SP=["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"],$C={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 qC(e){let{plugins:t,config:n}=e,o=!1,r=!1,s=!1,i=!1,l=null,c=[],p=()=>{for(let H of c.splice(0))try{H()}catch(_){Xf("renderHistoryView cleanup",_)}},d=(H,_)=>{for(let V of t){let oe=V[H];if(oe)try{let W=oe(_);if(W)return W}catch(W){Xf(H,W)}}return null},g=()=>({presentation:e.getPresentation(),config:n}),f={header:H=>i?d("renderHistoryHeader",Object.freeze({...g(),returnSurface:e.getReturnSurface(),identityStatus:Fr(H.identityStatus),pendingAction:jC(H.pendingAction),copy:Fr(H.copy),actions:Object.freeze({close:v.close,startNewConversation:v.startNewConversation}),defaultRenderer:H.defaultRenderer})):null,conversation:H=>i?d("renderHistoryConversation",Object.freeze({...g(),conversation:VC(H.conversation),active:H.active,pending:H.pending,open:H.open,requestDelete:H.requestDelete,defaultRenderer:H.defaultRenderer})):null,state:H=>i?d("renderHistoryState",Object.freeze({...g(),state:Fr(H.state),identityStatus:Fr(H.identityStatus),copy:Fr(H.copy),...H.retry?{retry:H.retry}:{},...H.startNewConversation?{startNewConversation:H.startNewConversation}:{},defaultRenderer:H.defaultRenderer})):null},h=t.flatMap(H=>(H.railSections??[]).map(_=>({..._,placement:_.placement??"above-conversations",items:[],render:V=>_.render(Object.freeze({collapsed:V,presentation:e.getPresentation(),actions:v}))}))),y=e.createView({slots:f,renderDom:!1,onModelChange:()=>I(),railSections:h}),v=Object.freeze({...y.operations,close:e.close}),C=()=>(i=!0,y.setDomRenderEnabled(!0),y.element),A=H=>Object.freeze({conversations:Object.freeze(H.conversations.map(VC)),activeConversationId:H.activeConversationId,state:Fr(H.state),pendingAction:jC(H.pendingAction),identityStatus:Fr(H.identityStatus),nextCursor:H.nextCursor,presentation:e.getPresentation(),returnSurface:e.getReturnSurface(),config:n,copy:Fr(y.copy),actions:v,defaultRenderer:C,requestRender:()=>I(),onCleanup:_=>{c.push(_)}}),L=()=>{i=!1;let H=null;for(let V of t)if(V.renderHistoryView){try{H=V.renderHistoryView(A(y.getModel()))}catch(oe){Xf("renderHistoryView",oe),H=null}if(H)break}let _=!H||H.contains(y.element);return i=_,y.setDomRenderEnabled(_),H??y.element};function I(){if(!(!s||o||r)){r=!0;try{p();let H=L();if(H===l)return;let _=l;l=H,e.onElementChanged(H,_)}finally{r=!1}}}return s=!0,I(),{view:y,get element(){return l??y.element},requestRender:I,dispose:()=>{o=!0,p()}}}var Xf,Fr,VC,jC,zC=Ve(()=>{"use strict";Xf=(e,t)=>{console.warn(`[persona] ${e} threw`,t)},Fr=e=>Object.freeze({...e}),VC=e=>Object.freeze({id:e.id,title:e.title,targetId:e.targetId,preview:e.preview,messageCount:e.messageCount,createdAt:e.createdAt,updatedAt:e.updatedAt}),jC=e=>e?Fr(e):null});var KC,Qf,AP,up,gp,xP,GC,fp,Nl,MP,EP,YC,mp=Ve(()=>{"use strict";KC=null,Qf=()=>{if(KC!==null)return KC;if(typeof navigator>"u")return!1;let t=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(t)},AP="ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space",up=(e,t)=>{console.warn(`[persona] ${e} shortcut: ${t}`)},gp=e=>{let t=e.toLowerCase().split("+").map(r=>r.trim()),n=t.pop(),o={key:n,mod:!1,shift:!1,alt:!1};for(let r of t)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 up("unknown modifier in",e),null;return!o.mod||o.shift&&o.alt||/^(enter|esc(ape)?)$/.test(n)||!/^([^+\s]|[a-z]{2,12})$/.test(n)?(up("unsupported",e),null):(n==="space"&&(o.key=" "),o)},xP=e=>AP.split(" ").find(t=>t.toLowerCase()===e)??(e===" "?"Space":e.length===1?e.toUpperCase():e[0].toUpperCase()+e.slice(1)),GC=(e,t)=>{let n=gp(e);if(!n)return"";let o=Qf(),r=xP(n.key);if(!t&&o)return`${n.alt?"\u2325":""}${n.shift?"\u21E7":""}\u2318${r}`;let s=[t?o?"Meta":"Control":"Ctrl"];return n.alt&&s.push("Alt"),n.shift&&s.push("Shift"),s.push(r),s.join("+")},fp=e=>GC(e,!1),Nl=e=>GC(e,!0),MP=(e,t)=>t.key?.toLowerCase()===e.key&&(Qf()?t.metaKey:t.ctrlKey)===e.mod&&!(Qf()?t.ctrlKey:t.metaKey)&&t.shiftKey===e.shift&&t.altKey===e.alt,EP=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable},YC=e=>{let t=new Map,n=e?.ownerDocument??(typeof document<"u"?document:null),o=(s,i)=>{if((s.scope??"widget")==="page")return!0;if(!e)return!1;let l=i.composedPath?.();return l?.length?l.includes(e):e.contains(i.target)},r=s=>{if(s.isComposing||!t.size)return;let i=s.composedPath?.()[0]??s.target;for(let l of t.values())if(MP(l.parsed,s)&&l.when?.()!==!1&&o(l,s)&&!(!l.allowInInput&&EP(i))){s.preventDefault();try{l.run(s)}catch(c){up(`${l.id} threw on`,l.combo),console.warn(c)}return}};return n?.addEventListener("keydown",r),{register(s){let i=gp(s.combo);if(!i)return()=>{};let l=`${i.mod?"m":""}${i.shift?"s":""}${i.alt?"a":""}${i.key}`,c=t.get(l);return c?(up(`${c.id} already owns`,s.combo),()=>{}):(t.set(l,{...s,parsed:i}),s.element?.setAttribute("aria-keyshortcuts",Nl(s.combo)),()=>{t.get(l)?.id===s.id&&t.delete(l),s.element?.removeAttribute("aria-keyshortcuts")})},destroy(){t.clear(),n?.removeEventListener("keydown",r)}}}});function XC(e){if(typeof e!="string"||e==="")return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function hp(e){return typeof e=="string"?e:void 0}function kP(e){if(typeof e!="object"||e===null)return null;let t=e;switch(t.type){case"text":return typeof t.text=="string"?So(t.text):null;case"image":return typeof t.image=="string"?Kd(t.image,{mimeType:hp(t.mimeType),alt:hp(t.alt)}):null;case"file":return typeof t.data=="string"&&typeof t.mimeType=="string"&&typeof t.filename=="string"?TC(t.data,t.mimeType,t.filename):null;case"audio":return typeof t.audio=="string"?{type:"audio",audio:t.audio,...hp(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;case"video":return typeof t.video=="string"?{type:"video",video:t.video,...hp(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;default:return null}}function LP(e,t){let n=XC(t),o=e.map(i=>XC(i.timestamp)),r=new Array(e.length),s=0;for(;s<o.length;){let i=o[s];if(i!==null){r[s]=i,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,d=l+1<o.length?o[l+1]:null,g=d!==null&&n!==null?Math.min(d,n):d??n;for(let f=0;f<c;f+=1)r[s+f]=g!==null?g-(c-f):p!==null?p+f+1:PP+f;s=l+1}return r.map(i=>new Date(i).toISOString())}function QC(e,t){let n=LP(e,t?.beforeCreatedAt),o=[];return e.forEach((r,s)=>{if(typeof r?.id!="string"||r.id===""||!TP.includes(r.role))return;let i=r.role,l=n[s];if(r.displayAvailable===!1){let c={historyDisplayUnavailable:!0};o.push({id:r.id,role:i,content:"",createdAt:l,agentMetadata:c});return}if(typeof r.displayContent=="string"){o.push({id:r.id,role:i,content:r.displayContent,createdAt:l});return}if(typeof r.content=="string"){o.push({id:r.id,role:i,content:r.content,createdAt:l});return}if(Array.isArray(r.content)){let c=r.content.map(kP).filter(d=>d!==null),p=zd(c);o.push({id:r.id,role:i,content:p||(Pa(c)?Ta:""),createdAt:l,...c.length>0&&{contentParts:c}});return}o.push({id:r.id,role:i,content:"",createdAt:l})}),o}function Fl(e){let t=e.content;if(typeof t!="string"||t==="")return;let n=e.contentParts??e.llmContent??e.rawContent??t;if(!(typeof n=="string"&&n===t))return t}function $l(e,t){let n=new Map;for(let o of e)n.set(o.id,o);for(let o of t)n.set(o.id,o);return[...n.values()].sort((o,r)=>{let s=new Date(o.createdAt).getTime(),i=new Date(r.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(i)&&s!==i)return s-i;let l=o.sequence??0,c=r.sequence??0;return l!==c?l-c:o.id.localeCompare(r.id)})}var TP,PP,yp=Ve(()=>{"use strict";Nr();TP=["user","assistant","system"],PP=0});function RP(e,{HistoryClientError:t,HistoryProviderError:n}){if(e instanceof n)return e;if(e instanceof t){let o=HP.get(e.code)??"unavailable";return new n(o,Jf(o),{...e.retryAfterSeconds!==void 0?{retryAfterSeconds:e.retryAfterSeconds}:{}})}return new n("unavailable",Jf("unavailable"))}function JC(e){let{HistoryProviderError:t}=e.errors,n=()=>e.getClient?.()??e.client,o=e.getIdentityProofConfigured()?["browser","verified-user"]:["browser"],r={scopes:o},s=c=>{if(!o.includes(c))throw new t("unsupported_scope",Jf("unsupported_scope"))},i=async(c,p)=>{s(c);try{return await p()}catch(d){throw RP(d,e.errors)}},l=c=>{let p=!1;return{conversationId:c.session.conversationId??"",conversationRevision:c.session.conversationRevision??"",async commit(){p||(p=!0,c.commit(),await e.onActivationCommitted(c.session))},discard(){p||(p=!0,c.discard())}}};return{capabilities:r,getIdentityStatus(){return n().getHistoryIdentityStatus()},subscribeIdentityStatus(c){return n().subscribeHistoryIdentityStatus(c)},subscribeAvailability(c){return n().subscribeHistoryAvailability(c)},async list(c){return i(c.context.scope,async()=>{let p=await n().listConversations({...c.cursor?{cursor:c.cursor}:{},...c.limit!==void 0?{limit:c.limit}:{},...c.targetId?{targetId:c.targetId}:{},scope:c.context.scope});return{items:p.data,nextCursor:p.nextCursor}})},async getPage(c,p){return i(p.context.scope,async()=>{let d=await n().getConversation(c,{...p.cursor?{messageCursor:p.cursor}:{},scope:p.context.scope}),g=QC(d.messages,{...p.beforeCreatedAt?{beforeCreatedAt:p.beforeCreatedAt}:{}});return{summary:d.summary,messages:$l([],g),conversationRevision:d.conversationRevision??"",nextCursor:d.nextMessageCursor}})},async prepareOpen(c,p){return i(p.context.scope,async()=>l(await n().prepareConversationSession(c)))},async prepareStartNew(c){return i(c.context.scope,async()=>l(await n().prepareNewConversationSession()))},async delete(c,p){await i(p.context.scope,()=>n().deleteConversation(c,{scope:p.context.scope}))},async deleteAll(c){return i(c.context.scope,()=>n().deleteAllConversations({...c.targetId!==void 0?{targetId:c.targetId}:{},scope:c.context.scope}))},async resetDevice(){try{return await n().resetVisitor(),{remoteRevocationConfirmed:!0}}catch{return{remoteRevocationConfirmed:!1}}}}}var HP,IP,Jf,ZC=Ve(()=>{"use strict";yp();HP=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"]]),IP=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."]]),Jf=e=>IP.get(e)??"Conversation history is unavailable right now."});var bp={};ys(bp,{createHistoryShell:()=>WP});var WP,Zf=Ve(()=>{"use strict";UC();zC();Je();mp();Bo();ZC();WP=e=>{let o=Yf(e.config.features?.history?.copy),r=null,s=!1,i=null,l=null,c="conversation",p=null,d=null,g=null,f=null,h=0,y=null,v=null,C=null,A=`persona-history-${Math.random().toString(36).slice(2,8)}`,L=()=>e.historyFeatureEnabled()&&!!r&&!s,I=()=>{let M=e.session.getStatus();return e.isStreaming||M==="paused"||M==="resuming"},H=()=>{let M=e.config.features?.history?.scope;if(M)return M;let N=e.config.getIdentityProof?"verified-user":"browser",ne=r?.capabilities.scopes;return!ne||ne.includes(N)?N:ne[0]??N},_=()=>l?.scope??H(),V=()=>e.session.getClientSession()?.targetId??null,oe=M=>`${M.state}:${"reason"in M?M.reason:""}`,W=M=>{let N=oe(M);N!==f&&(f=N,e.eventBus.emit("history:identityStatusChanged",{status:M,timestamp:Date.now()}))},j=null,X=null,E=()=>{if(!e.historyFeatureEnabled())return null;let M=e.getHistoryProviderFactory();if(M)return M();let N=e.config.features?.history?.provider;return N?typeof N!="function"?N:(j!==N&&(j=N,X=N()),X):e.session.isClientTokenMode()?JC({errors:e.historyErrors,client:e.session.getClient(),getIdentityProofConfigured:()=>typeof e.config.getIdentityProof=="function",onActivationCommitted:ne=>e.session.bindActivatedSession(ne),getClient:()=>e.session.getClient()}):null},T=()=>{v?.(),v=null,C?.(),C=null,s=!1,r=E();let M={...e.historyInternals};r?M.historyProvider=r:delete M.historyProvider,e.historyInternals=M,e.session.setHistoryInternals(e.historyInternals),r&&(v=r.subscribeAvailability?.(N=>{s=!N,N||xn({restoreFocus:!1}),jn()})??null,C=r.subscribeIdentityStatus(N=>W(N)),f=oe(r.getIdentityStatus()))},B=()=>{let M=e.config.features?.history?.presentation??"panel";if(M==="panel"||M==="auto"&&!(!e.launcherEnabled||e.isDockedMountMode(e.config)))return"panel";let N=e.artifactSplitRoot??e.container;return(N.getBoundingClientRect().width||N.clientWidth)>=720?"rail":"panel"},P=(M,N)=>{N?(M.setAttribute("aria-hidden","true"),M.setAttribute("inert","")):(M.removeAttribute("aria-hidden"),M.removeAttribute("inert"))},J="data-persona-history-suppressed",U=null,ue=null,fe=null,me=null,He=null,Ee="",Ie=()=>e.header===He?Ee:e.config.layout?.showHeader===!1?"none":"",yt=()=>e.historyPresentation==="panel"&&!!fe&&me===fe.element&&e.config.layout?.showHeader!==!1&&Ie()!=="none",qe=()=>{for(let M of Array.from(e.header.children))M!==U&&M.setAttribute(J,"")},Oe=()=>{for(let M of Array.from(e.container.querySelectorAll(`[${J}]`)))M.removeAttribute(J)},$=()=>{let M=fe;if(!M)return;if(Array.from(e.header.children).some(pe=>pe!==U&&!pe.hasAttribute(J))){ue&&ue!==e.header&&(ue.style.removeProperty("min-height"),ue=null);let pe=e.header.offsetHeight;pe>0&&(e.header.style.minHeight=`${pe}px`,ue=e.header)}U||(U=x("div","persona-history-header-host")),M.setHeaderPlacement("external");let ne=M.getHeaderElement();ne.parentNode!==U&&U.replaceChildren(ne),U.parentNode!==e.header&&e.header.appendChild(U),qe()},Be=()=>{ue&&(ue.style.removeProperty("min-height"),ue=null),U&&(fe?.setHeaderPlacement("inline"),U.remove(),U=null,Oe())},ye=null,ut=()=>{if(ye){if(e.body.style.display="none",P(e.body,!0),e.footer.hidden=!0,P(e.footer,!0),yt()){$(),e.header.style.display=Ie(),P(e.header,!1);return}Be(),e.header.style.display="none",P(e.header,!0)}};e.reapplyHistoryHostChrome=ut;let Zt=M=>{let N=e.body.style.display,ne=e.footer.hidden,pe=e.footer,Re=e.header,$t=e.header.style.display;He=Re,Ee=$t,ye=()=>{ye=null,Be(),He=null,e.body.style.display=N,P(e.body,!1),pe.hidden=ne,P(pe,!1),e.footer!==pe&&(e.footer.hidden=!1,P(e.footer,!1)),Re.style.display=$t,P(Re,!1),e.header!==Re&&(e.header.style.display=e.config.layout?.showHeader===!1?"none":"",P(e.header,!1))},e.footer.parentNode?.insertBefore(M,e.footer),ut()},xt=null,xe=null,Wt=null,vt=null,Le=()=>[e.header,e.panelElements.closeButtonWrapper,e.panelElements.clearChatButtonWrapper,e.body,e.footer],Ye=52,D=()=>e.config.features?.history?.rail?.collapsible!==!1,S=()=>e.config.features?.history?.rail?.side==="right"?"right":"left",F=200,z=400,K=M=>Math.min(z,Math.max(F,Math.round(M))),te=()=>e.config.features?.history?.rail?.resizable===!0,ve,Ce=()=>{if(ve===void 0&&(ve=null,e.config.persistState!==!1))try{let M=Number(window.localStorage.getItem(`${e.currentKeyPrefix()}rail-width`));M&&(ve=M)}catch{}return ve},Me=()=>K(Ce()??e.config.features?.history?.rail?.width??260),ot=M=>{if(ve=M,e.config.persistState!==!1)try{window.localStorage.setItem(`${e.currentKeyPrefix()}rail-width`,String(M))}catch{}},Ct=()=>D()&&e.config.features?.history?.rail?.collapsedBehavior==="overlay",De=!1,Xe=M=>{let N=x("img");return N.src=M,N.alt="",N.setAttribute("aria-hidden","true"),N},pn=()=>{let M=e.config.features?.history?.rail?.brand;if(!M)return;let N=!1,ne;return pe=>{if(M.render)try{return M.render({collapsed:pe})??null}catch(Re){return N||(N=!0,console.warn("[persona] history rail brand threw",Re)),null}return ne===void 0&&(M.iconUrl?ne=Xe(M.iconUrl):ne=M.icon?e.renderLucideIcon(M.icon,20):null),ne?ne.cloneNode(!0):null}},xo=()=>e.config.features?.history?.rail?.sections?.map(M=>{let N=!1,ne=pe=>{N||(N=!0,console.warn("[persona] history rail section threw",M.id,pe))};return{id:M.id,title:M.title,placement:M.placement??"above-conversations",items:M.items.map(pe=>{let Re;return{id:pe.id,label:pe.label,badge:pe.badge,iconNode:()=>{if(Re!==void 0)return Re;try{pe.renderIcon?Re=pe.renderIcon()??null:pe.iconUrl?Re=Xe(pe.iconUrl):Re=pe.icon?e.renderLucideIcon(pe.icon,20):null}catch($t){ne($t),Re=null}return Re},onSelect:()=>{try{pe.onSelect()}catch($t){ne($t)}}}})}})??[],ft=M=>{let N=xo();for(let ne of M)N.some(pe=>pe.id===ne.id)?console.warn("[persona] duplicate history rail section id",ne.id):N.push(ne);return N.length?N:void 0},bt=null,Ft=()=>`${e.currentKeyPrefix()}rail-collapsed`,Bi=()=>{if(bt===null&&(bt=e.config.features?.history?.rail?.defaultCollapsed===!0,e.config.persistState!==!1))try{let M=window.localStorage.getItem(Ft());M&&(bt=M==="1")}catch{}return bt},rn=M=>{if(bt=M,e.config.persistState!==!1)try{window.localStorage.setItem(Ft(),M?"1":"0")}catch{}},Sn=()=>e.historyPresentation==="rail"&&D()&&!Ct()&&Bi(),ao=()=>{},_i=()=>{if(Ct()){ao();return}rn(!Bi()),i?.view.setCollapsed(Sn()),e.applyRailChrome(),e.repinAnchoredMessage()},Di=()=>{let M=e.config.features?.history?.rail?.collapseShortcut;return!M||!gp(M)?null:{combo:M,hint:fp(M),aria:Nl(M)}},Qa=300,cr="var(--persona-history-overlay-margin,8px)",un=null,Un=null,dr=0,Vn=null,pr=null,Uo=!1,Yr=0,Cc=()=>window.matchMedia?.("(pointer: coarse)").matches===!0,eo=()=>L()&&Ct()&&(e.historyPresentation??B())==="rail",Dh=()=>e.historyVisible&&!De,ur=()=>{pr!==null&&clearTimeout(pr),pr=null},Bs=()=>{e.loadHistoryView().catch(()=>{})},Ln=()=>{ur(),De&&(pr=setTimeout(()=>{pr=null,!(Uo||!De)&&(Vn?.contains(document.activeElement)||xn({restoreFocus:!1}))},Qa))},Qe=(M,N)=>{let ne=Vn?.getBoundingClientRect();if(!ne)return!1;let pe=un?.getBoundingClientRect(),Re=pe?Math.min(pe.top,ne.top):ne.top;return M>=ne.left&&M<=ne.right&&N>=Re&&N<=ne.bottom||!!pe&&M>=pe.left&&M<=pe.right&&N>=pe.top&&N<=pe.bottom},Ae=M=>{De&&(Uo=Qe(M.clientX,M.clientY),Uo?ur():pr===null&&Ln())},Xt=M=>{e.historyVisible||!eo()||(De=!0,Ke({invoker:un,keyboard:M?.keyboard===!0}).then(()=>{e.historyVisible?!Uo&&document.activeElement!==un&&xn():De=!1}))},Ze=()=>{let M=me?.querySelector('[data-persona-history-focus="collapse"]');M&&(M.setAttribute("aria-label",De?o.expandLabel:o.collapseLabel),M.setAttribute("aria-expanded",De?"false":"true"))},we=()=>{rn(!1);let M=i;if(!De||!M){Ke({invoker:un});return}let N=document.activeElement===un;De=!1,Ni(),M.element.remove(),Ht(M.element),Ze(),N&&mt(),e.repinAnchoredMessage(),jn()},ae=()=>{rn(!0),xn()};ao=()=>{!e.historyVisible||De?we():ae()};let Te=()=>{let M=Di(),N=e.createHeaderIconButton({ariaLabel:o.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":A,...M?{"aria-keyshortcuts":M.aria}:{}}}),ne=N.button;ne.addEventListener("mouseenter",()=>{Uo=!0,ur(),!(Cc()||Date.now()<Yr)&&Xt()}),ne.addEventListener("mouseleave",()=>{Uo=!1,Yr=0,Ln()}),ne.addEventListener("focus",()=>{e.historyVisible||Bs()}),ne.addEventListener("click",pe=>{L()&&(pe.detail!==0&&Cc()&&!e.historyVisible?Xt():we())}),un=ne,Un=N.wrapper},gr=()=>{if(Un&&!Un.isConnected&&(Un=null,un=null),!eo()){Un?.remove(),Un=null,un=null;return}un||Te();let M=Un,N=un;if(!M||!N)return;let ne=S()!=="right"?e.header.firstChild:null;(ne??e.header.lastChild)!==M&&e.header.insertBefore(M,ne),M.style.display=Dh()||dr>0?"none":"",N.setAttribute("aria-label",o.expandLabel),N.setAttribute("aria-expanded",e.historyVisible?"true":"false"),Vn&&e.applyRailChrome()},Xr=M=>{if(!De)return;let N=M.target;N instanceof Node&&(Vn?.contains(N)||Un?.contains(N)||N instanceof Element&&N.closest('.persona-dropdown-menu,[role="alertdialog"]')||xn({restoreFocus:!1}))};document.addEventListener("pointerdown",Xr,!0),e.destroyCallbacks.push(()=>{document.removeEventListener("pointerdown",Xr,!0),document.removeEventListener("pointermove",Ae),ce?.(),ur()});let lo=null,ce=null,Pe=16,An=M=>{ot(K(M)),e.applyRailChrome(),e.repinAnchoredMessage()},rt=()=>{let M=x("div","persona-rail-resizer");return M.tabIndex=0,M.setAttribute("role","separator"),M.setAttribute("aria-orientation","vertical"),M.setAttribute("aria-valuemin",String(F)),M.setAttribute("aria-valuemax",String(z)),M.addEventListener("pointerdown",N=>{let ne=xe;if(!ne||N.button!==0)return;N.preventDefault(),ce?.();let pe=N.clientX,Re=ne.getBoundingClientRect().width||Me(),$t=S()==="right"?-1:1,Ot=Re,Bt=e.mount.ownerDocument;ne.style.transition="none";let je=be=>{Ot=K(Re+$t*(be.clientX-pe)),ne.style.flex=`0 0 ${Ot}px`,M.setAttribute("aria-valuenow",String(Ot))},at=()=>{ce=null,Bt.removeEventListener("pointermove",je),Bt.removeEventListener("pointerup",at),Bt.removeEventListener("pointercancel",at),ne.style.removeProperty("transition");try{M.releasePointerCapture(N.pointerId)}catch{}An(Ot)};ce=at,Bt.addEventListener("pointermove",je),Bt.addEventListener("pointerup",at),Bt.addEventListener("pointercancel",at);try{M.setPointerCapture(N.pointerId)}catch{}}),M.addEventListener("keydown",N=>{let ne=S()==="right"?-Pe:Pe,pe=Me(),Re=N.key==="ArrowRight"?pe+ne:N.key==="ArrowLeft"?pe-ne:N.key==="Home"?F:N.key==="End"?z:null;Re!==null&&(N.preventDefault(),An(Re))}),M},en=(M,N)=>{if(!te()||Sn()){ce?.(),lo?.remove();return}let ne=lo??rt();lo=ne,ne.setAttribute("aria-label",o.resizeLabel),ne.setAttribute("aria-valuenow",String(Me())),ne.nextElementSibling!==N&&M.insertBefore(ne,N)};e.applyRailChrome=()=>{i?.view.setRailSide(S());let M=S()==="right",N=Vn;if(N){let Bt=un?un.getBoundingClientRect().bottom-e.container.getBoundingClientRect().top:0;N.style.top=`calc(${Math.max(0,Math.round(Bt))}px + ${cr})`,N.style.width=`${Me()}px`,N.style.left=M?"":cr,N.style.right=M?cr:""}let ne=xe,pe=xt,Re=Wt;if(!ne||!pe||!Re)return;ne.style.flex=`0 0 ${Sn()?Ye:Me()}px`;let $t="1px solid var(--persona-divider,#e5e7eb)";ne.style.borderRight=M?"":$t,ne.style.borderLeft=M?$t:"";let Ot=M?Re:ne;pe.firstElementChild!==Ot&&pe.append(Ot,M?ne:Re),en(pe,M?ne:Re)};let wc=M=>{if(vt&&xe){vt.replaceWith(M),vt=null,e.applyRailChrome();return}let N=x("div","persona-history-rail-shell");N.style.cssText="display:flex;flex-direction:row;flex:1 1 auto;min-height:0";let ne=x("div","persona-history-rail-conversation");ne.style.cssText="display:flex;flex-direction:column;flex:1 1 auto;min-width:0;min-height:0;position:relative";let pe=x("div","persona-history-rail-host");pe.style.cssText="display:flex;min-height:0;overflow:hidden",e.container.insertBefore(N,e.header.parentNode===e.container?e.header:e.body);for(let Re of Le())Re?.parentNode===e.container&&ne.appendChild(Re);N.append(pe,ne),pe.appendChild(M),xt=N,xe=pe,Wt=ne,e.applyRailChrome()},In=()=>{if(xt)return;let M=x("div","persona-history-rail-placeholder");M.style.cssText="flex:1 1 auto;min-height:0",vt=M,wc(M),e.repinAnchoredMessage()},Sc=()=>{vt&&(Ni(),e.repinAnchoredMessage())},Wu=M=>{let N=x("div","persona-history-rail-overlay");N.style.cssText=`position:absolute;bottom:${cr};display:flex;overflow:hidden;z-index:${wa-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))`,e.container.style.position="relative",e.container.appendChild(N),N.appendChild(M),document.addEventListener("pointermove",Ae),Vn=N,e.applyRailChrome(),Ze()},Ni=()=>{ye?.(),Vn&&(Uo&&(Yr=Date.now()+150),document.removeEventListener("pointermove",Ae),Vn.remove(),Vn=null);let M=xt;if(M){ce?.();for(let N of Le())N&&M.contains(N)&&e.container.insertBefore(N,M);M.remove(),xt=null,xe=null,Wt=null,vt=null}},ze=M=>{me=M,M.id=A,M.style.flex="1 1 auto",M.style.minHeight="0"},Ht=M=>{ze(M),(e.historyPresentation!=="rail"||De)&&Sc(),e.historyPresentation!=="rail"?Zt(M):De?Wu(M):wc(M)},Vo=()=>{if(gr(),Jr(),!e.historyVisible||!i)return;let M=B();if(M===e.historyPresentation)return;let N=document.activeElement,ne=N instanceof HTMLElement&&(i.element.contains(N)||U?.contains(N)===!0)?N:null;Ni(),i.element.remove(),i.view.setHeaderPlacement("inline"),e.historyPresentation=M,i.view.setPresentation(M),i.view.setCollapsed(Sn()),i.requestRender(),i.element.isConnected||Ht(i.element),ne?.isConnected?ne.focus():mt(),e.syncScrollToBottomButton(),e.repinAnchoredMessage(),jn()},jo=(M,N)=>U?.querySelector(N)??M.querySelector(N),mt=()=>{let M=i?.element??me;if(!M)return;let N=jo(M,'[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]');if(N){N.focus();return}let ne=jo(M,".persona-history-title")??M;ne.tabIndex=-1,ne.focus()},Ke=async M=>{if(!L()||e.historyVisible)return;let N=r;if(!N)return;if(!De&&eo()&&Bi()){gr();return}Fi();let ne=++h;c=M?.returnSurface??"conversation",p=M?.invoker??d;let pe=eo()&&!De;pe&&(dr+=1,gr(),In());let Re;try{Re=await e.loadHistoryView()}catch{e.announceHistory(o.openHistoryLabel),pe&&(dr-=1,ne===h&&(Sc(),gr()));return}if(pe&&(dr-=1),ne!==h||e.historyVisible)return;l={scope:H()},e.historyPresentation=B(),e.historyVisible=!0;let $t=e.historyPresentation==="panel"&&e.config.layout?.showHeader!==!1&&e.header.style.display!=="none"?"external":"inline",Ot=e.config.features?.history?.rowAvatar,Bt=Di(),je=Bt?{hint:Bt.hint,aria:Bt.aria}:null,at={provider:N,context:l,targetId:V(),presentation:e.historyPresentation,collapsible:D(),collapsed:Sn(),railSide:S(),renderRailHeader:e.config.features?.history?.rail?.renderHeader,railBrand:pn(),onToggleCollapse:_i,...je?{collapseShortcut:je}:{},headerPlacement:$t,showScopeStatus:e.config.features?.history?.showScopeStatus!==!1,showDelete:e.config.features?.history?.showDelete!==!1,showDeleteAll:e.config.features?.history?.showDeleteAll!==!1,...e.config.features?.history?.listActions?.length?{listActions:e.config.features.history.listActions}:{},rowAvatar:Ot===!1?!1:typeof Ot=="string"?Ot:e.config.launcher?.iconUrl,activeConversationId:e.session.getActiveConversationId(),...e.config.features?.history?.grouping?{grouping:e.config.features.history.grouping}:{},...e.config.features?.history?.copy?{copy:e.config.features.history.copy}:{},...e.config.features?.history?.pageSize!==void 0?{pageSize:e.config.features.history.pageSize}:{},onSelect:be=>Mn(be,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:be=>e.setActiveConversationSummary(be),attachTooltip:e.attachTooltip,onStartNew:()=>Mo({focusComposer:!0}),onClose:()=>xn(),onRequestDeleteConversation:be=>Vt(be),onRequestClearHistory:()=>Fs(),...N.resetDevice?{onRequestResetIdentity:()=>el()}:{}};i=qC({plugins:e.plugins,config:e.config,getPresentation:()=>e.historyPresentation??"panel",getReturnSurface:()=>c,close:()=>xn(),createView:({slots:be,renderDom:Ui,onModelChange:co,railSections:mr})=>(fe=Re.createHistoryView({...at,railSections:ft(mr),slots:be,renderDom:Ui,onModelChange:co,onAnnounce:e.announceHistory}),fe),onElementChanged:(be,Ui)=>{if(!Ui?.isConnected)return Ht(be);ze(be),Ui.replaceWith(be),ut()}}),i.view.setNewConversationRequired(e.historySessionState.recovery==="new_conversation_required"),M?.focus!==!1&&(e.historyPresentation!=="rail"||M?.keyboard===!0)&&mt(),e.syncScrollToBottomButton(),e.repinAnchoredMessage(),jn(),e.eventBus.emit("history:opened",{presentation:e.historyPresentation,returnSurface:c,timestamp:Date.now()})},Fi=()=>{},xn=M=>{if(!e.historyVisible)return;h+=1;let N=c,ne=p,pe=i,Re=M?.restoreFocus!==!1;e.historyVisible=!1;let $t=!1,Ot=null,Bt=()=>{if(!$t){if($t=!0,Fi=()=>{},Ot!==null&&clearTimeout(Ot),De=!1,ur(),Ni(),pe?.dispose(),pe?.view.destroy(),pe?.element.remove(),i===pe&&(i=null,fe=null,me=null,e.historyPresentation=null,l=null,p=null),e.syncScrollToBottomButton(),e.repinAnchoredMessage(),jn(),Re){let at=ne??d;at?.isConnected?at.focus():e.maybeFocusInput()}e.eventBus.emit("history:closed",{returnSurface:N,timestamp:Date.now()})}},je=pe&&pe.element===pe.view.element?pe.view.playExit():null;if(!je){Bt();return}Fi=Bt,Ot=setTimeout(Bt,250),je.then(Bt)},_s=M=>{if(!(M.key!=="Escape"||!e.historyVisible||!i)){if(e.historyPresentation==="rail"){let N=M.target;if(!(N instanceof Node)||!(i.element.contains(N)||De&&Un?.contains(N)===!0))return}M.preventDefault(),M.stopPropagation(),xn()}};e.container.addEventListener("keydown",_s),e.destroyCallbacks.push(()=>e.container.removeEventListener("keydown",_s));let Rn=0,Ac=250,he=null,gn=()=>{he&&clearTimeout(he),he=null};e.destroyCallbacks.push(gn);let It=()=>{gn();let M=e.conversationOpenPendingEl;M&&(e.conversationOpenTakeover=!0,M.hidden=!1,e.messagesWrapper.style.display="none",e.updateWelcome())},sn=()=>{Rn+=1,gn(),e.conversationOpenPendingEl&&(e.conversationOpenPendingEl.remove(),e.conversationOpenPendingEl=null,e.conversationOpenTakeover=!1,e.messagesWrapper.style.removeProperty("display"),P(e.footer,!1),e.updateWelcome())},Mt=()=>{try{if(window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches)return;e.messagesWrapper.animate([{opacity:0},{opacity:1}],{duration:150,easing:"ease-out"})}catch{}},fn=(M,N)=>Q("div",{className:_n("persona-conversation-loading-bubble",N&&"persona-conversation-loading-bubble--trailing"),attrs:{"aria-hidden":"true"},style:{width:M}}),xc=()=>Q("div",{className:"persona-conversation-loading-body"},fn("58%",!1),fn("72%",!0),fn("44%",!1)),Qr=M=>{e.conversationOpenPendingEl?.remove(),e.conversationOpenPendingEl=M,M.hidden=!e.conversationOpenTakeover,e.body.insertBefore(M,e.messagesWrapper),gn(),e.conversationOpenTakeover||(he=setTimeout(It,Ac)),P(e.footer,!0)},Ou=()=>{let M={config:e.config,streaming:!1,location:"conversation-open",defaultRenderer:xc},N=null,ne=e.plugins.find(pe=>pe.renderLoadingIndicator);ne?.renderLoadingIndicator&&(N=ne.renderLoadingIndicator(M)),N===null&&e.config.loadingIndicator?.render&&(N=e.config.loadingIndicator.render(M)),Qr(Q("div",{className:"persona-conversation-loading",attrs:{role:"status","aria-label":o.openConversationLoadingLabel}},N??xc()))},Bu=M=>{let N=()=>{Mn(M,{focusComposer:!0}).catch(()=>{})},ne=L()?()=>{sn(),Ke()}:void 0,pe=(Bt,je)=>{let at=Q("button",{className:"persona-conversation-loading-error-action",attrs:{type:"button"},text:Bt});return at.addEventListener("click",je),at},Re=()=>Q("div",{className:"persona-conversation-loading-error-body"},Q("p",{className:"persona-conversation-loading-error-title",text:o.openConversationErrorTitle}),Q("div",{className:"persona-conversation-loading-error-actions"},pe(o.openConversationRetryLabel,N),ne?pe(o.openConversationBackLabel,ne):null)),$t=Object.freeze({conversationId:M,config:e.config,copy:Object.freeze({title:o.openConversationErrorTitle,retryLabel:o.openConversationRetryLabel,backLabel:o.openConversationBackLabel}),retry:N,...ne?{back:ne}:{},defaultRenderer:Re}),Ot=null;for(let Bt of e.plugins)if(Bt.renderHistoryOpenError){try{Ot=Bt.renderHistoryOpenError($t)}catch(je){console.warn("[persona] renderHistoryOpenError threw",je),Ot=null}if(Ot)break}Qr(Q("div",{className:"persona-conversation-loading-error",attrs:{role:"alert"}},Ot??Re())),It()};e.eventBus.on("history:closed",()=>{e.conversationOpenPendingEl&&P(e.footer,!0)});let Mn=async(M,{focusComposer:N=!1}={})=>{let ne=_(),pe=!!i;i?.view.setActiveConversationId(M),sn();let Re=Rn;Ou(),e.historyVisible&&(e.historyPresentation==="panel"||De)&&xn({restoreFocus:!1}),e.suppressScrollSend=!0;try{await e.session.openConversation(M,{scope:ne})}catch($t){throw Re===Rn&&Bu(M),$t}finally{e.suppressScrollSend=!1}Re===Rn&&(sn(),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),e.restoreScrollPosition()||e.jumpToBottomInstant(),Mt(),Qt(),pe||e.setActiveConversationSummary(null),e.eventBus.emit("history:conversationOpened",{conversationId:M,title:e.activeConversationTitle,scope:ne,timestamp:Date.now()}),N&&e.maybeFocusInput())},Mo=async({focusComposer:M=!1}={})=>{sn(),await e.session.startNewConversation({scope:_()}),e.setActiveConversationSummary(null),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),e.jumpToBottomInstant(),Qt();let N=e.session.getActiveConversationId();i?.view.setActiveConversationId(N),e.eventBus.emit("history:conversationStarted",{conversationId:N,timestamp:Date.now()}),e.historyVisible&&(e.historyPresentation==="panel"||De)&&xn({restoreFocus:!1}),M&&e.maybeFocusInput()},Ds=async(M,N)=>{let ne=await e.session.updateConversation(M,{...N,...N.title!==void 0?{title:N.title.trim()}:{}});return i?.view.applyConversationSummary(ne),!i&&M===e.session.getActiveConversationId()&&e.setActiveConversationSummary(ne),ne},Mc=async M=>{let N=_(),ne=e.session.getActiveConversationId()===M;await e.session.deleteConversation(M,{scope:N}),i?.view.removeConversationSummary(M),ne&&(e.setActiveConversationSummary(null),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),Qt()),e.eventBus.emit("history:conversationDeleted",{conversationId:M,scope:N,wasActive:ne,timestamp:Date.now()})},Ja=async M=>{let N=M?.scope??_(),ne=M?.allTargets?null:M?.targetId??V(),pe=await e.session.clearConversationHistory({...ne?{targetId:ne}:{},scope:N});return e.setActiveConversationSummary(null),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),Qt(),e.eventBus.emit("history:cleared",{deleted:pe.deleted,scope:N,targetId:ne,timestamp:Date.now()}),pe},Za=async()=>{if(!r?.resetDevice)throw new Error("[Persona] resetHistoryIdentity() requires a history provider that can reset this device");let M=!1;try{M=(await e.session.resetHistoryDevice()).remoteRevocationConfirmed}finally{e.setActiveConversationSummary(null),e.session.clearArtifacts(),e.messageCache.clear(),e.lastAppliedMessages=null,e.config.clearStoredSessionId?.(),e.config.clearStoredConversationId?.(),e.persistentMetadata={},e.actionManager.syncFromMetadata();let N=e.storageAdapter;N?.clear&&e.runStorageMutation(()=>N.clear(),"[AgentWidget] Failed to clear storage adapter:"),e.resetAnchorState(),e.resumeAutoScroll(),Qt(),xn({restoreFocus:!1}),e.maybeFocusInput(),e.open||e.launcherSurfaceInstance?.launcher.element.focus()}return e.announceHistory(M?o.identityResetNotice:o.identityResetUnconfirmedNotice),e.eventBus.emit("history:identityReset",{remoteRevocationConfirmed:M,timestamp:Date.now()}),{remoteRevocationConfirmed:M}},$i=()=>e.artifactSplitRoot?e.panel:e.container,Ns=async M=>{let N=await e.loadHistoryView().catch(()=>null);return typeof N?.showHistoryConfirm=="function"?N.showHistoryConfirm(M):window.confirm(`${M.title}
|
|
6
|
+
`);l=F.pop()??"";for(let q of F){let K=q.split(`
|
|
7
|
+
`),te="message",ve="",Me=null;for(let Qe of K)Qe.startsWith("event:")?te=Qe.replace("event:","").trim():Qe.startsWith("data:")?ve+=Qe.replace("data:","").trim():Qe.startsWith("id:")&&(Me=Qe.slice(3).trim());let Ce=()=>{Me!==null&&Me!==""&&n({type:"cursor",id:Me})};if(!ve){Ce();continue}let st;try{st=JSON.parse(ve)}catch(Qe){n({type:"error",error:Qe instanceof Error?Qe:new Error("Failed to parse chat stream payload")});continue}let Ct=st!==null&&typeof st=="object"&&!Array.isArray(st)?st:null,De=te!=="message"?te:typeof Ct?.type=="string"?Ct.type:"message";if(e.onSSEEvent?.(De,st),e.parseSSEEvent){C.current=y;let Qe=await ET(e,st,n,C,h,d,A);if(C.current&&C.current!==y&&(y=C.current),Qe){Ce();continue}}Ct&&(ye.push({...Ct,type:De}),ut()),Ce()}}ut()}var Fv,vf=Ve(()=>{"use strict";pi();ha();Cs();Nv();Fv=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<")});var qv,jv=Ve(()=>{qv="4.27.0"});var Xn,Sa=Ve(()=>{"use strict";jv();Xn=qv});var $d={};ys($d,{deleteAllConversations:()=>FT,deleteConversation:()=>NT,finalizeDisplayProjections:()=>DT,getConversation:()=>BT,historyErrorFor:()=>Zv,listConversations:()=>_T,readErrorCode:()=>wf,recoverFromUnauthorized:()=>Jv,resetVisitor:()=>$T});function HT(e,t,n){let o=new URLSearchParams;for(let[s,i]of Object.entries(n))i===void 0||i===""||o.set(s,String(i));let r=o.toString();return`${e.clientApiBase()}/v1/client/${t}${r?`?${r}`:""}`}function IT(e,t){if(t)return t;let n=e.config.features?.history?.scope;return n||(e.config.getIdentityProof?"verified-user":"browser")}async function RT(e,t,n){let o=e.config.getIdentityProof;if(!o)return n&&e.setHistoryIdentityStatus(e.browserOnlyStatus()),null;n&&e.setHistoryIdentityStatus({state:"verifying"});let r;try{r=await o()??null}catch{throw n&&e.setHistoryIdentityStatus({state:"identity_provider_failed"}),new e.HistoryClientError("identity_provider_failed","The identity proof provider failed")}if(r)return r;if(t.visitor?.endUserId!=null)throw n&&e.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new e.HistoryClientError("authentication_required","This browser is bound to a signed-in user and needs a fresh identity proof");return n&&e.setHistoryIdentityStatus({state:"browser_only",reason:"proof_unavailable_before_binding"}),null}async function WT(e,t,n,o){if(t.visitor?.endUserId!=null)return t;let r=await e.reinitWithProof(n);if(!(r.visitor?.identityStatus==="admitted"&&r.visitor?.endUserId!=null))throw o&&e.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new e.HistoryClientError("proof_not_admitted",Gv);return r}async function wf(e,t){let n=await t.json().catch(()=>({}));return typeof n.error=="string"?n.error:typeof n.message=="string"?n.message:""}async function Jv(e,t,n,o){let r=t.toLowerCase();if(r.includes("invalid_identity_proof"))throw o&&e.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new e.HistoryClientError("invalid_identity_proof",Yv);if(r.includes("visitor token required"))throw new e.HistoryClientError("visitor_token_missing",Xv);if(r.includes("visitor_identity_mismatch")){if(!n)throw o&&e.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new e.HistoryClientError("visitor_identity_mismatch",Qv);return e.reinitWithProof(n)}if(r.includes("expired")||r.includes("not found"))return e.clearClientSession(),e.initSession();throw new e.HistoryClientError("unauthorized",t||"History request was not authorized")}async function Zv(e,t,n){let o=await wf(e,t);if(t.status===404)return new e.HistoryClientError("not_found","Conversation not found");if(t.status===429){let r=Number.parseInt(t.headers.get("Retry-After")??"",10);return new e.HistoryClientError("rate_limited","Too many history requests",{...Number.isFinite(r)?{retryAfterSeconds:r}:{}})}if(t.status===503&&o.includes("identity_proof_not_admitted"))return n&&e.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new e.HistoryClientError("proof_not_admitted",Gv);if(t.status===401){let r=o.toLowerCase();return r.includes("invalid_identity_proof")?(n&&e.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new e.HistoryClientError("invalid_identity_proof",Yv)):r.includes("visitor token required")?new e.HistoryClientError("visitor_token_missing",Xv):r.includes("visitor_identity_mismatch")?new e.HistoryClientError("visitor_identity_mismatch",Qv):new e.HistoryClientError("unauthorized",o||"History request was not authorized")}return new e.HistoryClientError("request_failed",o||`History request failed (${t.status})`)}function OT(e,t,n,o){let r=t?.toLowerCase()??null;if(n){if(r==="admitted"){o&&e.setHistoryIdentityStatus({state:"verified"});return}throw o&&e.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),r==="ignored"?new e.HistoryClientError("identity_contract_violation","Server reported an ignored identity proof on a success response"):new e.HistoryClientError("proof_not_admitted","The response did not acknowledge the identity proof this request sent")}if(r==="admitted")throw new e.HistoryClientError("identity_contract_violation","Server admitted an identity proof that was never sent");o&&e.setHistoryIdentityStatus(e.browserOnlyStatus())}async function Aa(e,t,n){Sf(e);let o=n.trackIdentity!==!1,r=await e.initSession(),s=null;IT(e,n.scope)==="verified-user"&&(s=await RT(e,r,o),s&&(r=await WT(e,r,s,o)));let i=e.historyInternals.visitorStore,l=!1;for(;;){let c=i?.revision()??0,p=await e.readVisitorToken();if(!p&&!n.visitorTokenOptional)throw new e.HistoryClientError("visitor_token_missing","No visitor credential is stored for this browser");let d=await fetch(HT(e,t,{...n.query,sessionId:r.sessionId}),{method:n.method,headers:{"X-Persona-Version":Xn,...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(d.status===401&&!l){l=!0,r=await Jv(e,await wf(e,d),s,o);continue}if(!d.ok)throw await Zv(e,d,o);let g=d.headers.get("X-History-Identity-Status"),f=await d.json().catch(()=>{});if(i&&i.revision()!==c)throw new e.HistoryClientError("credential_changed","The visitor credential changed while the request was in flight");return OT(e,g,s!==null,o),f}}function Sf(e){if(!e.isClientTokenMode())throw new Error("Conversation history is only available in client token mode");if(!e.isHistoryCapable())throw new e.HistoryClientError("history_disabled","Visitor history is disabled for this surface")}async function _T(e,t){let n=await Aa(e,"conversations",{method:"GET",query:{...t?.cursor?{cursor:t.cursor}:{},...t?.limit!==void 0?{limit:t.limit}:{},...t?.targetId?{targetId:t.targetId}:{}},...t?.scope?{scope:t.scope}:{}});return{data:(Array.isArray(n?.data)?n.data:[]).map(Kv),nextCursor:typeof n?.nextCursor=="string"?n.nextCursor:null}}async function BT(e,t,n){let o=await Aa(e,`conversations/${encodeURIComponent(t)}`,{method:"GET",query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}});return{summary:Kv(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 function DT(e,t,n){Sf(e);let o=0;for(let c of n){let p=c.displayContent.length;if(p>zv)throw new e.HistoryClientError("payload_too_large",`displayContent exceeds the ${zv} character limit`);o+=p}if(o>Cf)throw new e.HistoryClientError("payload_too_large",`Display projection batch exceeds the ${Cf} character limit`);await e.initSession();let r=e.historyInternals.visitorStore,s=r?.revision()??0,i=await Aa(e,`conversations/${encodeURIComponent(t)}/display-projections`,{method:"PATCH",body:{messages:n},scope:"browser",keepalive:o<=Cf,trackIdentity:!1}),l=typeof i?.conversationRevision=="string"?i.conversationRevision:null;return l&&e.clientSession?.conversationId===t&&(r?.revision()??0)===s&&e.historyInternals.setStoredConversationRevision?.(l),{conversationRevision:l}}async function NT(e,t,n){let o=await Aa(e,`conversations/${encodeURIComponent(t)}`,{method:"DELETE",...n?.scope?{scope:n.scope}:{}});return{deleted:typeof o?.deleted=="number"?o.deleted:0}}async function FT(e,t){let n=await Aa(e,"conversations",{method:"DELETE",query:{...t?.targetId!==void 0?{targetId:t.targetId}:{}},...t?.scope?{scope:t.scope}:{}});return{deleted:typeof n?.deleted=="number"?n.deleted:0}}async function $T(e){Sf(e),e.setHistoryIdentityStatus({state:"resetting"});try{await Aa(e,"visitor/reset",{method:"POST",scope:"browser",visitorTokenOptional:!0})}finally{await e.historyInternals.visitorStore?.clear(),e.setHistoryIdentityStatus(e.derivedBrowserOnly())}return{reset:!0}}var zv,Cf,Kv,Gv,Yv,Xv,Qv,Af=Ve(()=>{"use strict";Sa();zv=32768,Cf=49152,Kv=e=>{let t=e??{},n=typeof t.targetId=="string"?t.targetId:null;return{id:typeof t.id=="string"?t.id:"",title:typeof t.title=="string"?t.title:"",targetId:n,preview:typeof t.preview=="string"?t.preview:null,messageCount:typeof t.messageCount=="number"?t.messageCount:0,createdAt:typeof t.createdAt=="string"?t.createdAt:"",updatedAt:typeof t.updatedAt=="string"?t.updatedAt:""}},Gv="The identity proof was not admitted; account history is unavailable",Yv="The identity proof was rejected",Xv="The request carried no visitor credential",Qv="The stored visitor belongs to a different signed-in user"});var tC,nC=Ve(()=>{"use strict";Rl();tC=e=>{let{mount:t,overlay:n,sessionRef:o}=e,r=(d,g,f)=>{let h=g.trim();if(!h||!o.current)return;let y=d.getAttribute("data-tool-call-id")??"",v=f.source==="free-text";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:y,answer:h,answers:f.structured,values:f.values??(f.source==="multi"?h.split(", "):[h]),isFreeText:v,source:f.source},bubbles:!0,composed:!0})),Wr(n,y);let C=o.current.getMessages().find(A=>A.toolCall?.id===y);C?.agentMetadata?.awaitingLocalTool?o.current.resolveAskUserQuestion(C,f.structured??h):o.current.sendMessage(h)},s=d=>{let g=o.current;if(!g)return;let f=d.getAttribute("data-tool-call-id")??"",h=g.getMessages().find(y=>y.toolCall?.id===f);h&&g.persistAskUserQuestionProgress(h,{answers:Rd(d,h),currentIndex:wo(d)})},i=d=>Object.entries(d).map(([g,f])=>`${g}: ${Array.isArray(f)?f.join(", "):f}`).join(" | "),l=d=>{if(e.config().features?.askUserQuestion?.groupedAutoAdvance===!1)return;let g=wo(d),f=va(d);if(g>=f-1)return;let h=o.current?.getMessages().find(y=>y.toolCall?.id===d.getAttribute("data-tool-call-id"));h&&(Od(d,h,e.config(),g+1),s(d))};return{click:d=>{let f=d.target.closest("[data-ask-user-action]");if(!f)return;let h=f.closest("[data-persona-ask-sheet-for]");if(!h)return;let y=f.getAttribute("data-ask-user-action");if(d.preventDefault(),d.stopPropagation(),y==="dismiss"){let v=h.getAttribute("data-tool-call-id")??"";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:v},bubbles:!0,composed:!0})),Wr(n,v);let C=o.current?.getMessages().find(A=>A.toolCall?.id===v);C?.agentMetadata?.awaitingLocalTool&&(o.current?.markAskUserQuestionResolved(C),o.current?.resolveAskUserQuestion(C,"(dismissed)"));return}if(y==="pick"){let v=f.getAttribute("data-option-label");if(!v)return;let C=h.getAttribute("data-multi-select")==="true",A=Ss(h);if(A&&C){let L=ui(h)[wo(h)],I=new Set(Array.isArray(L)?L:[]);I.has(v)?I.delete(v):I.add(v),As(h,Array.from(I)),s(h);return}if(A){As(h,v),s(h),l(h);return}if(C){let L=f.getAttribute("aria-pressed")==="true";f.setAttribute("aria-pressed",L?"false":"true"),f.classList.toggle("persona-ask-pill-selected",!L);let I=h.querySelector('[data-ask-user-action="submit-multi"]');I&&(I.disabled=ff(h).length===0);return}r(h,v,{source:"pick",values:[v]});return}if(y==="submit-multi"){let v=ff(h);if(v.length===0)return;r(h,v.join(", "),{source:"multi",values:v});return}if(y==="open-free-text"){let v=h.querySelector('[data-ask-free-text-row="true"]');v&&(v.classList.remove("persona-hidden"),v.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(y==="focus-free-text"){h.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(y==="submit-free-text"){let C=h.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!C.trim())return;if(Ss(h)){As(h,C.trim()),s(h),l(h);return}r(h,C,{source:"free-text"});return}if(y==="next"||y==="back"){if(!o.current)return;let v=h.getAttribute("data-tool-call-id")??"",C=o.current.getMessages().find(B=>B.toolCall?.id===v);if(!C)return;let L=h.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(L){let B=ui(h)[wo(h)];(typeof B!="string"||B!==L)&&As(h,L)}let I=y==="next"?1:-1,H=wo(h)+I;Od(h,C,e.config(),H),s(h);return}if(y==="submit-all"){if(!o.current)return;let v=h.getAttribute("data-tool-call-id")??"",C=o.current.getMessages().find(B=>B.toolCall?.id===v);if(!C)return;let L=h.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";L&&As(h,L);let I=Rd(h,C);o.current.persistAskUserQuestionProgress(C,{answers:I,currentIndex:wo(h)});let H=i(I);r(h,H||"(submitted)",{source:"submit-all",structured:I});return}if(y==="skip"){if(!o.current)return;let v=h.getAttribute("data-tool-call-id")??"",C=o.current.getMessages().find(V=>V.toolCall?.id===v);if(!C)return;let A=Ss(h),L=wo(h),I=va(h),H=L>=I-1;if(!A){t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:v},bubbles:!0,composed:!0})),Wr(n,v),C.agentMetadata?.awaitingLocalTool&&(o.current.markAskUserQuestionResolved(C),o.current.resolveAskUserQuestion(C,"(dismissed)"));return}As(h,"");let B=h.querySelector('[data-ask-free-text-input="true"]');if(B&&(B.value=""),H){let V=Rd(h,C),oe=i(V);r(h,oe||"(skipped)",{source:"submit-all",structured:V});return}Od(h,C,e.config(),L+1),s(h);return}},keydown:d=>{if(d.key!=="Enter")return;let f=d.target;if(!f.matches?.('[data-ask-free-text-input="true"]'))return;let h=f.closest("[data-persona-ask-sheet-for]");if(!h)return;d.preventDefault();let y=f.value;if(y.trim()){if(Ss(h)){As(h,y.trim()),s(h),l(h);return}r(h,y,{source:"free-text"})}}}}});function jT(e,t,n){if(n==="input-start")return t===0;let o=t>0?e[t-1]:"";return n==="line-start"?o===""||o===`
|
|
8
|
+
`:o===""||oC.test(o)}function qT(e,t,n="@",o="anywhere",r=!1){if(!n||t<=0||t>e.length)return null;let s=t-1;for(;s>=0;){let i=e[s];if(i===n)return jT(e,s,o)?{triggerIndex:s,query:e.slice(s+1,t)}:null;if(i===`
|
|
9
|
+
`||i==="\uFFFC"||!r&&oC.test(i))return null;s--}return null}function rC(e,t,n){for(let o of n){let r=qT(e,t,o.trigger,o.position??"anywhere",o.allowSpaces??!1);if(r)return{channel:o,match:r}}return null}function sC(e){return e?e!=="insertFromPaste"&&e!=="insertFromDrop":!0}var oC,iC=Ve(()=>{"use strict";oC=/\s/});function aC(e){let t={trigger:e.trigger??"@",position:e.triggerPosition??"anywhere",allowSpaces:!1,sources:Array.isArray(e.sources)?e.sources:[],searchPlaceholder:e.searchPlaceholder,showButton:e.showButton!==!1,buttonIconName:e.buttonIconName,buttonTooltipText:e.buttonTooltipText},n=(e.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[t,...n]}var lC=Ve(()=>{"use strict"});var Ud=Ve(()=>{"use strict"});function uC(e){e.delayMs!==void 0&&(cC=jd(e.delayMs)),e.skipDelayMs!==void 0&&(dC=jd(e.skipDelayMs))}function gC(e){Vd.get(e)?.hide()}function vn(e){Vd.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:o,hint:r,enabled:s=!0,gap:i=zT,viewportPadding:l=KT}=e,c=()=>t.ownerDocument,p=()=>c().defaultView??window,d=null,g=null,f=null,h=null,y,v=!1,C=!1,A=!1,L=()=>(typeof o=="function"?o():o).trim(),I=()=>(typeof r=="function"?r():r??"").trim(),H=()=>jd(e.delayMs??cC),B=()=>jd(e.skipDelayMs??dC),V=()=>{y!==void 0&&(p().clearTimeout(y),y=void 0)},oe=()=>{V();let me=d!==null;h?.(),h=null,d?.remove(),d=null,g=null,f=null,me&&YT(B())},W=()=>{if(!d)return;let me=c(),He=p(),Ee=t.getBoundingClientRect(),Ie=d.getBoundingClientRect(),yt=me.documentElement.clientWidth||He.innerWidth,qe=me.documentElement.clientHeight||He.innerHeight,Oe=yt-l-Ie.width,$=Ee.left+Ee.width/2-Ie.width/2,_e=Ef($,l,Oe),ye=Ee.top-l,ut=qe-l-Ee.bottom,Zt=Ie.height+i,xt=ye>=Zt||ye>=ut?"top":"bottom",xe=xt==="top"?Ee.top-i-Ie.height:Ee.bottom+i,Wt=qe-l-Ie.height,vt=Ef(xe,l,Wt),Le=Ee.left+Ee.width/2,Xe=Math.max(xf,Ie.width-xf),D=Ef(Le-_e,xf,Xe);d.dataset.placement=xt,d.style.left=`${_e}px`,d.style.top=`${vt}px`,d.style.setProperty("--persona-tooltip-arrow-x",`${D}px`)},j=()=>{if(A||!s||d||!t.isConnected||XT(t))return;let me=L(),He=QT(t);if(!me||!He)return;let Ee=c(),Ie=p();d=Ee.createElement("div"),d.className="persona-control-tooltip",d.setAttribute("role","tooltip"),d.dataset.state="measuring",d.style.zIndex=String(wa);let yt=Ie.getComputedStyle?.(t);if(yt){for(let Zt of JT){let xt=yt.getPropertyValue(Zt).trim();xt&&d.style.setProperty(Zt,xt)}yt.fontFamily&&(d.style.fontFamily=yt.fontFamily)}g=Ee.createElement("span"),g.className="persona-control-tooltip__label",g.textContent=me,d.appendChild(g);let qe=I();qe&&(f=Ee.createElement("span"),f.className="persona-control-tooltip__hint",f.textContent=qe,d.appendChild(f));let Oe=Ee.createElement("span");Oe.className="persona-control-tooltip__arrow",d.appendChild(Oe),He.appendChild(d),W(),d.dataset.state="open";let $=()=>{if(!t.isConnected){oe();return}g&&(g.textContent=L()),f&&(f.textContent=I()),W()};Ie.addEventListener("scroll",$,!0),Ie.addEventListener("resize",$);let _e=t.getRootNode(),ye=fC(_e)?_e:Ee.documentElement,ut=typeof MutationObserver>"u"?null:new MutationObserver(()=>{t.isConnected||oe()});ut?.observe(ye,{childList:!0,subtree:!0}),h=()=>{Ie.removeEventListener("scroll",$,!0),Ie.removeEventListener("resize",$),ut?.disconnect()}},X=me=>{if(!(A||d)){if(V(),me||H()<=0||GT()){j();return}y=p().setTimeout(()=>{y=void 0,j()},H())}},M=()=>{v||C?X(C):oe()},T=()=>{let me=p();(!me.matchMedia||!me.matchMedia("(hover: none)").matches)&&(v=!0,M())},_=()=>{v=!1,M()},P=()=>{try{C=t.matches(":focus-visible")}catch{C=!0}M()},J=()=>{C=!1,M()},U=()=>{v=!1,C=!1,oe()},ue=me=>{me.key==="Escape"&&U()};n.addEventListener("mouseenter",T),n.addEventListener("mouseleave",_),t.addEventListener("focus",P),t.addEventListener("blur",J),t.addEventListener("keydown",ue),t.addEventListener("click",U);let fe={get isOpen(){return d!==null},show:j,hide:oe,reposition:W,destroy:()=>{A||(A=!0,oe(),n.removeEventListener("mouseenter",T),n.removeEventListener("mouseleave",_),t.removeEventListener("focus",P),t.removeEventListener("blur",J),t.removeEventListener("keydown",ue),t.removeEventListener("click",U),Vd.delete(t))}};return Vd.set(t,fe),fe}var zT,KT,xf,cC,dC,pC,jd,GT,YT,Vd,Mf,XT,fC,QT,Ef,JT,xa=Ve(()=>{"use strict";_o();Ud();zT=8,KT=8,xf=10,cC=200,dC=300,pC=0,jd=e=>Math.max(0,e);GT=()=>Date.now()<pC,YT=e=>{pC=e>0?Date.now()+e:0},Vd=new WeakMap,Mf="data-persona-tooltip-suppressed",XT=e=>typeof e.closest=="function"&&e.closest(`[${Mf}]`)!==null;fC=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,QT=e=>{let t=e.getRootNode?.();return fC(t)?t:e.ownerDocument.body},Ef=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n)),JT=[...["background","foreground","hint-fg","radius","font-size","padding","max-width","shadow","arrow-display"].map(e=>`--persona-tooltip-${e}`),"--persona-font-family","--persona-radius-sm"]});var ZT,hi,Tf,Pf=Ve(()=>{"use strict";ZT=(e,t)=>e.visible!==!1&&(e.mode!=="transient"||t==="connecting"||t==="paused"||t==="resuming"||t==="error"),hi=(e,t,n)=>{let o=t.mode==="transient",r=e.hasAttribute("data-persona-composer-reason")||e.hasAttribute("data-persona-composer-notice");e.style.display=ZT(t,n)||o&&r&&t.visible!==!1?"":"none",e.classList.toggle("persona-mt-2",!o),e.classList.toggle("persona-mb-2",o)},Tf=(e,t,n)=>{!t.parentElement||e.parentElement!==t.parentElement||(n.mode==="transient"?e.nextElementSibling!==t&&t.before(e):t.nextElementSibling!==e&&t.after(e))}});function Bo(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];mC(s)&&mC(r)?n[o]=Bo(s,r):n[o]=r}return n}var mC,qd=Ve(()=>{"use strict";mC=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});function zd(e,t=""){return Object.entries(e).flatMap(([n,o])=>{let r=t?`${t}.${n}`:n;return Lf(o)?zd(o,r):[r]})}function hC(e,t){for(let n of t.split(".")){if(!Lf(e)||!Object.prototype.hasOwnProperty.call(e,n))return"absent";if(e=e[n],e===void 0)return"clear"}return"explicit"}function yC(e,t){return e?.[kf]??t.filter(n=>hC(e,n)==="explicit")}function Hf(e,t){return Object.defineProperty(e,kf,{value:t,enumerable:!0,configurable:!0}),e}function If(e,t,n){return Hf(e,yC(t,zd(n)))}function bC(e,t,n){let o=t[kf];if(o)return o;let r=new Set(yC(e,n));for(let s of n){let i=hC(t,s);i==="clear"&&r.delete(s),i==="explicit"&&r.add(s)}return[...r]}function vC(e,t,n){let o={...e};for(let r of t){if(n.includes(r))continue;let s=r.split("."),i=o;for(let l of s.slice(0,-1)){let c=i[l];if(!Lf(c)){i=void 0;break}i[l]={...c},i=i[l]}i&&delete i[s[s.length-1]]}return o}var kf,Lf,Rf=Ve(()=>{"use strict";kf=Symbol("persona.defaultsProvenance"),Lf=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});var CC,Wf,yi,Kd,eP,_r,Of,_f,wC,Ea=Ve(()=>{"use strict";CC="var(--persona-components-panel-width)",Wf=Symbol("persona.panelAliasProvenance"),yi=(e,t)=>e!=null&&Object.prototype.hasOwnProperty.call(e,t),Kd=(e,t)=>yi(e,t)&&e[t]!==void 0,eP=e=>({launcherWidth:Kd(e?.launcher,"width"),legacyLauncherWidth:Kd(e,"launcherWidth"),sidebarWidth:Kd(e?.launcher,"sidebarWidth"),dockWidth:Kd(e?.launcher?.dock,"width")}),_r=e=>{let t=e?.[Wf];return t?{...t}:eP(e)},Of=(e,t)=>(Object.defineProperty(e,Wf,{value:t,enumerable:!0,configurable:!0}),e),_f=(e,t)=>Of(e,_r(t)),wC=(e,t)=>{let n=t[Wf];if(n)return{...n};let o=_r(e);return yi(t,"launcherWidth")&&(o.legacyLauncherWidth=t.launcherWidth!==void 0),yi(t,"launcher")&&t.launcher===void 0?(o.launcherWidth=!1,o.sidebarWidth=!1,o.dockWidth=!1,o):(yi(t.launcher,"width")&&(o.launcherWidth=t.launcher?.width!==void 0),yi(t.launcher,"sidebarWidth")&&(o.sidebarWidth=t.launcher?.sidebarWidth!==void 0),yi(t.launcher,"dock")&&t.launcher?.dock===void 0?o.dockWidth=!1:yi(t.launcher?.dock,"width")&&(o.dockWidth=t.launcher?.dock?.width!==void 0),o)}});function Es(e){return e?.future?.v5Defaults===!0?"v5":"v4"}function xC(e){let t=Es(e)==="v5"?bi:oP;return Bo(nP,t)}function SC(e,t){if(!(!e&&!t))return e?t?Bo(e,t):e:t}function Ma(e){let t=xC(e);return e?If(_f({...t,...e,theme:SC(t.theme,e.theme),darkTheme:SC(t.darkTheme,e.darkTheme),launcher:{...t.launcher,...e.launcher,dock:{...t.launcher?.dock,...e.launcher?.dock},clearChat:{...t.launcher?.clearChat,...e.launcher?.clearChat}},...t.composer||e.composer?{composer:{...t.composer,...e.composer}}:{},tooltip:{...t.tooltip,...e.tooltip},copy:{...t.copy,...e.copy},sendButton:{...t.sendButton,...e.sendButton},statusIndicator:{...t.statusIndicator,...e.statusIndicator},voiceRecognition:{...t.voiceRecognition,...e.voiceRecognition},features:(()=>{let n=t.features?.artifacts,o=e.features?.artifacts,r=t.features?.scrollToBottom,s=e.features?.scrollToBottom,i=t.features?.scrollBehavior,l=e.features?.scrollBehavior,c=t.features?.streamAnimation,p=e.features?.streamAnimation,d=t.features?.askUserQuestion,g=e.features?.askUserQuestion,f=t.features?.history,h=e.features?.history,y=n===void 0&&o===void 0?void 0:{...n,...o,layout:{...n?.layout,...o?.layout}},v=r===void 0&&s===void 0?void 0:{...r,...s},C=i===void 0&&l===void 0?void 0:{...i,...l},A=c===void 0&&p===void 0?void 0:{...c,...p},L=d===void 0&&g===void 0?void 0:{...d,...g,styles:{...d?.styles,...g?.styles}},I=f===void 0&&h===void 0?void 0:{...f,...h,copy:{...f?.copy,...h?.copy}};return{...t.features,...e.features,toolCallDisplay:{...t.features?.toolCallDisplay,...e.features?.toolCallDisplay},reasoningDisplay:{...t.features?.reasoningDisplay,...e.features?.reasoningDisplay},...v!==void 0?{scrollToBottom:v}:{},...C!==void 0?{scrollBehavior:C}:{},...y!==void 0?{artifacts:y}:{},...A!==void 0?{streamAnimation:A}:{},...L!==void 0?{askUserQuestion:L}:{},...I!==void 0?{history:I}:{}}})(),suggestionChips:e.suggestionChips??t.suggestionChips,suggestionChipsConfig:{...t.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...t.layout,...e.layout,header:{...t.layout?.header,...e.layout?.header},messages:{...t.layout?.messages,...e.layout?.messages,...t.layout?.messages?.user||e.layout?.messages?.user?{user:{...t.layout?.messages?.user,...e.layout?.messages?.user}}:{},...t.layout?.messages?.assistant||e.layout?.messages?.assistant?{assistant:{...t.layout?.messages?.assistant,...e.layout?.messages?.assistant}}:{},avatar:{...t.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...t.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...t.layout?.slots,...e.layout?.slots}},markdown:{...t.markdown,...e.markdown,options:{...t.markdown?.options,...e.markdown?.options}},messageActions:{...t.messageActions,...e.messageActions}},e),e,bi):If(_f(t),void 0,bi)}var vi,AC,_l,Bf,Br,Ci,tP,nP,oP,rP,bi,EC,So=Ve(()=>{"use strict";qd();Rf();Ea();Ud();vi="min(440px, calc(100vw - 24px))",AC="440px",_l="40px",Bf="How can I help...",Br={collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",previewMaxLines:3,expandable:!0,loadingAnimation:"none"},Ci={activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},tP={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:vi,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:_l,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)"},nP={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:tP,copy:{inputPlaceholder:Bf,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:Br,reasoningDisplay:Ci,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},oP={},rP={variant:"circle",width:"min(400px, calc(100vw - 24px))",headerIconSize:"20px"},bi={launcher:rP,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"}}}};EC=xC()});function MC(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Gd(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Pa(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function TC(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function Ao(e){return{type:"text",text:e}}function Yd(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function PC(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;t({type:"image",image:r,mimeType:e.type,alt:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function kC(e,t=["image/png","image/jpeg","image/gif","image/webp"],n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}function iP(e){return LC.includes(e)||e.startsWith("image/")}function Xd(e){return iP(e.type)}function HC(e,t,n){return{type:"file",data:e,mimeType:t,filename:n}}async function IC(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;Xd(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function RC(e,t=Dr,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function aP(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function WC(e,t){let n=aP(t).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"}[e]||n||"FILE"}var Ta,LC,sP,Dr,Nr=Ve(()=>{"use strict";Ta="[Image]";LC=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],sP=["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"],Dr=[...LC,...sP]});function Df(e){let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return 20;let n=t.getComputedStyle(e).lineHeight;if(!n||!n.trim().endsWith("px"))return 20;let o=parseFloat(n);return Number.isFinite(o)&&o>0?o:20}function Qd(e,t){return typeof e!="number"||!Number.isFinite(e)?t:e>0?e:t}function OC(e,t){e.style.maxHeight=`${t*Df(e)}px`,e.style.overflowY="auto"}function Bl(e){let t=e?.ownerDocument?.defaultView??(typeof window<"u"?window:null);if(!t||typeof t.matchMedia!="function")return!1;try{return t.matchMedia("(pointer: coarse)").matches===!0}catch{return!1}}function _C(e){return e.insertNewlineOnTouchEnter===!0&&e.coarsePointer===!0}function BC(e,t){if(e.key!=="Enter"||e.shiftKey||e.isComposing)return!1;let n=e.metaKey===!0||e.ctrlKey===!0,o=t.submitKey??"enter";return o==="none"?!1:o==="mod-enter"?n:n||!_C(t)}function lP(e){return(e.submitKey??"enter")!=="enter"||_C(e)?"enter":"send"}function Jd(e,t){e.setAttribute("enterkeyhint",lP(t))}function Zd(e,t){let n=t?.autocomplete;e.setAttribute("autocomplete",typeof n=="string"&&n?n:"off");let o=(r,s)=>{s===void 0?e.removeAttribute(r):e.setAttribute(r,s)};o("autocapitalize",typeof t?.autocapitalize=="string"?t.autocapitalize:void 0),o("spellcheck",typeof t?.spellcheck=="boolean"?String(t.spellcheck):void 0),o("inputmode",typeof t?.inputmode=="string"&&t.inputmode?t.inputmode:void 0),o("aria-label",typeof t?.ariaLabel=="string"&&t.ariaLabel?t.ariaLabel:void 0)}function Nf(e){return e===!0?{disabled:!0}:!e||typeof e!="object"?{disabled:!1}:{disabled:!0,reason:typeof e.reason=="string"&&e.reason?e.reason:void 0}}var ep=Ve(()=>{"use strict"});var so,Do,$f,Qn,tp,np,dP,Uf,op,ka,rp,sp,ip,Ms=Ve(()=>{"use strict";Pf();Ze();kt();So();Nr();xa();ep();so="persona-composer-control",Do="persona-composer-control--glyph",$f=40,Qn=24,tp=(e,t,n)=>{let o=e.ownerDocument?.defaultView;if(!o)return;let r=o.getComputedStyle(e);for(let s of n){let i=r.getPropertyValue(s).trim();i?t.style.setProperty(s,i):t.style.removeProperty(s)}},np=(e,t)=>{let n=x("textarea");n.setAttribute("data-persona-composer-input",""),n.placeholder=e?.copy?.inputPlaceholder??Bf,n.dir="auto",Jd(n,{submitKey:e?.composer?.submitKey,insertNewlineOnTouchEnter:e?.composer?.insertNewlineOnTouchEnter,coarsePointer:Bl(n)}),Zd(n,e?.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=Qd(e?.composer?.maxLines,t?.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*Df(n);return r=`${c}px`,n.style.maxHeight=r,c},i=()=>{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:i}},dP="[data-persona-glyph-stack]",Uf=(e,t,n="send")=>{let o=Q("span",{className:"persona-composer-glyph-stack",attrs:{"data-mode":n,"data-persona-glyph-stack":""}});return e.setAttribute("data-glyph","send"),t.setAttribute("data-glyph","stop"),o.append(e,t),o},op=e=>{let t=e?.sendButton??{},n=t.useIcon??!1,o=t.iconText??"\u2191",r=t.iconName,s=t.stopIconName??"square",i=t.tooltipText??"Send message",l=t.stopTooltipText??"Stop generating",c=e?.copy?.sendButtonLabel??"Send",p=e?.copy?.stopButtonLabel??"Stop",d=t.showTooltip??!1,g=t.size,f=parseFloat(g??"")||$f,h=t.backgroundColor,y=t.textColor,v=x("div","persona-send-button-wrapper"),C=Q("button",{className:Dn("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?`persona-flex persona-items-center persona-justify-center ${so}`:"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!h&&"persona-bg-persona-primary",!n&&!y&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":"","data-persona-send-mode":"send"},style:{width:n?g:void 0,height:n?g:void 0,minWidth:n?g:void 0,minHeight:n?g:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?y||"var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))":y||void 0,backgroundColor:n&&h||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:n?"0":t.paddingX||void 0,paddingRight:n?"0":t.paddingX||void 0,paddingTop:n?"0":t.paddingY||void 0,paddingBottom:n?"0":t.paddingY||void 0}}),A=null,L=null,I=null;if(n){let V=parseFloat(t.iconSize??"")||Math.round(f*.5),oe=t.iconStrokeWidth??2,W=y?.trim()||"currentColor";if(r&&(A=ge(r,V,W,oe)),L=ge(s,V,W,oe),!t.iconSize)for(let j of[A,L])j&&(j.style.width=`var(--persona-components-composer-sendIconSize, ${V}px)`,j.style.height=`var(--persona-components-composer-sendIconSize, ${V}px)`);A&&L?(I=Uf(A,L),C.appendChild(I)):A?C.appendChild(A):(C.textContent=o,L=null)}else C.textContent=c;C.setAttribute("aria-label",i),v.appendChild(C),vn({anchor:C,trigger:v,text:()=>C.getAttribute("aria-label")??"",enabled:d});let H="send";return{button:C,wrapper:v,setMode:V=>{if(V===H)return;H=V;let oe=V==="stop"?l:i;C.setAttribute("aria-label",oe),C.setAttribute("data-persona-send-mode",V),n?(C.querySelector(dP)??I)?.setAttribute("data-mode",V):C.textContent=V==="stop"?p:c},glyphStack:I}},ka=e=>{let t=e?.voiceRecognition??{};if(!(t.enabled===!0))return null;let o=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),r=t.provider?.type==="runtype",s=t.provider?.type==="custom";if(!(o||r||s))return null;let l=t.iconName??"mic",c=t.iconSize,p=parseFloat(c??"")||Qn,d=t.backgroundColor??e?.sendButton?.backgroundColor,g=t.iconColor??e?.sendButton?.textColor,f=x("div","persona-send-button-wrapper"),h=Q("button",{className:Dn("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",so,!c&&Do),attrs:{type:"button","data-persona-composer-mic":"","data-state":"idle","aria-label":t.tooltipText??"Start voice recognition"},style:{width:c,height:c,minWidth:c,minHeight:c,fontSize:"18px",lineHeight:"1",color:g||"var(--persona-text, #111827)",backgroundColor:d||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),v=ge(l,p,g||"currentColor",1.5);v?h.appendChild(v):h.textContent="\u{1F3A4}",f.appendChild(h);let C=t.tooltipText??"Start voice recognition",A=t.showTooltip??!1;return vn({anchor:h,trigger:f,text:()=>h.getAttribute("aria-label")??C,enabled:A}),{button:h,wrapper:f}},rp=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=x("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=x("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=(t.allowedTypes??Dr).join(","),o.multiple=(t.maxFiles??4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let r=t.buttonIconName??"paperclip",s=x("div","persona-send-button-wrapper"),i=Q("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${so} ${Do}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),l=ge(r,Qn,"currentColor",1.5);l?i.appendChild(l):i.textContent="\u{1F4CE}",i.addEventListener("click",p=>{p.preventDefault(),o.click()}),s.appendChild(i);let c=t.buttonTooltipText??"Attach file";return vn({anchor:i,trigger:s,text:()=>i.getAttribute("aria-label")??c}),{button:i,wrapper:s,input:o,previewsContainer:n}},sp=e=>{let t=e?.statusIndicator??{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=x("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status",""),hi(o,t,"idle");let r=t.idleText??"Online";if(t.idleLink){let s=x("a");s.href=t.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},ip=()=>Q("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}})});function ap(e){let{config:t,onOpen:n}=e,o=t.buttonIconName??"plus",r=t.buttonTooltipText??"Add context",s=x("div","persona-send-button-wrapper"),i=Q("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${so} ${Do}`,attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":r,"aria-haspopup":"listbox","aria-expanded":"false"},style:{fontSize:"18px",lineHeight:"1"}}),l=ge(o,Qn,"currentColor",1.5);return l?i.appendChild(l):i.textContent="+",i.addEventListener("click",c=>{c.preventDefault(),c.stopPropagation(),n()}),s.appendChild(i),vn({anchor:i,trigger:s,text:()=>i.getAttribute("aria-label")??r}),{button:i,wrapper:s}}var Vf=Ve(()=>{"use strict";Ze();kt();xa();Ms()});var fW,pP,lp,jf=Ve(()=>{"use strict";dn();({setLoader:fW,load:pP}=lt({fallbackImport:()=>import("@runtypelabs/persona/context-mentions")})),lp=pP});var yW,uP,cp,qf=Ve(()=>{"use strict";dn();({setLoader:yW,load:uP}=lt({fallbackImport:()=>import("@runtypelabs/persona/context-mentions-inline"),resetOnSetLoader:!0})),cp=uP});function Dl(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=Q("span",{className:Dn("persona-mention-token",t.readonly&&"persona-mention-token-readonly"),attrs:{"data-mention-source":e.sourceId,title:e.label,role:"img","aria-label":`${e.label} mention`}});e.color&&n.style.setProperty("--persona-mention-token-accent",e.color);let o=ge(e.iconName??"at-sign",13,"currentColor",2);if(o){let r=x("span","persona-mention-token-icon");r.appendChild(o),n.appendChild(r)}return n.appendChild(Q("span",{className:"persona-mention-token-label",text:`@${e.label}`})),n}var zf=Ve(()=>{"use strict";Ze();kt()});function DC(e){let{loadContextMentions:t,loadContextMentionsInline:n,renderLucideIcon:o,createMentionButton:r}=e.deps??gP,s=e.config.contextMentions;if(!s?.enabled)return null;let i=aC(s).filter(W=>W.sources.length>0);if(i.length===0)return typeof console<"u"&&console.warn("[Persona] contextMentions.enabled is true but no sources were provided; mentions are disabled."),null;let l=i.filter(W=>W.sources.some(j=>typeof j.matchCommand=="function")),c=W=>l.some(j=>j.trigger?j.position==="line-start"?W.split(`
|
|
10
|
+
`).some(M=>M.startsWith(j.trigger)):(j.position==="anywhere"?W:W.split(`
|
|
11
|
+
`)[0]).startsWith(j.trigger):!1),p=(W,j)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${W}`,{detail:j}))}catch{}},d=!e.chipRow,g=e.chipRow??Q("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),f=null,h=null,y=e.textarea,v=null,C=null,A=null,L=null,I=()=>{if(f)return Promise.resolve(f);if(h)return h;let W=t().then(j=>(j.setMentionIconRenderer(o),f=j.mountContextMentions({mentionConfig:s,textarea:e.textarea,composerInput:v??void 0,anchor:e.anchor,contextRow:g,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:oe,emit:p}),f)).catch(j=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",j),h===W&&(h=null),null));return h=W,W},H=()=>{n().then(W=>{let j=W.mountInlineComposer({textarea:e.textarea,renderToken:M=>Dl(M,{render:s.renderMentionToken}),onMentionRemoved:M=>f?.untrackMention(M)});v=j.input,C=j.destroy;let X=y;X.replaceWith(j.element),y=j.element,L={next:j.element,prev:X},A?.(j.element,X),f?f.rebindComposer(j.input):h&&h.then(M=>M?.rebindComposer(j.input))}).catch(W=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",W)})};s.display==="inline"&&H();let B=[],V=new Map;for(let W of i){if(!W.showButton)continue;let j=r({config:{...s,buttonIconName:W.buttonIconName,buttonTooltipText:W.buttonTooltipText},onOpen:()=>{I().then(X=>X?.openMenu(W.trigger))}});B.push(j),V.set(W.trigger,j.button)}let oe=(W,j,X)=>{let M=V.get(j);M&&(M.setAttribute("aria-expanded",W?"true":"false"),W?M.setAttribute("aria-controls",X):M.removeAttribute("aria-controls"))};return{affordanceButtons:B.map(W=>W.wrapper),contextRow:g,handleInput:W=>{if(f){f.handleInput();return}if(!sC(W))return;let j=y,X=j.selectionStart??0;rC(j.value,X,i)&&I().then(M=>M?.handleInput())},handleKeydown:W=>{if(f?.isMenuOpen())return f.handleKeydown(W);if(W.key==="Backspace"&&f?.hasMentions()&&!L){let j=y,X=j.selectionStart===0&&j.selectionEnd===0;if((j.value.length===0||X)&&f.removeLastChip())return W.preventDefault(),!0}return!1},isMenuOpen:()=>f?.isMenuOpen()??!1,hasMentions:()=>f?.hasMentions()??!1,getMentionRefs:()=>f?.getMentionRefs()??[],collectForSubmit:()=>f?.collectForSubmit()??null,takeInlineCommand:async W=>c(W)?(f??await I())?.dispatchInlineCommand(W)??null:null,clear:()=>f?.clear(),prefetch:()=>{t().catch(()=>{})},onComposerSwap:W=>{A=W,L&&W(L.next,L.prev)},destroy:()=>{f?.destroy(),C?.();for(let W of B)W.wrapper.remove();d&&g.remove()}}}var gP,NC=Ve(()=>{"use strict";Ze();iC();lC();Vf();jf();kt();qf();zf();gP={loadContextMentions:()=>lp(),loadContextMentionsInline:()=>cp(),renderLucideIcon:(...e)=>ge(...e),createMentionButton:(...e)=>ap(...e)}});var dp={};ys(dp,{createAskUserSheetHandlers:()=>tC,createContextMentionOrchestrator:()=>DC});var Kf=Ve(()=>{"use strict";nC();NC()});var gp={};ys(gp,{resolveApproval:()=>bP,resolveAskUserQuestion:()=>vP,resolveWebMcpToolCall:()=>SP,resolveWebMcpToolCallBatch:()=>UC});async function bP(e,t,n,o){let r=`approval-${t.id}`,s=`approval-error-${t.id}`,i={};e.s.approvalTokens.set(r,i);let l={...t,status:n,resolvedAt:Date.now()},c=e.s.messages.find(f=>f.id===r),p={id:r,role:"assistant",content:"",createdAt:c?.createdAt??new Date().toISOString(),...c?.sequence!==void 0?{sequence:c.sequence}:{},streaming:!1,variant:"approval",approval:l};e.s.upsertMessage(p),e.s.abortController?.abort(),e.s.abortController=new AbortController,e.setStreaming(!0);let d=e.s.config.approval,g=d&&typeof d=="object"?d.onDecision:void 0;try{let f;if(g?f=await g({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,o):f=await e.s.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),f){let h=null;if(f instanceof Response){if(!f.ok){let y=await f.json().catch(()=>null),v=y?.message??y?.error??`Approval request failed: ${f.status}`,C=y?.code==="APPROVAL_ALREADY_RESOLVED"||f.status===404&&/no paused execution/i.test(String(y?.error)),A=e.s.messages.find(L=>L.id===r);throw e.s.approvalTokens.get(r)===i&&A?.approval?.resolvedAt===l.resolvedAt&&(e.s.upsertMessage({...p,approval:C?{...l,status:"timeout"}:t}),C&&e.settleApprovalPausedToolCall(r),e.s.upsertMessage({id:s,role:"assistant",content:v,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()})),new Error(v)}h=f.body}else f instanceof ReadableStream&&(h=f);e.s.approvalTokens.get(r)===i&&e.s.messages.some(y=>y.id===s)&&(e.s.messages=e.s.messages.filter(y=>y.id!==s),e.s.callbacks.onMessagesChanged([...e.s.messages])),h?await e.s.connectStream(h,{allowReentry:!0}):(n==="denied"&&(e.settleApprovalPausedToolCall(r),e.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()})),e.setStreaming(!1),e.s.abortController=null)}else e.setStreaming(!1),e.s.abortController=null}catch(f){let h=f instanceof Error&&(f.name==="AbortError"||f.message.includes("aborted")||f.message.includes("abort"));e.setStreaming(!1),e.s.abortController=null,h||e.s.callbacks.onError?.(f instanceof Error?f:new Error(String(f)))}finally{e.s.approvalTokens.get(r)===i&&e.s.approvalTokens.delete(r)}}async function vP(e,t,n){if(e.s.messages.find(d=>d.id===t.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=t.agentMetadata?.executionId,s=t.toolCall?.name;if(!r||!s){e.s.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let i=typeof n=="string"?void 0:n;if(i===void 0&&typeof n=="string"){let d=t.toolCall?.args,g=Array.isArray(d?.questions)?d.questions:[];if(g.length===1){let f=typeof g[0]?.question=="string"?g[0].question:"";f&&(i={[f]:n})}}e.s.markAskUserQuestionResolved(t,i),e.s.abortController?.abort(),e.s.abortController=new AbortController,e.setStreaming(!0);let l=t.toolCall.id,c=t.toolCall?.args,p=Array.isArray(c?.questions)?c.questions:[];if(p.length===0){let d=typeof n=="string"?n:Object.entries(n).map(([g,f])=>`${g}: ${Array.isArray(f)?f.join(", "):f}`).join(" | ");e.appendMessage({id:`ask-user-answer-${l}`,role:"user",content:d,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()})}else{let d=i??{};p.forEach((g,f)=>{let h=typeof g?.question=="string"?g.question:"";if(!h)return;let y=d[h],v=Array.isArray(y)?y.join(", "):typeof y=="string"?y:"";e.appendMessage({id:`ask-user-q-${l}-${f}`,role:"assistant",content:h,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()}),e.appendMessage({id:`ask-user-a-${l}-${f}`,role:"user",content:v||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()})})}try{let d=await e.s.client.resumeFlow(r,{[s]:n},{after:e.resumeAfter(r)});if(!d.ok){let g=await d.json().catch(()=>null);throw new Error(g?.error??`Resume failed: ${d.status}`)}d.body?await e.s.connectStream(d.body,{allowReentry:!0}):(e.setStreaming(!1),e.s.abortController=null)}catch(d){let g=d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"));e.setStreaming(!1),e.s.abortController=null,g||e.s.callbacks.onError?.(d instanceof Error?d:new Error(String(d)))}}function CP(e,t){let o=[e.s.messages.find(r=>r.id===t.id)?.toolCall?.startedAt,t.toolCall?.startedAt];for(let r of o)if(typeof r=="number"&&Number.isFinite(r))return r;return Date.now()}function $C(e,t){return t.toolCall?.name!==Oo?!1:(e.s.messages.find(o=>o.id===t.id)??t).agentMetadata?.suggestRepliesResolved===!0}function wP(e,t){let n=CP(e,t);return e.s.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}function up(e,t,n,o,r=Date.now(),s){e.s.messages.some(i=>i.id===t.id)&&e.s.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...s},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:o,completedAt:r,duration:void 0,durationMs:Math.max(0,r-o)}:t.toolCall})}async function UC(e,t,n){let o=[],r=new AbortController;e.s.webMcpResolveControllers.add(r),e.setStreaming(!0);let s=async c=>{let p=c.toolCall?.name,d=c.toolCall?.id;if(!p||!d)return null;let g=`${t}:${d}`;if(e.s.webMcpInflightKeys.has(g)||e.s.webMcpResolvedKeys.has(g)||$C(e,c))return null;e.s.webMcpInflightKeys.add(g),o.push(g);let f=wP(e,c),h=c.agentMetadata?.webMcpToolCallId??p;if(p===Oo)return{dedupeKey:g,resumeKey:h,output:_v(),toolMessage:c,startedAt:f,completedAt:Date.now()};let y=e.s.client.executeWebMcpToolCall(p,c.toolCall?.args,r.signal),v;if(!y)v={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{v=await y}catch(C){let A=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));return A||e.s.callbacks.onError?.(C instanceof Error?C:new Error(String(C))),up(e,c,Yf(A?"Aborted by cancel()":yP(C)),f),e.s.webMcpInflightKeys.delete(g),null}return r.signal.aborted?(up(e,c,Yf("Aborted by cancel()"),f),e.s.webMcpInflightKeys.delete(g),null):{dedupeKey:g,resumeKey:h,output:v,toolMessage:c,startedAt:f,completedAt:Date.now()}},i;if(e.s.config.webmcp?.execution==="sequential"){i=[];for(let c of n)i.push(await s(c))}else i=await Promise.all(n.map(s));let l=[];try{if(l=i.filter(g=>g!==null),l.length===0)return;let c={};for(let g of l)c[g.resumeKey]=g.output;let p=await e.s.client.resumeFlow(t,c,{signal:r.signal,after:e.resumeAfter(t)});if(!p.ok){let g=await p.json().catch(()=>null);throw new Error(g?.error??`Resume failed: ${p.status}`)}let d=l[0].dedupeKey;for(let g of l){e.s.webMcpResolvedKeys.add(g.dedupeKey);let f=g.toolMessage.toolCall?.name,h=g.toolMessage.agentMetadata?.webMcpToolCallId;up(e,g.toolMessage,g.output,g.startedAt,g.completedAt,{...f===Oo?{suggestRepliesResolved:!0}:{},...f&&h?{clientToolAnswer:{toolCallId:h,toolName:f,args:g.toolMessage.toolCall?.args,result:g.output,batch:d}}:{}})}p.body&&await e.s.connectStream(p.body,{allowReentry:!0})}catch(c){if(!(c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"))))e.s.callbacks.onError?.(c instanceof Error?c:new Error(String(c)));else for(let d of l)up(e,d.toolMessage,Yf("Aborted by cancel()"),d.startedAt)}finally{for(let c of o)e.s.webMcpInflightKeys.delete(c);e.s.webMcpResolveControllers.delete(r),e.s.webMcpResolveControllers.size===0&&!e.s.abortController&&e.setStreaming(!1)}}async function SP(e,t){let n=t.agentMetadata?.executionId,o=t.toolCall?.name,r=t.toolCall?.id;if(!n){e.s.callbacks.onError?.(new Error("WebMCP await missing executionId: dispatch left paused."));return}if(!o)return;if(!r){let i=`${n}:__no_tool_id__:${o}`;if(e.s.webMcpInflightKeys.has(i)||e.s.webMcpResolvedKeys.has(i))return;e.s.webMcpInflightKeys.add(i);try{await AP(e,n,o,{isError:!0,content:[{type:"text",text:"WebMCP await missing toolCall.id: cannot execute the page tool."}]}),e.s.webMcpResolvedKeys.add(i)}catch(l){e.s.callbacks.onError?.(l instanceof Error?l:new Error(String(l)))}finally{e.s.webMcpInflightKeys.delete(i)}return}let s=`${n}:${r}`;if(!(e.s.webMcpInflightKeys.has(s)||e.s.webMcpResolvedKeys.has(s)||$C(e,t)))return UC(e,n,[t])}async function AP(e,t,n,o,r){let s=await e.s.client.resumeFlow(t,{[n]:o},{signal:r?.signal,after:e.resumeAfter(t)});if(!s.ok){let i=await s.json().catch(()=>null);throw new Error(i?.error??`Resume failed: ${s.status}`)}r?.onHttpOk?.(),s.body?await e.s.connectStream(s.body,{allowReentry:!0}):e.s.webMcpResolveControllers.size===0&&(e.setStreaming(!1),e.s.abortController=null)}var Yf,yP,Xf=Ve(()=>{"use strict";Ca();Yf=e=>({isError:!0,content:[{type:"text",text:e}]}),yP=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t});function Jf(e){if(!e)return qC;let t={...qC};for(let n of TP){let o=e[n];typeof o=="string"&&o.length>0&&(t[n]=o)}return t}var TP,qC,zC=Ve(()=>{"use strict";TP=["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"],qC={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 YC(e){let{plugins:t,config:n}=e,o=!1,r=!1,s=!1,i=!1,l=null,c=[],p=()=>{for(let H of c.splice(0))try{H()}catch(B){Zf("renderHistoryView cleanup",B)}},d=(H,B)=>{for(let V of t){let oe=V[H];if(oe)try{let W=oe(B);if(W)return W}catch(W){Zf(H,W)}}return null},g=()=>({presentation:e.getPresentation(),config:n}),f={header:H=>i?d("renderHistoryHeader",Object.freeze({...g(),returnSurface:e.getReturnSurface(),identityStatus:Fr(H.identityStatus),pendingAction:GC(H.pendingAction),copy:Fr(H.copy),actions:Object.freeze({close:v.close,startNewConversation:v.startNewConversation}),defaultRenderer:H.defaultRenderer})):null,conversation:H=>i?d("renderHistoryConversation",Object.freeze({...g(),conversation:KC(H.conversation),active:H.active,pending:H.pending,open:H.open,requestDelete:H.requestDelete,defaultRenderer:H.defaultRenderer})):null,state:H=>i?d("renderHistoryState",Object.freeze({...g(),state:Fr(H.state),identityStatus:Fr(H.identityStatus),copy:Fr(H.copy),...H.retry?{retry:H.retry}:{},...H.startNewConversation?{startNewConversation:H.startNewConversation}:{},defaultRenderer:H.defaultRenderer})):null},h=t.flatMap(H=>(H.railSections??[]).map(B=>({...B,placement:B.placement??"above-conversations",items:[],render:V=>B.render(Object.freeze({collapsed:V,presentation:e.getPresentation(),actions:v}))}))),y=e.createView({slots:f,renderDom:!1,onModelChange:()=>I(),railSections:h}),v=Object.freeze({...y.operations,close:e.close}),C=()=>(i=!0,y.setDomRenderEnabled(!0),y.element),A=H=>Object.freeze({conversations:Object.freeze(H.conversations.map(KC)),activeConversationId:H.activeConversationId,state:Fr(H.state),pendingAction:GC(H.pendingAction),identityStatus:Fr(H.identityStatus),nextCursor:H.nextCursor,presentation:e.getPresentation(),returnSurface:e.getReturnSurface(),config:n,copy:Fr(y.copy),actions:v,defaultRenderer:C,requestRender:()=>I(),onCleanup:B=>{c.push(B)}}),L=()=>{i=!1;let H=null;for(let V of t)if(V.renderHistoryView){try{H=V.renderHistoryView(A(y.getModel()))}catch(oe){Zf("renderHistoryView",oe),H=null}if(H)break}let B=!H||H.contains(y.element);return i=B,y.setDomRenderEnabled(B),H??y.element};function I(){if(!(!s||o||r)){r=!0;try{p();let H=L();if(H===l)return;let B=l;l=H,e.onElementChanged(H,B)}finally{r=!1}}}return s=!0,I(),{view:y,get element(){return l??y.element},requestRender:I,dispose:()=>{o=!0,p()}}}var Zf,Fr,KC,GC,XC=Ve(()=>{"use strict";Zf=(e,t)=>{console.warn(`[persona] ${e} threw`,t)},Fr=e=>Object.freeze({...e}),KC=e=>Object.freeze({id:e.id,title:e.title,targetId:e.targetId,preview:e.preview,messageCount:e.messageCount,createdAt:e.createdAt,updatedAt:e.updatedAt}),GC=e=>e?Fr(e):null});var QC,em,PP,fp,mp,kP,JC,hp,Nl,LP,HP,ZC,yp=Ve(()=>{"use strict";QC=null,em=()=>{if(QC!==null)return QC;if(typeof navigator>"u")return!1;let t=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(t)},PP="ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space",fp=(e,t)=>{console.warn(`[persona] ${e} shortcut: ${t}`)},mp=e=>{let t=e.toLowerCase().split("+").map(r=>r.trim()),n=t.pop(),o={key:n,mod:!1,shift:!1,alt:!1};for(let r of t)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 fp("unknown modifier in",e),null;return!o.mod||o.shift&&o.alt||/^(enter|esc(ape)?)$/.test(n)||!/^([^+\s]|[a-z]{2,12})$/.test(n)?(fp("unsupported",e),null):(n==="space"&&(o.key=" "),o)},kP=e=>PP.split(" ").find(t=>t.toLowerCase()===e)??(e===" "?"Space":e.length===1?e.toUpperCase():e[0].toUpperCase()+e.slice(1)),JC=(e,t)=>{let n=mp(e);if(!n)return"";let o=em(),r=kP(n.key);if(!t&&o)return`${n.alt?"\u2325":""}${n.shift?"\u21E7":""}\u2318${r}`;let s=[t?o?"Meta":"Control":"Ctrl"];return n.alt&&s.push("Alt"),n.shift&&s.push("Shift"),s.push(r),s.join("+")},hp=e=>JC(e,!1),Nl=e=>JC(e,!0),LP=(e,t)=>t.key?.toLowerCase()===e.key&&(em()?t.metaKey:t.ctrlKey)===e.mod&&!(em()?t.ctrlKey:t.metaKey)&&t.shiftKey===e.shift&&t.altKey===e.alt,HP=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable},ZC=e=>{let t=new Map,n=e?.ownerDocument??(typeof document<"u"?document:null),o=(s,i)=>{if((s.scope??"widget")==="page")return!0;if(!e)return!1;let l=i.composedPath?.();return l?.length?l.includes(e):e.contains(i.target)},r=s=>{if(s.isComposing||!t.size)return;let i=s.composedPath?.()[0]??s.target;for(let l of t.values())if(LP(l.parsed,s)&&l.when?.()!==!1&&o(l,s)&&!(!l.allowInInput&&HP(i))){s.preventDefault();try{l.run(s)}catch(c){fp(`${l.id} threw on`,l.combo),console.warn(c)}return}};return n?.addEventListener("keydown",r),{register(s){let i=mp(s.combo);if(!i)return()=>{};let l=`${i.mod?"m":""}${i.shift?"s":""}${i.alt?"a":""}${i.key}`,c=t.get(l);return c?(fp(`${c.id} already owns`,s.combo),()=>{}):(t.set(l,{...s,parsed:i}),s.element?.setAttribute("aria-keyshortcuts",Nl(s.combo)),()=>{t.get(l)?.id===s.id&&t.delete(l),s.element?.removeAttribute("aria-keyshortcuts")})},destroy(){t.clear(),n?.removeEventListener("keydown",r)}}}});function ew(e){if(typeof e!="string"||e==="")return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function bp(e){return typeof e=="string"?e:void 0}function WP(e){if(typeof e!="object"||e===null)return null;let t=e;switch(t.type){case"text":return typeof t.text=="string"?Ao(t.text):null;case"image":return typeof t.image=="string"?Yd(t.image,{mimeType:bp(t.mimeType),alt:bp(t.alt)}):null;case"file":return typeof t.data=="string"&&typeof t.mimeType=="string"&&typeof t.filename=="string"?HC(t.data,t.mimeType,t.filename):null;case"audio":return typeof t.audio=="string"?{type:"audio",audio:t.audio,...bp(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;case"video":return typeof t.video=="string"?{type:"video",video:t.video,...bp(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;default:return null}}function OP(e,t){let n=ew(t),o=e.map(i=>ew(i.timestamp)),r=new Array(e.length),s=0;for(;s<o.length;){let i=o[s];if(i!==null){r[s]=i,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,d=l+1<o.length?o[l+1]:null,g=d!==null&&n!==null?Math.min(d,n):d??n;for(let f=0;f<c;f+=1)r[s+f]=g!==null?g-(c-f):p!==null?p+f+1:RP+f;s=l+1}return r.map(i=>new Date(i).toISOString())}function tw(e,t){let n=OP(e,t?.beforeCreatedAt),o=[];return e.forEach((r,s)=>{if(typeof r?.id!="string"||r.id===""||!IP.includes(r.role))return;let i=r.role,l=n[s];if(r.displayAvailable===!1){let c={historyDisplayUnavailable:!0};o.push({id:r.id,role:i,content:"",createdAt:l,agentMetadata:c});return}if(typeof r.displayContent=="string"){o.push({id:r.id,role:i,content:r.displayContent,createdAt:l});return}if(typeof r.content=="string"){o.push({id:r.id,role:i,content:r.content,createdAt:l});return}if(Array.isArray(r.content)){let c=r.content.map(WP).filter(d=>d!==null),p=Gd(c);o.push({id:r.id,role:i,content:p||(Pa(c)?Ta:""),createdAt:l,...c.length>0&&{contentParts:c}});return}o.push({id:r.id,role:i,content:"",createdAt:l})}),o}function Fl(e){let t=e.content;if(typeof t!="string"||t==="")return;let n=e.contentParts??e.llmContent??e.rawContent??t;if(!(typeof n=="string"&&n===t))return t}function $l(e,t){let n=new Map;for(let o of e)n.set(o.id,o);for(let o of t)n.set(o.id,o);return[...n.values()].sort((o,r)=>{let s=new Date(o.createdAt).getTime(),i=new Date(r.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(i)&&s!==i)return s-i;let l=o.sequence??0,c=r.sequence??0;return l!==c?l-c:o.id.localeCompare(r.id)})}var IP,RP,vp=Ve(()=>{"use strict";Nr();IP=["user","assistant","system"],RP=0});function DP(e,{HistoryClientError:t,HistoryProviderError:n}){if(e instanceof n)return e;if(e instanceof t){let o=_P.get(e.code)??"unavailable";return new n(o,tm(o),{...e.retryAfterSeconds!==void 0?{retryAfterSeconds:e.retryAfterSeconds}:{}})}return new n("unavailable",tm("unavailable"))}function nw(e){let{HistoryProviderError:t}=e.errors,n=()=>e.getClient?.()??e.client,o=e.getIdentityProofConfigured()?["browser","verified-user"]:["browser"],r={scopes:o},s=c=>{if(!o.includes(c))throw new t("unsupported_scope",tm("unsupported_scope"))},i=async(c,p)=>{s(c);try{return await p()}catch(d){throw DP(d,e.errors)}},l=c=>{let p=!1;return{conversationId:c.session.conversationId??"",conversationRevision:c.session.conversationRevision??"",async commit(){p||(p=!0,c.commit(),await e.onActivationCommitted(c.session))},discard(){p||(p=!0,c.discard())}}};return{capabilities:r,getIdentityStatus(){return n().getHistoryIdentityStatus()},subscribeIdentityStatus(c){return n().subscribeHistoryIdentityStatus(c)},subscribeAvailability(c){return n().subscribeHistoryAvailability(c)},async list(c){return i(c.context.scope,async()=>{let p=await n().listConversations({...c.cursor?{cursor:c.cursor}:{},...c.limit!==void 0?{limit:c.limit}:{},...c.targetId?{targetId:c.targetId}:{},scope:c.context.scope});return{items:p.data,nextCursor:p.nextCursor}})},async getPage(c,p){return i(p.context.scope,async()=>{let d=await n().getConversation(c,{...p.cursor?{messageCursor:p.cursor}:{},scope:p.context.scope}),g=tw(d.messages,{...p.beforeCreatedAt?{beforeCreatedAt:p.beforeCreatedAt}:{}});return{summary:d.summary,messages:$l([],g),conversationRevision:d.conversationRevision??"",nextCursor:d.nextMessageCursor}})},async prepareOpen(c,p){return i(p.context.scope,async()=>l(await n().prepareConversationSession(c)))},async prepareStartNew(c){return i(c.context.scope,async()=>l(await n().prepareNewConversationSession()))},async delete(c,p){await i(p.context.scope,()=>n().deleteConversation(c,{scope:p.context.scope}))},async deleteAll(c){return i(c.context.scope,()=>n().deleteAllConversations({...c.targetId!==void 0?{targetId:c.targetId}:{},scope:c.context.scope}))},async resetDevice(){try{return await n().resetVisitor(),{remoteRevocationConfirmed:!0}}catch{return{remoteRevocationConfirmed:!1}}}}}var _P,BP,tm,ow=Ve(()=>{"use strict";vp();_P=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"]]),BP=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."]]),tm=e=>BP.get(e)??"Conversation history is unavailable right now."});var Cp={};ys(Cp,{createHistoryShell:()=>NP});var NP,nm=Ve(()=>{"use strict";zC();XC();Ze();yp();_o();ow();NP=e=>{let o=Jf(e.config.features?.history?.copy),r=null,s=!1,i=null,l=null,c="conversation",p=null,d=null,g=null,f=null,h=0,y=null,v=null,C=null,A=`persona-history-${Math.random().toString(36).slice(2,8)}`,L=()=>e.historyFeatureEnabled()&&!!r&&!s,I=()=>{let E=e.session.getStatus();return e.isStreaming||E==="paused"||E==="resuming"},H=()=>{let E=e.config.features?.history?.scope;if(E)return E;let N=e.config.getIdentityProof?"verified-user":"browser",ne=r?.capabilities.scopes;return!ne||ne.includes(N)?N:ne[0]??N},B=()=>l?.scope??H(),V=()=>e.session.getClientSession()?.targetId??null,oe=E=>`${E.state}:${"reason"in E?E.reason:""}`,W=E=>{let N=oe(E);N!==f&&(f=N,e.eventBus.emit("history:identityStatusChanged",{status:E,timestamp:Date.now()}))},j=null,X=null,M=()=>{if(!e.historyFeatureEnabled())return null;let E=e.getHistoryProviderFactory();if(E)return E();let N=e.config.features?.history?.provider;return N?typeof N!="function"?N:(j!==N&&(j=N,X=N()),X):e.session.isClientTokenMode()?nw({errors:e.historyErrors,client:e.session.getClient(),getIdentityProofConfigured:()=>typeof e.config.getIdentityProof=="function",onActivationCommitted:ne=>e.session.bindActivatedSession(ne),getClient:()=>e.session.getClient()}):null},T=()=>{v?.(),v=null,C?.(),C=null,s=!1,r=M();let E={...e.historyInternals};r?E.historyProvider=r:delete E.historyProvider,e.historyInternals=E,e.session.setHistoryInternals(e.historyInternals),r&&(v=r.subscribeAvailability?.(N=>{s=!N,N||xn({restoreFocus:!1}),jn()})??null,C=r.subscribeIdentityStatus(N=>W(N)),f=oe(r.getIdentityStatus()))},_=()=>{let E=e.config.features?.history?.presentation??"panel";if(E==="panel"||E==="auto"&&!(!e.launcherEnabled||e.isDockedMountMode(e.config)))return"panel";let N=e.artifactSplitRoot??e.container;return(N.getBoundingClientRect().width||N.clientWidth)>=720?"rail":"panel"},P=(E,N)=>{N?(E.setAttribute("aria-hidden","true"),E.setAttribute("inert","")):(E.removeAttribute("aria-hidden"),E.removeAttribute("inert"))},J="data-persona-history-suppressed",U=null,ue=null,fe=null,me=null,He=null,Ee="",Ie=()=>e.header===He?Ee:e.config.layout?.showHeader===!1?"none":"",yt=()=>e.historyPresentation==="panel"&&!!fe&&me===fe.element&&e.config.layout?.showHeader!==!1&&Ie()!=="none",qe=()=>{for(let E of Array.from(e.header.children))E!==U&&E.setAttribute(J,"")},Oe=()=>{for(let E of Array.from(e.container.querySelectorAll(`[${J}]`)))E.removeAttribute(J)},$=()=>{let E=fe;if(!E)return;if(Array.from(e.header.children).some(pe=>pe!==U&&!pe.hasAttribute(J))){ue&&ue!==e.header&&(ue.style.removeProperty("min-height"),ue=null);let pe=e.header.offsetHeight;pe>0&&(e.header.style.minHeight=`${pe}px`,ue=e.header)}U||(U=x("div","persona-history-header-host")),E.setHeaderPlacement("external");let ne=E.getHeaderElement();ne.parentNode!==U&&U.replaceChildren(ne),U.parentNode!==e.header&&e.header.appendChild(U),qe()},_e=()=>{ue&&(ue.style.removeProperty("min-height"),ue=null),U&&(fe?.setHeaderPlacement("inline"),U.remove(),U=null,Oe())},ye=null,ut=()=>{if(ye){if(e.body.style.display="none",P(e.body,!0),e.footer.hidden=!0,P(e.footer,!0),yt()){$(),e.header.style.display=Ie(),P(e.header,!1);return}_e(),e.header.style.display="none",P(e.header,!0)}};e.reapplyHistoryHostChrome=ut;let Zt=E=>{let N=e.body.style.display,ne=e.footer.hidden,pe=e.footer,Re=e.header,$t=e.header.style.display;He=Re,Ee=$t,ye=()=>{ye=null,_e(),He=null,e.body.style.display=N,P(e.body,!1),pe.hidden=ne,P(pe,!1),e.footer!==pe&&(e.footer.hidden=!1,P(e.footer,!1)),Re.style.display=$t,P(Re,!1),e.header!==Re&&(e.header.style.display=e.config.layout?.showHeader===!1?"none":"",P(e.header,!1))},e.footer.parentNode?.insertBefore(E,e.footer),ut()},xt=null,xe=null,Wt=null,vt=null,Le=()=>[e.header,e.panelElements.closeButtonWrapper,e.panelElements.clearChatButtonWrapper,e.body,e.footer],Xe=52,D=()=>e.config.features?.history?.rail?.collapsible!==!1,S=()=>e.config.features?.history?.rail?.side==="right"?"right":"left",F=200,q=400,K=E=>Math.min(q,Math.max(F,Math.round(E))),te=()=>e.config.features?.history?.rail?.resizable===!0,ve,Me=()=>{if(ve===void 0&&(ve=null,e.config.persistState!==!1))try{let E=Number(window.localStorage.getItem(`${e.currentKeyPrefix()}rail-width`));E&&(ve=E)}catch{}return ve},Ce=()=>K(Me()??e.config.features?.history?.rail?.width??260),st=E=>{if(ve=E,e.config.persistState!==!1)try{window.localStorage.setItem(`${e.currentKeyPrefix()}rail-width`,String(E))}catch{}},Ct=()=>D()&&e.config.features?.history?.rail?.collapsedBehavior==="overlay",De=!1,Qe=E=>{let N=x("img");return N.src=E,N.alt="",N.setAttribute("aria-hidden","true"),N},pn=()=>{let E=e.config.features?.history?.rail?.brand;if(!E)return;let N=!1,ne;return pe=>{if(E.render)try{return E.render({collapsed:pe})??null}catch(Re){return N||(N=!0,console.warn("[persona] history rail brand threw",Re)),null}return ne===void 0&&(E.iconUrl?ne=Qe(E.iconUrl):ne=E.icon?e.renderLucideIcon(E.icon,20):null),ne?ne.cloneNode(!0):null}},Eo=()=>e.config.features?.history?.rail?.sections?.map(E=>{let N=!1,ne=pe=>{N||(N=!0,console.warn("[persona] history rail section threw",E.id,pe))};return{id:E.id,title:E.title,placement:E.placement??"above-conversations",items:E.items.map(pe=>{let Re;return{id:pe.id,label:pe.label,badge:pe.badge,iconNode:()=>{if(Re!==void 0)return Re;try{pe.renderIcon?Re=pe.renderIcon()??null:pe.iconUrl?Re=Qe(pe.iconUrl):Re=pe.icon?e.renderLucideIcon(pe.icon,20):null}catch($t){ne($t),Re=null}return Re},onSelect:()=>{try{pe.onSelect()}catch($t){ne($t)}}}})}})??[],ft=E=>{let N=Eo();for(let ne of E)N.some(pe=>pe.id===ne.id)?console.warn("[persona] duplicate history rail section id",ne.id):N.push(ne);return N.length?N:void 0},bt=null,Ft=()=>`${e.currentKeyPrefix()}rail-collapsed`,_i=()=>{if(bt===null&&(bt=e.config.features?.history?.rail?.defaultCollapsed===!0,e.config.persistState!==!1))try{let E=window.localStorage.getItem(Ft());E&&(bt=E==="1")}catch{}return bt},rn=E=>{if(bt=E,e.config.persistState!==!1)try{window.localStorage.setItem(Ft(),E?"1":"0")}catch{}},Sn=()=>e.historyPresentation==="rail"&&D()&&!Ct()&&_i(),lo=()=>{},Bi=()=>{if(Ct()){lo();return}rn(!_i()),i?.view.setCollapsed(Sn()),e.applyRailChrome(),e.repinAnchoredMessage()},Di=()=>{let E=e.config.features?.history?.rail?.collapseShortcut;return!E||!mp(E)?null:{combo:E,hint:hp(E),aria:Nl(E)}},Qa=300,cr="var(--persona-history-overlay-margin,8px)",un=null,Un=null,dr=0,Vn=null,pr=null,Uo=!1,Yr=0,wc=()=>window.matchMedia?.("(pointer: coarse)").matches===!0,to=()=>L()&&Ct()&&(e.historyPresentation??_())==="rail",$h=()=>e.historyVisible&&!De,ur=()=>{pr!==null&&clearTimeout(pr),pr=null},_s=()=>{e.loadHistoryView().catch(()=>{})},Ln=()=>{ur(),De&&(pr=setTimeout(()=>{pr=null,!(Uo||!De)&&(Vn?.contains(document.activeElement)||xn({restoreFocus:!1}))},Qa))},Je=(E,N)=>{let ne=Vn?.getBoundingClientRect();if(!ne)return!1;let pe=un?.getBoundingClientRect(),Re=pe?Math.min(pe.top,ne.top):ne.top;return E>=ne.left&&E<=ne.right&&N>=Re&&N<=ne.bottom||!!pe&&E>=pe.left&&E<=pe.right&&N>=pe.top&&N<=pe.bottom},Ae=E=>{De&&(Uo=Je(E.clientX,E.clientY),Uo?ur():pr===null&&Ln())},Xt=E=>{e.historyVisible||!to()||(De=!0,Ke({invoker:un,keyboard:E?.keyboard===!0}).then(()=>{e.historyVisible?!Uo&&document.activeElement!==un&&xn():De=!1}))},et=()=>{let E=me?.querySelector('[data-persona-history-focus="collapse"]');E&&(E.setAttribute("aria-label",De?o.expandLabel:o.collapseLabel),E.setAttribute("aria-expanded",De?"false":"true"))},we=()=>{rn(!1);let E=i;if(!De||!E){Ke({invoker:un});return}let N=document.activeElement===un;De=!1,Ni(),E.element.remove(),Ht(E.element),et(),N&&mt(),e.repinAnchoredMessage(),jn()},ae=()=>{rn(!0),xn()};lo=()=>{!e.historyVisible||De?we():ae()};let Te=()=>{let E=Di(),N=e.createHeaderIconButton({ariaLabel:o.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":A,...E?{"aria-keyshortcuts":E.aria}:{}}}),ne=N.button;ne.addEventListener("mouseenter",()=>{Uo=!0,ur(),!(wc()||Date.now()<Yr)&&Xt()}),ne.addEventListener("mouseleave",()=>{Uo=!1,Yr=0,Ln()}),ne.addEventListener("focus",()=>{e.historyVisible||_s()}),ne.addEventListener("click",pe=>{L()&&(pe.detail!==0&&wc()&&!e.historyVisible?Xt():we())}),un=ne,Un=N.wrapper},gr=()=>{if(Un&&!Un.isConnected&&(Un=null,un=null),!to()){Un?.remove(),Un=null,un=null;return}un||Te();let E=Un,N=un;if(!E||!N)return;let ne=S()!=="right"?e.header.firstChild:null;(ne??e.header.lastChild)!==E&&e.header.insertBefore(E,ne),E.style.display=$h()||dr>0?"none":"",N.setAttribute("aria-label",o.expandLabel),N.setAttribute("aria-expanded",e.historyVisible?"true":"false"),Vn&&e.applyRailChrome()},Xr=E=>{if(!De)return;let N=E.target;N instanceof Node&&(Vn?.contains(N)||Un?.contains(N)||N instanceof Element&&N.closest('.persona-dropdown-menu,[role="alertdialog"]')||xn({restoreFocus:!1}))};document.addEventListener("pointerdown",Xr,!0),e.destroyCallbacks.push(()=>{document.removeEventListener("pointerdown",Xr,!0),document.removeEventListener("pointermove",Ae),ce?.(),ur()});let co=null,ce=null,Pe=16,An=E=>{st(K(E)),e.applyRailChrome(),e.repinAnchoredMessage()},tt=()=>{let E=x("div","persona-rail-resizer");return E.tabIndex=0,E.setAttribute("role","separator"),E.setAttribute("aria-orientation","vertical"),E.setAttribute("aria-valuemin",String(F)),E.setAttribute("aria-valuemax",String(q)),E.addEventListener("pointerdown",N=>{let ne=xe;if(!ne||N.button!==0)return;N.preventDefault(),ce?.();let pe=N.clientX,Re=ne.getBoundingClientRect().width||Ce(),$t=S()==="right"?-1:1,Ot=Re,_t=e.mount.ownerDocument;ne.style.transition="none";let je=be=>{Ot=K(Re+$t*(be.clientX-pe)),ne.style.flex=`0 0 ${Ot}px`,E.setAttribute("aria-valuenow",String(Ot))},at=()=>{ce=null,_t.removeEventListener("pointermove",je),_t.removeEventListener("pointerup",at),_t.removeEventListener("pointercancel",at),ne.style.removeProperty("transition");try{E.releasePointerCapture(N.pointerId)}catch{}An(Ot)};ce=at,_t.addEventListener("pointermove",je),_t.addEventListener("pointerup",at),_t.addEventListener("pointercancel",at);try{E.setPointerCapture(N.pointerId)}catch{}}),E.addEventListener("keydown",N=>{let ne=S()==="right"?-Pe:Pe,pe=Ce(),Re=N.key==="ArrowRight"?pe+ne:N.key==="ArrowLeft"?pe-ne:N.key==="Home"?F:N.key==="End"?q:null;Re!==null&&(N.preventDefault(),An(Re))}),E},en=(E,N)=>{if(!te()||Sn()){ce?.(),co?.remove();return}let ne=co??tt();co=ne,ne.setAttribute("aria-label",o.resizeLabel),ne.setAttribute("aria-valuenow",String(Ce())),ne.nextElementSibling!==N&&E.insertBefore(ne,N)};e.applyRailChrome=()=>{i?.view.setRailSide(S());let E=S()==="right",N=Vn;if(N){let _t=un?un.getBoundingClientRect().bottom-e.container.getBoundingClientRect().top:0;N.style.top=`calc(${Math.max(0,Math.round(_t))}px + ${cr})`,N.style.width=`${Ce()}px`,N.style.left=E?"":cr,N.style.right=E?cr:""}let ne=xe,pe=xt,Re=Wt;if(!ne||!pe||!Re)return;ne.style.flex=`0 0 ${Sn()?Xe:Ce()}px`;let $t="1px solid var(--persona-divider,#e5e7eb)";ne.style.borderRight=E?"":$t,ne.style.borderLeft=E?$t:"";let Ot=E?Re:ne;pe.firstElementChild!==Ot&&pe.append(Ot,E?ne:Re),en(pe,E?ne:Re)};let Sc=E=>{if(vt&&xe){vt.replaceWith(E),vt=null,e.applyRailChrome();return}let N=x("div","persona-history-rail-shell");N.style.cssText="display:flex;flex-direction:row;flex:1 1 auto;min-height:0";let ne=x("div","persona-history-rail-conversation");ne.style.cssText="display:flex;flex-direction:column;flex:1 1 auto;min-width:0;min-height:0;position:relative";let pe=x("div","persona-history-rail-host");pe.style.cssText="display:flex;min-height:0;overflow:hidden",e.container.insertBefore(N,e.header.parentNode===e.container?e.header:e.body);for(let Re of Le())Re?.parentNode===e.container&&ne.appendChild(Re);N.append(pe,ne),pe.appendChild(E),xt=N,xe=pe,Wt=ne,e.applyRailChrome()},Rn=()=>{if(xt)return;let E=x("div","persona-history-rail-placeholder");E.style.cssText="flex:1 1 auto;min-height:0",vt=E,Sc(E),e.repinAnchoredMessage()},Ac=()=>{vt&&(Ni(),e.repinAnchoredMessage())},Bu=E=>{let N=x("div","persona-history-rail-overlay");N.style.cssText=`position:absolute;bottom:${cr};display:flex;overflow:hidden;z-index:${wa-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))`,e.container.style.position="relative",e.container.appendChild(N),N.appendChild(E),document.addEventListener("pointermove",Ae),Vn=N,e.applyRailChrome(),et()},Ni=()=>{ye?.(),Vn&&(Uo&&(Yr=Date.now()+150),document.removeEventListener("pointermove",Ae),Vn.remove(),Vn=null);let E=xt;if(E){ce?.();for(let N of Le())N&&E.contains(N)&&e.container.insertBefore(N,E);E.remove(),xt=null,xe=null,Wt=null,vt=null}},ze=E=>{me=E,E.id=A,E.style.flex="1 1 auto",E.style.minHeight="0"},Ht=E=>{ze(E),(e.historyPresentation!=="rail"||De)&&Ac(),e.historyPresentation!=="rail"?Zt(E):De?Bu(E):Sc(E)},Vo=()=>{if(gr(),Jr(),!e.historyVisible||!i)return;let E=_();if(E===e.historyPresentation)return;let N=document.activeElement,ne=N instanceof HTMLElement&&(i.element.contains(N)||U?.contains(N)===!0)?N:null;Ni(),i.element.remove(),i.view.setHeaderPlacement("inline"),e.historyPresentation=E,i.view.setPresentation(E),i.view.setCollapsed(Sn()),i.requestRender(),i.element.isConnected||Ht(i.element),ne?.isConnected?ne.focus():mt(),e.syncScrollToBottomButton(),e.repinAnchoredMessage(),jn()},jo=(E,N)=>U?.querySelector(N)??E.querySelector(N),mt=()=>{let E=i?.element??me;if(!E)return;let N=jo(E,'[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]');if(N){N.focus();return}let ne=jo(E,".persona-history-title")??E;ne.tabIndex=-1,ne.focus()},Ke=async E=>{if(!L()||e.historyVisible)return;let N=r;if(!N)return;if(!De&&to()&&_i()){gr();return}Fi();let ne=++h;c=E?.returnSurface??"conversation",p=E?.invoker??d;let pe=to()&&!De;pe&&(dr+=1,gr(),Rn());let Re;try{Re=await e.loadHistoryView()}catch{e.announceHistory(o.openHistoryLabel),pe&&(dr-=1,ne===h&&(Ac(),gr()));return}if(pe&&(dr-=1),ne!==h||e.historyVisible)return;l={scope:H()},e.historyPresentation=_(),e.historyVisible=!0;let $t=e.historyPresentation==="panel"&&e.config.layout?.showHeader!==!1&&e.header.style.display!=="none"?"external":"inline",Ot=e.config.features?.history?.rowAvatar,_t=Di(),je=_t?{hint:_t.hint,aria:_t.aria}:null,at={provider:N,context:l,targetId:V(),presentation:e.historyPresentation,collapsible:D(),collapsed:Sn(),railSide:S(),renderRailHeader:e.config.features?.history?.rail?.renderHeader,railBrand:pn(),onToggleCollapse:Bi,...je?{collapseShortcut:je}:{},headerPlacement:$t,showScopeStatus:e.config.features?.history?.showScopeStatus!==!1,showDelete:e.config.features?.history?.showDelete!==!1,showDeleteAll:e.config.features?.history?.showDeleteAll!==!1,...e.config.features?.history?.listActions?.length?{listActions:e.config.features.history.listActions}:{},rowAvatar:Ot===!1?!1:typeof Ot=="string"?Ot:e.config.launcher?.iconUrl,activeConversationId:e.session.getActiveConversationId(),...e.config.features?.history?.grouping?{grouping:e.config.features.history.grouping}:{},...e.config.features?.history?.copy?{copy:e.config.features.history.copy}:{},...e.config.features?.history?.pageSize!==void 0?{pageSize:e.config.features.history.pageSize}:{},onSelect:be=>En(be,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:be=>e.setActiveConversationSummary(be),attachTooltip:e.attachTooltip,onStartNew:()=>Mo({focusComposer:!0}),onClose:()=>xn(),onRequestDeleteConversation:be=>Vt(be),onRequestClearHistory:()=>Fs(),...N.resetDevice?{onRequestResetIdentity:()=>el()}:{}};i=YC({plugins:e.plugins,config:e.config,getPresentation:()=>e.historyPresentation??"panel",getReturnSurface:()=>c,close:()=>xn(),createView:({slots:be,renderDom:Ui,onModelChange:po,railSections:mr})=>(fe=Re.createHistoryView({...at,railSections:ft(mr),slots:be,renderDom:Ui,onModelChange:po,onAnnounce:e.announceHistory}),fe),onElementChanged:(be,Ui)=>{if(!Ui?.isConnected)return Ht(be);ze(be),Ui.replaceWith(be),ut()}}),i.view.setNewConversationRequired(e.historySessionState.recovery==="new_conversation_required"),E?.focus!==!1&&(e.historyPresentation!=="rail"||E?.keyboard===!0)&&mt(),e.syncScrollToBottomButton(),e.repinAnchoredMessage(),jn(),e.eventBus.emit("history:opened",{presentation:e.historyPresentation,returnSurface:c,timestamp:Date.now()})},Fi=()=>{},xn=E=>{if(!e.historyVisible)return;h+=1;let N=c,ne=p,pe=i,Re=E?.restoreFocus!==!1;e.historyVisible=!1;let $t=!1,Ot=null,_t=()=>{if(!$t){if($t=!0,Fi=()=>{},Ot!==null&&clearTimeout(Ot),De=!1,ur(),Ni(),pe?.dispose(),pe?.view.destroy(),pe?.element.remove(),i===pe&&(i=null,fe=null,me=null,e.historyPresentation=null,l=null,p=null),e.syncScrollToBottomButton(),e.repinAnchoredMessage(),jn(),Re){let at=ne??d;at?.isConnected?at.focus():e.maybeFocusInput()}e.eventBus.emit("history:closed",{returnSurface:N,timestamp:Date.now()})}},je=pe&&pe.element===pe.view.element?pe.view.playExit():null;if(!je){_t();return}Fi=_t,Ot=setTimeout(_t,250),je.then(_t)},Bs=E=>{if(!(E.key!=="Escape"||!e.historyVisible||!i)){if(e.historyPresentation==="rail"){let N=E.target;if(!(N instanceof Node)||!(i.element.contains(N)||De&&Un?.contains(N)===!0))return}E.preventDefault(),E.stopPropagation(),xn()}};e.container.addEventListener("keydown",Bs),e.destroyCallbacks.push(()=>e.container.removeEventListener("keydown",Bs));let Wn=0,xc=250,he=null,gn=()=>{he&&clearTimeout(he),he=null};e.destroyCallbacks.push(gn);let It=()=>{gn();let E=e.conversationOpenPendingEl;E&&(e.conversationOpenTakeover=!0,E.hidden=!1,e.messagesWrapper.style.display="none",e.updateWelcome())},sn=()=>{Wn+=1,gn(),e.conversationOpenPendingEl&&(e.conversationOpenPendingEl.remove(),e.conversationOpenPendingEl=null,e.conversationOpenTakeover=!1,e.messagesWrapper.style.removeProperty("display"),P(e.footer,!1),e.updateWelcome())},Et=()=>{try{if(window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches)return;e.messagesWrapper.animate([{opacity:0},{opacity:1}],{duration:150,easing:"ease-out"})}catch{}},fn=(E,N)=>Q("div",{className:Dn("persona-conversation-loading-bubble",N&&"persona-conversation-loading-bubble--trailing"),attrs:{"aria-hidden":"true"},style:{width:E}}),Ec=()=>Q("div",{className:"persona-conversation-loading-body"},fn("58%",!1),fn("72%",!0),fn("44%",!1)),Qr=E=>{e.conversationOpenPendingEl?.remove(),e.conversationOpenPendingEl=E,E.hidden=!e.conversationOpenTakeover,e.body.insertBefore(E,e.messagesWrapper),gn(),e.conversationOpenTakeover||(he=setTimeout(It,xc)),P(e.footer,!0)},Du=()=>{let E={config:e.config,streaming:!1,location:"conversation-open",defaultRenderer:Ec},N=null,ne=e.plugins.find(pe=>pe.renderLoadingIndicator);ne?.renderLoadingIndicator&&(N=ne.renderLoadingIndicator(E)),N===null&&e.config.loadingIndicator?.render&&(N=e.config.loadingIndicator.render(E)),Qr(Q("div",{className:"persona-conversation-loading",attrs:{role:"status","aria-label":o.openConversationLoadingLabel}},N??Ec()))},Nu=E=>{let N=()=>{En(E,{focusComposer:!0}).catch(()=>{})},ne=L()?()=>{sn(),Ke()}:void 0,pe=(_t,je)=>{let at=Q("button",{className:"persona-conversation-loading-error-action",attrs:{type:"button"},text:_t});return at.addEventListener("click",je),at},Re=()=>Q("div",{className:"persona-conversation-loading-error-body"},Q("p",{className:"persona-conversation-loading-error-title",text:o.openConversationErrorTitle}),Q("div",{className:"persona-conversation-loading-error-actions"},pe(o.openConversationRetryLabel,N),ne?pe(o.openConversationBackLabel,ne):null)),$t=Object.freeze({conversationId:E,config:e.config,copy:Object.freeze({title:o.openConversationErrorTitle,retryLabel:o.openConversationRetryLabel,backLabel:o.openConversationBackLabel}),retry:N,...ne?{back:ne}:{},defaultRenderer:Re}),Ot=null;for(let _t of e.plugins)if(_t.renderHistoryOpenError){try{Ot=_t.renderHistoryOpenError($t)}catch(je){console.warn("[persona] renderHistoryOpenError threw",je),Ot=null}if(Ot)break}Qr(Q("div",{className:"persona-conversation-loading-error",attrs:{role:"alert"}},Ot??Re())),It()};e.eventBus.on("history:closed",()=>{e.conversationOpenPendingEl&&P(e.footer,!0)});let En=async(E,{focusComposer:N=!1}={})=>{let ne=B(),pe=!!i;i?.view.setActiveConversationId(E),sn();let Re=Wn;Du(),e.historyVisible&&(e.historyPresentation==="panel"||De)&&xn({restoreFocus:!1}),e.suppressScrollSend=!0;try{await e.session.openConversation(E,{scope:ne})}catch($t){throw Re===Wn&&Nu(E),$t}finally{e.suppressScrollSend=!1}Re===Wn&&(sn(),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),e.restoreScrollPosition()||e.jumpToBottomInstant(),Et(),Qt(),pe||e.setActiveConversationSummary(null),e.eventBus.emit("history:conversationOpened",{conversationId:E,title:e.activeConversationTitle,scope:ne,timestamp:Date.now()}),N&&e.maybeFocusInput())},Mo=async({focusComposer:E=!1}={})=>{sn(),await e.session.startNewConversation({scope:B()}),e.setActiveConversationSummary(null),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),e.jumpToBottomInstant(),Qt();let N=e.session.getActiveConversationId();i?.view.setActiveConversationId(N),e.eventBus.emit("history:conversationStarted",{conversationId:N,timestamp:Date.now()}),e.historyVisible&&(e.historyPresentation==="panel"||De)&&xn({restoreFocus:!1}),E&&e.maybeFocusInput()},Ds=async(E,N)=>{let ne=await e.session.updateConversation(E,{...N,...N.title!==void 0?{title:N.title.trim()}:{}});return i?.view.applyConversationSummary(ne),!i&&E===e.session.getActiveConversationId()&&e.setActiveConversationSummary(ne),ne},Mc=async E=>{let N=B(),ne=e.session.getActiveConversationId()===E;await e.session.deleteConversation(E,{scope:N}),i?.view.removeConversationSummary(E),ne&&(e.setActiveConversationSummary(null),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),Qt()),e.eventBus.emit("history:conversationDeleted",{conversationId:E,scope:N,wasActive:ne,timestamp:Date.now()})},Ja=async E=>{let N=E?.scope??B(),ne=E?.allTargets?null:E?.targetId??V(),pe=await e.session.clearConversationHistory({...ne?{targetId:ne}:{},scope:N});return e.setActiveConversationSummary(null),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),Qt(),e.eventBus.emit("history:cleared",{deleted:pe.deleted,scope:N,targetId:ne,timestamp:Date.now()}),pe},Za=async()=>{if(!r?.resetDevice)throw new Error("[Persona] resetHistoryIdentity() requires a history provider that can reset this device");let E=!1;try{E=(await e.session.resetHistoryDevice()).remoteRevocationConfirmed}finally{e.setActiveConversationSummary(null),e.session.clearArtifacts(),e.messageCache.clear(),e.lastAppliedMessages=null,e.config.clearStoredSessionId?.(),e.config.clearStoredConversationId?.(),e.persistentMetadata={},e.actionManager.syncFromMetadata();let N=e.storageAdapter;N?.clear&&e.runStorageMutation(()=>N.clear(),"[AgentWidget] Failed to clear storage adapter:"),e.resetAnchorState(),e.resumeAutoScroll(),Qt(),xn({restoreFocus:!1}),e.maybeFocusInput(),e.open||e.launcherSurfaceInstance?.launcher.element.focus()}return e.announceHistory(E?o.identityResetNotice:o.identityResetUnconfirmedNotice),e.eventBus.emit("history:identityReset",{remoteRevocationConfirmed:E,timestamp:Date.now()}),{remoteRevocationConfirmed:E}},$i=()=>e.artifactSplitRoot?e.panel:e.container,Ns=async E=>{let N=await e.loadHistoryView().catch(()=>null);return typeof N?.showHistoryConfirm=="function"?N.showHistoryConfirm(E):window.confirm(`${E.title}
|
|
12
12
|
|
|
13
|
-
${M.description}`)},Vt=async M=>await Ns({host:$i(),title:o.deleteConversationConfirmTitle,description:o.deleteConversationConfirm,confirmLabel:o.deleteConversationConfirmLabel,cancelLabel:o.confirmCancelLabel})?(await Mc(M),"deleted"):"cancelled",Fs=async()=>{let M=_()==="verified-user";return await Ns({host:$i(),title:o.clearHistoryConfirmTitle,description:M?o.clearHistoryVerifiedConfirm:o.clearHistoryConfirm,confirmLabel:o.clearHistoryConfirmLabel,cancelLabel:o.confirmCancelLabel})?(await Ja(),"cleared"):"cancelled"},el=async()=>{if(!await Ns({host:$i(),title:o.resetIdentityConfirmTitle,description:o.resetIdentityConfirm,confirmLabel:o.resetIdentityConfirmLabel,cancelLabel:o.confirmCancelLabel}))return{outcome:"cancelled"};let{remoteRevocationConfirmed:N}=await Za();return{outcome:"reset",remoteRevocationConfirmed:N}},tn=x("button","persona-history-earlier");tn.type="button",tn.textContent=o.showEarlierMessagesLabel,tn.setAttribute("data-persona-history-earlier",""),Object.assign(tn.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 Qt=()=>{if(!(L()&&!!e.historySessionState.nextMessageCursor&&!!e.session.getActiveConversationId())){tn.remove();return}tn.textContent=o.showEarlierMessagesLabel,tn.parentNode!==e.body&&e.body.insertBefore(tn,e.body.firstChild)};tn.addEventListener("click",()=>{let M=e.session.getActiveConversationId(),N=e.historySessionState.nextMessageCursor;if(!M||!N||tn.disabled)return;tn.disabled=!0;let ne=e.body.scrollHeight,pe=e.body.scrollTop;e.session.loadOlderMessages(M,N,{scope:_()}).then(()=>{e.body.scrollTop=pe+(e.body.scrollHeight-ne),e.repinAnchoredMessage()}).catch(()=>{}).finally(()=>{tn.disabled=!1,Qt()})});let Eo=()=>{let M=e.createHeaderIconButton({ariaLabel:o.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 M.button.addEventListener("click",N=>{if(!(!L()||I())){if(e.historyVisible){xn();return}Ke({invoker:M.button,keyboard:N.detail===0})}}),M},Jr=()=>{if(!L()){g?.remove(),d=null,g=null;return}if(g&&!g.isConnected&&(d=null,g=null),!d&&e.header){let pe=Eo();d=pe.button,g=pe.wrapper;let Re=e.panelElements.clearChatButtonWrapper||e.panelElements.closeButtonWrapper;Re?.parentNode&&e.header.contains(Re)?Re.parentNode.insertBefore(g,Re):e.header.appendChild(g)}if(!d||!g)return;let M=eo()||e.historyVisible&&e.historyPresentation==="rail";if(g.style.display=M?"none":"",M){document.activeElement===d&&mt();return}let N=I();d.disabled=N,d.setAttribute("aria-disabled",N?"true":"false");let ne=N?o.openHistoryBusyLabel:o.openHistoryLabel;d.setAttribute("aria-label",ne),(e.config.features?.history?.presentation??"panel")==="panel"?(d.removeAttribute("aria-expanded"),d.removeAttribute("aria-controls")):(d.setAttribute("aria-expanded",e.historyVisible?"true":"false"),d.setAttribute("aria-controls",A))},fr=!1,$s=()=>{let M=e.panelElements.clearChatButton;if(M){if(L()){fr||(y=M.getAttribute("aria-label")??"",fr=!0),M.setAttribute("aria-label",o.newConversationLabel),M.removeAttribute("title");return}fr&&(fr=!1,y&&M.setAttribute("aria-label",y))}},jn=()=>{o=Yf(e.config.features?.history?.copy),Jr(),gr(),$s(),Qt()};return e.historyChromeSync=jn,T(),jn(),e.destroyCallbacks.push(()=>{v?.(),C?.(),h+=1,Fi(),i?.dispose(),i?.view.destroy(),i=null}),{historyAvailable:L,historyScope:H,installHistoryProvider:T,syncHistoryChromeImpl:jn,syncHistoryPresentation:Vo,syncEarlierMessagesPill:Qt,openHistory:Ke,closeHistory:xn,openHistoryConversation:Mn,startNewConversation:Mo,updateHistoryConversation:Ds,deleteHistoryConversation:Mc,requestDeleteConversation:Vt,clearConversationHistory:Ja,resetHistoryIdentity:Za,railCollapseShortcut:Di,railCollapsible:D,railTriggerApplies:eo,railOverlayMode:Ct,toggleRailCollapsed:_i,toggleRailPinned:()=>ao(),get historyProvider(){return r},get historySurface(){return i},get railShell(){return xt},get railHost(){return xe},get railColumn(){return Wt}}}});var Ra,dm=Ve(()=>{"use strict";Ra=class{#e=null;#n=0;#o=[];#t=[];#s=[];#r=!1;#p=!1;#f=0;#i=!1;#g=!1;#l;#c=[];#a=0;#E=!1;#h;#S;#v;#A=null;constructor(t=24e3,n={}){this.#S=t;let o=Math.max(0,n.prebufferMs??0);this.#v=Math.round(t*o/1e3),this.#l=this.#v>0}#d(){if(!this.#e){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.#e=new o({sampleRate:this.#S})}let t=this.#e;return t.state==="suspended"&&!this.#g&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.#A){let r=new Uint8Array(this.#A.length+t.length);r.set(this.#A),r.set(t,this.#A.length),n=r,this.#A=null}if(n.length%2!==0&&(this.#A=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let o=this.#x(n);o.length!==0&&(this.#l?(this.#c.push(o),this.#a+=o.length,clearTimeout(this.#h),this.#a>=this.#v?this.#u():this.#E&&(this.#h=setTimeout(()=>this.#u(),this.#v/this.#S*1e3))):this.#m(o))}markStreamEnd(){this.#c.length>0&&this.#u(),this.#p=!0,this.#C()}flush(){for(let t of this.#o){t.onended=null;try{t.stop(),t.disconnect()}catch{}}this.#o=[],this.#f=0,this.#n=0,this.#r=!1,this.#p=!1,this.#t=[],this.#s=[],this.#A=null,this.#c=[],this.#a=0,this.#l=this.#v>0,this.#i=!1,clearTimeout(this.#h)}setContinuousMode(t){this.#E=t}isPlaying(){return this.#r}onFinished(t){this.#t.push(t)}onStarted(t){this.#s.push(t)}pause(){this.#g=!0,this.#e&&this.#e.state==="running"&&this.#e.suspend()}resume(){this.#g=!1,this.#e&&this.#e.state==="suspended"&&this.#e.resume()}async destroy(){this.flush(),this.#e&&(await this.#e.close(),this.#e=null)}#u(){this.#l=!1;let t=this.#c;this.#c=[],this.#a=0;for(let n of t)this.#m(n)}#m(t){if(t.length===0)return;let n=this.#d(),o=n.createBuffer(1,t.length,this.#S);o.getChannelData(0).set(t);let r=n.createBufferSource();r.buffer=o,r.connect(n.destination);let s=n.currentTime;if(this.#n===0?this.#n=s:this.#n<s&&(this.#n=s,this.#v>0&&(this.#l=!0)),r.start(this.#n),this.#n+=o.duration,this.#o.push(r),this.#f++,this.#r=!0,!this.#i){this.#i=!0;let i=this.#s.slice();this.#s=[];for(let l of i)l()}r.onended=()=>{let i=this.#o.indexOf(r);i!==-1&&(this.#o.splice(i,1),this.#f--,this.#C())}}#C(){if(this.#p&&this.#f<=0&&this.#c.length===0){this.#r=!1,this.#p=!1;let t=this.#t.slice();this.#t=[];for(let n of t)n()}}#x(t){let n=Math.floor(t.length/2),o=new Float32Array(n),r=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let s=0;s<n;s++){let i=r.getInt16(s*2,!0);o[s]=i/32768}return o}}});function pk(e){return e.replace(/\/+$/,"")}async function uk(e){try{let t=await e.json();return t.detail?`${t.error??`Runtype TTS ${e.status}`}: ${t.detail}`:t.error??`Runtype TTS request failed (${e.status})`}catch{return`Runtype TTS request failed (${e.status})`}}var Lp,Ww=Ve(()=>{"use strict";dm();Lp=class{constructor(t){this.id="runtype-tts";this.supportsPause=!0;this.#e=null;this.#n=null;this.#o=0;this.#t=t}#e;#n;#o;#t;#s(){return this.#n??=Promise.resolve(this.#t.createPlaybackEngine?this.#t.createPlaybackEngine():new Ra(24e3,{prebufferMs:this.#t.prebufferMs??200})).then(t=>this.#e=t)}speak(t,n){let o=++this.#o;this.#r(o,t,n)}async#r(t,n,o){try{let r=await this.#s();if(t!==this.#o)return;r.flush(),r.resume(),r.onStarted(()=>{t===this.#o&&o.onStart?.()}),r.onFinished(()=>{t===this.#o&&o.onEnd?.()});let s=`${pk(this.#t.host)}/v1/agents/${encodeURIComponent(this.#t.agentId)}/speak`,i=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.#t.clientToken}`},body:JSON.stringify({text:n.text,voice:n.voice??this.#t.voice,format:"pcm"})});if(t!==this.#o)return;if(!i.ok||!i.body)throw new Error(await uk(i));let l=i.body.getReader();for(;;){let{done:c,value:p}=await l.read();if(t!==this.#o){await l.cancel().catch(()=>{});return}if(c)break;p&&p.byteLength>0&&r.enqueue(p)}r.markStreamEnd()}catch(r){if(t!==this.#o)return;let s=r instanceof Error?r:new Error(String(r));this.#t.onError?.(s),o.onError?.(s)}}pause(){this.#e?.pause()}resume(){this.#e?.resume()}stop(){this.#o++,this.#e?.flush()}destroy(){this.#o++,this.#e?.destroy(),this.#e=null,this.#n=null}}});var Hp,Ow=Ve(()=>{"use strict";Hp=class{constructor(t,n,o={}){this.id="fallback";this.#n=t,this.#o=n,this.#t=o,this.#e=t}#e;#n;#o;#t;get supportsPause(){return this.#e.supportsPause}speak(t,n){this.#e=this.#n;let o=!1;this.#n.speak(t,{onStart:()=>{o=!0,n.onStart?.()},onEnd:()=>n.onEnd?.(),onError:r=>{if(o){n.onError?.(r);return}this.#t.onFallback?.(r),this.#e=this.#o,this.#o.speak(t,n)}})}pause(){this.#e.pause()}resume(){this.#e.resume()}stop(){this.#e.stop()}destroy(){this.#n.destroy?.(),this.#o.destroy?.()}}});var Bw={};ys(Bw,{FallbackSpeechEngine:()=>Hp,RuntypeSpeechEngine:()=>Lp});var _w=Ve(()=>{"use strict";Ww();Ow()});var LI={};ys(LI,{ASK_USER_QUESTION_CLIENT_TOOL:()=>mf,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>ff,ASK_USER_QUESTION_TOOL_NAME:()=>Hl,AgentWidgetClient:()=>wi,AgentWidgetSession:()=>Wa,AttachmentManager:()=>Ai,BrowserSpeechEngine:()=>ks,DEFAULT_COMPONENTS:()=>TS,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>vC,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>vi,DEFAULT_PALETTE:()=>xS,DEFAULT_SEMANTIC:()=>ES,DEFAULT_WIDGET_CONFIG:()=>wC,HistoryProviderError:()=>Vr,PRESETS:()=>Ih,PRESET_FULLSCREEN:()=>Hh,PRESET_MINIMAL:()=>Lh,PRESET_SHOP:()=>kh,ReadAloudController:()=>Si,SUGGEST_REPLIES_CLIENT_TOOL:()=>Wd,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>uf,SUGGEST_REPLIES_TOOL_NAME:()=>Oo,THEME_ZONES:()=>kS,VERSION:()=>Yn,WEBMCP_TOOL_PREFIX:()=>Ml,WebMcpBridge:()=>Iu,accessibilityPlugin:()=>kx,animationsPlugin:()=>Lx,applyFeaturePreferences:()=>fh,applyThemeVariables:()=>Mi,attachHeaderToContainer:()=>Ti,brandPlugin:()=>Hx,buildComposer:()=>ki,buildDefaultHeader:()=>_m,buildHeader:()=>jr,buildHeaderWithLayout:()=>Na,buildMinimalHeader:()=>Dm,builtInClientToolsForDispatch:()=>fi,canonicalArtifactDisplayMode:()=>Gn,collectEnrichedPageContext:()=>xx,componentRegistry:()=>Fo,createActionManager:()=>mc,createAgentExperience:()=>yu,createAskUserQuestionBubble:()=>Lv,createBestAvailableVoiceProvider:()=>Pu,createBubbleWithLayout:()=>pA,createCSATFeedback:()=>fu,createComboButton:()=>Qp,createComponentMiddleware:()=>ox,createComponentStreamParser:()=>pu,createDefaultSanitizer:()=>nm,createDemoCarousel:()=>Gx,createDirectivePostprocessor:()=>cw,createDropdownMenu:()=>Pi,createFlexibleJsonStreamParser:()=>yv,createIconButton:()=>Zn,createImagePart:()=>Kd,createJsonStreamParser:()=>Pd,createLabelButton:()=>Bm,createLocalStorageAdapter:()=>du,createMarkdownProcessor:()=>Vl,createMarkdownProcessorFromConfig:()=>jl,createMessageActions:()=>jm,createNPSFeedback:()=>mu,createPlainTextParser:()=>Ed,createPlugin:()=>Wx,createRegexJsonParser:()=>Td,createRovingTablist:()=>tM,createSlashCommandsSource:()=>eM,createSplitButton:()=>oA,createStandardBubble:()=>Fa,createStaticMentionSource:()=>Zx,createTextPart:()=>So,createTheme:()=>Gl,createThemeObserver:()=>Oa,createToggleGroup:()=>lc,createTypingIndicator:()=>Li,createVoiceProvider:()=>Xa,createWidgetHostLayout:()=>yc,createXmlParser:()=>kd,default:()=>Px,defaultActionHandlers:()=>Wi,defaultJsonActionParser:()=>fc,defaultMentionFilter:()=>Ru,defaultParseRules:()=>Th,detectColorScheme:()=>Xl,directivePostprocessor:()=>dw,ensureAskUserQuestionSheet:()=>Id,escapeHtml:()=>Ur,extractComponentDirectiveFromMessage:()=>gu,fileToImagePart:()=>xC,formatEnrichedContext:()=>Mx,generateAssistantMessageId:()=>Ps,generateCodeSnippet:()=>Fx,generateMessageId:()=>Sw,generateStableSelector:()=>Ph,generateUserMessageId:()=>Ha,getActiveTheme:()=>No,getAgentWidgetHandles:()=>gx,getColorScheme:()=>xi,getDisplayText:()=>zd,getHeaderLayout:()=>Nm,getImageParts:()=>AC,getPreset:()=>Tx,hasComponentDirective:()=>hc,hasImages:()=>Pa,headerLayouts:()=>Jp,highContrastPlugin:()=>Rx,initAgentWidget:()=>Ah,isAskUserQuestionMessage:()=>Ir,isComponentDirectiveType:()=>nx,isDockedMountMode:()=>Lt,isHistoryProviderError:()=>Tw,isSuggestRepliesMessage:()=>gi,isVoiceSupported:()=>_h,isWebMcpToolName:()=>bs,isWelcomeVisible:()=>Ws,latestAgentSuggestions:()=>Od,listRegisteredStreamAnimations:()=>QS,loadMarkdownParsers:()=>yd,markdownPostprocessor:()=>tm,mergeWithDefaults:()=>Ea,normalizeContent:()=>SC,normalizeMediaType:()=>vs,onMarkdownParsersReady:()=>ua,parseAskUserQuestionPayload:()=>Rr,parseSuggestRepliesPayload:()=>gf,parseWidgetPreferenceSlice:()=>gh,pickBestVoice:()=>Ia,pluginRegistry:()=>gc,reducedMotionPlugin:()=>Ix,registerIcons:()=>cv,registerStreamAnimationPlugin:()=>ec,removeAskUserQuestionSheet:()=>Wr,renderComponentDirective:()=>uu,renderLoadingIndicatorWithFallback:()=>Vm,renderLucideIcon:()=>ge,resolveArtifactDisplay:()=>rf,resolveArtifactDisplayMode:()=>or,resolveConfigPreferences:()=>uc,resolveDockConfig:()=>Jn,resolveSanitizer:()=>Pp,resolveTokens:()=>Vp,resolveWelcomeConfig:()=>Ua,stripWebMcpPrefix:()=>of,themeToCssVariables:()=>jp,unregisterStreamAnimationPlugin:()=>XS,validateImageFile:()=>MC,validateTheme:()=>Am});module.exports=BE(LI);var sv=require("marked"),iv=Bn(require("dompurify"),1);dn();var{setLoader:DI,load:_E,provide:DE,getSync:Qg}=lt({fallbackImport:()=>Promise.resolve().then(()=>(nv(),tv))}),hd=new Set,ov=()=>{let e=[...hd];hd.clear();for(let t of e)try{t()}catch{}};var yd=()=>{let e=Qg();return e?Promise.resolve(e):_E().then(t=>(ov(),t))},ua=e=>Qg()?()=>{}:(hd.add(e),()=>{hd.delete(e)}),rv=e=>{DE(e),ov()},nr=Qg;rv({Marked:sv.Marked,DOMPurify:iv.default});var G=require("lucide"),av={user:G.User,mail:G.Mail,phone:G.Phone,calendar:G.Calendar,clock:G.Clock,building:G.Building,"map-pin":G.MapPin,lock:G.Lock,key:G.Key,"credit-card":G.CreditCard,hash:G.Hash,globe:G.Globe,link:G.Link,"circle-check":G.CircleCheck,"circle-x":G.CircleX,"triangle-alert":G.TriangleAlert,info:G.Info,ban:G.Ban,shield:G.Shield,house:G.House,"pen-line":G.PenLine,save:G.Save,share:G.Share,funnel:G.Funnel,settings:G.Settings,"rotate-cw":G.RotateCw,"shopping-cart":G.ShoppingCart,"shopping-bag":G.ShoppingBag,package:G.Package,truck:G.Truck,tag:G.Tag,gift:G.Gift,receipt:G.Receipt,wallet:G.Wallet,store:G.Store,"dollar-sign":G.DollarSign,percent:G.Percent,play:G.Play,pause:G.Pause,"volume-x":G.VolumeX,camera:G.Camera,image:G.Image,film:G.Film,headphones:G.Headphones,"message-circle":G.MessageCircle,bell:G.Bell,heart:G.Heart,"eye-off":G.EyeOff,bookmark:G.Bookmark,"calendar-days":G.CalendarDays,timer:G.Timer,folder:G.Folder,"folder-open":G.FolderOpen,files:G.Files,"chart-column":G.ChartColumn,sparkles:G.Sparkles,zap:G.Zap,sun:G.Sun,moon:G.Moon,flag:G.Flag,lightbulb:G.Lightbulb,monitor:G.Monitor,smartphone:G.Smartphone};kt();dv(av);hf();dn();var{setLoader:hR,load:ST,provide:AT,getSync:xT}=lt({fallbackImport:()=>Promise.resolve().then(()=>(hf(),Dd))});var mi=ST,Dv=AT,Nv=xT;Dv(Dd);Cf();dn();var{setLoader:xR,load:_T,provide:DT}=lt({fallbackImport:()=>Promise.resolve().then(()=>(Cf(),Nd))});var Or=_T,Xv=DT;Xv(Nd);jf();dn();var{setLoader:EW,load:cP,provide:dP,getSync:pP}=lt({fallbackImport:()=>Promise.resolve().then(()=>(jf(),lp))});var cp=cP,BC=dP,qf=pP;BC(lp);Kf();dn();var{setLoader:HW,load:vP,provide:CP,getSync:wP}=lt({fallbackImport:()=>Promise.resolve().then(()=>(Kf(),pp))});var Gf=vP,NC=CP,FC=wP;NC(pp);Zf();dn();var{setLoader:GW,load:OP,provide:BP,getSync:_P}=lt({fallbackImport:()=>Promise.resolve().then(()=>(Zf(),bp))});var ew=OP,tw=BP,vp=_P;tw(bp);var Ep=require("lucide");Lr();wo();Je();kt();Je();var Cp=require("lucide");Lr();var DP=["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"],NP="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",FP="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",$P=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),wp=(e,t)=>{let n=x("div",["persona-message-bubble",e,...DP].join(" "));return n.id=`bubble-${t}`,n.setAttribute("data-message-id",t),n},Sp=e=>{let t=x("button",e.expandable?NP:FP);return t.type="button",e.expandable&&(t.setAttribute("aria-expanded",e.expanded?"true":"false"),t.setAttribute("data-expand-header","true")),t.setAttribute("data-bubble-type",e.bubbleType),t},em=(e,t,n)=>{e.innerHTML="";let o=Nt(t?Cp.ChevronUp:Cp.ChevronDown,16,n,2);o?e.appendChild(o):e.textContent=t?"Hide":"Show"},La=(e,t,n)=>{if(!n.expandable)return e.append(t),null;let o=x("div","persona-flex persona-items-center");em(o,n.expanded,n.iconColor);let r=x("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),e.append(t,r),o},Ap=e=>{let t=x("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(t.setAttribute("data-persona-collapsed-preview",e.previewKind),t.style.display="none",t.style.whiteSpace="pre-wrap",!e.expanded&&e.isActive&&e.activePreview&&e.previewText){let n=e.renderPreview?.();$P(t,n)||(t.textContent=e.previewText),t.style.display=""}return!e.expanded&&e.isActive&&e.activeMinHeight&&(e.bubble.style.minHeight=e.activeMinHeight),t},xp=e=>{e.header.setAttribute("aria-expanded",e.expanded?"true":"false"),e.toggleIcon&&em(e.toggleIcon,e.expanded,e.iconColor),e.content.style.display=e.expanded?"":"none",e.collapsedPreview.style.display=e.expanded?"none":e.collapsedPreview.textContent||e.collapsedPreview.childNodes.length?"":"none"},Mp=(e,t,n)=>{let o=n.stateSet.has(e),r=t.querySelector('button[data-expand-header="true"]'),s=t.querySelector(".persona-border-t"),i=t.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&&em(c,o,n.iconColor),s.style.display=o?"":"none",i&&(i.style.display=o?"none":i.textContent||i.childNodes.length?"":"none")};function Tp(e,t){let n=t==="tool"?"toolCallDisplay":"reasoningDisplay";return{...e,features:{...e?.features,[n]:{...t==="tool"?_r:Ci,...e?.future?.v5Defaults===!0?bi.features?.[n]:{},...e?.features?.[n]}}}}function Ts(e,t){let n=t==="tool"?"toolCallDisplay":"reasoningDisplay";return e?.features?.[n]?.variant??(e?.future?.v5Defaults?"row":"card")}function Ul(e){let t=Math.max(0,Math.floor((e??0)/1e3));return t<1?"a moment":t<60?`${t}s`:`${Math.floor(t/60)}m ${t%60}s`}function $r(e,t,n,o){if(Ts(n,o)!=="row")return e;e.className=`persona-message-bubble persona-${o}-bubble persona-activity-row`,e.dataset.activityKind=o,o==="tool"&&n.toolCall?.shadow===void 0&&(e.style.boxShadow="var(--persona-tool-bubble-shadow, none)");let r=e.querySelector(":scope > button");if(!r)return e;r.className="persona-activity-header";let s=o==="tool"?t.toolCall:t.reasoning,i=s?.status!=="complete",l=t.approval?.status??t.toolCall?.approvalStatus,c=l==="denied"?"denied":l==="pending"?"awaiting-approval":t.toolCall?.success===!1?"error":i?s?.status==="pending"?"pending":"running":"done";e.dataset.activityState=c;let p=x("span","persona-activity-icon");p.dataset.activityIcon=c;let d={pending:"circle",running:"loader-circle",done:"check",error:"x",denied:"x","awaiting-approval":"clock"},g=o==="reasoning"?n.features?.reasoningDisplay?.iconName:void 0,f=g?ge(g,16,"currentColor",2):c==="pending"?Nt(Ep.Circle,16,"currentColor",2):c==="awaiting-approval"?Nt(Ep.Clock,16,"currentColor",2):ge(d[c],16,"currentColor",2);f&&p.appendChild(f),r.querySelector(".persona-reasoning-header-icon")?.remove();let h=o==="tool"?"toolCallDisplay":"reasoningDisplay",y=n.features?.[h]?.iconVisibility??(n.future?.v5Defaults?"active":"always");if((y==="always"||y==="active"&&c!=="done")&&r.prepend(p),o==="tool"&&s){let L=x("span","persona-activity-duration");i&&s.startedAt&&L.setAttribute("data-tool-elapsed",String(s.startedAt));let I=(o==="tool"?t.toolCall?.duration:void 0)??s.durationMs??(s.completedAt!==void 0&&s.startedAt!==void 0?s.completedAt-s.startedAt:void 0);L.textContent=I===void 0?"":Ul(I),r.appendChild(L)}r.querySelector(":scope > div:not(.persona-ml-auto)")?.classList.add("persona-activity-label"),r.querySelector(".persona-ml-auto")?.classList.add("persona-activity-chevron");let A=e.querySelector(":scope > .persona-border-t");return A?.classList.add("persona-activity-body"),A&&(A.id=`activity-details-${t.id}`,r.setAttribute("aria-controls",A.id)),e}function nw(e){let t=new Set,n=new Set,o=new Set,r=new Map,s=i=>{clearTimeout(r.get(i)),r.delete(i)};return{observe(i,l,c,p={}){let d=l==="tool"?i.toolCall:i.reasoning;if(!(!d||n.has(i.id))&&(!t.has(i.id)&&d.status!=="complete"&&d.chunks?.some(Boolean)&&(t.add(i.id),p.autoExpand!==!1&&c.add(i.id)),t.has(i.id)&&d.status==="complete"&&!o.has(i.id))){if(o.add(i.id),p.autoCollapseDelay===!1)return;r.set(i.id,setTimeout(()=>{r.delete(i.id),c.delete(i.id),e(i.id,l)},p.autoCollapseDelay??1e3))}},manual(i){n.add(i),s(i)},prune(i){for(let l of new Set([...t,...n,...o]))i.has(l)||(s(l),t.delete(l),n.delete(l),o.delete(l))},clear(){for(let i of r.keys())s(i);t.clear(),n.clear(),o.clear()}}}function ow(e,t,n,o){let r=x("div","");r.id=`bubble-${e.id}`,r.dataset.messageId=e.id;let s=x("button","");s.type="button",s.dataset.expandHeader="true",s.dataset.bubbleType="tool",s.setAttribute("aria-expanded",String(n));let i=x("div","");typeof o=="string"?i.textContent=o:i.appendChild(o),La(s,i,{expandable:!0,expanded:n,iconColor:t.toolCall?.toggleTextColor||t.toolCall?.headerTextColor||"currentColor",metaGap:!0});let l=x("div","persona-border-t");return l.id=`activity-details-${e.id}`,l.style.display=n?"":"none",s.setAttribute("aria-controls",l.id),r.append(s,l),$r(r,e,{...t,features:{...t.features,toolCallDisplay:{...t.features?.toolCallDisplay,variant:"row"}}},"tool"),r.dataset.personaToolGroup="true",t.features?.toolCallDisplay?.loadingAnimation==="shimmer"&&(r.dataset.activityGroupShimmer="true"),{bubble:r,body:l}}Mf();function rw(e,t){let n=e.voiceRecognition,o=t.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)||e.agentId!==t.agentId||e.clientToken!==t.clientToken||e.apiUrl!==t.apiUrl}function Dn(e){return e?.type==="runtype"||e?.type==="custom"}var UP=()=>typeof window<"u"&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window);function sw(e){try{if(e?.type==="custom"&&e.custom){let t=e.custom,n=typeof t=="function"?t():t;return!!n&&typeof n.startListening=="function"}return e?.type==="runtype"&&e.runtype?!0:UP()}catch{return!1}}var VP=e=>{if(!e)return;let t={},n=e;if(n.heading){let o=n.heading;t.heading=(r,s,i)=>o({type:"heading",raw:i,depth:s,text:r,tokens:[]})}if(n.code){let o=n.code;t.code=(r,s,i)=>o({type:"code",raw:"",text:r,lang:s,escaped:i})}if(n.blockquote){let o=n.blockquote;t.blockquote=r=>o({type:"blockquote",raw:"",text:r,tokens:[]})}if(n.table){let o=n.table;t.table=(r,s)=>o({type:"table",raw:"",header:[],rows:[],align:[],headerHtml:r,bodyHtml:s})}if(n.link){let o=n.link;t.link=(r,s,i)=>o({type:"link",raw:"",href:r,title:s??null,text:i,tokens:[]})}if(n.image){let o=n.image;t.image=(r,s,i)=>o({type:"image",raw:"",href:r,title:s??null,text:i})}if(n.list){let o=n.list;t.list=(r,s,i)=>o({type:"list",raw:"",ordered:s,start:i,loose:!1,items:[],itemsHtml:r})}if(n.listitem){let o=n.listitem;t.listitem=(r,s,i)=>o({type:"list_item",raw:"",task:s,checked:i,loose:!1,text:r,tokens:[]})}if(n.paragraph){let o=n.paragraph;t.paragraph=r=>o({type:"paragraph",raw:"",text:r,tokens:[]})}if(n.codespan){let o=n.codespan;t.codespan=r=>o({type:"codespan",raw:"",text:r})}if(n.strong){let o=n.strong;t.strong=r=>o({type:"strong",raw:"",text:r,tokens:[]})}if(n.em){let o=n.em;t.em=r=>o({type:"em",raw:"",text:r,tokens:[]})}if(n.del){let o=n.del;t.del=r=>o({type:"del",raw:"",text:r,tokens:[]})}if(n.html){let o=n.html;t.html=r=>o({type:"html",raw:r,text:r})}if(n.text){let o=n.text;t.text=r=>o({type:"text",raw:r,text:r})}if(n.checkbox){let o=n.checkbox;t.checkbox=r=>o({checked:r})}return n.hr&&(t.hr=n.hr),n.br&&(t.br=n.br),t},Vl=e=>{let t=null;return n=>{let o=nr();if(!o)return Ur(n);if(!t){let{Marked:r}=o,s=e?.markedOptions;t=new r({gfm:s?.gfm??!0,breaks:s?.breaks??!0,pedantic:s?.pedantic,silent:s?.silent});let i=VP(e?.renderer);i&&t.use({renderer:i})}return t.parse(n)}},jl=e=>e?Vl({markedOptions:e.options,renderer:e.renderer}):Vl(),jP=Vl(),tm=e=>jP(e),Ur=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),aw=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),iw=e=>`%%FORM_PLACEHOLDER_${e}%%`,lw=(e,t)=>{let n=e;return n=n.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(o,r)=>{try{let s=JSON.parse(r.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let i=iw(t.length);return t.push({token:i,type:String(s.type)}),i}}catch{return o}return o}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(o,r)=>{let s=iw(t.length);return t.push({token:s,type:r}),s}),n},cw=e=>{let t=jl(e);return n=>{let o=[],r=lw(n,o),s=t(r);return o.forEach(({token:i,type:l})=>{let c=new RegExp(i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${aw(l)}"></div>`;s=s.replace(c,d)}),s}},dw=e=>{let t=[],n=lw(e,t),o=tm(n);return t.forEach(({token:r,type:s})=>{let i=new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),c=`<div class="persona-form-directive" data-tv-form="${aw(s)}"></div>`;o=o.replace(i,c)}),o};var qP={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"]},zP=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,nm=()=>{let e=null;return t=>{let n=nr();if(!n)return Ur(t);if(!e){let{DOMPurify:o}=n;e=o(typeof window<"u"?window:void 0),e.addHook("uponSanitizeAttribute",(r,s)=>{if(s.attrName==="src"||s.attrName==="href"){let i=s.attrValue;i.toLowerCase().startsWith("data:")&&!zP.test(i)&&(s.attrValue="",s.keepAttr=!1)}})}return e.sanitize(t,qP)}},Pp=e=>e===!1?null:typeof e=="function"?e:nm();var pw=/^\s*\|?[\s:|-]*-[\s:|-]*$/,uw=e=>e.includes("|"),gw=e=>{let t=e.trim();return t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1)),t.split("|").map(n=>n.trim())},KP=e=>`| ${e.join(" | ")} |`,GP=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,YP=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),fw=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
|
|
14
|
-
`),n=!1;for(let o=0;o<t.length-1;o++){let r=t[o],s=t[o+1];if(!
|
|
15
|
-
`):e};var mw="var(--persona-md-table-scroll-fade, 24px)",hw=new WeakSet;function bw(e){e.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(e){let t=e.scrollWidth-e.clientWidth;if(t<=1){e.removeAttribute("data-persona-scroll-x");return}e.setAttribute("data-persona-scroll-x","");let o=getComputedStyle(e).direction==="rtl"?t+e.scrollLeft:e.scrollLeft,r=t-o;e.style.setProperty("--persona-fade-l",o<=1?"0px":mw),e.style.setProperty("--persona-fade-r",r<=1?"0px":mw)}function om(e){hw.has(e)||(hw.add(e),e.addEventListener("scroll",t=>{let n=t.target;n?.classList?.contains("persona-table-scroll")&&yw(n)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(yw)}pi();dn();var{setLoader:mO,load:XP}=lt({fallbackImport:()=>import("@runtypelabs/persona/webmcp-runtime")});var vw=XP;var QP="agent_",JP="flow_";function Cw(e){return e.startsWith(QP)?{kind:"agentId",agentId:e}:e.startsWith(JP)?{kind:"flowId",flowId:e}:null}function ww(e,t){let n=e.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let i=n.slice(0,o),l=n.slice(o+1);if(i==="runtype"){let p=Cw(l);if(p)return p;throw new Error(`[Persona] target "runtype:${l}" is not a valid Runtype agent_/flow_ id.`)}let c=t?.[i];if(!c)throw new Error(`[Persona] No target provider registered for "${i}". Add a \`targetProviders.${i}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:c(l).payload}}let r=Cw(n);if(r)return r;let s=t?.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 Sw(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Ha(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Ps(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}function Aw(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`turn_${e}_${t}`}Bd();var ZP=e=>e.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase().replace(/_+/g,"_").replace(/^_|_$/g,""),ek=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),tk=e=>{if(e.variant!=="tool")return null;let t=e.agentMetadata?.clientToolAnswer;if(!t||!t.toolCallId||t.result===void 0)return null;let n=ZP(t.toolName);return n?{call:{toolCallId:t.toolCallId,toolName:n,args:ek(t.args)?t.args:{}},result:{toolCallId:t.toolCallId,toolName:n,result:t.result}}:null},rm=(e,t)=>{let n=[],o=[],r=[],s="",i,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 e){let p=tk(c);if(p){let g=c.agentMetadata?.clientToolAnswer?.batch;o.length>0&&(g===void 0||g!==i)&&l(),o.length===0&&(s=c.createdAt,i=g),o.some(f=>f.toolCallId===p.call.toolCallId)||(o.push(p.call),r.push(p.result));continue}let d=t(c);d&&(l(),n.push(d))}return l(),n};Cs();Sa();yp();Bo();var nk="https://api.runtype.com/v1/dispatch",on=class extends Error{constructor(t,n,o){super(n),this.name="HistoryClientError",this.code=t,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}},xw=e=>"reason"in e?e.reason:void 0,ok="The identity proof was rejected",sm=(e,t)=>e instanceof on&&e.code===t,im=e=>e.voiceCaption?!1:!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0),Mw=e=>e.slice().sort((t,n)=>new Date(t.createdAt).getTime()-new Date(n.createdAt).getTime()),Ew=e=>({role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,createdAt:e.createdAt});function rk(e){switch(e){case"json":return Pd;case"regex-json":return Td;case"xml":return kd;default:return Ed}}var wi=class{constructor(t={},n={}){this.config=t;this.historyInternals=n;this.#g=null;this.clientSession=null;this.#l=null;this.#c=!1;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.#a=null;this.#E=!1;this.#h=!1;this.#S=!1;this.#v=null;this.#A=new Set;this.#d=new Set;this.webMcpBridge=null;this.#u=null;this.#$=null;this.#de=null;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.#e=t.apiUrl??nk,this.#n={"Content-Type":"application/json","X-Persona-Version":Yn,...t.headers},this.debug=!!t.debug,this.#o=t.streamParser??rk(t.parserType),this.#t=t.contextProviders??[],this.#s=t.requestMiddleware,this.#r=t.customFetch,this.#p=t.parseSSEEvent,this.#f=t.getHeaders,t.webmcp?.enabled===!0&&(this.#u=this.#C(t.webmcp))}#e;#n;#o;#t;#s;#r;#p;#f;#i;#g;#l;#c;#a;#E;#h;#S;#v;#A;#d;#u;#m;#C(t){return vw().then(n=>{let o=new n.WebMcpBridge(t,{recordToolDisplayTitles:Cd,getToolDisplayTitle:ma,loadPolyfill:wd});return this.#m!==void 0&&o.setConfirmHandler(this.#m),this.webMcpBridge=o,o}).catch(n=>(this.#u=null,console.warn("[Persona] Failed to load the WebMCP runtime chunk",n),null))}#x(){return this.webMcpBridge?Promise.resolve(this.webMcpBridge):this.config.webmcp?.enabled!==!0?Promise.resolve(null):(this.#u||(this.#u=this.#C(this.config.webmcp)),this.#u)}updateConfig(t){this.config=t}setHistoryInternals(t){this.historyInternals=t}setSSEEventCallback(t){this.#i=t}setWebMcpConfirmHandler(t){this.#m=t,this.webMcpBridge?.setConfirmHandler(t)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(t,n,o){return this.config.webmcp?.enabled!==!0?null:this.#x().then(r=>r?r.executeToolCall(t,n,o):{isError:!0,content:[{type:"text",text:"WebMCP runtime failed to load."}]})}getSSEEventCallback(){return this.#i}isClientTokenMode(){return!!this.config.clientToken}#y(){let{agentId:t,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:t,flowId:n};let s=ww(o,r);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.#y().agentId)}#b(){return this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||_d}#H(t){return`${this.#b()}/v1/client/${t}`}getClientSession(){return this.clientSession}async reconnectClientTokenStream(t){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 on("visitor_token_missing","Durable recovery is not enabled for this client session");let i=`${this.#b()}/v1/client/conversations/${encodeURIComponent(r)}/executions/${encodeURIComponent(t.executionId)}/events`,l=new URLSearchParams({sessionId:n.sessionId,after:t.after}),c=await fetch(`${i}?${l}`,{method:"GET",headers:{"X-Persona-Version":Yn,"X-Visitor-Token":s},signal:t.signal});if(c.status===401&&!o){o=!0;let p=await Or();n=await p.recoverFromUnauthorized(this.#W(),await p.readErrorCode(this.#W(),c),null,!0);continue}if(!c.ok)throw await(await Or()).historyErrorFor(this.#W(),c,!0);return c}}async warmSession(){let t=this.clientSession;return!this.isClientTokenMode()||this.#l||t&&new Date<t.expiresAt||this.#c===t?null:(this.#c=t,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.#l)return this.#l;let t=this.#l=this.#K().then(n=>this.#l!==t?this.initSession():(this.clientSession=n,this.#c=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(n),n)).finally(()=>{this.#l===t&&(this.#l=null)});return t}#k(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()&&!this.#E}async readVisitorToken(){let t=this.historyInternals.visitorStore;return t?(await t.ready,await t.get()??null):null}#M(){if(!this.#E){this.#B({state:"unavailable",reason:"history_disabled"}),this.#E=!0,!this.#h&&typeof console<"u"&&(this.#h=!0,console.warn("[Persona] Visitor history is disabled for this surface; continuing without it.")),this.historyInternals.onHistoryAvailabilityChanged?.(!1);for(let t of[...this.#d])t(!1)}}getHistoryIdentityStatus(){return this.#v??this.#I()}subscribeHistoryIdentityStatus(t){return this.#A.add(t),()=>{this.#A.delete(t)}}subscribeHistoryAvailability(t){return this.#d.add(t),this.#E&&t(!1),()=>{this.#d.delete(t)}}#I(){return this.isClientTokenMode()?this.config.features?.history?.enabled!==!0||this.#E?{state:"unavailable",reason:"history_disabled"}:this.#Y():{state:"unavailable",reason:"ineligible_mode"}}#Y(){let t=this.#v;return t?.state==="browser_only"?t:this.#j()}#j(){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"}}#B(t){let n=this.getHistoryIdentityStatus(),o=n.state===t.state&&xw(n)===xw(t);if(this.#v=t,!o){this.historyInternals.onHistoryIdentityStatusChanged?.(t);for(let r of[...this.#A])r(t)}}async#T(t){let n=this.#k()&&!t.omitVisitorFields,o=!t.omitVisitorFields,r=null;(n||o)&&(await this.historyInternals.historyBootstrapReady,r=await this.readVisitorToken());let s=this.#y(),i=s.agentId??s.flowId,l=n||t.durableResume?t.conversationId:void 0,c={token:this.config.clientToken,...i&&{flowId:i},...n&&{visitorHistory:!0},...o&&{durableRecovery:!0},...(n||o)&&r?{visitorToken:r}:{},...n&&t.identityProof?{identityProof:t.identityProof}:{},...l?{conversationId:l}:t.storedSessionId?{sessionId:t.storedSessionId}:{}};t.signal?.throwIfAborted();let p=await fetch(this.#H("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Yn},body:JSON.stringify(c),signal:t.signal});if(!p.ok){let g=await p.json().catch(()=>({error:"Session initialization failed"}));if(n&&p.status===403&&g.error==="visitor_history_disabled"){if(this.#M(),l)throw new on("history_disabled","Visitor history is disabled for this surface");return this.#T({...t,omitVisitorFields:!0})}throw p.status===403&&g.error==="durable_recovery_disabled"?new on("history_disabled","Durable recovery is disabled for this surface"):(n||t.durableResume)&&p.status===401&&g.error==="visitor_required"?new on("visitor_required","Visitor credential no longer resolves"):l&&p.status===404?new on("not_found","Conversation not found"):p.status===401?new Error(`Invalid client token: ${g.hint||g.error}`):p.status===403?new Error(`Origin not allowed: ${g.hint||g.error}`):new Error(g.error||"Failed to initialize session")}let d=await p.json();return d.visitor?.token&&await this.historyInternals.visitorStore?.set(d.visitor.token),{sessionId:d.sessionId,expiresAt:new Date(d.expiresAt),flow:d.flow,...d.conversationId?{conversationId:d.conversationId}:{},...d.targetId?{targetId:d.targetId}:{},...d.conversationRevision?{conversationRevision:d.conversationRevision}:{},...d.durableRecovery?{durableRecovery:d.durableRecovery}:{},...d.visitor?{visitor:d.visitor}:{},config:{welcomeMessage:d.config.welcomeMessage,placeholder:d.config.placeholder,theme:d.config.theme}}}async#K(){await this.historyInternals.historyBootstrapReady;let t=this.config.getStoredConversationId?.()||null,n=this.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.#k()&&!n)return this.#_(t,!1);let o=await this.readVisitorToken();if(t&&o)try{let r=await this.#T({conversationId:t,durableResume:n});return n&&r.durableRecovery?.enabled!==!0&&this.historyInternals.setStoredResumableHandle?.(null),this.#D(r,t,!1)}catch(r){if(!sm(r,"not_found")&&!sm(r,"visitor_required")&&!sm(r,"history_disabled"))throw r;return n&&this.historyInternals.setStoredResumableHandle?.(null),this.#_(t,!0)}return this.#_(t,!1)}async#_(t,n){let o=this.historyInternals.visitorStore;return o&&!await this.readVisitorToken()?o.withFirstInitLock(()=>this.#F(t,n)):this.#F(t,n)}async#F(t,n){let o=this.config.getStoredSessionId?.()||null,r=await this.#T({storedSessionId:o}),s=await this.#te(r);return this.#D(s,t,n)}async#ee(t){let n=this.config.getStoredSessionId?.()||null,o=this.config.getStoredConversationId?.()||null,r=await this.#T({storedSessionId:n,identityProof:t}),s=this.#D(r,o,!1);return this.clientSession=s,this.#l=null,this.#c=!1,this.resetClientToolsFingerprint(),s}async#te(t){if(!t.visitor?.token||this.#S||!this.#k()&&t.durableRecovery?.enabled!==!0)return t;this.#S=!0;try{return await this.#T({storedSessionId:t.sessionId})}catch{return t}finally{this.#S=!1}}#D(t,n,o){let r=t.conversationId;return r&&n&&(o||r!==n)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:n,conversationId:r}),this.config.setStoredSessionId?.(t.sessionId),r&&(this.config.setStoredConversationId?.(r),this.historyInternals.setStoredConversationRevision?.(t.conversationRevision??null)),t}#X(t){let n=!1;return{session:t,commit:()=>{n||(n=!0,this.clientSession=t,this.#c=!1,this.resetClientToolsFingerprint())},discard:()=>{n=!0}}}async prepareConversationSession(t,n){if(!this.isClientTokenMode())throw new Error("prepareConversationSession() only available in client token mode");if(!this.#k())throw new on("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 on("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let s=await this.#T({conversationId:t,identityProof:o});return this.#X(s)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw new Error("prepareNewConversationSession() only available in client token mode");await this.historyInternals.historyBootstrapReady;let t=await this.#T({});return this.#X(t)}handleExternalCredentialChange(){this.clearClientSession(),this.#k()&&this.#B(this.#j())}clearClientSession(){this.clientSession=null,this.#l=null,this.#c=!1,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.#a=null}#Z(){return`${this.#b()}/v1/client/feedback`}async sendFeedback(t){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(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.#Z(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Yn},body:JSON.stringify(r)});if(!s.ok){let i=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,this.#c=!1,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:n})}async#ne(t){t?.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 i=Promise.resolve().then(()=>o());r=t?await Promise.race([i,new Promise((l,c)=>{s=()=>c(t.reason),t.addEventListener("abort",s,{once:!0}),t.aborted&&s()})]):await i}catch{throw t?.throwIfAborted(),new Error("The identity proof provider failed.")}finally{s&&t?.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}}#$;#U(){let t=this;return this.#$??={get config(){return t.config},headers:this.#n,getHeaders:this.#f,debug:this.debug,clientApiBase:()=>t.#b(),getClientApiUrl:n=>t.#H(n),getWebMcpBridge:()=>t.#x(),sendWithClientToolsDiff:(n,o,r,s)=>t.#re(n,o,r,s),initSession:()=>t.initSession(),readVisitorToken:()=>t.readVisitorToken(),isClientTokenMode:()=>t.isClientTokenMode()}}#de;#W(){let t=this;return this.#de??={HistoryClientError:on,get config(){return t.config},get historyInternals(){return t.historyInternals},get clientSession(){return t.clientSession},clientApiBase:()=>t.#b(),setHistoryIdentityStatus:n=>t.#B(n),browserOnlyStatus:()=>t.#Y(),derivedBrowserOnly:()=>t.#j(),reinitWithProof:n=>t.#ee(n),isHistoryCapable:()=>t.#k(),clearClientSession:()=>t.clearClientSession(),initSession:()=>t.initSession(),readVisitorToken:()=>t.readVisitorToken(),isClientTokenMode:()=>t.isClientTokenMode()}}async listConversations(t){return(await Or()).listConversations(this.#W(),t)}async getConversation(t,n){return(await Or()).getConversation(this.#W(),t,n)}async finalizeDisplayProjections(t,n){return(await Or()).finalizeDisplayProjections(this.#W(),t,n)}async deleteConversation(t,n){return(await Or()).deleteConversation(this.#W(),t,n)}async deleteAllConversations(t){return(await Or()).deleteAllConversations(this.#W(),t)}async resetVisitor(){return(await Or()).resetVisitor(this.#W())}async dispatch(t,n){return t.signal?.throwIfAborted(),mi().catch(()=>{}),this.isClientTokenMode()?this.#be(t,n):this.isAgentMode()?this.#pe(t,n):this.#oe(t,n)}async#be(t,n){let o=Aw();this.#g=o;let r=()=>this.#g===o,s=i=>{r()&&n(i)};n({type:"status",status:"connecting"});try{let i=()=>{if(t.signal?.throwIfAborted(),!r())throw new DOMException("Turn superseded","AbortError")},l=this.clientSession??await this.initSession();i();let c=async()=>{i();let A=l,L=A.durableRecovery?.enabled===!0;if(L&&(!A.conversationId||!await this.readVisitorToken()))throw new Error("Renewing this conversation requires its visitor credential.");i();let I=await this.#T({...L||this.#k()?{conversationId:A.conversationId,durableResume:L}:{storedSessionId:A.sessionId},signal:t.signal});if(i(),A.conversationId&&I.conversationId!==A.conversationId||L&&I.durableRecovery?.enabled!==!0)throw new Error("Session renewal did not preserve this conversation.");l=this.#D(I,A.conversationId??null,!1),this.clientSession=l,this.#c=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(l)};Date.now()>=l.expiresAt.getTime()-6e4&&await c();let p=await this.#N(t.messages),d=p.metadata?Object.fromEntries(Object.entries(p.metadata).filter(([A])=>A!=="sessionId"&&A!=="session_id")):void 0,g=this.#k(),f={sessionId:l.sessionId,messages:t.messages.filter(im).map(A=>{let L=g?Fl(A):void 0;return{id:A.id,role:A.role,content:A.contentParts??A.llmContent??A.rawContent??A.content,...L!==void 0&&{displayContent:L}}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...d&&Object.keys(d).length>0&&{metadata:d},...p.inputs&&Object.keys(p.inputs).length>0&&{inputs:p.inputs},...p.context&&{context:p.context},turnId:o,...t.interrupt&&{submitMode:"interrupt"}},h=async()=>{i();let A=l.durableRecovery?.enabled===!0?await this.readVisitorToken():null;return i(),this.#re(l.sessionId,p.clientTools,async L=>{i();let I=await this.#ne(t.signal);i();let H={...f,sessionId:l.sessionId,...L,...I&&{identityProof:I}};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",{...H,...I&&{identityProof:{provider:I.provider,token:"[REDACTED]"}}}),fetch(this.#H("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Yn,...A?{"X-Visitor-Token":A}:{}},body:JSON.stringify(H),signal:t.signal})})},y=await h();if(i(),y.response.status===401){let A=await y.response.clone().json().catch(()=>null);i(),A?.error==="Session not found or expired"&&(await c(),y=await h(),i())}let{response:v,commit:C}=y;if(!v.ok){let A=await v.json().catch(()=>({error:"Chat request failed"}));if(v.status===401&&A.error==="invalid_identity_proof"){let I=new on("invalid_identity_proof",ok);throw s({type:"error",error:I}),I}if(v.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let I=new Error("Session expired. Please refresh to continue.");throw s({type:"error",error:I}),I}if(v.status===429){let I=new Error(A.hint||"Message limit reached for this session.");throw s({type:"error",error:I}),I}if(v.status===410&&A.error==="conversation_deleted"){let I=new on("conversation_deleted","This conversation was deleted");throw s({type:"error",error:I}),I}let L=new Error(A.error||"Failed to send message");throw s({type:"error",error:L}),L}if(!v.body){let A=new Error("No response body received");throw s({type:"error",error:A}),A}C(),s({type:"status",status:"connected"});try{await this.#G(v.body,s,t.assistantMessageId)}finally{s({type:"status",status:"idle"})}}catch(i){let l=i instanceof Error?i:new Error(String(i));throw!(l instanceof on)&&!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&s({type:"error",error:l}),l}}async#oe(t,n){n({type:"status",status:"connecting"});let o=await this.#N(t.messages,t.composerOptions);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.#n};if(this.#f)try{let i=await this.#f();r={...r,...i}}catch(i){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.#r)try{s=await this.#r(this.#e,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(i){let l=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:l}),l}else s=await fetch(this.#e,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let i=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.#G(s.body,n)}finally{n({type:"status",status:"idle"})}}async#pe(t,n){n({type:"status",status:"connecting"});let o=await this.#L(t.messages,t.composerOptions);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.#n};if(this.#f)try{let i=await this.#f();r={...r,...i}}catch(i){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.#r)try{s=await this.#r(this.#e,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(i){let l=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:l}),l}else s=await fetch(this.#e,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let i=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.#G(s.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o,r){n({type:"status",status:"connected"});try{await this.#G(t,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){return(await mi()).resolveApproval(this.#U(),t,n)}async#re(t,n,o,r){let s=!!(n&&n.length>0),i=s?gv(n):void 0,l=this.clientToolsFingerprintSessionId===t,c=s&&l&&this.lastSentClientToolsFingerprint===i,p=!s&&r?.emptyMeansReplace===!0&&this.#a===t,d=!1,g;for(let f=0;;f++){if(g=await o({...s&&(d||!c)&&n?{clientTools:n}:{},...p?{clientTools:[]}:{},...i?{clientToolsFingerprint:i}:{}}),g.status===409&&f===0&&s&&(await g.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){d=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:g,commit:()=>{this.lastSentClientToolsFingerprint=i??null,this.clientToolsFingerprintSessionId=t,s?this.#a=t:p&&(this.#a=null)}}}async resumeFlow(t,n,o){return(await mi()).resumeFlow(this.#U(),t,n,o)}#se(t){for(let n=t.length-1;n>=0;n--){let o=t[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async#q(t){let n={};this.#t.length&&await Promise.all(this.#t.map(async r=>{try{let s=await r({messages:t,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.#se(t);return o&&Object.assign(n,o),Object.keys(n).length?n:null}#R(t){if(!t)return;let n={};return t.selectedModelId&&(n.selectedModelId=t.selectedModelId),t.activeModeIds?.length&&(n.activeModeIds=[...t.activeModeIds]),Object.keys(n).length>0?n:void 0}#O(t,n){let o=n?.selectedModelId;return!o||!("model"in t)?t:this.config.composer?.models?.some(s=>s.id===o)?{...t,model:o}:t}async#L(t,n){let o=this.#y().agentId;if(!this.config.agent&&!o)throw new Error("Agent configuration required for agent mode");let r=rm(Mw(t),p=>im(p)&&(p.role==="user"||p.role==="assistant"||p.role==="system")&&(!p.variant||p.variant==="assistant")?Ew(p):null),s=this.#R(n),i={agent:this.#O(this.config.agent??{agentId:o},s),messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};s&&(i.composerOptions=s);let l=[...fi(this.config),...await(await this.#x())?.snapshotForDispatch()??[]];l.length>0&&(i.clientTools=l);let c=await this.#q(t);return c&&(i.context=c),i}async#N(t,n){let o=rm(Mw(t),p=>im(p)?Ew(p):null),r=this.#y(),s={messages:o,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[p,d]of Object.entries(r.targetPayload))p!=="messages"&&(s[p]=d);let i=[...fi(this.config),...await(await this.#x())?.snapshotForDispatch()??[]];i.length>0&&(s.clientTools=i);let l=await this.#q(t);l&&(s.context=l);let c=this.#R(n);if(c&&(s.composerOptions=c),this.#s)try{let p=await this.#s({payload:{...s},config:this.config});if(p&&typeof p=="object"){let d=p;return s.clientTools!==void 0&&!("clientTools"in d)&&(d.clientTools=s.clientTools),d}}catch(p){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",p)}return s}async#G(t,n,o,r){let{streamResponse:s}=Nv()??await mi();return s({config:()=>this.config,createStreamParser:this.#o,parseSSEEvent:this.#p,onSSEEvent:(i,l)=>this.#i?.(i,l)},t,n,o,r)}};var Vr=class extends Error{constructor(t,n,o){super(n),this.name="HistoryProviderError",this.code=t,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}};function Tw(e){return e instanceof Vr}pi();Ca();Nr();ha();Nr();function sk(e){let t=0;for(let n of e.split(`
|
|
16
|
-
`)){let o=/^ {0,3}(`+)/.exec(n);o&&o[1].length>t&&(t=o[1].length)}return t}function
|
|
13
|
+
${E.description}`)},Vt=async E=>await Ns({host:$i(),title:o.deleteConversationConfirmTitle,description:o.deleteConversationConfirm,confirmLabel:o.deleteConversationConfirmLabel,cancelLabel:o.confirmCancelLabel})?(await Mc(E),"deleted"):"cancelled",Fs=async()=>{let E=B()==="verified-user";return await Ns({host:$i(),title:o.clearHistoryConfirmTitle,description:E?o.clearHistoryVerifiedConfirm:o.clearHistoryConfirm,confirmLabel:o.clearHistoryConfirmLabel,cancelLabel:o.confirmCancelLabel})?(await Ja(),"cleared"):"cancelled"},el=async()=>{if(!await Ns({host:$i(),title:o.resetIdentityConfirmTitle,description:o.resetIdentityConfirm,confirmLabel:o.resetIdentityConfirmLabel,cancelLabel:o.confirmCancelLabel}))return{outcome:"cancelled"};let{remoteRevocationConfirmed:N}=await Za();return{outcome:"reset",remoteRevocationConfirmed:N}},tn=x("button","persona-history-earlier");tn.type="button",tn.textContent=o.showEarlierMessagesLabel,tn.setAttribute("data-persona-history-earlier",""),Object.assign(tn.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 Qt=()=>{if(!(L()&&!!e.historySessionState.nextMessageCursor&&!!e.session.getActiveConversationId())){tn.remove();return}tn.textContent=o.showEarlierMessagesLabel,tn.parentNode!==e.body&&e.body.insertBefore(tn,e.body.firstChild)};tn.addEventListener("click",()=>{let E=e.session.getActiveConversationId(),N=e.historySessionState.nextMessageCursor;if(!E||!N||tn.disabled)return;tn.disabled=!0;let ne=e.body.scrollHeight,pe=e.body.scrollTop;e.session.loadOlderMessages(E,N,{scope:B()}).then(()=>{e.body.scrollTop=pe+(e.body.scrollHeight-ne),e.repinAnchoredMessage()}).catch(()=>{}).finally(()=>{tn.disabled=!1,Qt()})});let To=()=>{let E=e.createHeaderIconButton({ariaLabel:o.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 E.button.addEventListener("click",N=>{if(!(!L()||I())){if(e.historyVisible){xn();return}Ke({invoker:E.button,keyboard:N.detail===0})}}),E},Jr=()=>{if(!L()){g?.remove(),d=null,g=null;return}if(g&&!g.isConnected&&(d=null,g=null),!d&&e.header){let pe=To();d=pe.button,g=pe.wrapper;let Re=e.panelElements.clearChatButtonWrapper||e.panelElements.closeButtonWrapper;Re?.parentNode&&e.header.contains(Re)?Re.parentNode.insertBefore(g,Re):e.header.appendChild(g)}if(!d||!g)return;let E=to()||e.historyVisible&&e.historyPresentation==="rail";if(g.style.display=E?"none":"",E){document.activeElement===d&&mt();return}let N=I();d.disabled=N,d.setAttribute("aria-disabled",N?"true":"false");let ne=N?o.openHistoryBusyLabel:o.openHistoryLabel;d.setAttribute("aria-label",ne),(e.config.features?.history?.presentation??"panel")==="panel"?(d.removeAttribute("aria-expanded"),d.removeAttribute("aria-controls")):(d.setAttribute("aria-expanded",e.historyVisible?"true":"false"),d.setAttribute("aria-controls",A))},fr=!1,$s=()=>{let E=e.panelElements.clearChatButton;if(E){if(L()){fr||(y=E.getAttribute("aria-label")??"",fr=!0),E.setAttribute("aria-label",o.newConversationLabel),E.removeAttribute("title");return}fr&&(fr=!1,y&&E.setAttribute("aria-label",y))}},jn=()=>{o=Jf(e.config.features?.history?.copy),Jr(),gr(),$s(),Qt()};return e.historyChromeSync=jn,T(),jn(),e.destroyCallbacks.push(()=>{v?.(),C?.(),h+=1,Fi(),i?.dispose(),i?.view.destroy(),i=null}),{historyAvailable:L,historyScope:H,installHistoryProvider:T,syncHistoryChromeImpl:jn,syncHistoryPresentation:Vo,syncEarlierMessagesPill:Qt,openHistory:Ke,closeHistory:xn,openHistoryConversation:En,startNewConversation:Mo,updateHistoryConversation:Ds,deleteHistoryConversation:Mc,requestDeleteConversation:Vt,clearConversationHistory:Ja,resetHistoryIdentity:Za,railCollapseShortcut:Di,railCollapsible:D,railTriggerApplies:to,railOverlayMode:Ct,toggleRailCollapsed:Bi,toggleRailPinned:()=>lo(),get historyProvider(){return r},get historySurface(){return i},get railShell(){return xt},get railHost(){return xe},get railColumn(){return Wt}}}});var Ra,gm=Ve(()=>{"use strict";Ra=class{#e=null;#n=0;#o=[];#t=[];#s=[];#r=!1;#p=!1;#f=0;#i=!1;#u=!1;#c;#l=[];#a=0;#M=!1;#h;#A;#w;#x=null;constructor(t=24e3,n={}){this.#A=t;let o=Math.max(0,n.prebufferMs??0);this.#w=Math.round(t*o/1e3),this.#c=this.#w>0}#d(){if(!this.#e){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.#e=new o({sampleRate:this.#A})}let t=this.#e;return t.state==="suspended"&&!this.#u&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.#x){let r=new Uint8Array(this.#x.length+t.length);r.set(this.#x),r.set(t,this.#x.length),n=r,this.#x=null}if(n.length%2!==0&&(this.#x=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let o=this.#E(n);o.length!==0&&(this.#c?(this.#l.push(o),this.#a+=o.length,clearTimeout(this.#h),this.#a>=this.#w?this.#g():this.#M&&(this.#h=setTimeout(()=>this.#g(),this.#w/this.#A*1e3))):this.#m(o))}markStreamEnd(){this.#l.length>0&&this.#g(),this.#p=!0,this.#S()}flush(){for(let t of this.#o){t.onended=null;try{t.stop(),t.disconnect()}catch{}}this.#o=[],this.#f=0,this.#n=0,this.#r=!1,this.#p=!1,this.#t=[],this.#s=[],this.#x=null,this.#l=[],this.#a=0,this.#c=this.#w>0,this.#i=!1,clearTimeout(this.#h)}setContinuousMode(t){this.#M=t}isPlaying(){return this.#r}onFinished(t){this.#t.push(t)}onStarted(t){this.#s.push(t)}pause(){this.#u=!0,this.#e&&this.#e.state==="running"&&this.#e.suspend()}resume(){this.#u=!1,this.#e&&this.#e.state==="suspended"&&this.#e.resume()}async destroy(){this.flush(),this.#e&&(await this.#e.close(),this.#e=null)}#g(){this.#c=!1;let t=this.#l;this.#l=[],this.#a=0;for(let n of t)this.#m(n)}#m(t){if(t.length===0)return;let n=this.#d(),o=n.createBuffer(1,t.length,this.#A);o.getChannelData(0).set(t);let r=n.createBufferSource();r.buffer=o,r.connect(n.destination);let s=n.currentTime;if(this.#n===0?this.#n=s:this.#n<s&&(this.#n=s,this.#w>0&&(this.#c=!0)),r.start(this.#n),this.#n+=o.duration,this.#o.push(r),this.#f++,this.#r=!0,!this.#i){this.#i=!0;let i=this.#s.slice();this.#s=[];for(let l of i)l()}r.onended=()=>{let i=this.#o.indexOf(r);i!==-1&&(this.#o.splice(i,1),this.#f--,this.#S())}}#S(){if(this.#p&&this.#f<=0&&this.#l.length===0){this.#r=!1,this.#p=!1;let t=this.#t.slice();this.#t=[];for(let n of t)n()}}#E(t){let n=Math.floor(t.length/2),o=new Float32Array(n),r=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let s=0;s<n;s++){let i=r.getInt16(s*2,!0);o[s]=i/32768}return o}}});function hk(e){return e.replace(/\/+$/,"")}async function yk(e){try{let t=await e.json();return t.detail?`${t.error??`Runtype TTS ${e.status}`}: ${t.detail}`:t.error??`Runtype TTS request failed (${e.status})`}catch{return`Runtype TTS request failed (${e.status})`}}var Ip,Dw=Ve(()=>{"use strict";gm();Ip=class{constructor(t){this.id="runtype-tts";this.supportsPause=!0;this.#e=null;this.#n=null;this.#o=0;this.#t=t}#e;#n;#o;#t;#s(){return this.#n??=Promise.resolve(this.#t.createPlaybackEngine?this.#t.createPlaybackEngine():new Ra(24e3,{prebufferMs:this.#t.prebufferMs??200})).then(t=>this.#e=t)}speak(t,n){let o=++this.#o;this.#r(o,t,n)}async#r(t,n,o){try{let r=await this.#s();if(t!==this.#o)return;r.flush(),r.resume(),r.onStarted(()=>{t===this.#o&&o.onStart?.()}),r.onFinished(()=>{t===this.#o&&o.onEnd?.()});let s=`${hk(this.#t.host)}/v1/agents/${encodeURIComponent(this.#t.agentId)}/speak`,i=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.#t.clientToken}`},body:JSON.stringify({text:n.text,voice:n.voice??this.#t.voice,format:"pcm"})});if(t!==this.#o)return;if(!i.ok||!i.body)throw new Error(await yk(i));let l=i.body.getReader();for(;;){let{done:c,value:p}=await l.read();if(t!==this.#o){await l.cancel().catch(()=>{});return}if(c)break;p&&p.byteLength>0&&r.enqueue(p)}r.markStreamEnd()}catch(r){if(t!==this.#o)return;let s=r instanceof Error?r:new Error(String(r));this.#t.onError?.(s),o.onError?.(s)}}pause(){this.#e?.pause()}resume(){this.#e?.resume()}stop(){this.#o++,this.#e?.flush()}destroy(){this.#o++,this.#e?.destroy(),this.#e=null,this.#n=null}}});var Rp,Nw=Ve(()=>{"use strict";Rp=class{constructor(t,n,o={}){this.id="fallback";this.#n=t,this.#o=n,this.#t=o,this.#e=t}#e;#n;#o;#t;get supportsPause(){return this.#e.supportsPause}speak(t,n){this.#e=this.#n;let o=!1;this.#n.speak(t,{onStart:()=>{o=!0,n.onStart?.()},onEnd:()=>n.onEnd?.(),onError:r=>{if(o){n.onError?.(r);return}this.#t.onFallback?.(r),this.#e=this.#o,this.#o.speak(t,n)}})}pause(){this.#e.pause()}resume(){this.#e.resume()}stop(){this.#e.stop()}destroy(){this.#n.destroy?.(),this.#o.destroy?.()}}});var Fw={};ys(Fw,{FallbackSpeechEngine:()=>Rp,RuntypeSpeechEngine:()=>Ip});var $w=Ve(()=>{"use strict";Dw();Nw()});var DI={};ys(DI,{ASK_USER_QUESTION_CLIENT_TOOL:()=>bf,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>yf,ASK_USER_QUESTION_TOOL_NAME:()=>Hl,AgentWidgetClient:()=>wi,AgentWidgetSession:()=>Wa,AttachmentManager:()=>Ai,BrowserSpeechEngine:()=>ks,DEFAULT_COMPONENTS:()=>HS,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>AC,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>vi,DEFAULT_PALETTE:()=>PS,DEFAULT_SEMANTIC:()=>LS,DEFAULT_WIDGET_CONFIG:()=>EC,HistoryProviderError:()=>Vr,PRESETS:()=>Oh,PRESET_FULLSCREEN:()=>Wh,PRESET_MINIMAL:()=>Rh,PRESET_SHOP:()=>Ih,ReadAloudController:()=>Si,SUGGEST_REPLIES_CLIENT_TOOL:()=>_d,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>mf,SUGGEST_REPLIES_TOOL_NAME:()=>Oo,THEME_ZONES:()=>RS,VERSION:()=>Xn,WEBMCP_TOOL_PREFIX:()=>El,WebMcpBridge:()=>Ou,accessibilityPlugin:()=>Rx,animationsPlugin:()=>Wx,applyFeaturePreferences:()=>yh,applyThemeVariables:()=>Ei,attachHeaderToContainer:()=>Ti,brandPlugin:()=>Ox,buildComposer:()=>ki,buildDefaultHeader:()=>Fm,buildHeader:()=>jr,buildHeaderWithLayout:()=>Na,buildMinimalHeader:()=>$m,builtInClientToolsForDispatch:()=>fi,canonicalArtifactDisplayMode:()=>Yn,collectEnrichedPageContext:()=>Px,componentRegistry:()=>Fo,createActionManager:()=>mc,createAgentExperience:()=>vu,createAskUserQuestionBubble:()=>Wv,createBestAvailableVoiceProvider:()=>Hu,createBubbleWithLayout:()=>mA,createCSATFeedback:()=>hu,createComboButton:()=>Zp,createComponentMiddleware:()=>ax,createComponentStreamParser:()=>gu,createDefaultSanitizer:()=>sm,createDemoCarousel:()=>Jx,createDirectivePostprocessor:()=>gw,createDropdownMenu:()=>Pi,createFlexibleJsonStreamParser:()=>wv,createIconButton:()=>eo,createImagePart:()=>Yd,createJsonStreamParser:()=>Ld,createLabelButton:()=>Nm,createLocalStorageAdapter:()=>uu,createMarkdownProcessor:()=>Vl,createMarkdownProcessorFromConfig:()=>jl,createMessageActions:()=>Km,createNPSFeedback:()=>yu,createPlainTextParser:()=>Pd,createPlugin:()=>Dx,createRegexJsonParser:()=>kd,createRovingTablist:()=>iE,createSlashCommandsSource:()=>sE,createSplitButton:()=>aA,createStandardBubble:()=>Fa,createStaticMentionSource:()=>rE,createTextPart:()=>Ao,createTheme:()=>Gl,createThemeObserver:()=>Oa,createToggleGroup:()=>lc,createTypingIndicator:()=>Li,createVoiceProvider:()=>Xa,createWidgetHostLayout:()=>bc,createXmlParser:()=>Hd,default:()=>Ix,defaultActionHandlers:()=>Wi,defaultJsonActionParser:()=>fc,defaultMentionFilter:()=>_u,defaultParseRules:()=>Lh,detectColorScheme:()=>Xl,directivePostprocessor:()=>fw,ensureAskUserQuestionSheet:()=>Wd,escapeHtml:()=>Ur,extractComponentDirectiveFromMessage:()=>mu,fileToImagePart:()=>PC,formatEnrichedContext:()=>kx,generateAssistantMessageId:()=>Ps,generateCodeSnippet:()=>jx,generateMessageId:()=>Mw,generateStableSelector:()=>Hh,generateUserMessageId:()=>Ha,getActiveTheme:()=>No,getAgentWidgetHandles:()=>yx,getColorScheme:()=>xi,getDisplayText:()=>Gd,getHeaderLayout:()=>Um,getImageParts:()=>TC,getPreset:()=>Hx,hasComponentDirective:()=>hc,hasImages:()=>Pa,headerLayouts:()=>eu,highContrastPlugin:()=>Bx,initAgentWidget:()=>Mh,isAskUserQuestionMessage:()=>Ir,isComponentDirectiveType:()=>ix,isDockedMountMode:()=>Lt,isHistoryProviderError:()=>Hw,isSuggestRepliesMessage:()=>gi,isVoiceSupported:()=>Fh,isWebMcpToolName:()=>bs,isWelcomeVisible:()=>Ws,latestAgentSuggestions:()=>Bd,listRegisteredStreamAnimations:()=>tA,loadMarkdownParsers:()=>vd,markdownPostprocessor:()=>rm,mergeWithDefaults:()=>Ma,normalizeContent:()=>MC,normalizeMediaType:()=>vs,onMarkdownParsersReady:()=>ua,parseAskUserQuestionPayload:()=>Rr,parseSuggestRepliesPayload:()=>hf,parseWidgetPreferenceSlice:()=>hh,pickBestVoice:()=>Ia,pluginRegistry:()=>gc,reducedMotionPlugin:()=>_x,registerIcons:()=>gv,registerStreamAnimationPlugin:()=>ec,removeAskUserQuestionSheet:()=>Wr,renderComponentDirective:()=>fu,renderLoadingIndicatorWithFallback:()=>zm,renderLucideIcon:()=>ge,resolveArtifactDisplay:()=>lf,resolveArtifactDisplayMode:()=>or,resolveConfigPreferences:()=>uc,resolveDockConfig:()=>Zn,resolveSanitizer:()=>Lp,resolveTokens:()=>qp,resolveWelcomeConfig:()=>Ua,stripWebMcpPrefix:()=>af,themeToCssVariables:()=>zp,unregisterStreamAnimationPlugin:()=>eA,validateImageFile:()=>kC,validateTheme:()=>Mm});module.exports=$M(DI);var cv=require("marked"),dv=Bn(require("dompurify"),1);dn();var{setLoader:zI,load:UM,provide:VM,getSync:ef}=lt({fallbackImport:()=>Promise.resolve().then(()=>(iv(),sv))}),bd=new Set,av=()=>{let e=[...bd];bd.clear();for(let t of e)try{t()}catch{}};var vd=()=>{let e=ef();return e?Promise.resolve(e):UM().then(t=>(av(),t))},ua=e=>ef()?()=>{}:(bd.add(e),()=>{bd.delete(e)}),lv=e=>{VM(e),av()},nr=ef;lv({Marked:cv.Marked,DOMPurify:dv.default});var G=require("lucide"),pv={user:G.User,mail:G.Mail,phone:G.Phone,calendar:G.Calendar,clock:G.Clock,building:G.Building,"map-pin":G.MapPin,lock:G.Lock,key:G.Key,"credit-card":G.CreditCard,hash:G.Hash,globe:G.Globe,link:G.Link,"circle-check":G.CircleCheck,"circle-x":G.CircleX,"triangle-alert":G.TriangleAlert,info:G.Info,ban:G.Ban,shield:G.Shield,house:G.House,"pen-line":G.PenLine,save:G.Save,share:G.Share,funnel:G.Funnel,settings:G.Settings,"rotate-cw":G.RotateCw,"shopping-cart":G.ShoppingCart,"shopping-bag":G.ShoppingBag,package:G.Package,truck:G.Truck,tag:G.Tag,gift:G.Gift,receipt:G.Receipt,wallet:G.Wallet,store:G.Store,"dollar-sign":G.DollarSign,percent:G.Percent,play:G.Play,pause:G.Pause,"volume-x":G.VolumeX,camera:G.Camera,image:G.Image,film:G.Film,headphones:G.Headphones,"message-circle":G.MessageCircle,bell:G.Bell,heart:G.Heart,"eye-off":G.EyeOff,bookmark:G.Bookmark,"calendar-days":G.CalendarDays,timer:G.Timer,folder:G.Folder,"folder-open":G.FolderOpen,files:G.Files,"chart-column":G.ChartColumn,sparkles:G.Sparkles,zap:G.Zap,sun:G.Sun,moon:G.Moon,flag:G.Flag,lightbulb:G.Lightbulb,monitor:G.Monitor,smartphone:G.Smartphone};kt();fv(pv);vf();dn();var{setLoader:xR,load:TT,provide:PT,getSync:kT}=lt({fallbackImport:()=>Promise.resolve().then(()=>(vf(),Fd))});var mi=TT,Uv=PT,Vv=kT;Uv(Fd);Af();dn();var{setLoader:IR,load:UT,provide:VT}=lt({fallbackImport:()=>Promise.resolve().then(()=>(Af(),$d))});var Or=UT,eC=VT;eC($d);Kf();dn();var{setLoader:WW,load:fP,provide:mP,getSync:hP}=lt({fallbackImport:()=>Promise.resolve().then(()=>(Kf(),dp))});var pp=fP,FC=mP,Gf=hP;FC(dp);Xf();dn();var{setLoader:NW,load:xP,provide:EP,getSync:MP}=lt({fallbackImport:()=>Promise.resolve().then(()=>(Xf(),gp))});var Qf=xP,VC=EP,jC=MP;VC(gp);nm();dn();var{setLoader:nO,load:FP,provide:$P,getSync:UP}=lt({fallbackImport:()=>Promise.resolve().then(()=>(nm(),Cp))});var rw=FP,sw=$P,wp=UP;sw(Cp);var Pp=require("lucide");Lr();So();Ze();kt();Ze();var Sp=require("lucide");Lr();var VP=["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"],jP="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",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-default persona-border-none",zP=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Ap=(e,t)=>{let n=x("div",["persona-message-bubble",e,...VP].join(" "));return n.id=`bubble-${t}`,n.setAttribute("data-message-id",t),n},xp=e=>{let t=x("button",e.expandable?jP:qP);return t.type="button",e.expandable&&(t.setAttribute("aria-expanded",e.expanded?"true":"false"),t.setAttribute("data-expand-header","true")),t.setAttribute("data-bubble-type",e.bubbleType),t},om=(e,t,n)=>{e.innerHTML="";let o=Nt(t?Sp.ChevronUp:Sp.ChevronDown,16,n,2);o?e.appendChild(o):e.textContent=t?"Hide":"Show"},La=(e,t,n)=>{if(!n.expandable)return e.append(t),null;let o=x("div","persona-flex persona-items-center");om(o,n.expanded,n.iconColor);let r=x("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),e.append(t,r),o},Ep=e=>{let t=x("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(t.setAttribute("data-persona-collapsed-preview",e.previewKind),t.style.display="none",t.style.whiteSpace="pre-wrap",!e.expanded&&e.isActive&&e.activePreview&&e.previewText){let n=e.renderPreview?.();zP(t,n)||(t.textContent=e.previewText),t.style.display=""}return!e.expanded&&e.isActive&&e.activeMinHeight&&(e.bubble.style.minHeight=e.activeMinHeight),t},Mp=e=>{e.header.setAttribute("aria-expanded",e.expanded?"true":"false"),e.toggleIcon&&om(e.toggleIcon,e.expanded,e.iconColor),e.content.style.display=e.expanded?"":"none",e.collapsedPreview.style.display=e.expanded?"none":e.collapsedPreview.textContent||e.collapsedPreview.childNodes.length?"":"none"},Tp=(e,t,n)=>{let o=n.stateSet.has(e),r=t.querySelector('button[data-expand-header="true"]'),s=t.querySelector(".persona-border-t"),i=t.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&&om(c,o,n.iconColor),s.style.display=o?"":"none",i&&(i.style.display=o?"none":i.textContent||i.childNodes.length?"":"none")};function kp(e,t){let n=t==="tool"?"toolCallDisplay":"reasoningDisplay";return{...e,features:{...e?.features,[n]:{...t==="tool"?Br:Ci,...e?.future?.v5Defaults===!0?bi.features?.[n]:{},...e?.features?.[n]}}}}function Ts(e,t){let n=t==="tool"?"toolCallDisplay":"reasoningDisplay";return e?.features?.[n]?.variant??(e?.future?.v5Defaults?"row":"card")}function Ul(e){let t=Math.max(0,Math.floor((e??0)/1e3));return t<1?"a moment":t<60?`${t}s`:`${Math.floor(t/60)}m ${t%60}s`}function $r(e,t,n,o){if(Ts(n,o)!=="row")return e;e.className=`persona-message-bubble persona-${o}-bubble persona-activity-row`,e.dataset.activityKind=o,o==="tool"&&n.toolCall?.shadow===void 0&&(e.style.boxShadow="var(--persona-tool-bubble-shadow, none)");let r=e.querySelector(":scope > button");if(!r)return e;r.className="persona-activity-header";let s=o==="tool"?t.toolCall:t.reasoning,i=s?.status!=="complete",l=t.approval?.status??t.toolCall?.approvalStatus,c=l==="denied"?"denied":l==="pending"?"awaiting-approval":t.toolCall?.success===!1?"error":i?s?.status==="pending"?"pending":"running":"done";e.dataset.activityState=c;let p=x("span","persona-activity-icon");p.dataset.activityIcon=c;let d={pending:"circle",running:"loader-circle",done:"check",error:"x",denied:"x","awaiting-approval":"clock"},g=o==="reasoning"?n.features?.reasoningDisplay?.iconName:void 0,f=g?ge(g,16,"currentColor",2):c==="pending"?Nt(Pp.Circle,16,"currentColor",2):c==="awaiting-approval"?Nt(Pp.Clock,16,"currentColor",2):ge(d[c],16,"currentColor",2);f&&p.appendChild(f),r.querySelector(".persona-reasoning-header-icon")?.remove();let h=o==="tool"?"toolCallDisplay":"reasoningDisplay",y=n.features?.[h]?.iconVisibility??(n.future?.v5Defaults?"active":"always");if((y==="always"||y==="active"&&c!=="done")&&r.prepend(p),o==="tool"&&s){let L=x("span","persona-activity-duration");i&&s.startedAt&&L.setAttribute("data-tool-elapsed",String(s.startedAt));let I=(o==="tool"?t.toolCall?.duration:void 0)??s.durationMs??(s.completedAt!==void 0&&s.startedAt!==void 0?s.completedAt-s.startedAt:void 0);L.textContent=I===void 0?"":Ul(I),r.appendChild(L)}r.querySelector(":scope > div:not(.persona-ml-auto)")?.classList.add("persona-activity-label"),r.querySelector(".persona-ml-auto")?.classList.add("persona-activity-chevron");let A=e.querySelector(":scope > .persona-border-t");return A?.classList.add("persona-activity-body"),A&&(A.id=`activity-details-${t.id}`,r.setAttribute("aria-controls",A.id)),e}function iw(e){let t=new Set,n=new Set,o=new Set,r=new Map,s=i=>{clearTimeout(r.get(i)),r.delete(i)};return{observe(i,l,c,p={}){let d=l==="tool"?i.toolCall:i.reasoning;if(!(!d||n.has(i.id))&&(!t.has(i.id)&&d.status!=="complete"&&d.chunks?.some(Boolean)&&(t.add(i.id),p.autoExpand!==!1&&c.add(i.id)),t.has(i.id)&&d.status==="complete"&&!o.has(i.id))){if(o.add(i.id),p.autoCollapseDelay===!1)return;r.set(i.id,setTimeout(()=>{r.delete(i.id),c.delete(i.id),e(i.id,l)},p.autoCollapseDelay??1e3))}},manual(i){n.add(i),s(i)},prune(i){for(let l of new Set([...t,...n,...o]))i.has(l)||(s(l),t.delete(l),n.delete(l),o.delete(l))},clear(){for(let i of r.keys())s(i);t.clear(),n.clear(),o.clear()}}}function aw(e,t,n,o){let r=x("div","");r.id=`bubble-${e.id}`,r.dataset.messageId=e.id;let s=x("button","");s.type="button",s.dataset.expandHeader="true",s.dataset.bubbleType="tool",s.setAttribute("aria-expanded",String(n));let i=x("div","");typeof o=="string"?i.textContent=o:i.appendChild(o),La(s,i,{expandable:!0,expanded:n,iconColor:t.toolCall?.toggleTextColor||t.toolCall?.headerTextColor||"currentColor",metaGap:!0});let l=x("div","persona-border-t");return l.id=`activity-details-${e.id}`,l.style.display=n?"":"none",s.setAttribute("aria-controls",l.id),r.append(s,l),$r(r,e,{...t,features:{...t.features,toolCallDisplay:{...t.features?.toolCallDisplay,variant:"row"}}},"tool"),r.dataset.personaToolGroup="true",t.features?.toolCallDisplay?.loadingAnimation==="shimmer"&&(r.dataset.activityGroupShimmer="true"),{bubble:r,body:l}}Pf();function lw(e,t){let n=e.voiceRecognition,o=t.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)||e.agentId!==t.agentId||e.clientToken!==t.clientToken||e.apiUrl!==t.apiUrl}function In(e){return e?.type==="runtype"||e?.type==="custom"}var KP=()=>typeof window<"u"&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window);function cw(e){try{if(e?.type==="custom"&&e.custom){let t=e.custom,n=typeof t=="function"?t():t;return!!n&&typeof n.startListening=="function"}return e?.type==="runtype"&&e.runtype?!0:KP()}catch{return!1}}var GP=e=>{if(!e)return;let t={},n=e;if(n.heading){let o=n.heading;t.heading=(r,s,i)=>o({type:"heading",raw:i,depth:s,text:r,tokens:[]})}if(n.code){let o=n.code;t.code=(r,s,i)=>o({type:"code",raw:"",text:r,lang:s,escaped:i})}if(n.blockquote){let o=n.blockquote;t.blockquote=r=>o({type:"blockquote",raw:"",text:r,tokens:[]})}if(n.table){let o=n.table;t.table=(r,s)=>o({type:"table",raw:"",header:[],rows:[],align:[],headerHtml:r,bodyHtml:s})}if(n.link){let o=n.link;t.link=(r,s,i)=>o({type:"link",raw:"",href:r,title:s??null,text:i,tokens:[]})}if(n.image){let o=n.image;t.image=(r,s,i)=>o({type:"image",raw:"",href:r,title:s??null,text:i})}if(n.list){let o=n.list;t.list=(r,s,i)=>o({type:"list",raw:"",ordered:s,start:i,loose:!1,items:[],itemsHtml:r})}if(n.listitem){let o=n.listitem;t.listitem=(r,s,i)=>o({type:"list_item",raw:"",task:s,checked:i,loose:!1,text:r,tokens:[]})}if(n.paragraph){let o=n.paragraph;t.paragraph=r=>o({type:"paragraph",raw:"",text:r,tokens:[]})}if(n.codespan){let o=n.codespan;t.codespan=r=>o({type:"codespan",raw:"",text:r})}if(n.strong){let o=n.strong;t.strong=r=>o({type:"strong",raw:"",text:r,tokens:[]})}if(n.em){let o=n.em;t.em=r=>o({type:"em",raw:"",text:r,tokens:[]})}if(n.del){let o=n.del;t.del=r=>o({type:"del",raw:"",text:r,tokens:[]})}if(n.html){let o=n.html;t.html=r=>o({type:"html",raw:r,text:r})}if(n.text){let o=n.text;t.text=r=>o({type:"text",raw:r,text:r})}if(n.checkbox){let o=n.checkbox;t.checkbox=r=>o({checked:r})}return n.hr&&(t.hr=n.hr),n.br&&(t.br=n.br),t},Vl=e=>{let t=null;return n=>{let o=nr();if(!o)return Ur(n);if(!t){let{Marked:r}=o,s=e?.markedOptions;t=new r({gfm:s?.gfm??!0,breaks:s?.breaks??!0,pedantic:s?.pedantic,silent:s?.silent});let i=GP(e?.renderer);i&&t.use({renderer:i})}return t.parse(n)}},jl=e=>e?Vl({markedOptions:e.options,renderer:e.renderer}):Vl(),YP=Vl(),rm=e=>YP(e),Ur=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),pw=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),dw=e=>`%%FORM_PLACEHOLDER_${e}%%`,uw=(e,t)=>{let n=e;return n=n.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(o,r)=>{try{let s=JSON.parse(r.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let i=dw(t.length);return t.push({token:i,type:String(s.type)}),i}}catch{return o}return o}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(o,r)=>{let s=dw(t.length);return t.push({token:s,type:r}),s}),n},gw=e=>{let t=jl(e);return n=>{let o=[],r=uw(n,o),s=t(r);return o.forEach(({token:i,type:l})=>{let c=new RegExp(i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${pw(l)}"></div>`;s=s.replace(c,d)}),s}},fw=e=>{let t=[],n=uw(e,t),o=rm(n);return t.forEach(({token:r,type:s})=>{let i=new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),c=`<div class="persona-form-directive" data-tv-form="${pw(s)}"></div>`;o=o.replace(i,c)}),o};var XP={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"]},QP=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,sm=()=>{let e=null;return t=>{let n=nr();if(!n)return Ur(t);if(!e){let{DOMPurify:o}=n;e=o(typeof window<"u"?window:void 0),e.addHook("uponSanitizeAttribute",(r,s)=>{if(s.attrName==="src"||s.attrName==="href"){let i=s.attrValue;i.toLowerCase().startsWith("data:")&&!QP.test(i)&&(s.attrValue="",s.keepAttr=!1)}})}return e.sanitize(t,XP)}},Lp=e=>e===!1?null:typeof e=="function"?e:sm();var mw=/^\s*\|?[\s:|-]*-[\s:|-]*$/,hw=e=>e.includes("|"),yw=e=>{let t=e.trim();return t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1)),t.split("|").map(n=>n.trim())},JP=e=>`| ${e.join(" | ")} |`,ZP=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,ek=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),bw=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
|
|
14
|
+
`),n=!1;for(let o=0;o<t.length-1;o++){let r=t[o],s=t[o+1];if(!hw(r)||mw.test(r)||!mw.test(s))continue;let i=yw(r).length;if(i<1)continue;let l=ZP(i);t[o+1]!==l&&(t[o+1]=l,n=!0);let c=o+2;for(;c<t.length;c++){let p=t[c];if(p.trim()===""||!hw(p))break;let d=JP(ek(yw(p),i));t[c]!==d&&(t[c]=d,n=!0)}o=c-1}return n?t.join(`
|
|
15
|
+
`):e};var vw="var(--persona-md-table-scroll-fade, 24px)",Cw=new WeakSet;function Sw(e){e.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 ww(e){let t=e.scrollWidth-e.clientWidth;if(t<=1){e.removeAttribute("data-persona-scroll-x");return}e.setAttribute("data-persona-scroll-x","");let o=getComputedStyle(e).direction==="rtl"?t+e.scrollLeft:e.scrollLeft,r=t-o;e.style.setProperty("--persona-fade-l",o<=1?"0px":vw),e.style.setProperty("--persona-fade-r",r<=1?"0px":vw)}function im(e){Cw.has(e)||(Cw.add(e),e.addEventListener("scroll",t=>{let n=t.target;n?.classList?.contains("persona-table-scroll")&&ww(n)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(ww)}pi();dn();var{setLoader:AO,load:tk}=lt({fallbackImport:()=>import("@runtypelabs/persona/webmcp-runtime")});var Aw=tk;var nk="agent_",ok="flow_";function xw(e){return e.startsWith(nk)?{kind:"agentId",agentId:e}:e.startsWith(ok)?{kind:"flowId",flowId:e}:null}function Ew(e,t){let n=e.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let i=n.slice(0,o),l=n.slice(o+1);if(i==="runtype"){let p=xw(l);if(p)return p;throw new Error(`[Persona] target "runtype:${l}" is not a valid Runtype agent_/flow_ id.`)}let c=t?.[i];if(!c)throw new Error(`[Persona] No target provider registered for "${i}". Add a \`targetProviders.${i}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:c(l).payload}}let r=xw(n);if(r)return r;let s=t?.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 Mw(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Ha(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Ps(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}function Tw(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`turn_${e}_${t}`}Dd();var rk=e=>e.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase().replace(/_+/g,"_").replace(/^_|_$/g,""),sk=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ik=e=>{if(e.variant!=="tool")return null;let t=e.agentMetadata?.clientToolAnswer;if(!t||!t.toolCallId||t.result===void 0)return null;let n=rk(t.toolName);return n?{call:{toolCallId:t.toolCallId,toolName:n,args:sk(t.args)?t.args:{}},result:{toolCallId:t.toolCallId,toolName:n,result:t.result}}:null},am=(e,t)=>{let n=[],o=[],r=[],s="",i,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 e){let p=ik(c);if(p){let g=c.agentMetadata?.clientToolAnswer?.batch;o.length>0&&(g===void 0||g!==i)&&l(),o.length===0&&(s=c.createdAt,i=g),o.some(f=>f.toolCallId===p.call.toolCallId)||(o.push(p.call),r.push(p.result));continue}let d=t(c);d&&(l(),n.push(d))}return l(),n};Cs();Sa();vp();_o();var ak="https://api.runtype.com/v1/dispatch",on=class extends Error{constructor(t,n,o){super(n),this.name="HistoryClientError",this.code=t,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}},Pw=e=>"reason"in e?e.reason:void 0,lk="The identity proof was rejected",lm=(e,t)=>e instanceof on&&e.code===t,cm=e=>e.voiceCaption?!1:!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0),kw=e=>e.slice().sort((t,n)=>new Date(t.createdAt).getTime()-new Date(n.createdAt).getTime()),Lw=e=>({role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,createdAt:e.createdAt});function ck(e){switch(e){case"json":return Ld;case"regex-json":return kd;case"xml":return Hd;default:return Pd}}var wi=class{constructor(t={},n={}){this.config=t;this.historyInternals=n;this.#u=null;this.clientSession=null;this.#c=null;this.#l=!1;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.#a=null;this.#M=!1;this.#h=!1;this.#A=!1;this.#w=null;this.#x=new Set;this.#d=new Set;this.webMcpBridge=null;this.#g=null;this.#U=null;this.#be=null;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.#e=t.apiUrl??ak,this.#n={"Content-Type":"application/json","X-Persona-Version":Xn,...t.headers},this.debug=!!t.debug,this.#o=t.streamParser??ck(t.parserType),this.#t=t.contextProviders??[],this.#s=t.requestMiddleware,this.#r=t.customFetch,this.#p=t.parseSSEEvent,this.#f=t.getHeaders,t.webmcp?.enabled===!0&&(this.#g=this.#S(t.webmcp))}#e;#n;#o;#t;#s;#r;#p;#f;#i;#u;#c;#l;#a;#M;#h;#A;#w;#x;#d;#g;#m;#S(t){return Aw().then(n=>{let o=new n.WebMcpBridge(t,{recordToolDisplayTitles:Sd,getToolDisplayTitle:ma,loadPolyfill:Ad});return this.#m!==void 0&&o.setConfirmHandler(this.#m),this.webMcpBridge=o,o}).catch(n=>(this.#g=null,console.warn("[Persona] Failed to load the WebMCP runtime chunk",n),null))}#E(){return this.webMcpBridge?Promise.resolve(this.webMcpBridge):this.config.webmcp?.enabled!==!0?Promise.resolve(null):(this.#g||(this.#g=this.#S(this.config.webmcp)),this.#g)}updateConfig(t){this.config=t}setHistoryInternals(t){this.historyInternals=t}setSSEEventCallback(t){this.#i=t}setWebMcpConfirmHandler(t){this.#m=t,this.webMcpBridge?.setConfirmHandler(t)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(t,n,o){return this.config.webmcp?.enabled!==!0?null:this.#E().then(r=>r?r.executeToolCall(t,n,o):{isError:!0,content:[{type:"text",text:"WebMCP runtime failed to load."}]})}getSSEEventCallback(){return this.#i}isClientTokenMode(){return!!this.config.clientToken}#b(){let{agentId:t,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:t,flowId:n};let s=Ew(o,r);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.#b().agentId)}#v(){return this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||Nd}#H(t){return`${this.#v()}/v1/client/${t}`}getClientSession(){return this.clientSession}async reconnectClientTokenStream(t){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 on("visitor_token_missing","Durable recovery is not enabled for this client session");let i=`${this.#v()}/v1/client/conversations/${encodeURIComponent(r)}/executions/${encodeURIComponent(t.executionId)}/events`,l=new URLSearchParams({sessionId:n.sessionId,after:t.after}),c=await fetch(`${i}?${l}`,{method:"GET",headers:{"X-Persona-Version":Xn,"X-Visitor-Token":s},signal:t.signal});if(c.status===401&&!o){o=!0;let p=await Or();n=await p.recoverFromUnauthorized(this.#N(),await p.readErrorCode(this.#N(),c),null,!0);continue}if(!c.ok)throw await(await Or()).historyErrorFor(this.#N(),c,!0);return c}}async warmSession(){let t=this.clientSession;return!this.isClientTokenMode()||this.#c||t&&new Date<t.expiresAt||this.#l===t?null:(this.#l=t,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.#c)return this.#c;let t=this.#c=this.#X().then(n=>this.#c!==t?this.initSession():(this.clientSession=n,this.#l=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(n),n)).finally(()=>{this.#c===t&&(this.#c=null)});return t}#T(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()&&!this.#M}async readVisitorToken(){let t=this.historyInternals.visitorStore;return t?(await t.ready,await t.get()??null):null}#C(){if(!this.#M){this.#$({state:"unavailable",reason:"history_disabled"}),this.#M=!0,!this.#h&&typeof console<"u"&&(this.#h=!0,console.warn("[Persona] Visitor history is disabled for this surface; continuing without it.")),this.historyInternals.onHistoryAvailabilityChanged?.(!1);for(let t of[...this.#d])t(!1)}}getHistoryIdentityStatus(){return this.#w??this.#R()}subscribeHistoryIdentityStatus(t){return this.#x.add(t),()=>{this.#x.delete(t)}}subscribeHistoryAvailability(t){return this.#d.add(t),this.#M&&t(!1),()=>{this.#d.delete(t)}}#R(){return this.isClientTokenMode()?this.config.features?.history?.enabled!==!0||this.#M?{state:"unavailable",reason:"history_disabled"}:this.#Y():{state:"unavailable",reason:"ineligible_mode"}}#Y(){let t=this.#w;return t?.state==="browser_only"?t:this.#z()}#z(){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"}}#$(t){let n=this.getHistoryIdentityStatus(),o=n.state===t.state&&Pw(n)===Pw(t);if(this.#w=t,!o){this.historyInternals.onHistoryIdentityStatusChanged?.(t);for(let r of[...this.#x])r(t)}}async#P(t){let n=this.#T()&&!t.omitVisitorFields,o=!t.omitVisitorFields,r=null;(n||o)&&(await this.historyInternals.historyBootstrapReady,r=await this.readVisitorToken());let s=this.#b(),i=s.agentId??s.flowId,l=n||t.durableResume?t.conversationId:void 0,c={token:this.config.clientToken,...i&&{flowId:i},...n&&{visitorHistory:!0},...o&&{durableRecovery:!0},...(n||o)&&r?{visitorToken:r}:{},...n&&t.identityProof?{identityProof:t.identityProof}:{},...l?{conversationId:l}:t.storedSessionId?{sessionId:t.storedSessionId}:{}};t.signal?.throwIfAborted();let p=await fetch(this.#H("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Xn},body:JSON.stringify(c),signal:t.signal});if(!p.ok){let g=await p.json().catch(()=>({error:"Session initialization failed"}));if(n&&p.status===403&&g.error==="visitor_history_disabled"){if(this.#C(),l)throw new on("history_disabled","Visitor history is disabled for this surface");return this.#P({...t,omitVisitorFields:!0})}throw p.status===403&&g.error==="durable_recovery_disabled"?new on("history_disabled","Durable recovery is disabled for this surface"):(n||t.durableResume)&&p.status===401&&g.error==="visitor_required"?new on("visitor_required","Visitor credential no longer resolves"):l&&p.status===404?new on("not_found","Conversation not found"):p.status===401?new Error(`Invalid client token: ${g.hint||g.error}`):p.status===403?new Error(`Origin not allowed: ${g.hint||g.error}`):new Error(g.error||"Failed to initialize session")}let d=await p.json();return d.visitor?.token&&await this.historyInternals.visitorStore?.set(d.visitor.token),{sessionId:d.sessionId,expiresAt:new Date(d.expiresAt),flow:d.flow,...d.conversationId?{conversationId:d.conversationId}:{},...d.targetId?{targetId:d.targetId}:{},...d.conversationRevision?{conversationRevision:d.conversationRevision}:{},...d.durableRecovery?{durableRecovery:d.durableRecovery}:{},...d.visitor?{visitor:d.visitor}:{},config:{welcomeMessage:d.config.welcomeMessage,placeholder:d.config.placeholder,theme:d.config.theme}}}async#X(){await this.historyInternals.historyBootstrapReady;let t=this.config.getStoredConversationId?.()||null,n=this.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.#T()&&!n)return this.#W(t,!1);let o=await this.readVisitorToken();if(t&&o)try{let r=await this.#P({conversationId:t,durableResume:n});return n&&r.durableRecovery?.enabled!==!0&&this.historyInternals.setStoredResumableHandle?.(null),this.#O(r,t,!1)}catch(r){if(!lm(r,"not_found")&&!lm(r,"visitor_required")&&!lm(r,"history_disabled"))throw r;return n&&this.historyInternals.setStoredResumableHandle?.(null),this.#W(t,!0)}return this.#W(t,!1)}async#W(t,n){let o=this.historyInternals.visitorStore;return o&&!await this.readVisitorToken()?o.withFirstInitLock(()=>this.#D(t,n)):this.#D(t,n)}async#D(t,n){let o=this.config.getStoredSessionId?.()||null,r=await this.#P({storedSessionId:o}),s=await this.#ne(r);return this.#O(s,t,n)}async#Q(t){let n=this.config.getStoredSessionId?.()||null,o=this.config.getStoredConversationId?.()||null,r=await this.#P({storedSessionId:n,identityProof:t}),s=this.#O(r,o,!1);return this.clientSession=s,this.#c=null,this.#l=!1,this.resetClientToolsFingerprint(),s}async#ne(t){if(!t.visitor?.token||this.#A||!this.#T()&&t.durableRecovery?.enabled!==!0)return t;this.#A=!0;try{return await this.#P({storedSessionId:t.sessionId})}catch{return t}finally{this.#A=!1}}#O(t,n,o){let r=t.conversationId;return r&&n&&(o||r!==n)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:n,conversationId:r}),this.config.setStoredSessionId?.(t.sessionId),r&&(this.config.setStoredConversationId?.(r),this.historyInternals.setStoredConversationRevision?.(t.conversationRevision??null)),t}#K(t){let n=!1;return{session:t,commit:()=>{n||(n=!0,this.clientSession=t,this.#l=!1,this.resetClientToolsFingerprint())},discard:()=>{n=!0}}}async prepareConversationSession(t,n){if(!this.isClientTokenMode())throw new Error("prepareConversationSession() only available in client token mode");if(!this.#T())throw new on("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 on("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let s=await this.#P({conversationId:t,identityProof:o});return this.#K(s)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw new Error("prepareNewConversationSession() only available in client token mode");await this.historyInternals.historyBootstrapReady;let t=await this.#P({});return this.#K(t)}handleExternalCredentialChange(){this.clearClientSession(),this.#T()&&this.#$(this.#z())}clearClientSession(){this.clientSession=null,this.#c=null,this.#l=!1,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.#a=null}#G(){return`${this.#v()}/v1/client/feedback`}async sendFeedback(t){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(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.#G(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Xn},body:JSON.stringify(r)});if(!s.ok){let i=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,this.#l=!1,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:n})}async#oe(t){t?.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 i=Promise.resolve().then(()=>o());r=t?await Promise.race([i,new Promise((l,c)=>{s=()=>c(t.reason),t.addEventListener("abort",s,{once:!0}),t.aborted&&s()})]):await i}catch{throw t?.throwIfAborted(),new Error("The identity proof provider failed.")}finally{s&&t?.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}}#U;#_(){let t=this;return this.#U??={get config(){return t.config},headers:this.#n,getHeaders:this.#f,debug:this.debug,clientApiBase:()=>t.#v(),getClientApiUrl:n=>t.#H(n),getWebMcpBridge:()=>t.#E(),sendWithClientToolsDiff:(n,o,r,s)=>t.#se(n,o,r,s),initSession:()=>t.initSession(),readVisitorToken:()=>t.readVisitorToken(),isClientTokenMode:()=>t.isClientTokenMode()}}#be;#N(){let t=this;return this.#be??={HistoryClientError:on,get config(){return t.config},get historyInternals(){return t.historyInternals},get clientSession(){return t.clientSession},clientApiBase:()=>t.#v(),setHistoryIdentityStatus:n=>t.#$(n),browserOnlyStatus:()=>t.#Y(),derivedBrowserOnly:()=>t.#z(),reinitWithProof:n=>t.#Q(n),isHistoryCapable:()=>t.#T(),clearClientSession:()=>t.clearClientSession(),initSession:()=>t.initSession(),readVisitorToken:()=>t.readVisitorToken(),isClientTokenMode:()=>t.isClientTokenMode()}}async listConversations(t){return(await Or()).listConversations(this.#N(),t)}async getConversation(t,n){return(await Or()).getConversation(this.#N(),t,n)}async finalizeDisplayProjections(t,n){return(await Or()).finalizeDisplayProjections(this.#N(),t,n)}async deleteConversation(t,n){return(await Or()).deleteConversation(this.#N(),t,n)}async deleteAllConversations(t){return(await Or()).deleteAllConversations(this.#N(),t)}async resetVisitor(){return(await Or()).resetVisitor(this.#N())}async dispatch(t,n){return t.signal?.throwIfAborted(),mi().catch(()=>{}),this.isClientTokenMode()?this.#de(t,n):this.isAgentMode()?this.#pe(t,n):this.#re(t,n)}async#de(t,n){let o=Tw();this.#u=o;let r=()=>this.#u===o,s=i=>{r()&&n(i)};n({type:"status",status:"connecting"});try{let i=()=>{if(t.signal?.throwIfAborted(),!r())throw new DOMException("Turn superseded","AbortError")},l=this.clientSession??await this.initSession();i();let c=async()=>{i();let A=l,L=A.durableRecovery?.enabled===!0;if(L&&(!A.conversationId||!await this.readVisitorToken()))throw new Error("Renewing this conversation requires its visitor credential.");i();let I=await this.#P({...L||this.#T()?{conversationId:A.conversationId,durableResume:L}:{storedSessionId:A.sessionId},signal:t.signal});if(i(),A.conversationId&&I.conversationId!==A.conversationId||L&&I.durableRecovery?.enabled!==!0)throw new Error("Session renewal did not preserve this conversation.");l=this.#O(I,A.conversationId??null,!1),this.clientSession=l,this.#l=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(l)};Date.now()>=l.expiresAt.getTime()-6e4&&await c();let p=await this.#j(t.messages),d=p.metadata?Object.fromEntries(Object.entries(p.metadata).filter(([A])=>A!=="sessionId"&&A!=="session_id")):void 0,g=this.#T(),f={sessionId:l.sessionId,messages:t.messages.filter(cm).map(A=>{let L=g?Fl(A):void 0;return{id:A.id,role:A.role,content:A.contentParts??A.llmContent??A.rawContent??A.content,...L!==void 0&&{displayContent:L}}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...d&&Object.keys(d).length>0&&{metadata:d},...p.inputs&&Object.keys(p.inputs).length>0&&{inputs:p.inputs},...p.context&&{context:p.context},turnId:o,...t.interrupt&&{submitMode:"interrupt"}},h=async()=>{i();let A=l.durableRecovery?.enabled===!0?await this.readVisitorToken():null;return i(),this.#se(l.sessionId,p.clientTools,async L=>{i();let I=await this.#oe(t.signal);i();let H={...f,sessionId:l.sessionId,...L,...I&&{identityProof:I}};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",{...H,...I&&{identityProof:{provider:I.provider,token:"[REDACTED]"}}}),fetch(this.#H("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Xn,...A?{"X-Visitor-Token":A}:{}},body:JSON.stringify(H),signal:t.signal})})},y=await h();if(i(),y.response.status===401){let A=await y.response.clone().json().catch(()=>null);i(),A?.error==="Session not found or expired"&&(await c(),y=await h(),i())}let{response:v,commit:C}=y;if(!v.ok){let A=await v.json().catch(()=>({error:"Chat request failed"}));if(v.status===401&&A.error==="invalid_identity_proof"){let I=new on("invalid_identity_proof",lk);throw s({type:"error",error:I}),I}if(v.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let I=new Error("Session expired. Please refresh to continue.");throw s({type:"error",error:I}),I}if(v.status===429){let I=new Error(A.hint||"Message limit reached for this session.");throw s({type:"error",error:I}),I}if(v.status===410&&A.error==="conversation_deleted"){let I=new on("conversation_deleted","This conversation was deleted");throw s({type:"error",error:I}),I}let L=new Error(A.error||"Failed to send message");throw s({type:"error",error:L}),L}if(!v.body){let A=new Error("No response body received");throw s({type:"error",error:A}),A}C(),s({type:"status",status:"connected"});try{await this.#J(v.body,s,t.assistantMessageId)}finally{s({type:"status",status:"idle"})}}catch(i){let l=i instanceof Error?i:new Error(String(i));throw!(l instanceof on)&&!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&s({type:"error",error:l}),l}}async#re(t,n){n({type:"status",status:"connecting"});let o=await this.#j(t.messages,t.composerOptions);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.#n};if(this.#f)try{let i=await this.#f();r={...r,...i}}catch(i){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.#r)try{s=await this.#r(this.#e,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(i){let l=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:l}),l}else s=await fetch(this.#e,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let i=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.#J(s.body,n)}finally{n({type:"status",status:"idle"})}}async#pe(t,n){n({type:"status",status:"connecting"});let o=await this.#L(t.messages,t.composerOptions);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.#n};if(this.#f)try{let i=await this.#f();r={...r,...i}}catch(i){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.#r)try{s=await this.#r(this.#e,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(i){let l=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:l}),l}else s=await fetch(this.#e,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let i=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.#J(s.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o,r){n({type:"status",status:"connected"});try{await this.#J(t,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){return(await mi()).resolveApproval(this.#_(),t,n)}async#se(t,n,o,r){let s=!!(n&&n.length>0),i=s?yv(n):void 0,l=this.clientToolsFingerprintSessionId===t,c=s&&l&&this.lastSentClientToolsFingerprint===i,p=!s&&r?.emptyMeansReplace===!0&&this.#a===t,d=!1,g;for(let f=0;;f++){if(g=await o({...s&&(d||!c)&&n?{clientTools:n}:{},...p?{clientTools:[]}:{},...i?{clientToolsFingerprint:i}:{}}),g.status===409&&f===0&&s&&(await g.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){d=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:g,commit:()=>{this.lastSentClientToolsFingerprint=i??null,this.clientToolsFingerprintSessionId=t,s?this.#a=t:p&&(this.#a=null)}}}async resumeFlow(t,n,o){return(await mi()).resumeFlow(this.#_(),t,n,o)}#ie(t){for(let n=t.length-1;n>=0;n--){let o=t[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async#V(t){let n={};this.#t.length&&await Promise.all(this.#t.map(async r=>{try{let s=await r({messages:t,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.#ie(t);return o&&Object.assign(n,o),Object.keys(n).length?n:null}#B(t){if(!t)return;let n={};return t.selectedModelId&&(n.selectedModelId=t.selectedModelId),t.activeModeIds?.length&&(n.activeModeIds=[...t.activeModeIds]),Object.keys(n).length>0?n:void 0}#I(t,n){let o=n?.selectedModelId;return!o||!("model"in t)?t:this.config.composer?.models?.some(s=>s.id===o)?{...t,model:o}:t}async#L(t,n){let o=this.#b().agentId;if(!this.config.agent&&!o)throw new Error("Agent configuration required for agent mode");let r=am(kw(t),p=>cm(p)&&(p.role==="user"||p.role==="assistant"||p.role==="system")&&(!p.variant||p.variant==="assistant")?Lw(p):null),s=this.#B(n),i={agent:this.#I(this.config.agent??{agentId:o},s),messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};s&&(i.composerOptions=s);let l=[...fi(this.config),...await(await this.#E())?.snapshotForDispatch()??[]];l.length>0&&(i.clientTools=l);let c=await this.#V(t);return c&&(i.context=c),i}async#j(t,n){let o=am(kw(t),p=>cm(p)?Lw(p):null),r=this.#b(),s={messages:o,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[p,d]of Object.entries(r.targetPayload))p!=="messages"&&(s[p]=d);let i=[...fi(this.config),...await(await this.#E())?.snapshotForDispatch()??[]];i.length>0&&(s.clientTools=i);let l=await this.#V(t);l&&(s.context=l);let c=this.#B(n);if(c&&(s.composerOptions=c),this.#s)try{let p=await this.#s({payload:{...s},config:this.config});if(p&&typeof p=="object"){let d=p;return s.clientTools!==void 0&&!("clientTools"in d)&&(d.clientTools=s.clientTools),d}}catch(p){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",p)}return s}async#J(t,n,o,r){let{streamResponse:s}=Vv()??await mi();return s({config:()=>this.config,createStreamParser:this.#o,parseSSEEvent:this.#p,onSSEEvent:(i,l)=>this.#i?.(i,l)},t,n,o,r)}};var Vr=class extends Error{constructor(t,n,o){super(n),this.name="HistoryProviderError",this.code=t,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}};function Hw(e){return e instanceof Vr}pi();Ca();Nr();ha();Nr();function dk(e){let t=0;for(let n of e.split(`
|
|
16
|
+
`)){let o=/^ {0,3}(`+)/.exec(n);o&&o[1].length>t&&(t=o[1].length)}return t}function Iw(e,t){let n="`".repeat(Math.max(3,dk(t)+1));return`${n}${e}
|
|
17
17
|
${t}
|
|
18
|
-
${n}`}var
|
|
18
|
+
${n}`}var pk=e=>e.sourceLabel?`quoted-text source=${e.sourceLabel}`:"quoted-text";function uk(e){let t=e?.text?.trim()??"";return t?Iw(pk(e),t):""}function Rw(e){let t=uk(e.quote);return t?e.contentParts&&e.contentParts.length>0?{contentParts:[Ao(t),...e.contentParts]}:{llmContent:[t,e.text].filter(Boolean).join(`
|
|
19
19
|
|
|
20
|
-
`)}:{}}function
|
|
20
|
+
`)}:{}}function Hp(e,t=140){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function Ww(e,t){let n=e.findIndex(r=>r.id===t);if(n===-1||e[n].role!=="user")return null;let o=n+1;for(;o<e.length&&e[o].role!=="user";)o+=1;return{start:n,end:o}}function dm(e,t){let n=e.findIndex(o=>o.id===t);if(n<=0)return null;for(let o=n-1;o>=0;o-=1)if(e[o].role==="user")return e[o].id;return null}function Ow(e){for(let t=e.length-1;t>=0;t-=1){let n=e[t];if(n.role==="user"||n.streaming)return null;if(!(n.role!=="assistant"||n.variant))return dm(e,n.id)?n.id:null}return null}function pm(e){return e.role!=="user"||e.variant||e.streaming||e.contentParts?.length||e.contextMentions?.length||e.contentSegments?.length||e.mentionContext&&Object.keys(e.mentionContext).length>0||e.rawContent!==void 0||e.llmContent!==void 0&&e.llmContent!==e.content||e.quote?!1:typeof e.content=="string"&&e.content.length>0}vp();function Ia(e){let t=["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 t){let o=e.find(r=>r.name===n);if(o)return o}return e.find(n=>n.lang.startsWith("en"))??e[0]}var ks=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(t,n){if(!e.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(t.text),s=o.getVoices();if(t.voice){let i=s.find(l=>l.name===t.voice);i&&(r.voice=i)}else s.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(s):Ia(s));t.rate!==void 0&&(r.rate=t.rate),t.pitch!==void 0&&(r.pitch=t.pitch),r.onend=()=>n.onEnd?.(),r.onerror=i=>{let l=i.error;l==="canceled"||l==="interrupted"?n.onEnd?.():n.onError?.(new Error(l||"Speech synthesis failed"))},setTimeout(()=>{o.speak(r),n.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var Si=class{#e=null;#n=null;#o="idle";#t=new Set;#s=0;#r;constructor(t){this.#r=t}get supportsPause(){return this.#e?.supportsPause??!0}stateFor(t){return this.#n===t?this.#o:"idle"}activeMessageId(){return this.#n}onChange(t){return this.#t.add(t),()=>this.#t.delete(t)}toggle(t,n){if(this.#n===t){if(this.#o==="playing"){this.#e?.supportsPause?(this.#e.pause(),this.#p(t,"paused")):this.stop();return}if(this.#o==="paused"){this.#e?.resume(),this.#p(t,"playing");return}if(this.#o==="loading"){this.stop();return}}this.play(t,n)}async play(t,n){let o=++this.#s;this.#e?.stop(),this.#p(t,"loading");try{if(!this.#e){let r=await this.#r();if(o!==this.#s)return;if(!r){this.#p(null,"idle");return}this.#e=r}this.#e.speak(n,{onStart:()=>{o===this.#s&&this.#p(t,"playing")},onEnd:()=>{o===this.#s&&this.#p(null,"idle")},onError:()=>{o===this.#s&&this.#p(null,"idle")}})}catch{o===this.#s&&this.#p(null,"idle")}}stop(){this.#s++,this.#e?.stop(),this.#p(null,"idle")}destroy(){this.stop(),this.#e?.destroy?.(),this.#e=null,this.#t.clear()}#p(t,n){this.#n=n==="idle"?null:t,this.#o=n;for(let o of this.#t)o(this.#n,this.#o)}};var ql=class{#e;#n=!1;start(t){this.#e=t,this.#n=!1}cancel(){this.#n=!0}accepts(t){return!this.#n&&(!t||!this.#e||t===this.#e)}};dn();var{setLoader:QO,load:gk,getSync:fk}=lt({fallbackImport:()=>import("@runtypelabs/persona/voice-runtime")});var zl=gk,_w=fk;function um(e){if(!e)return"";let t=mk(e);return Bw(t!==null?t:e)}function mk(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(t=n[1].trim()),!t.startsWith("{"))return null;try{let o=JSON.parse(t);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function Bw(e){if(!e)return"";let t=e;return t=t.replace(/```[\s\S]*?```/g," "),t=t.replace(/~~~[\s\S]*?~~~/g," "),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),t=t.replace(/<\/?[a-zA-Z][^>]*>/g," "),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),t=t.replace(/^[ \t]*>[ \t]?/gm,""),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,""),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,""),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),t=t.replace(/(\*\*|__)(.*?)\1/g,"$2"),t=t.replace(/(\*|_)(.*?)\1/g,"$2"),t=t.replace(/~~(.*?)~~/g,"$1"),t=t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
|
|
21
21
|
`),t=t.replace(/\n{2,}/g,`
|
|
22
|
-
`),t.trim()}var
|
|
22
|
+
`),t.trim()}var Uw=null;var fm=()=>Uw?Uw():Promise.resolve().then(()=>($w(),Fw));dn();var{setLoader:l_,load:bk}=lt({fallbackImport:()=>import("@runtypelabs/persona/session-reconnect")});var Vw=bk;var vk=["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 Ck(e,t){return vk.some(n=>e[n]!==t[n])}var rr=class extends Error{constructor(t,n){super(n),this.name="SessionHistoryError",this.code=t}};function mm(e,t){let n=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(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}
|
|
23
23
|
|
|
24
|
-
_Details: ${n.message}_`:o}var Fw=e=>bs(e)||e===Oo,Wa=class e{constructor(t={},n,o={}){this.config=t;this.callbacks=n;this.historyInternals=o;this.status="idle";this.streaming=!1;this.#e=new Map;this.abortController=null;this.#o=Date.now();this.clientSession=null;this.agentExecution=null;this.#t=null;this.#s=null;this.#r=!1;this.#p=null;this.#f=null;this.#i=null;this.artifacts=new Map;this.#g=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.#l=0;this.webMcpApprovalResolvers=new Map;this.#c=0;this.approvalTokens=new Map;this.webMcpAwaitBatches=new Map;this.#a=null;this.#E=null;this.#h=0;this.#S=0;this.#v=!1;this.#A="disconnected";this.#d=null;this.#u=null;this.#m=null;this.#C=0;this.#x=!1;this.#y=null;this.#b=!1;this.#H=null;this.#k=new Map;this.#M=null;this.#I=new Map;this.#Y=null;this.#j=null;this.#B=!1;this.#T=null;this.#K=null;this.#_=!1;this.#F=null;this.#D=null;this.#X=null;this.#Z=new ql;this.#ne=Promise.resolve();this.#$=null;this.#U=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new Si(()=>this.#de());this.#Ze=null;this.#le=0;this.handleEvent=t=>{let n=this.#U;if(n&&(t.type==="error"||t.type==="status"&&t.status==="error"?n.failed=!0:t.type==="message"&&t.message.role==="assistant"&&(n.dropped||this.ttsSpokenMessageIds.add(t.message.id),n.ids.includes(t.message.id)||n.ids.push(t.message.id))),t.type==="message"){this.upsertMessage(t.message),t.message.variant==="approval"&&t.message.approval&&t.message.approval.status!=="pending"&&this.#e.set(t.message.id,this.#n),t.message.role==="assistant"&&!t.message.variant&&t.message.streaming&&(this.#s=t.message.id),(t.message.variant==="approval"||t.message.agentMetadata?.awaitingLocalTool===!0)&&Gf().catch(()=>{});let o=t.message.toolCall,r=!!o?.name&&(bs(o.name)||o.name===Oo&&xs(this.config).enabled);t.message.agentMetadata?.awaitingLocalTool===!0&&r&&this.#et(t.message),t.message.agentMetadata?.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:t.message.agentMetadata.agentName??"",status:"running",currentIteration:t.message.agentMetadata.iteration??0,maxTurns:0})}else if(t.type==="cursor")this.#st(t.id);else if(t.type==="status"){if(t.status==="idle"&&!t.terminal&&this.#it()){this.#Pe();return}if(this.#z(t.status),t.status==="connecting")this.#P(!0);else if(t.status==="idle"||t.status==="error"){this.#De()||this.#Ae(),this.webMcpResolveControllers.size===0&&(this.#P(!1),this.abortController=null,this.#Ke(),this.#qe());let o=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(t.status==="error"?this.agentExecution.status="error":o||(this.agentExecution.status="complete")),this.#tt()}}else t.type==="error"?(this.#z("error"),this.#Ae(),this.webMcpResolveControllers.size===0&&(this.#P(!1),this.abortController=null),this.agentExecution?.status==="running"&&(this.agentExecution.status="error"),this.callbacks.onError?.(t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.#rt(t)};this.historyInternals=this.#se(o),this.messages=[...t.initialMessages??[]].map(r=>({...r,sequence:r.sequence??this.#V()})),this.messages=this.#ce(this.messages),this.client=new wi(t,this.historyInternals),this.#Le(),this.#Be();for(let r of t.initialArtifacts??[])this.artifacts.set(r.id,{...r,status:"complete"});t.initialSelectedArtifactId!=null&&(this.#g=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.#he(),this.callbacks.onStatusChanged(this.status),this.#te(),this.#ee()}#e;#n;#o;#t;#s;#r;#p;#f;#i;#g;#l;#c;#a;#E;#h;#S;#v;#A;#d;#u;#m;#C;#x;#y;#b;#H;#k;#M;#I;#Y;#j;#B;#T;#K;#_;#F;#ee(){this.config.voiceRecognition?.provider&&zl().catch(()=>{})}#te(){let t=this.config.textToSpeech;if(t?.provider!=="runtype"||t.createEngine)return;let n=t.host??this.config.apiUrl,o=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!n||!o||!this.config.clientToken||pm().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return sw(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.#v}getVoiceStatus(){return this.#A}getVoiceDisclosure(){return this.#a?.getDisclosure?.()??null}getVoiceLevel(){return this.#a?.onLevel?this.#S:null}getVoiceInterruptionMode(){return this.#a?.getInterruptionMode?this.#a.getInterruptionMode():"none"}stopVoicePlayback(){this.#a?.stopPlayback&&(this.#Z.cancel(),this.#$?.cancel(),this.#a.stopPlayback())}isBargeInActive(){return this.#a?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.#a?.deactivateBargeIn&&await this.#a.deactivateBargeIn()}#D;#X;#Z;#ne;#$;#U;#de(){let t=this.config.textToSpeech;if(t?.createEngine)return t.createEngine();let n=ks.isSupported()?new ks({pickVoice:t?.pickVoice}):null;if(t?.provider==="runtype"){let o=t.host??this.config.apiUrl,r=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,s=this.config.clientToken,i=t.browserFallback!==!1;if(o&&r&&s)return pm().then(({RuntypeSpeechEngine:l,FallbackSpeechEngine:c})=>{let p=new l({host:o,agentId:r,clientToken:s,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return i&&n?new c(p,n,{onFallback:d=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${d.message}`)}):p});if(i&&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(t){try{let n=t||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.cleanupVoice();let o=this.#ne,r=++this.#h;this.#E=zl().then(async s=>{await o,r===this.#h&&this.#W(s,s.createVoiceProvider(n))}).catch(s=>{console.error("Failed to setup voice:",s)}).finally(()=>{r===this.#h&&(this.#E=null)})}catch(n){console.error("Failed to setup voice:",n)}}#W(t,n){this.#a=n;let o=this;t.wireSessionVoice({session:this,provider:()=>o.#a,generation:()=>o.#h,get keyed(){return o.#$},set keyed(r){o.#$=r},get pendingUser(){return o.#D},set pendingUser(r){o.#D=r},get pendingAssistant(){return o.#X},set pendingAssistant(r){o.#X=r},turns:()=>o.#Z,busy:()=>o.#be(),setStreaming:r=>o.#P(r),setDelegation:r=>{o.#U=r},setLevel:r=>{o.#S=r},setStatus:r=>{o.#A=r,o.#v=r==="listening"},settlePending:r=>o.#pe(r)},n,t.KeyedVoiceTranscript,t.createVoiceSessionBridge)}async toggleVoice(){if(!this.#a&&this.#E&&await this.#E,!this.#a){console.error("Voice not configured");return}if(this.#v)await this.#a.stopListening();else{this.stopSpeaking();try{await this.#a.startListening()}catch(t){console.error("Failed to start voice:",t)}}}prewarmVoice(){if(!Dn(this.config.voiceRecognition?.provider)){this.warmClientSession();return}let t=this.#h,n=()=>{let o=this.#a;!o?.prewarm||t!==this.#h||this.#v||this.isBargeInActive()||Promise.resolve().then(()=>o.prewarm?.()).catch(()=>{})};if(!this.#a&&this.#E){this.#E.then(n,()=>{});return}n()}#be(){return!!this.abortController||this.webMcpResolveControllers.size>0||this.webMcpAwaitBatches.size>0||this.#r||this.status==="resuming"}cleanupVoice(){let t=this.#a!==null;if(this.#h++,this.#E=null,this.#a){let n=this.#a;this.#a=null,this.#ne=this.#oe(n)}this.#v=!1,this.#A="disconnected",this.#pe(!0),this.#$?.settle(),this.#$=null,this.#Z=new ql,t&&this.callbacks.onVoiceStatusChanged?.("disconnected")}async#oe(t){try{await t.disconnect()}catch(n){console.error("Failed to disconnect voice:",n)}}#pe(t){let n=t?this.#D:null,o=this.#X;!n&&!o||(o&&this.#Z.cancel(),t&&(this.#D=null),this.#X=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.#P(!1))}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:t.runtype?.agentId??this.config.agentId??"",clientToken:t.runtype?.clientToken??this.config.clientToken,host:t.runtype?.host??this.config.apiUrl,voiceId:t.runtype?.voiceId,createPlaybackEngine:t.runtype?.createPlaybackEngine,prewarmMode:t.runtype?.prewarmMode,attachIdleMs:t.runtype?.attachIdleMs,clientDelegation:t.runtype?.clientDelegation,callContext:t.runtype?.callContext,approvalTimeoutMs:t.runtype?.approvalTimeoutMs,disclosureText:t.runtype?.disclosureText}};case"browser":return{type:"browser",browser:{language:t.browser?.language||"en-US",continuous:t.browser?.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;this.config.features?.history?.enabled&&(await this.historyInternals.historyBootstrapReady,this.#j=this.historyInternals.getStoredConversationRevision?.()??null,this.#B=!0);try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return this.callbacks.onError?.(t instanceof Error?t:new Error(String(t))),null}}warmClientSession(){let t=!this.messages.length;this.client.warmSession().then(n=>{n&&this.client.getClientSession()===n&&this.setClientSession(n,t)})}setClientSession(t,n){this.clientSession=t,this.#re(t,n)}#re(t,n=!this.messages.length){if(this.#x||!t.config.welcomeMessage||!n)return;let o=this.messages[0],r={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:o?.createdAt??new Date().toISOString(),sequence:o?(o.sequence??0)-1:this.#V()};this.#J(r)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}setHistoryInternals(t){this.historyInternals=this.#se(t),this.client.setHistoryInternals(this.historyInternals),this.#Le()}destroy(){this.cleanupVoice(),this.#T?.(),this.#T=null,this.#K=null}#se(t){let n=t.onHistoryContinuityChanged;return{...t,onHistoryContinuityChanged:o=>{this.#Fe(o),n?.(o)}}}get#q(){return this.historyInternals.historyProvider??null}#R(){let t=this.#q;if(!t)throw new rr("history_unavailable","No conversation history provider is installed");return t}#O(t){let n=this.#R(),o=t??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 Vr("unsupported_scope","This history scope is not supported.");return{scope:s}}getHistoryState(){return{activeConversationId:this.#d,conversationRevision:this.#u,nextMessageCursor:this.#m,recovery:this.#y,sendBlocked:this.#b}}getActiveConversationId(){return this.#d}#L(){this.callbacks.onHistoryStateChanged?.(this.getHistoryState())}#N(t,n){this.callbacks.onHistoryNotice?.({code:t,message:n})}async awaitHistorySettled(){let t=this.#H;t&&await t.catch(()=>{});let n=this.#M;n&&await n.catch(()=>{})}#G(){if(this.streaming||this.status==="paused"||this.status==="resuming")throw new rr("conversation_busy","Finish or stop the current turn before switching conversations")}listConversations(t){return this.#R().list({...t?.cursor?{cursor:t.cursor}:{},...t?.limit!==void 0?{limit:t.limit}:{},...t?.targetId!==void 0?{targetId:t.targetId}:{},context:this.#O(t?.scope)})}async openConversation(t,n){let o=this.#R();this.#G();let r=this.#O(n?.scope);await this.awaitHistorySettled();let s=++this.#C,i=await o.getPage(t,{context:r});if(s!==this.#C)throw new rr("superseded","A later selection won");let l=await o.prepareOpen(t,{context:r});if(s!==this.#C)throw l.discard(),new rr("superseded","A later selection won");this.#x=!0;try{await this.#ie(l)}finally{this.#x=!1}this.#d=l.conversationId||t,this.#u=l.conversationRevision||i.conversationRevision||null,this.#m=i.nextCursor,this.#y=null,this.#b=!1,this.#we();for(let c of i.messages)this.#I.set(c.id,c.content);return this.#ae(),this.hydrateMessages(i.messages),this.#L(),{summary:i.summary,nextMessageCursor:i.nextCursor}}loadOlderMessages(t,n,o){let r=this.#R(),s=this.#O(o?.scope),i=n??this.#m;if(!i)return Promise.resolve({messages:[],nextMessageCursor:null});let l=`${t} ${i}`,c=this.#k.get(l);if(c)return c;let p=this.#xe(r,t,i,s).finally(()=>{this.#k.delete(l)});return this.#k.set(l,p),p}async#xe(t,n,o,r){let s=this.messages[0]?.createdAt,i=await t.getPage(n,{cursor:o,...s?{beforeCreatedAt:s}:{},context:r});if(this.#d&&this.#d!==n)return{messages:[],nextMessageCursor:i.nextCursor};let l=$l(this.messages,i.messages);this.messages=this.#ce(l.map(c=>this.#Ce(c))),this.#m=i.nextCursor;for(let c of i.messages)this.#I.set(c.id,c.content);return this.historyInternals.setStoredMessageCursor?.(i.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.#L(),{messages:i.messages,nextMessageCursor:i.nextCursor}}async startNewConversation(t){let n=this.#R(),o=this.#O(t?.scope);await this.awaitHistorySettled();let r=++this.#C,s=await n.prepareStartNew({context:o});if(r!==this.#C)throw s.discard(),new rr("superseded","A later action won");await this.#ue(s)}async#ue(t){this.#ge(),await this.#ie(t),this.#d=t.conversationId||null,this.#u=t.conversationRevision||null,this.#m=null,this.#y=null,this.#b=!1,this.#ae(),this.#L()}async deleteConversation(t,n){let o=this.#R(),r=this.#O(n?.scope);await this.awaitHistorySettled(),await o.delete(t,{context:r}),t===this.#d&&await this.#ve(r)}async updateConversation(t,n,o){let r=this.#R();if(!r.update)throw new rr("history_unavailable","This history provider cannot update conversations");let s=this.#O(o?.scope);return await this.awaitHistorySettled(),r.update(t,n,{context:s})}canUpdateConversations(){return typeof this.#q?.update=="function"}async clearConversationHistory(t){let n=this.#R(),o=this.#O(t?.scope);await this.awaitHistorySettled();let r=await n.deleteAll({...t?.targetId!==void 0?{targetId:t.targetId}:{},context:o});return await this.#ve(o),r}async resetHistoryDevice(){let t=this.#R();if(!t.resetDevice)throw new rr("history_unavailable","This history provider cannot reset the device");this.#C+=1,this.#M=null;try{return await t.resetDevice()}finally{this.#ge(),this.#d=null,this.#u=null,this.#m=null,this.#y=null,this.#b=!1,this.#L()}}async#ve(t){this.#C+=1,this.#M=null,this.#ge(),this.#d=null,this.#u=null,this.#m=null,this.#b=!0,this.#y=null,this.#L(),await this.#Q(t)}async#Q(t){let n=this.#q;if(!n){this.#b=!1,this.#L();return}try{let o=await n.prepareStartNew({context:t});await this.#ue(o)}catch{this.#b=!0,this.#y="new_conversation_required",this.#L(),this.#N("new_conversation_required","That conversation was deleted. Start a new conversation to continue.")}}async#w(){if(!(this.#y!=="new_conversation_required"||!this.#q)&&(this.#y=null,await this.#Q(this.#O()),this.#y==="new_conversation_required"))throw new rr("new_conversation_required","A new conversation is required before sending")}async#ie(t){await t.commit();let n=this.client.getClientSession();n&&n.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(n)}bindActivatedSession(t){this.clientSession=t,this.config.setStoredSessionId?.(t.sessionId),t.conversationId&&(this.#d=t.conversationId,this.#u=t.conversationRevision??null,this.config.setStoredConversationId?.(t.conversationId),this.historyInternals.setStoredConversationRevision?.(t.conversationRevision??null)),this.#x||this.#re(t)}#ae(){this.#d?this.config.setStoredConversationId?.(this.#d):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.#u),this.historyInternals.setStoredMessageCursor?.(this.#m)}#we(){this.historyInternals.setStoredResumableHandle?.(null),this.agentExecution=null,this.#Te(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#I.clear(),this.#fe(null)}#ge(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#ye(),this.#me(),this.#le++,this.messages=[],this.#we(),this.#k.clear(),this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),this.#P(!1),this.#z("idle"),this.callbacks.onMessagesChanged([...this.messages])}#Fe(t){this.#C+=1,this.#M=null,this.#b=!0,this.#ge(),this.#d=t.conversationId,this.#u=null,this.#m=null,this.#y=null,this.#L(),this.#N("history_continuity_reset","This browser was reconnected to a different conversation, so the previous messages were cleared."),this.#H=Promise.resolve().then(()=>{this.#b=!1,this.#H=null,this.#L()})}#Le(){let t=this.historyInternals.visitorStore??null;t!==this.#K&&(this.#T?.(),this.#T=null,this.#K=t,t&&(this.#T=t.subscribe(n=>this.#$e(n))))}#$e(t){if(t.source!=="external"||t.previousToken===null)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.#C+=1,this.#M=null,this.#_=!0,this.#F=null;let n=this.messages.length>0;n||this.#d!==null||(this.config.getStoredConversationId?.()??null)!==null?this.#ge():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.#k.clear(),this.#fe(null)),this.#d=null,this.#u=null,this.#m=null,this.#y=null,this.#L(),n&&this.#N("history_continuity_reset","This browser's conversation history was reset in another tab, so the previous messages were cleared.")}#Ue(){return this.#_?(this.#F||(this.#F=this.#Ve().finally(()=>{this.#F=null})),this.#F):Promise.resolve()}async#Ve(){if(!this.isClientTokenMode()){this.#_=!1;return}try{this.bindActivatedSession(await this.client.initSession()),this.#_=!1}catch{}}reconcileBootConversation(t){let n=this.#q,o=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.#d;if(!n||!o)return Promise.resolve();let r=this.#O(t?.scope);this.#b=!0,this.#L();let s=this.#je(n,o,r).finally(()=>{this.#b=this.#y!==null,this.#H===s&&(this.#H=null),this.#L()});return this.#H=s,s}async#je(t,n,o){this.#d=n;let r=this.clientSession?.conversationRevision??this.#u??null,s=this.#B?this.#j:this.historyInternals.getStoredConversationRevision?.()??null;if(this.#B=!1,this.#m=this.historyInternals.getStoredMessageCursor?.()??this.#m,await this.replayPendingProjections(),r&&s&&r===s){this.#u=r;return}let i=await t.getPage(n,{context:o}),l=new Set(i.messages.map(g=>g.id)),c=this.messages.some(g=>l.has(g.id)),p=i.messages[0]?.createdAt,d;if(!c)d=i.messages.map(g=>this.#Ce(g));else{let g=this.#t?this.#s:null,f=this.messages.filter(h=>l.has(h.id)||h.id===g?!0:p!==void 0&&h.createdAt<p);d=$l(f,i.messages).map(h=>this.#Ce(h))}this.#m=i.nextCursor,this.#u=i.conversationRevision||r||null,this.#I.clear();for(let g of i.messages)this.#I.set(g.id,g.content);this.#ae(),this.messages=this.#ce(d),this.callbacks.onMessagesChanged([...this.messages])}#Me(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}#fe(t){this.#Y=t,this.historyInternals.setPendingDisplayProjections?.(t)}#He(){return this.historyInternals.getPendingDisplayProjections?.()??this.#Y}#Ie(t){if(this.#Me())for(let n of t){let o=Fl(n);o!==void 0&&this.#I.set(n.id,o)}}#qe(){if(!this.#Me())return;let t=this.#d;if(!t)return;let n=[];for(let o of this.messages){if(o.role!=="assistant"||o.streaming)continue;let r=Fl(o);r!==void 0&&this.#I.get(o.id)!==r&&n.push({id:o.id,displayContent:r})}n.length!==0&&(this.#fe({conversationId:t,messageIds:n.map(o=>o.id)}),this.#Re(t,n))}#Re(t,n){let r=(this.#M??Promise.resolve()).catch(()=>{}).then(()=>this.#We(t,n,!1)).finally(()=>{this.#M===r&&(this.#M=null)});this.#M=r}async#We(t,n,o){if(this.#d!==t)return;let r=n.filter(s=>this.#I.get(s.id)!==s.displayContent);if(r.length===0){this.#Ee(t,n);return}try{let{conversationRevision:s}=await this.client.finalizeDisplayProjections(t,r);for(let i of r)this.#I.set(i.id,i.displayContent);this.#d===t&&s&&(this.#u=s),this.#Ee(t,n)}catch(s){if(!o&&this.#ze(s)){await this.#We(t,r,!0);return}if(s instanceof on&&(s.code==="not_found"||s.code==="conversation_deleted")){this.#Ee(t,n);return}this.#N("projection_finalization_failed","Some message formatting could not be saved for history; it will be retried.")}}#ze(t){return t instanceof on?t.code==="request_failed":t instanceof Error}#Ee(t,n){let o=this.#He();if(!o||o.conversationId!==t)return;let r=new Set(n.map(i=>i.id)),s=o.messageIds.filter(i=>!r.has(i));this.#fe(s.length?{conversationId:t,messageIds:s}:null)}async replayPendingProjections(){if(!this.#Me())return;let t=this.#He();if(!t)return;if(this.#d&&t.conversationId!==this.#d){this.#fe(null);return}let n=[];for(let o of t.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.#fe(null);return}this.#Re(t.conversationId,n),await this.#M?.catch(()=>{})}#Ke(){this.#d&&(this.#u=null,this.historyInternals.setStoredConversationRevision?.(null))}async#Oe(){await this.awaitHistorySettled(),await this.#Ue(),this.#y==="new_conversation_required"&&await this.#w()}static#Ge(t){return t instanceof on&&t.code==="conversation_deleted"}async#Ye(t,n,o,r,s){this.#Ie(t);try{await this.client.dispatch({messages:t,signal:n.signal,assistantMessageId:o,composerOptions:s?.composerOptions,interrupt:s?.interrupt},this.handleEvent);return}catch(i){if(!e.#Ge(i))throw i;let l=await this.#Xe(r);if(!l)throw i;this.#Ie([l]),await this.client.dispatch({messages:[l],signal:n.signal,assistantMessageId:o,composerOptions:s?.composerOptions},this.handleEvent)}}async#Xe(t){let n=this.messages.find(r=>r.id===t);if(!n)return null;let o={...n};this.#C+=1,this.#M=null,this.#ge(),this.#d=null,this.#u=null,this.#m=null,this.#x=!0;try{let r=this.#q;if(r){let s=await r.prepareStartNew({context:this.#O()});await this.#ue(s)}else{this.client.clearClientSession();let s=await this.client.initSession();this.bindActivatedSession(s)}}catch{return this.#b=!0,this.#y="new_conversation_required",this.#L(),this.#N("new_conversation_required","That conversation was deleted. Start a new conversation to continue."),null}finally{this.#x=!1}return this.#J(o),this.#P(!0),this.#N("conversation_deleted_recovered","That conversation was deleted. Started a new conversation."),this.messages.find(r=>r.id===o.id)??o}updateConfig(t){let n=this.config.features?.artifacts?.display,o={...this.config,...t},r=rw(this.config,o),s=mk(this.config,o);this.config=o,r&&(this.cleanupVoice(),o.voiceRecognition?.enabled===!0&&Dn(o.voiceRecognition.provider)&&this.setupVoice());let i=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!s){this.client.updateConfig(o),i&&this.#_e();return}this.#me(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let l=this.client.getSSEEventCallback();this.client=new wi(this.config,this.historyInternals),i&&this.#_e(),this.#Be(),l&&this.client.setSSEEventCallback(l)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:o,llmContent:r,contentParts:s,id:i,createdAt:l,sequence:c,streaming:p=!1,voiceProcessing:d,voiceCaption:g,rawContent:f}=t,y={id:i??(n==="user"?Ha():n==="assistant"?Ps():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:l??new Date().toISOString(),sequence:c??this.#V(),streaming:p,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...d!==void 0&&{voiceProcessing:d},...g&&{voiceCaption:g},...f!==void 0&&{rawContent:f}};return this.upsertMessage(y),y}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:r,content:s,llmContent:i,contentParts:l,id:c,createdAt:p,sequence:d,streaming:g=!1,voiceProcessing:f,rawContent:h}=o,v={id:c??(r==="user"?Ha():r==="assistant"?Ps():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:s,createdAt:p??new Date().toISOString(),sequence:d??this.#V(),streaming:g,...i!==void 0&&{llmContent:i},...l!==void 0&&{contentParts:l},...f!==void 0&&{voiceProcessing:f},...h!==void 0&&{rawContent:h}};n.push(v)}return this.messages=this.#ce([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:o={},text:r="",llmContent:s,id:i,createdAt:l,sequence:c}=t,p={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(p),...s!==void 0&&{llmContent:s},...i!==void 0&&{id:i},...l!==void 0&&{createdAt:l},...c!==void 0&&{sequence:c}})}async#Qe(t,n,o){let r;try{r=await o()}catch{return}let s=r.blocks.join(`
|
|
24
|
+
_Details: ${n.message}_`:o}var jw=e=>bs(e)||e===Oo,Wa=class e{constructor(t={},n,o={}){this.config=t;this.callbacks=n;this.historyInternals=o;this.status="idle";this.streaming=!1;this.#e=new Map;this.abortController=null;this.#o=Date.now();this.clientSession=null;this.agentExecution=null;this.#t=null;this.#s=null;this.#r=!1;this.#p=null;this.#f=null;this.#i=null;this.artifacts=new Map;this.#u=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.#c=0;this.webMcpApprovalResolvers=new Map;this.#l=0;this.approvalTokens=new Map;this.webMcpAwaitBatches=new Map;this.#a=null;this.#M=null;this.#h=0;this.#A=0;this.#w=!1;this.#x="disconnected";this.#d=null;this.#g=null;this.#m=null;this.#S=0;this.#E=!1;this.#b=null;this.#v=!1;this.#H=null;this.#T=new Map;this.#C=null;this.#R=new Map;this.#Y=null;this.#z=null;this.#$=!1;this.#P=null;this.#X=null;this.#W=!1;this.#D=null;this.#O=null;this.#K=null;this.#G=new ql;this.#oe=Promise.resolve();this.#U=null;this.#_=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new Si(()=>this.#be());this.#Ze=null;this.#le=0;this.handleEvent=t=>{let n=this.#_;if(n&&(t.type==="error"||t.type==="status"&&t.status==="error"?n.failed=!0:t.type==="message"&&t.message.role==="assistant"&&(n.dropped||this.ttsSpokenMessageIds.add(t.message.id),n.ids.includes(t.message.id)||n.ids.push(t.message.id))),t.type==="message"){this.upsertMessage(t.message),t.message.variant==="approval"&&t.message.approval&&t.message.approval.status!=="pending"&&this.#e.set(t.message.id,this.#n),t.message.role==="assistant"&&!t.message.variant&&t.message.streaming&&(this.#s=t.message.id),(t.message.variant==="approval"||t.message.agentMetadata?.awaitingLocalTool===!0)&&Qf().catch(()=>{});let o=t.message.toolCall,r=!!o?.name&&(bs(o.name)||o.name===Oo&&xs(this.config).enabled);t.message.agentMetadata?.awaitingLocalTool===!0&&r&&this.#et(t.message),t.message.agentMetadata?.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:t.message.agentMetadata.agentName??"",status:"running",currentIteration:t.message.agentMetadata.iteration??0,maxTurns:0})}else if(t.type==="cursor")this.#st(t.id);else if(t.type==="status"){if(t.status==="idle"&&!t.terminal&&this.#it()){this.#Re();return}if(this.#q(t.status),t.status==="connecting")this.#k(!0);else if(t.status==="idle"||t.status==="error"){this.#Ue()||this.#Te(),this.webMcpResolveControllers.size===0&&(this.#k(!1),this.abortController=null,this.#Ke(),this.#qe());let o=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(t.status==="error"?this.agentExecution.status="error":o||(this.agentExecution.status="complete")),this.#tt()}}else t.type==="error"?(this.#q("error"),this.#Te(),this.webMcpResolveControllers.size===0&&(this.#k(!1),this.abortController=null),this.agentExecution?.status==="running"&&(this.agentExecution.status="error"),this.callbacks.onError?.(t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.#rt(t)};this.historyInternals=this.#ie(o),this.messages=[...t.initialMessages??[]].map(r=>({...r,sequence:r.sequence??this.#F()})),this.messages=this.#ce(this.messages),this.client=new wi(t,this.historyInternals),this.#y(),this.#Fe();for(let r of t.initialArtifacts??[])this.artifacts.set(r.id,{...r,status:"complete"});t.initialSelectedArtifactId!=null&&(this.#u=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.#he(),this.callbacks.onStatusChanged(this.status),this.#ne(),this.#Q()}#e;#n;#o;#t;#s;#r;#p;#f;#i;#u;#c;#l;#a;#M;#h;#A;#w;#x;#d;#g;#m;#S;#E;#b;#v;#H;#T;#C;#R;#Y;#z;#$;#P;#X;#W;#D;#Q(){this.config.voiceRecognition?.provider&&zl().catch(()=>{})}#ne(){let t=this.config.textToSpeech;if(t?.provider!=="runtype"||t.createEngine)return;let n=t.host??this.config.apiUrl,o=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!n||!o||!this.config.clientToken||fm().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return cw(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.#w}getVoiceStatus(){return this.#x}getVoiceNotice(){return this.#a?.takeNotice?.()??null}getVoiceDisclosure(){return this.#a?.getDisclosure?.()??null}getVoiceLevel(){return this.#a?.onLevel?this.#A:null}getVoiceInterruptionMode(){return this.#a?.getInterruptionMode?this.#a.getInterruptionMode():"none"}stopVoicePlayback(){this.#a?.stopPlayback&&(this.#G.cancel(),this.#U?.cancel(),this.#a.stopPlayback())}isBargeInActive(){return this.#a?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.#a?.deactivateBargeIn&&await this.#a.deactivateBargeIn()}#O;#K;#G;#oe;#U;#_;#be(){let t=this.config.textToSpeech;if(t?.createEngine)return t.createEngine();let n=ks.isSupported()?new ks({pickVoice:t?.pickVoice}):null;if(t?.provider==="runtype"){let o=t.host??this.config.apiUrl,r=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,s=this.config.clientToken,i=t.browserFallback!==!1;if(o&&r&&s)return fm().then(({RuntypeSpeechEngine:l,FallbackSpeechEngine:c})=>{let p=new l({host:o,agentId:r,clientToken:s,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return i&&n?new c(p,n,{onFallback:d=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${d.message}`)}):p});if(i&&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(t){try{let n=t||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.cleanupVoice();let o=this.#oe,r=++this.#h;this.#M=zl().then(async s=>{await o,r===this.#h&&this.#N(s,s.createVoiceProvider(n))}).catch(s=>{console.error("Failed to setup voice:",s)}).finally(()=>{r===this.#h&&(this.#M=null)})}catch(n){console.error("Failed to setup voice:",n)}}#N(t,n){this.#a=n;let o=this;t.wireSessionVoice({session:this,provider:()=>o.#a,generation:()=>o.#h,get keyed(){return o.#U},set keyed(r){o.#U=r},get pendingUser(){return o.#O},set pendingUser(r){o.#O=r},get pendingAssistant(){return o.#K},set pendingAssistant(r){o.#K=r},turns:()=>o.#G,busy:()=>o.#de(),setStreaming:r=>o.#k(r),setDelegation:r=>{o.#_=r},setLevel:r=>{o.#A=r},setStatus:r=>{o.#x=r,o.#w=r==="listening"},settlePending:r=>o.#pe(r)},n,t.KeyedVoiceTranscript,t.createVoiceSessionBridge)}async toggleVoice(){if(!this.#a&&this.#M&&await this.#M,!this.#a){console.error("Voice not configured");return}if(this.#w)await this.#a.stopListening();else{this.stopSpeaking();try{await this.#a.startListening()}catch(t){console.error("Failed to start voice:",t)}}}prewarmVoice(){if(!In(this.config.voiceRecognition?.provider)){this.warmClientSession();return}let t=this.#h,n=()=>{let o=this.#a;!o?.prewarm||t!==this.#h||this.#w||this.isBargeInActive()||Promise.resolve().then(()=>o.prewarm?.()).catch(()=>{})};if(!this.#a&&this.#M){this.#M.then(n,()=>{});return}n()}#de(){return!!this.abortController||this.webMcpResolveControllers.size>0||this.webMcpAwaitBatches.size>0||this.#r||this.status==="resuming"}cleanupVoice(){let t=this.#a!==null;if(this.#h++,this.#M=null,this.#a){let n=this.#a;this.#a=null,this.#oe=this.#re(n)}this.#w=!1,this.#x="disconnected",this.#pe(!0),this.#U?.settle(),this.#U=null,this.#G=new ql,t&&this.callbacks.onVoiceStatusChanged?.("disconnected")}async#re(t){try{await t.disconnect()}catch(n){console.error("Failed to disconnect voice:",n)}}#pe(t){let n=t?this.#O:null,o=this.#K;!n&&!o||(o&&this.#G.cancel(),t&&(this.#O=null),this.#K=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.#k(!1))}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:t.runtype?.agentId??this.config.agentId??"",clientToken:t.runtype?.clientToken??this.config.clientToken,host:t.runtype?.host??this.config.apiUrl,voiceId:t.runtype?.voiceId,createPlaybackEngine:t.runtype?.createPlaybackEngine,prewarmMode:t.runtype?.prewarmMode,attachIdleMs:t.runtype?.attachIdleMs,clientDelegation:t.runtype?.clientDelegation,callContext:t.runtype?.callContext,approvalTimeoutMs:t.runtype?.approvalTimeoutMs,disclosureText:t.runtype?.disclosureText}};case"browser":return{type:"browser",browser:{language:t.browser?.language||"en-US",continuous:t.browser?.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;this.config.features?.history?.enabled&&(await this.historyInternals.historyBootstrapReady,this.#z=this.historyInternals.getStoredConversationRevision?.()??null,this.#$=!0);try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return this.callbacks.onError?.(t instanceof Error?t:new Error(String(t))),null}}warmClientSession(){let t=!this.messages.length;this.client.warmSession().then(n=>{n&&this.client.getClientSession()===n&&this.setClientSession(n,t)})}setClientSession(t,n){this.clientSession=t,this.#se(t,n)}#se(t,n=!this.messages.length){if(this.#E||!t.config.welcomeMessage||!n)return;let o=this.messages[0],r={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:o?.createdAt??new Date().toISOString(),sequence:o?(o.sequence??0)-1:this.#F()};this.#te(r)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}setHistoryInternals(t){this.historyInternals=this.#ie(t),this.client.setHistoryInternals(this.historyInternals),this.#y()}destroy(){this.cleanupVoice(),this.#P?.(),this.#P=null,this.#X=null}#ie(t){let n=t.onHistoryContinuityChanged;return{...t,onHistoryContinuityChanged:o=>{this.#ee(o),n?.(o)}}}get#V(){return this.historyInternals.historyProvider??null}#B(){let t=this.#V;if(!t)throw new rr("history_unavailable","No conversation history provider is installed");return t}#I(t){let n=this.#B(),o=t??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 Vr("unsupported_scope","This history scope is not supported.");return{scope:s}}getHistoryState(){return{activeConversationId:this.#d,conversationRevision:this.#g,nextMessageCursor:this.#m,recovery:this.#b,sendBlocked:this.#v}}getActiveConversationId(){return this.#d}#L(){this.callbacks.onHistoryStateChanged?.(this.getHistoryState())}#j(t,n){this.callbacks.onHistoryNotice?.({code:t,message:n})}async awaitHistorySettled(){let t=this.#H;t&&await t.catch(()=>{});let n=this.#C;n&&await n.catch(()=>{})}#J(){if(this.streaming||this.status==="paused"||this.status==="resuming")throw new rr("conversation_busy","Finish or stop the current turn before switching conversations")}listConversations(t){return this.#B().list({...t?.cursor?{cursor:t.cursor}:{},...t?.limit!==void 0?{limit:t.limit}:{},...t?.targetId!==void 0?{targetId:t.targetId}:{},context:this.#I(t?.scope)})}async openConversation(t,n){let o=this.#B();this.#J();let r=this.#I(n?.scope);await this.awaitHistorySettled();let s=++this.#S,i=await o.getPage(t,{context:r});if(s!==this.#S)throw new rr("superseded","A later selection won");let l=await o.prepareOpen(t,{context:r});if(s!==this.#S)throw l.discard(),new rr("superseded","A later selection won");this.#E=!0;try{await this.#ge(l)}finally{this.#E=!1}this.#d=l.conversationId||t,this.#g=l.conversationRevision||i.conversationRevision||null,this.#m=i.nextCursor,this.#b=null,this.#v=!1,this.#we();for(let c of i.messages)this.#R.set(c.id,c.content);return this.#Ce(),this.hydrateMessages(i.messages),this.#L(),{summary:i.summary,nextMessageCursor:i.nextCursor}}loadOlderMessages(t,n,o){let r=this.#B(),s=this.#I(o?.scope),i=n??this.#m;if(!i)return Promise.resolve({messages:[],nextMessageCursor:null});let l=`${t} ${i}`,c=this.#T.get(l);if(c)return c;let p=this.#Pe(r,t,i,s).finally(()=>{this.#T.delete(l)});return this.#T.set(l,p),p}async#Pe(t,n,o,r){let s=this.messages[0]?.createdAt,i=await t.getPage(n,{cursor:o,...s?{beforeCreatedAt:s}:{},context:r});if(this.#d&&this.#d!==n)return{messages:[],nextMessageCursor:i.nextCursor};let l=$l(this.messages,i.messages);this.messages=this.#ce(l.map(c=>this.#Ae(c))),this.#m=i.nextCursor;for(let c of i.messages)this.#R.set(c.id,c.content);return this.historyInternals.setStoredMessageCursor?.(i.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.#L(),{messages:i.messages,nextMessageCursor:i.nextCursor}}async startNewConversation(t){let n=this.#B(),o=this.#I(t?.scope);await this.awaitHistorySettled();let r=++this.#S,s=await n.prepareStartNew({context:o});if(r!==this.#S)throw s.discard(),new rr("superseded","A later action won");await this.#ue(s)}async#ue(t){this.#Z(),await this.#ge(t),this.#d=t.conversationId||null,this.#g=t.conversationRevision||null,this.#m=null,this.#b=null,this.#v=!1,this.#Ce(),this.#L()}async deleteConversation(t,n){let o=this.#B(),r=this.#I(n?.scope);await this.awaitHistorySettled(),await o.delete(t,{context:r}),t===this.#d&&await this.#xe(r)}async updateConversation(t,n,o){let r=this.#B();if(!r.update)throw new rr("history_unavailable","This history provider cannot update conversations");let s=this.#I(o?.scope);return await this.awaitHistorySettled(),r.update(t,n,{context:s})}canUpdateConversations(){return typeof this.#V?.update=="function"}async clearConversationHistory(t){let n=this.#B(),o=this.#I(t?.scope);await this.awaitHistorySettled();let r=await n.deleteAll({...t?.targetId!==void 0?{targetId:t.targetId}:{},context:o});return await this.#xe(o),r}async resetHistoryDevice(){let t=this.#B();if(!t.resetDevice)throw new rr("history_unavailable","This history provider cannot reset the device");this.#S+=1,this.#C=null;try{return await t.resetDevice()}finally{this.#Z(),this.#d=null,this.#g=null,this.#m=null,this.#b=null,this.#v=!1,this.#L()}}async#xe(t){this.#S+=1,this.#C=null,this.#Z(),this.#d=null,this.#g=null,this.#m=null,this.#v=!0,this.#b=null,this.#L(),await this.#Ee(t)}async#Ee(t){let n=this.#V;if(!n){this.#v=!1,this.#L();return}try{let o=await n.prepareStartNew({context:t});await this.#ue(o)}catch{this.#v=!0,this.#b="new_conversation_required",this.#L(),this.#j("new_conversation_required","That conversation was deleted. Start a new conversation to continue.")}}async#ve(){if(!(this.#b!=="new_conversation_required"||!this.#V)&&(this.#b=null,await this.#Ee(this.#I()),this.#b==="new_conversation_required"))throw new rr("new_conversation_required","A new conversation is required before sending")}async#ge(t){await t.commit();let n=this.client.getClientSession();n&&n.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(n)}bindActivatedSession(t){this.clientSession=t,this.config.setStoredSessionId?.(t.sessionId),t.conversationId&&(this.#d=t.conversationId,this.#g=t.conversationRevision??null,this.config.setStoredConversationId?.(t.conversationId),this.historyInternals.setStoredConversationRevision?.(t.conversationRevision??null)),this.#E||this.#se(t)}#Ce(){this.#d?this.config.setStoredConversationId?.(this.#d):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.#g),this.historyInternals.setStoredMessageCursor?.(this.#m)}#we(){this.historyInternals.setStoredResumableHandle?.(null),this.agentExecution=null,this.#Ie(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#R.clear(),this.#fe(null)}#Z(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#ye(),this.#me(),this.#le++,this.messages=[],this.#we(),this.#T.clear(),this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),this.#k(!1),this.#q("idle"),this.callbacks.onMessagesChanged([...this.messages])}#ee(t){this.#S+=1,this.#C=null,this.#v=!0,this.#Z(),this.#d=t.conversationId,this.#g=null,this.#m=null,this.#b=null,this.#L(),this.#j("history_continuity_reset","This browser was reconnected to a different conversation, so the previous messages were cleared."),this.#H=Promise.resolve().then(()=>{this.#v=!1,this.#H=null,this.#L()})}#y(){let t=this.historyInternals.visitorStore??null;t!==this.#X&&(this.#P?.(),this.#P=null,this.#X=t,t&&(this.#P=t.subscribe(n=>this.#ae(n))))}#ae(t){if(t.source!=="external"||t.previousToken===null)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.#S+=1,this.#C=null,this.#W=!0,this.#D=null;let n=this.messages.length>0;n||this.#d!==null||(this.config.getStoredConversationId?.()??null)!==null?this.#Z():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.#T.clear(),this.#fe(null)),this.#d=null,this.#g=null,this.#m=null,this.#b=null,this.#L(),n&&this.#j("history_continuity_reset","This browser's conversation history was reset in another tab, so the previous messages were cleared.")}#Se(){return this.#W?(this.#D||(this.#D=this.#ke().finally(()=>{this.#D=null})),this.#D):Promise.resolve()}async#ke(){if(!this.isClientTokenMode()){this.#W=!1;return}try{this.bindActivatedSession(await this.client.initSession()),this.#W=!1}catch{}}reconcileBootConversation(t){let n=this.#V,o=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.#d;if(!n||!o)return Promise.resolve();let r=this.#I(t?.scope);this.#v=!0,this.#L();let s=this.#je(n,o,r).finally(()=>{this.#v=this.#b!==null,this.#H===s&&(this.#H=null),this.#L()});return this.#H=s,s}async#je(t,n,o){this.#d=n;let r=this.clientSession?.conversationRevision??this.#g??null,s=this.#$?this.#z:this.historyInternals.getStoredConversationRevision?.()??null;if(this.#$=!1,this.#m=this.historyInternals.getStoredMessageCursor?.()??this.#m,await this.replayPendingProjections(),r&&s&&r===s){this.#g=r;return}let i=await t.getPage(n,{context:o}),l=new Set(i.messages.map(g=>g.id)),c=this.messages.some(g=>l.has(g.id)),p=i.messages[0]?.createdAt,d;if(!c)d=i.messages.map(g=>this.#Ae(g));else{let g=this.#t?this.#s:null,f=this.messages.filter(h=>l.has(h.id)||h.id===g?!0:p!==void 0&&h.createdAt<p);d=$l(f,i.messages).map(h=>this.#Ae(h))}this.#m=i.nextCursor,this.#g=i.conversationRevision||r||null,this.#R.clear();for(let g of i.messages)this.#R.set(g.id,g.content);this.#Ce(),this.messages=this.#ce(d),this.callbacks.onMessagesChanged([...this.messages])}#Le(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}#fe(t){this.#Y=t,this.historyInternals.setPendingDisplayProjections?.(t)}#Oe(){return this.historyInternals.getPendingDisplayProjections?.()??this.#Y}#_e(t){if(this.#Le())for(let n of t){let o=Fl(n);o!==void 0&&this.#R.set(n.id,o)}}#qe(){if(!this.#Le())return;let t=this.#d;if(!t)return;let n=[];for(let o of this.messages){if(o.role!=="assistant"||o.streaming)continue;let r=Fl(o);r!==void 0&&this.#R.get(o.id)!==r&&n.push({id:o.id,displayContent:r})}n.length!==0&&(this.#fe({conversationId:t,messageIds:n.map(o=>o.id)}),this.#Be(t,n))}#Be(t,n){let r=(this.#C??Promise.resolve()).catch(()=>{}).then(()=>this.#De(t,n,!1)).finally(()=>{this.#C===r&&(this.#C=null)});this.#C=r}async#De(t,n,o){if(this.#d!==t)return;let r=n.filter(s=>this.#R.get(s.id)!==s.displayContent);if(r.length===0){this.#He(t,n);return}try{let{conversationRevision:s}=await this.client.finalizeDisplayProjections(t,r);for(let i of r)this.#R.set(i.id,i.displayContent);this.#d===t&&s&&(this.#g=s),this.#He(t,n)}catch(s){if(!o&&this.#ze(s)){await this.#De(t,r,!0);return}if(s instanceof on&&(s.code==="not_found"||s.code==="conversation_deleted")){this.#He(t,n);return}this.#j("projection_finalization_failed","Some message formatting could not be saved for history; it will be retried.")}}#ze(t){return t instanceof on?t.code==="request_failed":t instanceof Error}#He(t,n){let o=this.#Oe();if(!o||o.conversationId!==t)return;let r=new Set(n.map(i=>i.id)),s=o.messageIds.filter(i=>!r.has(i));this.#fe(s.length?{conversationId:t,messageIds:s}:null)}async replayPendingProjections(){if(!this.#Le())return;let t=this.#Oe();if(!t)return;if(this.#d&&t.conversationId!==this.#d){this.#fe(null);return}let n=[];for(let o of t.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.#fe(null);return}this.#Be(t.conversationId,n),await this.#C?.catch(()=>{})}#Ke(){this.#d&&(this.#g=null,this.historyInternals.setStoredConversationRevision?.(null))}async#Ne(){await this.awaitHistorySettled(),await this.#Se(),this.#b==="new_conversation_required"&&await this.#ve()}static#Ge(t){return t instanceof on&&t.code==="conversation_deleted"}async#Ye(t,n,o,r,s){this.#_e(t);try{await this.client.dispatch({messages:t,signal:n.signal,assistantMessageId:o,composerOptions:s?.composerOptions,interrupt:s?.interrupt},this.handleEvent);return}catch(i){if(!e.#Ge(i))throw i;let l=await this.#Xe(r);if(!l)throw i;this.#_e([l]),await this.client.dispatch({messages:[l],signal:n.signal,assistantMessageId:o,composerOptions:s?.composerOptions},this.handleEvent)}}async#Xe(t){let n=this.messages.find(r=>r.id===t);if(!n)return null;let o={...n};this.#S+=1,this.#C=null,this.#Z(),this.#d=null,this.#g=null,this.#m=null,this.#E=!0;try{let r=this.#V;if(r){let s=await r.prepareStartNew({context:this.#I()});await this.#ue(s)}else{this.client.clearClientSession();let s=await this.client.initSession();this.bindActivatedSession(s)}}catch{return this.#v=!0,this.#b="new_conversation_required",this.#L(),this.#j("new_conversation_required","That conversation was deleted. Start a new conversation to continue."),null}finally{this.#E=!1}return this.#te(o),this.#k(!0),this.#j("conversation_deleted_recovered","That conversation was deleted. Started a new conversation."),this.messages.find(r=>r.id===o.id)??o}updateConfig(t){let n=this.config.features?.artifacts?.display,o={...this.config,...t},r=lw(this.config,o),s=Ck(this.config,o);this.config=o,r&&(this.cleanupVoice(),o.voiceRecognition?.enabled===!0&&In(o.voiceRecognition.provider)&&this.setupVoice());let i=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!s){this.client.updateConfig(o),i&&this.#$e();return}this.#me(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let l=this.client.getSSEEventCallback();this.client=new wi(this.config,this.historyInternals),i&&this.#$e(),this.#Fe(),l&&this.client.setSSEEventCallback(l)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:o,llmContent:r,contentParts:s,id:i,createdAt:l,sequence:c,streaming:p=!1,voiceProcessing:d,voiceCaption:g,rawContent:f}=t,y={id:i??(n==="user"?Ha():n==="assistant"?Ps():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:l??new Date().toISOString(),sequence:c??this.#F(),streaming:p,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...d!==void 0&&{voiceProcessing:d},...g&&{voiceCaption:g},...f!==void 0&&{rawContent:f}};return this.upsertMessage(y),y}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:r,content:s,llmContent:i,contentParts:l,id:c,createdAt:p,sequence:d,streaming:g=!1,voiceProcessing:f,rawContent:h}=o,v={id:c??(r==="user"?Ha():r==="assistant"?Ps():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:s,createdAt:p??new Date().toISOString(),sequence:d??this.#F(),streaming:g,...i!==void 0&&{llmContent:i},...l!==void 0&&{contentParts:l},...f!==void 0&&{voiceProcessing:f},...h!==void 0&&{rawContent:h}};n.push(v)}return this.messages=this.#ce([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:o={},text:r="",llmContent:s,id:i,createdAt:l,sequence:c}=t,p={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(p),...s!==void 0&&{llmContent:s},...i!==void 0&&{id:i},...l!==void 0&&{createdAt:l},...c!==void 0&&{sequence:c}})}async#Qe(t,n,o){let r;try{r=await o()}catch{return}let s=r.blocks.join(`
|
|
25
25
|
|
|
26
26
|
`),i=[s,n].filter(Boolean).join(`
|
|
27
27
|
|
|
28
|
-
`),l=Array.isArray(t.contentParts)&&t.contentParts.length>0,c=r.contentParts.length>0;if(l){let p=[];s&&p.push(So(s)),p.push(...r.contentParts),p.push(...t.contentParts),t.contentParts=p}else if(c){let p=[];i&&p.push(So(i)),p.push(...r.contentParts),t.contentParts=p}else s&&(t.llmContent=i);Object.keys(r.context).length>0&&(t.mentionContext=r.context)}async sendMessage(t,n){let o=t.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.#U&&!n?.voiceTurn&&(this.#U.failed=!0,this.#U=null),(this.#H||this.#M||this.#b||this.#_)&&await this.#Oe(),this.stopSpeaking(),this.abortController?.abort(),this.#me(),this.#le++,this.#ye();let s=n?.voiceTurn?.userMessageId,i=s?this.messages.find(h=>h.id===s&&h.role==="user"):void 0,l=i?.id??Ha(),c=Ps();this.#s=null;let p=n?.contentParts&&Pa(n.contentParts)?Ta:"",d={id:l,role:"user",content:o||p,createdAt:new Date().toISOString(),sequence:this.#V(),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??{}};i?(i.viaVoice=!0,delete i.voiceCaption,i.content.trim()!==o&&(i.llmContent=o),this.callbacks.onMessagesChanged([...this.messages])):this.#J(d),this.#P(!0);let g=new AbortController;if(this.abortController=g,n?.mentions){let h=this.messages.find(y=>y.id===l)??d;if(await this.#Qe(h,o,n.mentions.finalize),g.signal.aborted||this.abortController!==g)return;this.callbacks.onMessagesChanged([...this.messages])}if(n?.quote&&!n.replayFields){let h=this.messages.find(v=>v.id===l)??d,y=kw({quote:n.quote,text:h.llmContent??h.content,contentParts:h.contentParts});y.contentParts&&(h.contentParts=y.contentParts),y.llmContent!==void 0&&(h.llmContent=y.llmContent),(y.contentParts||y.llmContent!==void 0)&&(h.quote={...n.quote},this.callbacks.onMessagesChanged([...this.messages]))}let f=i?[...this.messages.filter(h=>h!==i),{...i,createdAt:new Date().toISOString()}]:[...this.messages];try{await this.#Ye(f,g,c,l,{composerOptions:n?.composerOptions,interrupt:n?.interrupt})}catch(h){if(this.status==="resuming"||this.#r)return;this.#U&&(this.#U.failed=!0);let y=h instanceof Error&&(h.name==="AbortError"||h.message.includes("aborted")||h.message.includes("abort"));if(!y){let v=um(h,this.config.errorMessage);if(v){let C={id:c,role:"assistant",createdAt:new Date().toISOString(),content:v,sequence:this.#V()};this.#J(C)}}this.#z("idle"),this.#P(!1),this.abortController=null,y||(h instanceof Error?this.callbacks.onError?.(h):this.callbacks.onError?.(new Error(String(h))))}}resubmitFrom(t,n){let o=Lw(this.messages,t);if(!o)return!1;let r=this.messages[o.start],s=n.replacement,i=s?s.text:r.content,l=s?s.contentParts:r.contentParts;if(!(!!i?.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}},d=s?this.#Je(s.options):r.composerOptions,g=s?s.contentSegments:r.contentSegments,f=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(i??"",{...l?.length?{contentParts:[...l]}:{},...g?.length?{contentSegments:[...g]}:{},...d?{composerOptions:d}:{},...f?{quote:f}:{},...p&&Object.keys(p).length>0?{replayFields:p}:{},viaVoice:h===!0}),!0}#Je(t){if(!t)return;let n={};return t.selectedModelId&&(n.selectedModelId=t.selectedModelId),t.activeModeIds?.length&&(n.activeModeIds=[...t.activeModeIds]),Object.keys(n).length>0?n:void 0}async continueConversation(){if(this.streaming)return;(this.#H||this.#M||this.#b||this.#_)&&await this.#Oe(),this.abortController?.abort(),this.#ye();let t=Ps();this.#s=null,this.#P(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(r){if(this.status==="resuming"||this.#r)return;let s=r instanceof Error&&(r.name==="AbortError"||r.message.includes("aborted")||r.message.includes("abort"));if(!s){let i=um(r,this.config.errorMessage);if(i){let l={id:t,role:"assistant",createdAt:new Date().toISOString(),content:i,sequence:this.#V()};this.#J(l)}}this.#z("idle"),this.#P(!1),this.abortController=null,s||(r instanceof Error?this.callbacks.onError?.(r):this.callbacks.onError?.(new Error(String(r))))}}async connectStream(t,n){if(this.streaming&&!n?.allowReentry)return;n?.allowReentry||this.abortController?.abort(),n?.preserveAssistantId&&n.assistantMessageId&&(this.#s=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,r=!1;for(let i of this.messages)i.streaming&&i.id!==o&&(i.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.#P(!0);let s={};try{await this.client.processStream(t,i=>{let l=this.#n;this.#n=s;try{this.handleEvent(i)}finally{this.#n=l}},n?.assistantMessageId,n?.seedContent),this.#ke(s)}catch(i){if(this.status==="resuming"||this.#r){this.#pt(s);return}this.#ke(s),this.#z("error"),this.webMcpResolveControllers.size===0&&(this.#P(!1),this.abortController=null),this.callbacks.onError?.(i instanceof Error?i:new Error(String(i)))}}#Be(){let t=this.config.webmcp;t?.enabled===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){try{if(this.config.webmcp?.autoApprove?.(t)===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.#c}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:t.description??`Allow the assistant to run ${t.toolName}?`,parameters:t.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(t,n){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let r=this.messages.find(s=>s.id===t);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}#Ze;#le;#Se(t){let n=this.#Ze??={s:this,setStreaming:s=>this.#P(s),appendMessage:s=>this.#J(s),nextSequence:()=>this.#V(),settleApprovalPausedToolCall:s=>this.#Ne(s),resumeAfter:s=>this.#t?.executionId===s?this.#t.lastEventId:void 0},o=FC();if(o)return t(o,n);let r=this.#le;return Gf().then(s=>r===this.#le?t(s,n):void 0,s=>{this.callbacks.onError?.(s instanceof Error?s:new Error(String(s)))})}resolveApproval(t,n,o){return this.#Se((r,s)=>r.resolveApproval(s,t,n,o))}resolveAskUserQuestion(t,n){return this.#Se((o,r)=>o.resolveAskUserQuestion(r,t,n))}resolveWebMcpToolCall(t){return this.#Se((n,o)=>n.resolveWebMcpToolCall(o,t))}persistAskUserQuestionProgress(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}#et(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.id;if(!n||!o){let s=this.#l;queueMicrotask(()=>{s===this.#l&&this.resolveWebMcpToolCall(t)});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(t))}#tt(){if(this.webMcpAwaitBatches.size===0)return;let t=this.#l;queueMicrotask(()=>{if(t===this.#l)for(let n of[...this.webMcpAwaitBatches.keys()])this.#nt(n)})}#nt(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.#Se((r,s)=>r.resolveWebMcpToolCallBatch(s,t,o))}#me(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.#l++}cancel(){this.abortController?.abort(),this.abortController=null,this.#ye(),this.#me(),this.#le++,this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.#P(!1),this.#z("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#ye(),this.#me(),this.#le++,this.messages=[],this.agentExecution=null,this.#Te(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#P(!1),this.#z("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.#g}selectArtifact(t){this.#g=t,this.#he()}clearArtifacts(){this.#Te()}upsertArtifact(t){let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=t.artifactType==="markdown"?{id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{}}:{id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:t.props??{},...t.presentation?{presentation:t.presentation}:{}};return this.artifacts.set(n,o),this.#g=n,this.#he(),t.transcript!==!1&&this.#ot(o),o}#ot(t){let n=`artifact-ref-${t.id}`,o=or(this.config.features?.artifacts,t),r=El(o,{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:"complete",...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...t.component?{component:t.component}:{},...t.props?{componentProps:t.props}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}),s=this.messages.find(i=>i.id===n);if(s){s.rawContent=r,s.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:n,content:"",rawContent:r})}#_e(){let t=!1;for(let n of this.artifacts.values()){let o=this.messages.find(i=>i.id===`artifact-ref-${n.id}`);if(!o)continue;let r=or(this.config.features?.artifacts,n),s=El(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",t=!0)}t&&this.callbacks.onMessagesChanged([...this.messages])}#Te(){this.artifacts.size===0&&this.#g===null||(this.artifacts.clear(),this.#g=null,this.#he())}#he(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.#g})}#rt(t){switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:"",...t.file?{file:t.file}:{}}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:t.component??"",props:{}}),this.#g=t.id;break}case"artifact_delta":{let n=this.artifacts.get(t.id);n?.artifactType==="markdown"&&(n.markdown=(n.markdown??"")+t.artDelta);break}case"artifact_update":{let n=this.artifacts.get(t.id);n?.artifactType==="component"&&(n.props={...n.props,...t.props},t.component&&(n.component=t.component));break}case"artifact_complete":{let n=this.artifacts.get(t.id);n&&(n.status="complete");break}default:return}this.#he()}hydrateMessages(t){this.abortController?.abort(),this.abortController=null,this.#ye(),this.#me(),this.#le++,this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.#ce(t.map(n=>({...n,streaming:!1,sequence:n.sequence??this.#V()}))),this.#P(!1),this.#z("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let o of t)this.artifacts.set(o.id,{...o,status:"complete"});this.#g=n,this.#he()}#st(t){let n=this.agentExecution?.executionId;if(!n||!this.#s||this.agentExecution?.status!=="running")return;let o=this.#t===null;this.#t={executionId:n,lastEventId:t,assistantMessageId:this.#s,status:"running"},this.#dt(o)}#it(){return this.#t!==null&&typeof this.config.reconnectStream=="function"&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.#De()}#De(){return this.messages.some(t=>t.agentMetadata?.awaitingLocalTool===!0&&t.agentMetadata?.askUserQuestionAnswered!==!0||t.variant==="approval"&&t.approval?.status==="pending")}#Pe(){this.#r||!this.#t||typeof this.config.reconnectStream!="function"||(this.#r=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.#t}),this.#P(!0),this.#z("resuming"),this.#at().then(t=>{this.#r&&this.#t&&t.begin()}))}#at(){return this.#p?Promise.resolve(this.#p):(this.#f||(this.#f=Nw().then(({createReconnectController:t})=>{let n=t(this.#lt());return this.#p=n,n}),this.#f.catch(()=>{this.#f=null})),this.#f)}#lt(){let t=this;return{get config(){return t.config},getResumable:()=>t.#t,clearResumable:()=>t.#Ae(),getStatus:()=>t.status,setStatus:n=>t.#z(n),setStreaming:n=>t.#P(n),setReconnecting:n=>{t.#r=n},setAbortController:n=>{t.abortController=n},getMessages:()=>t.messages,notifyMessagesChanged:()=>t.callbacks.onMessagesChanged([...t.messages]),resumeConnect:(n,o,r)=>t.connectStream(n,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:n=>t.#J(n),nextSequence:()=>t.#V(),emitReconnect:n=>t.callbacks.onReconnect?.(n),buildErrorContent:n=>um(new Error(n),t.config.errorMessage),onError:n=>t.callbacks.onError?.(n)}}reconnectNow(){if(this.#r){this.#p?.wake();return}this.#Pe()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.#r)return;let n=this.#ct();n||(n=Ps(),this.#J({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.#V()})),this.#s=n,this.agentExecution||(this.agentExecution={executionId:t.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.#t={executionId:t.executionId,lastEventId:t.after,assistantMessageId:n,status:"running"},this.#Pe()}#ct(){for(let t=this.messages.length-1;t>=0;t--){let n=this.messages[t];if(n.role==="assistant"&&!n.variant)return n.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),n.id;if(n.role==="user")break}return null}#ye(){this.#r=!1,this.#p?.teardown(),this.#Ae()}#Ae(){this.#i&&(clearTimeout(this.#i),this.#i=null);let t=this.#t!==null;this.#t=null,t&&this.config.onExecutionState?.(null)}#dt(t){let n=this.config.onExecutionState;if(n){if(t){this.#i&&(clearTimeout(this.#i),this.#i=null),n(this.#t);return}this.#i||(this.#i=setTimeout(()=>{this.#i=null,this.config.onExecutionState?.(this.#t)},500))}}getResumableHandle(){return this.#t}#z(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}#P(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&(this.#ke(void 0),this.speakLatestAssistantMessage())}speakLatestAssistantMessage(t){let n=this.config.textToSpeech;if(!n?.enabled||!(!n.provider||n.provider==="browser"||n.provider==="runtype"&&n.browserFallback))return;let r=[...this.messages].reverse().find(i=>i.role==="assistant"&&i.content&&!i.voiceProcessing);if(!r||t&&!t.includes(r.id))return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let s=cm(r.content);s.trim()&&this.readAloud.play(r.id,{text:s,voice:n.voice,rate:n.rate,pitch:n.pitch})}static pickBestVoice(t){return Ia(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let o=cm(n.content||"");if(!o.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(t,{text:o,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}#ke(t){for(let[n,o]of[...this.#e])o===t&&(this.#e.delete(n),this.#Ne(n))}#pt(t){for(let[n,o]of this.#e)o===t&&this.#e.set(n,void 0)}#Ne(t){let n=this.messages.find(l=>l.id===t)?.approval,o=n?.toolCallId,r=o&&this.messages.find(l=>l.toolCall?.id===o),s=r&&r.toolCall;if(!s||s.status==="complete"||n.status==="pending")return;let i={...s,status:"complete",approvalStatus:n.status,completedAt:Date.now(),...n.status==="approved"?{superseded:!0}:{success:!1,error:n.status==="denied"?"Denied":"Approval timed out"}};this.upsertMessage({...r,streaming:!1,toolCall:i})}#J(t){let n=this.#Ce(t);this.messages=this.#ce([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.#Ce(t),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.#J(n);return}this.messages=this.messages.map((r,s)=>{if(s!==o)return r;let i={...r,...n};r.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(i.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(i.agentMetadata={...i.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1});let l=r.agentMetadata?.clientToolAnswer;if(l&&i.agentMetadata&&!i.agentMetadata.clientToolAnswer&&(i.agentMetadata={...i.agentMetadata,clientToolAnswer:l}),r.approval&&n.approval&&r.approval.id===n.approval.id){let g=r.approval,f=n.approval;i.approval={...g,...f,executionId:f.executionId||g.executionId,toolName:f.toolName||g.toolName,description:f.description||g.description,toolType:f.toolType??g.toolType,reason:f.reason??g.reason,parameters:f.parameters??g.parameters,toolCallId:f.toolCallId??g.toolCallId}}let c=n.toolCall?.name,p=n.agentMetadata?.executionId,d=n.toolCall?.id;if(c&&Fw(c)&&p&&d&&n.agentMetadata?.awaitingLocalTool===!0){let g=`${p}:${d}`,f=this.webMcpInflightKeys.has(g),h=this.webMcpResolvedKeys.has(g),y=r.toolCall?.name,v=r.agentMetadata?.executionId===p&&r.toolCall?.id===d&&y!==void 0&&Fw(y)&&r.toolCall?.status==="complete";(f||h||v)&&(i.agentMetadata={...i.agentMetadata??{},awaitingLocalTool:!1},i.toolCall=r.toolCall,i.streaming=r.streaming)}return i}),this.messages=this.#ce(this.messages),this.callbacks.onMessagesChanged([...this.messages])}#Ce(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.#V()}}#V(){return this.#o++}#ce(t){return[...t].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 i=n.sequence??0,l=o.sequence??0;return i!==l?i-l:n.id.localeCompare(o.id)})}};Je();var Ao=require("lucide");Lr();kt();Nr();var hk={add:e=>PC(e)},yk=e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0,Ip={allowedTypes:Dr,maxFileSize:10*1024*1024,maxFiles:4};function bk(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function vk(e){return e==="application/pdf"?Ao.FileText:e.startsWith("text/")?Ao.FileText:e.includes("word")?Ao.FileText:e.includes("excel")||e.includes("spreadsheet")?Ao.FileSpreadsheet:e==="application/json"?Ao.FileCode:Ao.File}var Ai=class e{constructor(t={}){this.attachments=[];this.#e=null;this.#n=new Map;this.#o=!1;this.config={allowedTypes:t.allowedTypes??Ip.allowedTypes,maxFileSize:t.maxFileSize??Ip.maxFileSize,maxFiles:t.maxFiles??Ip.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange,adapter:t.adapter}}#e;#n;#o;#t(){return typeof this.config.adapter?.add=="function"}#s(){return this.#t()?this.config.adapter:hk}setPreviewsContainer(t){this.#e=t}remountPreviews(t){if(this.#e=t,t){t.innerHTML="";for(let n of this.attachments)this.#g(n)}this.#a()}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:Ip.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange),t.adapter!==void 0&&(this.config.adapter=t.adapter)}isReady(){return this.attachments.every(t=>t.status==="ready")}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart).filter(t=>t!==null)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){if(!t.length||this.#o)return;let n=[];for(let o of t){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(o,"count");continue}let r=kC(o,this.config.allowedTypes,this.config.maxFileSize);if(!r.valid){let i=r.error?.includes("type")?"type":"size";this.config.onFileRejected?.(o,i);continue}let s={id:bk(),file:o,previewUrl:Gd(o)?URL.createObjectURL(o):null,contentPart:null,status:this.#t()?"uploading":"processing",progress:this.#t()?0:void 0};this.attachments.push(s),this.#g(s),n.push(s)}this.#a(),this.#i(),await Promise.all(n.map(o=>this.#r(o)))}async#r(t){let n=new AbortController;this.#n.set(t.id,n);let o=()=>this.#o||n.signal.aborted||this.#n.get(t.id)!==n||!this.attachments.includes(t);try{let r=await this.#s().add(t.file,{signal:n.signal,onProgress:s=>{o()||t.status!=="uploading"||(t.progress=yk(s),this.#l(t),this.#i())}});if(o())return;t.contentPart=r,t.status="ready",t.progress=void 0,t.error=void 0}catch(r){if(o())return;t.status="error",t.progress=void 0,t.error=r instanceof Error?r.message:String(r??"Upload failed")}finally{this.#n.get(t.id)===n&&this.#n.delete(t.id)}this.#l(t),this.#i()}retryAttachment(t){let n=this.attachments.find(o=>o.id===t);!n||n.status!=="error"||this.#o||(n.status=this.#t()?"uploading":"processing",n.progress=this.#t()?0:void 0,n.error=void 0,this.#l(n),this.#i(),this.#r(n))}#p(t){let n=this.#n.get(t);n&&(this.#n.delete(t),n.abort())}removeAttachment(t){let n=this.attachments.findIndex(s=>s.id===t);if(n===-1)return;let o=this.attachments[n];this.#p(t),o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let r=this.#e?.querySelector(`[data-attachment-id="${t}"]`);r&&r.remove(),o.status==="ready"&&o.contentPart&&this.#f(o.contentPart),this.#a(),this.#i()}#f(t){let n=this.config.adapter?.remove;if(n)try{let o=n(t,{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 t of this.attachments)this.#p(t.id),t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.#n.clear(),this.#e&&(this.#e.innerHTML=""),this.#a(),this.#i()}destroy(){if(!this.#o){this.#o=!0;for(let t of this.#n.values())t.abort();this.#n.clear();for(let t of this.attachments)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.#e=null}}#i(){this.#o||this.config.onAttachmentsChange?.(this.getAttachments())}#g(t){if(!this.#e)return;let n=Gd(t.file),o=x("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",t.id),o.style.width="48px",o.style.height="48px",n&&t.previewUrl){let d=x("img");d.src=t.previewUrl,d.alt=t.file.name,d.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",d.style.width="48px",d.style.height="48px",d.style.objectFit="cover",d.style.borderRadius="8px",o.appendChild(d)}else{let d=x("div");d.style.width="48px",d.style.height="48px",d.style.borderRadius="8px",d.style.backgroundColor="var(--persona-container, #f3f4f6)",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.display="flex",d.style.flexDirection="column",d.style.alignItems="center",d.style.justifyContent="center",d.style.gap="2px",d.style.overflow="hidden";let g=vk(t.file.type),f=Nt(g,20,"var(--persona-muted, #6b7280)",1.5);f&&d.appendChild(f);let h=x("span");h.textContent=LC(t.file.type,t.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",d.appendChild(h),o.appendChild(d)}let r=Q("div",{className:"persona-attachment-status",attrs:{"data-persona-attachment-status":""}}),s=x("div","persona-attachment-progress");s.appendChild(x("div","persona-attachment-progress__bar"));let i=Q("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),l=ge("rotate-cw",12,"var(--persona-text-inverse, #ffffff)",2);l?i.appendChild(l):i.textContent="\u21BB",i.addEventListener("click",d=>{d.preventDefault(),d.stopPropagation(),this.retryAttachment(t.id)}),r.append(s,i),o.appendChild(r);let c=x("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=Nt(Ao.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",d=>{d.preventDefault(),d.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(c),this.#e.appendChild(o),this.#c(o,t)}#l(t){let n=this.#e?.querySelector(`[data-attachment-id="${t.id}"]`);n&&this.#c(n,t)}#c(t,n){t.dataset.status=n.status;let o=n.status!=="ready"&&n.status!=="error";t.setAttribute("aria-busy",o?"true":"false"),t.title=n.status==="error"?`${n.file.name}: ${n.error??"Upload failed"}`:n.file.name;let r=t.querySelector(".persona-attachment-progress__bar");if(r){let s=n.progress;r.style.width=typeof s=="number"?`${Math.round(s*100)}%`:""}}#a(){this.#e&&(this.#e.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t?.allowedTypes,maxFileSize:t?.maxFileSize,maxFiles:t?.maxFiles,onFileRejected:t?.onFileRejected,onAttachmentsChange:n,adapter:t?.adapter})}};var $w=(e,t)=>e.length===t.length&&e.every((n,o)=>n===t[o]),Ck=(e,t)=>e.length===t.length&&e.every((n,o)=>{let r=t[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 Uw(){let e={text:"",attachments:[],mentionRefs:[],selectedModelId:void 0,activeModeIds:[],quote:void 0,pendingSubmission:void 0,preparing:!1,streaming:!1,inputDisabled:!1,sendDisabled:!1},t=new Set,n=null,o=!1,r=!1,s=()=>e.preparing?"preparing":e.streaming?"streaming":"idle",i=()=>{let d=s();return Object.freeze({text:e.text,attachments:Object.freeze(e.attachments.map(g=>Object.freeze({...g}))),mentionRefs:Object.freeze([...e.mentionRefs]),selectedModelId:e.selectedModelId,activeModeIds:Object.freeze([...e.activeModeIds]),quote:e.quote?Object.freeze({...e.quote}):void 0,pendingSubmission:e.pendingSubmission,phase:d,inputDisabled:e.inputDisabled,sendDisabled:d!=="idle"||e.sendDisabled||e.inputDisabled})},l=()=>(n||(n=i()),n),c=()=>{if(o=!1,r||t.size===0)return;let d=l();for(let g of[...t])try{g(d)}catch(f){typeof console<"u"&&console.error("[AgentWidget] composer state listener failed:",f)}},p=()=>{n=null,!(r||o)&&(o=!0,queueMicrotask(c))};return{getState:l,subscribe:d=>(t.add(d),()=>t.delete(d)),setText:d=>{e.text!==d&&(e.text=d,p())},setAttachments:d=>{Ck(e.attachments,d)||(e.attachments=[...d],p())},setMentionRefs:d=>{$w(e.mentionRefs,d)||(e.mentionRefs=[...d],p())},setSelectedModelId:d=>{e.selectedModelId!==d&&(e.selectedModelId=d,p())},setActiveModeIds:d=>{$w(e.activeModeIds,d)||(e.activeModeIds=[...d],p())},setQuote:d=>{let g=e.quote;g?.text===d?.text&&g?.messageId===d?.messageId&&g?.sourceLabel===d?.sourceLabel||(e.quote=d?{...d}:void 0,p())},setPendingSubmission:d=>{e.pendingSubmission!==d&&(e.pendingSubmission=d,p())},setPreparing:d=>{e.preparing!==d&&(e.preparing=d,p())},setStreaming:d=>{e.streaming!==d&&(e.streaming=d,p())},setInputDisabled:d=>{e.inputDisabled!==d&&(e.inputDisabled=d,p())},setSendDisabled:d=>{e.sendDisabled!==d&&(e.sendDisabled=d,p())},flush:()=>{o&&c()},destroy:()=>{r=!0,o=!1,t.clear()}}}Je();var Qn=(e,...t)=>{for(let n of t){let o=e.querySelector(n);if(o)return o}return null},Vw=(e,t)=>{let n=x("div",e);return n.setAttribute(t,""),n.setAttribute("data-persona-composer-synthesized",""),n.style.display="contents",n};function jw(e,t={}){let n=Qn(e,"[data-persona-composer-form]"),o=Qn(e,"[data-persona-composer-input]");if(!n||!o){let A=`[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(t.debug&&(n||o))throw new Error(A);return typeof console<"u"&&console.warn(A),null}let r={header:Qn(e,"[data-persona-composer-header]"),body:Qn(e,"[data-persona-composer-body]"),actionsStart:Qn(e,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:Qn(e,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:Qn(e,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:Qn(e,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:Qn(e,"[data-persona-composer-status]")},s=new Set,i=r.header;i||(s.add("header"),i=Vw("persona-widget-composer__header","data-persona-composer-header"),n.parentNode?n.parentNode.insertBefore(i,n):e.appendChild(i));let l=r.body??o.parentElement??n,c=(C,A,L,I,H)=>{if(A)return A;s.add(C);let _=Vw(L,I);return H.appendChild(_),_},p=c("actionsStart",r.actionsStart,"persona-widget-composer__left-actions","data-persona-composer-actions-start",n),d=c("actionsEnd",r.actionsEnd,"persona-widget-composer__right-actions","data-persona-composer-actions-end",n),g=c("suggestions",r.suggestions,"persona-widget-composer__suggestions","data-persona-composer-suggestions",e),f=c("status",r.status,"persona-widget-composer__status","data-persona-composer-status",e),h=[],y=(C,A)=>C.target===A.target&&C.type===A.type&&C.handler===A.handler,v=Qn(e,"[data-persona-composer-attachment-input]",'input[type="file"]')??void 0;return{footer:e,form:n,input:o,header:i,body:l,actionsStart:p,actionsEnd:d,suggestions:g,status:f,attachmentInput:v,attachmentPreviews:Qn(e,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:Qn(e,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:Qn(e,"[data-persona-composer-submit]")??void 0,micButton:Qn(e,"[data-persona-composer-mic]")??void 0,synthesized:s,found:r,addListener:(C,A,L,I)=>{C.addEventListener(A,L,I),h.push({target:C,type:A,handler:L,options:I})},removeListener:(C,A,L,I)=>{C.removeEventListener(A,L,I),h=h.filter(H=>!y(H,{target:C,type:A,handler:L}))},destroy:()=>{for(let C of h)C.target.removeEventListener(C.type,C.handler,C.options);h=[]}}}Je();kt();xa();Es();function wk(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function Rp(e){let{anchor:t,content:n,placement:o="bottom-start",offset:r=6,matchAnchorWidth:s=!1,horizontalOffset:i,verticalOffset:l,zIndex:c=2147483e3,onOpen:p,onDismiss:d}=e,g=e.container??wk(t),f=!1,h=null,y=()=>{if(!f)return;let A=t.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${A.width}px`),i&&(n.style.maxWidth=`${A.width}px`);let L=n.getBoundingClientRect(),I=l?.()??null,H=I!=null?A.top+I:A.top,_=o==="top-start"||o==="top-end"?H-r-L.height:A.bottom+r,oe=o==="bottom-end"||o==="top-end"?A.right-L.width:A.left,W=i?.()??null;if(W!=null){let j=Math.max(A.left,A.right-L.width);oe=Math.min(Math.max(A.left+W,A.left),j)}n.style.top=`${_}px`,n.style.left=`${oe}px`},v=()=>{f&&(f=!1,h&&(h(),h=null),n.remove())},C=()=>{if(f)return;f=!0,c!=null&&(n.style.zIndex=String(c)),g.appendChild(n),y();let A=(t.ownerDocument??document).defaultView??window,L=t.ownerDocument??document,I=()=>{if(!t.isConnected){v(),d?.("anchor-removed");return}y()},H=V=>{let oe=typeof V.composedPath=="function"?V.composedPath():[];oe.includes(n)||oe.includes(t)||(v(),d?.("outside"))},_=A.setTimeout(()=>{L.addEventListener("pointerdown",H,!0)},0);A.addEventListener("scroll",I,!0),A.addEventListener("resize",I),h=()=>{A.clearTimeout(_),L.removeEventListener("pointerdown",H,!0),A.removeEventListener("scroll",I,!0),A.removeEventListener("resize",I)},p?.()};return{get isOpen(){return f},open:C,close:v,toggle:()=>f?v():C(),reposition:y,destroy:v}}Je();kt();Es();var Sk='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',Ak=["--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"],gm="data-persona-menu-focus",xk=new Set(["ArrowDown","ArrowUp","Home","End"]);function qw(e){return e.getAttribute("role")==="menuitem"?e:e.querySelector(Sk)??e}var Mk=e=>e.disabled===!0||e.getAttribute("aria-disabled")==="true";function zw(e){let t=e.label,n=!1,o=x("div","persona-send-button-wrapper"),r=Q("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${ro} ${Do}`,attrs:{type:"button","aria-haspopup":"menu","aria-expanded":"false","data-persona-composer-overflow-trigger":""}});o.appendChild(r);let s=Q("div",{className:"persona-composer-overflow-menu",attrs:{role:"menu",tabindex:"-1","data-persona-composer-overflow-menu":""}}),i=()=>{let P=e.getButtonSize?.()??"";r.style.width=P,r.style.height=P,r.style.minWidth=P,r.style.minHeight=P,r.style.lineHeight="1",r.replaceChildren();let J=ge("plus",Xn,"currentColor",1.5);J?r.appendChild(J):r.textContent="+"},l=()=>{r.setAttribute("aria-label",t),r.setAttribute("title",t),s.setAttribute("aria-label",t)};l(),i();let c=[],p=-1,d=!1,g=()=>{let J=s.getRootNode().activeElement;return J instanceof HTMLElement?J:null},f=()=>{let P=g();for(let J of c){let U=!!P&&qw(J)===P;J.toggleAttribute(gm,U&&d)}},h=()=>c.filter(P=>P.isConnected||s.contains(P)).map(qw).filter(P=>!Mk(P)),y=(P,J)=>{P.forEach((U,ue)=>{U.setAttribute("tabindex",ue===J?"0":"-1")})},v=P=>{let J=h();if(J.length===0)return;let U=(P%J.length+J.length)%J.length;p=U,y(J,U),J[U].focus(),f()},C=()=>o.ownerDocument??document,A=null,L=null,I=null,H=()=>{A&&(C().removeEventListener("focusin",A,!0),A=null)},_=()=>{L&&(s.removeEventListener("focusin",L),L=null),I&&(s.removeEventListener("pointerdown",I,!0),I=null)},V=null,oe=()=>(V||(V=Rp({anchor:r,content:s,placement:"top-start",offset:6,onDismiss:()=>{r.setAttribute("aria-expanded","false"),H()}})),V),W=()=>V?.isOpen===!0,j=(P=!1)=>{if(W()){V?.close(),r.setAttribute("aria-expanded","false"),H(),_(),p=-1,d=!1;for(let J of c)J.removeAttribute(gm);P&&r.focus()}},X=(P=0,J=!1)=>{if(n||W())return;d=J,Zd(r,s,Ak),oe().open(),r.setAttribute("aria-expanded","true");let U=h();y(U,-1),v(P<0?U.length-1:P),A=ue=>{let fe=typeof ue.composedPath=="function"?ue.composedPath():[];fe.includes(s)||fe.includes(o)||j()},C().addEventListener("focusin",A,!0),L=()=>f(),s.addEventListener("focusin",L),I=()=>{d=!1},s.addEventListener("pointerdown",I,!0)},E=P=>{P.preventDefault(),P.stopPropagation(),W()?j(!0):X(0)},T=P=>{if(P.key==="ArrowDown"||P.key==="Enter"||P.key===" "){P.preventDefault(),d=!0,W()?v(0):X(0,!0);return}P.key==="ArrowUp"&&(P.preventDefault(),d=!0,W()?v(-1):X(-1,!0))},B=P=>{switch(xk.has(P.key)&&(d=!0),P.key){case"ArrowDown":P.preventDefault(),v(p+1);return;case"ArrowUp":P.preventDefault(),v(p-1);return;case"Home":P.preventDefault(),v(0);return;case"End":P.preventDefault(),v(h().length-1);return;case"Escape":P.preventDefault(),P.stopPropagation(),j(!0);return;case"Tab":j(!0);return;default:}};return r.addEventListener("click",E),r.addEventListener("keydown",T),s.addEventListener("keydown",B),{trigger:o,triggerButton:r,panel:s,setItems:P=>{for(let U of c)P.includes(U)||U.removeAttribute(gm);if(c=[...P],!W())return;let J=h();y(J,Math.min(p,J.length-1)),f()},isOpen:W,open:()=>X(0),close:j,setLabel:P=>{P!==t&&(t=P,l())},applyButtonSize:i,destroy:()=>{n=!0,H(),_(),r.removeEventListener("click",E),r.removeEventListener("keydown",T),s.removeEventListener("keydown",B),V?.destroy(),V=null,o.remove(),s.remove(),c=[]}}}var sr={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},Kw="data-persona-composer-action",fm="data-persona-composer-disable-when-streaming",Ek="core:overflow",Tk=e=>e==="core:attachment"?"attachments":e.startsWith("core:mention")?"mentions":null;function Pk(e,t){if(e===void 0)return null;if(typeof e=="number")return Number.isFinite(e)?e:null;let n=Number.parseFloat(e);if(/^\s*-?\d*\.?\d+(px)?\s*$/.test(e)&&Number.isFinite(n))return n;let o=x("div");o.style.position="absolute",o.style.visibility="hidden",o.style.pointerEvents="none",o.style.height="0",o.style.width=e,t.appendChild(o);let r=o.getBoundingClientRect().width;return o.remove(),Number.isFinite(r)&&r>0?r:Number.isFinite(n)?n:null}function mm(e){let t=e.clientWidth;if(!t)return 0;let n=e.ownerDocument?.defaultView;if(!n?.getComputedStyle)return t;let o=n.getComputedStyle(e),r=(Number.parseFloat(o.paddingLeft)||0)+(Number.parseFloat(o.paddingRight)||0);return Math.max(0,t-r)}var Gw=(e,t)=>{!e||typeof console>"u"||console.warn(t)},kk=(e,t)=>t.includes(":")?t:`${e}:${t}`;function Lk(e){let{debug:t}=e,n=[],o=new Map,r=0,s=l=>{let c=o.get(l.id);if(c){Gw(t,`[Persona] composer action "${l.id}" is already contributed by ${Yw(c)}; the ${Yw(l)} copy is ignored.`);return}o.set(l.id,l),n.push(l)};for(let l of e.builtIns)s({id:l.id,placement:l.placement,presentation:"bar",order:l.order,sequence:r++,source:"core",builtIn:l});let i=(l,c,p)=>{let d=p?kk(p,l.id):l.id,g=l.order??sr.custom;l.placement==="end"&&g>=sr.send&&(Gw(t,`[Persona] composer action "${d}" ordered at ${g} would render after send; clamped to ${sr.send-1}.`),g=sr.send-1),s({id:d,placement:l.placement,presentation:l.presentation??"bar",order:g,sequence:r++,source:c,pluginId:p,action:l})};for(let l of e.configActions??[])i(l,"config");for(let l of e.plugins){if(!l.contributeComposerActions)continue;let c;try{c=l.contributeComposerActions(e.contributionContext)}catch(p){typeof console<"u"&&console.error(`[Persona] plugin "${l.id}" contributeComposerActions failed:`,p);continue}for(let p of c??[])i(p,"plugin",l.id)}return n.sort((l,c)=>l.order===c.order?l.sequence-c.sequence:l.order-c.order)}var Yw=e=>e.source==="plugin"?`plugin "${e.pluginId}"`:e.source==="config"?"composer.actions":"a core built-in",Xw=(e,t,n)=>e===void 0?n:typeof e=="function"?e(t)===!0:e===!0,Hk=e=>e.phase==="streaming"||e.text.trim().length>0||e.attachments.length>0;function Ik(e,t){if(!e||e==="always")return!0;let n=Hk(t);return e==="when-text"?n:!n}var Ls=e=>e.kind==="custom",hm=e=>e instanceof HTMLButtonElement?e:e.querySelector("button")??e,Rk=e=>{let t=hm(e);return t.getAttribute("aria-label")?.trim()||t.getAttribute("title")?.trim()||""},Wk='.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]';function Ok(e){let t="",n=o=>{if(o.nodeType===Node.TEXT_NODE){t+=o.nodeValue??"";return}if(o.nodeType!==Node.ELEMENT_NODE)return;let r=o;typeof r.matches=="function"&&r.matches(Wk)||o.childNodes.forEach(n)};return n(e),t.trim()}var Bk=e=>Ok(e).length===0;function Qw(e){let t=new Map,n=[],o=!1,r=()=>e.getButtonSize?.(),s=(E,T)=>{let B=E.button;if(!B)return;B.setAttribute("role","menuitem"),B.setAttribute("tabindex","-1"),B.className="persona-composer-overflow-menu__item";for(let U of["width","height","minWidth","minHeight","fontSize","color","backgroundColor"])B.style[U]="";B.style.lineHeight="1",T.tooltipText?B.setAttribute("title",T.tooltipText):B.removeAttribute("title"),B.replaceChildren();let P=x("span","persona-composer-overflow-menu__icon");if(T.iconName){let U=ge(T.iconName,16,"currentColor",1.5);U&&P.appendChild(U)}let J=x("span","persona-composer-overflow-menu__label");J.textContent=T.shortLabel??T.label,B.append(P,J)},i=(E,T)=>{let B=E.button;if(!B)return;if(B.setAttribute("aria-label",T.label),T.pressed===void 0?B.removeAttribute("aria-pressed"):B.setAttribute("aria-pressed",T.pressed?"true":"false"),B.toggleAttribute(fm,T.disableWhenStreaming===!0),E.mode==="menu"){E.tooltip?.destroy(),E.tooltip=void 0,s(E,T);return}B.removeAttribute("role"),B.removeAttribute("tabindex"),B.removeAttribute("title");let P=r(),J=!!T.shortLabel;if(B.className=_n("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",ro,Do,J&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),B.style.width=P&&!J?P:"",B.style.height=P??"",B.style.minWidth=P&&!J?P:"",B.style.minHeight=P??"",B.style.fontSize=J?"":"18px",B.style.lineHeight="1",B.style.color=T.iconColor??"",B.style.backgroundColor=T.backgroundColor??"",B.replaceChildren(),T.iconName){let U=ge(T.iconName,Xn,"currentColor",1.5);U&&B.appendChild(U)}if(J){let U=x("span","persona-composer-action-button__label");U.textContent=T.shortLabel,B.appendChild(U)}else B.firstChild||(B.textContent=T.label);E.tooltip?.destroy(),E.tooltip=vn({anchor:B,trigger:E.element,text:()=>T.tooltipText??T.label,enabled:!!T.tooltipText})},l=(E,T)=>{let B=E.action,P=Q("button",{attrs:{type:"button"}}),J=P;if(T==="bar"){let fe=x("div","persona-send-button-wrapper");fe.appendChild(P),J=fe}J.setAttribute(Kw,E.id);let U={resolved:E,element:J,button:P,owned:!0,managed:!0,busy:!1,visible:!0,mode:T},ue=fe=>{if(fe.preventDefault(),fe.stopPropagation(),U.busy||P.disabled)return;let me=U.resolved.action;U.mode==="menu"&&h?.close(!0);let He;try{He=me.onSelect(e.actionContext,fe)}catch(Ee){e.reportError(Ee,{actionId:U.resolved.id});return}!He||typeof He.then!="function"||(U.busy=!0,P.setAttribute("aria-busy","true"),He.catch(Ee=>{e.reportError(Ee,{actionId:U.resolved.id})}).finally(()=>{U.busy=!1,P.removeAttribute("aria-busy")}))};return P.addEventListener("click",ue),U.detach=()=>P.removeEventListener("click",ue),i(U,B),U},c=E=>{let T=E.action,B;try{B=T.render({...e.actionContext,id:E.id,action:T})}catch(P){return e.reportError(P,{actionId:E.id}),null}return B?.element?(B.element.setAttribute(Kw,E.id),B.element.toggleAttribute(fm,T.disableWhenStreaming===!0),{resolved:E,element:B.element,owned:!0,managed:!0,destroy:B.destroy,busy:!1,visible:!0,mode:"bar"}):null},p=(E,T)=>{if(E.builtIn){let P=E.builtIn.element;return P?{resolved:E,element:P,owned:!1,managed:E.builtIn.managed===!0,busy:!1,visible:!0,mode:"bar"}:null}let B=E.action;return B?Ls(B)?c(E):l(E,T):null},d=E=>{if(E.detach?.(),E.tooltip?.destroy(),E.detachMenuSlot?.(),E.detachMenuSlot=void 0,E.menuLabel?.remove(),E.menuLabel=void 0,E.menuSlot?.remove(),E.menuSlot=void 0,E.owned){try{E.destroy?.()}catch(T){e.reportError(T,{actionId:E.resolved.id})}E.element.remove()}},g=(E,T)=>{for(let B=0;B<T.length;B++){let P=T[B];if(!P.managed)continue;let J=null;for(let U=B+1;U<T.length;U++){let ue=T[U];if(!ue.managed&&ue.element.parentElement===E){J=ue.element;break}}J?(P.element.parentElement!==E||P.element.nextSibling!==J)&&E.insertBefore(P.element,J):E.lastChild!==P.element&&E.appendChild(P.element)}},f=(E,T)=>{if(E.button){E.button.disabled=T;return}if(!E.owned)return;let B=E.element;B.toggleAttribute("data-disabled",T),B.setAttribute("aria-disabled",T?"true":"false");let P=B instanceof HTMLButtonElement||B instanceof HTMLSelectElement||B instanceof HTMLInputElement||B instanceof HTMLTextAreaElement?B:B.querySelector("button, select, input, textarea");P&&(P.disabled=T)},h=null,y=null,v=null,C=0,A=()=>{let E=e.getOverflow?.();return E?.enabled===!0?E:void 0},L=()=>(h?h.setLabel(e.getOverflowLabel?.()??"More actions"):h=zw({label:e.getOverflowLabel?.()??"More actions",getButtonSize:r}),h),I=E=>{y!==E&&(v?.disconnect(),y=E,C=mm(E),!(typeof ResizeObserver>"u")&&(v=new ResizeObserver(T=>{let P=T[T.length-1]?.contentRect?.width??mm(E);P!==C&&(C=P,j())}),v.observe(E)))},H=(E,T)=>{let B=Pk(E.collapseAutoActionsBelow,T);if(B===null)return!1;let P=C||mm(T);return P>0&&P<B},_=(E,T,B)=>{if(!T)return"bar";if(E.resolved.builtIn){let J=Tk(E.resolved.id);return J&&T.includeBuiltIns?.includes(J)?"menu":"bar"}let P=E.resolved.presentation;return P==="overflow"||P==="auto"&&B?"menu":"bar"},V=E=>{let T=E.menuSlot;if(!T)return;if(!Bk(E.element)){E.menuLabel?.remove(),E.menuLabel=void 0;return}let B=Rk(E.element);if(!B){E.menuLabel?.remove(),E.menuLabel=void 0;return}E.menuLabel||(E.menuLabel=x("span","persona-composer-overflow-menu__label")),E.menuLabel.textContent!==B&&(E.menuLabel.textContent=B),E.menuLabel.parentElement!==T&&T.appendChild(E.menuLabel)},oe=(E,T)=>{if(E.mode===T)return E;let B=E.resolved.action;if(B&&!Ls(B)){d(E),t.delete(E.resolved.id);let P=l(E.resolved,T);return t.set(E.resolved.id,P),P}if(T==="menu"){let P=Q("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none",[Af]:""}});P.appendChild(E.element),cC(hm(E.element)),E.menuSlot=P;let J=U=>{let ue=hm(E.element);if(ue.disabled)return;let fe=U.target===ue||ue.contains(U.target);h?.close(!0),fe||ue.click()};P.addEventListener("click",J,!0),E.detachMenuSlot=()=>P.removeEventListener("click",J,!0),E.managed=!0,V(E)}else E.detachMenuSlot?.(),E.detachMenuSlot=void 0,E.menuLabel?.remove(),E.menuLabel=void 0,E.menuSlot?.remove(),E.menuSlot=void 0;return E.mode=T,E},W=(E,T)=>{let B=T.map(P=>P.menuSlot??P.element);for(B.forEach((P,J)=>{let U=E.children[J];U!==P&&(U?E.insertBefore(P,U):E.appendChild(P))});E.children.length>B.length;)E.lastElementChild?.remove()},j=()=>{if(o)return;let E=e.getBindings();if(!E)return;let T=e.getState(),B=T.phase==="streaming",P=A();P&&I(E.footer);let J=P?H(P,E.footer):!1,U={start:[],end:[]},ue=[];for(let fe of n){let me=t.get(fe.id);if(!me)continue;let He=fe.action,Ee=He?Xw(He.visible,T,!0)&&Ik(He.visibility,T):!0;if(me.visible!==Ee&&(me.visible=Ee,!Ee&&me.managed&&(me.menuSlot??me.element).remove()),!!Ee){if(me=oe(me,_(me,P,J)),He){let Ie=Xw(He.disabled,T,!1)||He.disableWhenStreaming===!0&&B;f(me,Ie),!Ls(He)&&He.pressed!==void 0&&me.button?.setAttribute("aria-pressed",He.pressed?"true":"false")}me.mode==="menu"?(V(me),ue.push(me)):U[fe.placement].push(me)}}if(ue.length>0){let fe=L();W(fe.panel,ue),fe.setItems(ue.map(Ie=>Ie.menuSlot??Ie.element)),fe.applyButtonSize();let me=Number.isFinite(P?.order)?P?.order:sr.overflow,He=U.start.findIndex(Ie=>Ie.resolved.order>me),Ee={resolved:{id:Ek,placement:"start",presentation:"bar",order:me,sequence:-1,source:"core"},element:fe.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};U.start.splice(He<0?U.start.length:He,0,Ee)}else h&&(h.close(),h.trigger.remove(),h.setItems([]));g(E.actionsStart,U.start),g(E.actionsEnd,U.end)};return{resolve:()=>{if(o)return;let E=Lk(e.collect()),T=new Set(E.map(B=>B.id));for(let[B,P]of t)T.has(B)||(d(P),t.delete(B));for(let B of E){let P=t.get(B.id);if(!P){let fe=p(B,"bar");fe&&t.set(B.id,fe);continue}let J=P.resolved.action,U=B.action;if(!!J!=!!U||J&&U&&Ls(J)!==Ls(U)||J&&U&&Ls(J)&&Ls(U)&&J.render!==U.render){d(P),t.delete(B.id);let fe=p(B,P.mode);fe&&t.set(B.id,fe);continue}P.resolved=B,B.builtIn?(P.managed=B.builtIn.managed===!0||P.mode==="menu",B.builtIn.element&&P.mode==="bar"&&(P.element=B.builtIn.element)):U&&!Ls(U)?i(P,U):U&&P.element.toggleAttribute(fm,U.disableWhenStreaming===!0)}n=E,j()},sync:j,getResolved:()=>n,getOverflowMenu:()=>h,destroy:()=>{if(!o){o=!0,v?.disconnect(),v=null,y=null;for(let E of t.values())d(E);t.clear(),h?.destroy(),h=null,n=[]}}}}Je();kt();Es();var _k="core:model",Dk=700,Jw=16,Nk=["--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"],Zw=()=>{let e=Q("span",{className:"persona-composer-model-picker-wrapper",attrs:{"data-persona-composer-model-picker-wrapper":""}}),t=Q("span",{className:"persona-composer-model-picker-chevron",attrs:{"aria-hidden":"true"}});return{wrapper:e,chevron:t}};function eS(e){let t=e.label??"Model",n=e.presentation??"native",o=null,r=c=>{let p=e.getSelectedModelId();return c.find(d=>d.id===p)??c[0]},s=()=>{let c=Q("select",{className:"persona-composer-model-picker",attrs:{"aria-label":t,"data-persona-composer-model-picker":""}}),p="",d=()=>{let v=e.getModels(),C=v.map(A=>`${A.id}:${A.label}`).join("|");C!==p&&(p=C,c.replaceChildren(...v.map(A=>{let L=Q("option",{attrs:{value:A.id}});return L.textContent=A.label,L}))),c.value=r(v)?.id??""};d(),o=d;let g=()=>{c.value&&e.onSelect(c.value)};c.addEventListener("change",g);let f=v=>v.stopPropagation();c.addEventListener("click",f);let{wrapper:h,chevron:y}=Zw();return h.append(c,y),{element:h,destroy:()=>{o===d&&(o=null),c.removeEventListener("change",g),c.removeEventListener("click",f)}}},i=()=>{let c=Q("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=x("span","persona-composer-model-picker-label"),d=x("span","persona-composer-model-picker-suffix");c.append(p,d);let g=Q("div",{className:"persona-composer-model-menu",attrs:{role:"listbox",tabindex:"-1","aria-label":t,"data-persona-composer-model-menu":""}}),f=new Map,h="",y=null,v=()=>y?.isOpen===!0,C=(T=!1)=>{v()&&(y?.close(),c.setAttribute("aria-expanded","false"),T&&c.focus())},A=T=>{let B=[...f.values()];if(B.length===0)return;let P=(T%B.length+B.length)%B.length;B[P].focus()},L=T=>{if(v())return;y||(y=Rp({anchor:c,content:g,placement:"top-start",offset:6,onDismiss:()=>c.setAttribute("aria-expanded","false")})),Zd(c,g,Nk),y.open(),c.setAttribute("aria-expanded","true");let P=[...f.keys()].indexOf(r(e.getModels())?.id??"");A(T??(P>=0?P:0))},I=T=>{C(!0),e.onSelect(T)},H=T=>{T.preventDefault(),T.stopPropagation();let B=T.currentTarget.getAttribute("data-persona-model-option");B&&I(B)},_=T=>{let B=Q("button",{className:"persona-composer-model-option",attrs:{type:"button",role:"option",tabindex:"-1","aria-selected":"false","data-persona-model-option":T.id}});if(T.icon){let fe=ge(T.icon,Jw,"currentColor",1.5);if(fe){let me=x("span","persona-composer-model-option-icon");me.appendChild(fe),B.appendChild(me)}}let P=x("span","persona-composer-model-option-body"),J=x("span","persona-composer-model-option-label");if(J.textContent=T.label,P.appendChild(J),T.description){let fe=x("span","persona-composer-model-option-description");fe.textContent=T.description,P.appendChild(fe)}B.appendChild(P);let U=x("span","persona-composer-model-option-check");U.setAttribute("aria-hidden","true");let ue=ge("check",Jw,"currentColor",2);return ue&&U.appendChild(ue),B.appendChild(U),B.addEventListener("click",H),B},V=()=>{let T=e.getModels(),B=T.map(U=>`${U.id}:${U.label}:${U.icon??""}:${U.description??""}`).join("|");if(B!==h){h=B;for(let U of f.values())U.removeEventListener("click",H);f.clear(),g.replaceChildren(...T.map(U=>{let ue=_(U);return f.set(U.id,ue),ue}))}let P=r(T);for(let[U,ue]of f)ue.setAttribute("aria-selected",String(U===P?.id));p.textContent=P?.label??"";let J=e.getSuffix?.()??"";d.textContent=J,c.setAttribute("aria-label",[t,[P?.label,J].filter(Boolean).join(" ")].filter(Boolean).join(": "))};V(),o=V;let oe=T=>{T.preventDefault(),T.stopPropagation(),v()?C(!0):L()},W=T=>{if(T.key==="ArrowDown"){T.preventDefault(),v()?A(0):L(0);return}T.key==="ArrowUp"&&(T.preventDefault(),v()?A(-1):L(-1))},j=T=>{let B=[...f.values()],P=B.indexOf(T.target?.closest?.(".persona-composer-model-option"));switch(T.key){case"ArrowDown":T.preventDefault(),A(P+1);return;case"ArrowUp":T.preventDefault(),A(P-1);return;case"Home":T.preventDefault(),A(0);return;case"End":T.preventDefault(),A(B.length-1);return;case"Escape":T.preventDefault(),T.stopPropagation(),C(!0);return;case"Tab":C(!0);return;default:}};c.addEventListener("click",oe),c.addEventListener("keydown",W),g.addEventListener("keydown",j);let{wrapper:X,chevron:E}=Zw();return X.append(c,E),{element:X,destroy:()=>{o===V&&(o=null),c.removeEventListener("click",oe),c.removeEventListener("keydown",W),g.removeEventListener("keydown",j);for(let T of f.values())T.removeEventListener("click",H);f.clear(),y?.destroy(),y=null,g.remove()}}};return{action:{id:_k,kind:"custom",placement:"end",order:Dk,presentation:n==="popover"?"bar":"auto",label:t,render:()=>n==="popover"?i():s()},repaint:()=>o?.()}}Je();kt();Je();var ym="[data-persona-composer-chip-row]";function Wp(e){e.style.display=e.childElementCount>0?"flex":"none"}function bm(e){let t=e.querySelector(ym);if(t)return t;let n=Q("div",{className:"persona-composer-chip-row",attrs:{"data-persona-composer-chip-row":""}});n.style.display="none";let o=e.querySelector("[data-persona-composer-quote], [data-persona-composer-pending]");return o?.parentElement===e?e.insertBefore(n,o):e.appendChild(n),n}var Fk=":scope > [data-persona-composer-mode]";function tS(e){let t=e.row,n="",o=!1,r=new Set(e.initialIds??[]),s=p=>{let d=Q("span",{className:"persona-mention-chip persona-composer-mode-chip",attrs:{"data-persona-composer-mode":p.id}});if(p.iconName){let y=x("span","persona-mention-chip-icon"),v=ge(p.iconName,12,"currentColor",1.5);v&&y.appendChild(v),d.appendChild(y)}let g=x("span","persona-mention-chip-label");g.textContent=p.shortLabel??p.label,d.appendChild(g);let f=Q("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${p.label}`}}),h=ge("x",12,"currentColor",2);return h?f.appendChild(h):f.textContent="\xD7",f.addEventListener("click",y=>{y.preventDefault(),y.stopPropagation(),e.onRemove(p.id)}),d.appendChild(f),d},i=()=>Array.from(t.querySelectorAll(Fk)),l=p=>{p.setAttribute("data-persona-chip-exit",""),p.setAttribute("aria-hidden","true"),p.style.pointerEvents="none";let d=()=>{p.remove(),Wp(t)},g=t.ownerDocument.defaultView,f=typeof g?.getComputedStyle=="function"?g.getComputedStyle(p).animationName:"";if(!f||f==="none"){d();return}p.addEventListener("animationend",d,{once:!0}),p.addEventListener("animationcancel",d,{once:!0})},c=()=>{for(let p of i())p.remove()};return{element:t,render:(p,d)=>{if(o)return;let g=d.filter(v=>p.includes(v.id)),f=g.map(v=>`${v.id}:${v.shortLabel??v.label}`).join("|");if(f===n)return;n=f;let h=new Map;for(let v of i()){let C=v.getAttribute("data-persona-composer-mode");C&&g.some(L=>L.id===C)&&!v.hasAttribute("data-persona-chip-exit")?h.set(C,v):v.hasAttribute("data-persona-chip-exit")||l(v)}let y=t.firstChild;for(let v of g){let C=h.get(v.id);C||(C=s(v),r.has(v.id)||(C.setAttribute("data-persona-chip-enter",""),C.addEventListener("animationend",()=>C?.removeAttribute("data-persona-chip-enter"),{once:!0}))),r.delete(v.id),C!==y&&t.insertBefore(C,y),y=C.nextSibling}Wp(t)},destroy:()=>{o=!0,c(),Wp(t)}}}Je();kt();var nS=e=>`core:mode:${e}`;var vm=e=>Math.min(300+e,499),oS=e=>`core:mode-group:${e}`;function Op(e,t){return e?t?.find(n=>n.id===e)?.presentation==="segmented":!1}function $k(e,t){return e?t?.find(n=>n.id===e)?.chipVisibility==="hidden":!1}function rS(e,t){return e?.length?e.filter(n=>!Op(n.groupId,t)&&!$k(n.groupId,t)):[]}var Uk=(e,t)=>e.groupId?t?.find(n=>n.id===e.groupId)?.selection??null:null;function sS(e,t,n,o){let r=n.find(l=>l.id===t);if(!r)return[...e];let s=e.includes(t),i=new Set(e);if(s)i.delete(t);else{if(Uk(r,o)==="single"){let l=n.filter(c=>c.groupId===r.groupId).map(c=>c.id);i=new Set([...i].filter(c=>!l.includes(c)))}i.add(t)}return n.filter(l=>i.has(l.id)).map(l=>l.id)}function Bp(e,t){return t?.length?t.filter(n=>e.includes(n.id)).map(n=>n.id):[]}function iS(e,t){return t?.length?t.filter(n=>e.includes(n.id)&&(n.persistence??"sticky")!=="once").map(n=>n.id):[]}function aS(e,t){if(!(!t?.length||e.length===0))return t.find(n=>e.includes(n.id)&&n.placeholder)?.placeholder}var Vk=16;function lS(e){let t=null;return{action:{id:oS(e.groupId),kind:"custom",placement:"start",presentation:"bar",label:e.getGroup()?.label??e.groupId,render:()=>{let o=Q("div",{className:"persona-composer-segmented",attrs:{"data-persona-composer-mode-group":e.groupId}}),r=new Map,s="",i=p=>{p.preventDefault(),p.stopPropagation();let g=p.currentTarget.getAttribute("data-persona-composer-mode");!g||e.getActiveIds().includes(g)&&e.getGroup()?.selection==="single"||e.onSelect(g)},l=p=>{let d=Q("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":p.id,"aria-label":p.label}});if(p.iconName){let f=ge(p.iconName,Vk,"currentColor",1.5);f&&d.appendChild(f)}let g=x("span","persona-composer-segmented-label");return g.textContent=p.shortLabel??p.label,d.appendChild(g),d.addEventListener("click",i),d},c=()=>{let p=e.getGroup();p?.label?(o.setAttribute("role","group"),o.setAttribute("aria-label",p.label)):(o.removeAttribute("role"),o.removeAttribute("aria-label"));let d=e.getModes(),g=d.map(h=>`${h.id}:${h.shortLabel??h.label}:${h.iconName??""}`).join("|");if(g!==s){s=g;for(let y of r.values())y.removeEventListener("click",i);r.clear();let h=d.map(y=>{let v=l(y);return r.set(y.id,v),v});o.replaceChildren(...h)}let f=e.getActiveIds();for(let[h,y]of r)y.setAttribute("aria-pressed",String(f.includes(h)))};return c(),t=c,{element:o,destroy:()=>{t===c&&(t=null);for(let p of r.values())p.removeEventListener("click",i);r.clear()}}}},repaint:()=>t?.()}}Je();kt();function cS(e){let t=Q("div",{className:"persona-composer-quote",attrs:{"data-persona-composer-quote":""}});t.style.display="none";let n="",o=!1,r=s=>{let i=x("span","persona-composer-quote-bar"),l=x("div","persona-composer-quote-content");if(s.sourceLabel){let g=x("div","persona-composer-quote-source");g.textContent=s.sourceLabel,l.appendChild(g)}let c=Q("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});c.textContent=kp(s.text),l.appendChild(c);let p=Q("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":e.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),d=ge("x",12,"currentColor",2);d?p.appendChild(d):p.textContent="\xD7",p.addEventListener("click",g=>{g.preventDefault(),g.stopPropagation(),e.onDismiss()}),t.replaceChildren(i,l,p)};return{element:t,render:s=>{if(o)return;let i=s?`${s.sourceLabel??""}\0${s.text}`:"";if(i!==n){if(n=i,!s){t.replaceChildren(),t.style.display="none";return}r(s),t.style.display="flex"}},destroy:()=>{o=!0,t.replaceChildren(),t.remove()}}}Je();kt();function dS(e){let t=Q("div",{className:"persona-composer-pending",attrs:{"data-persona-composer-pending":""}});t.style.display="none";let n,o=!1,r=(i,l,c,p)=>{let d=Q("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":l,[c]:""}}),g=ge(i,12,"currentColor",2);return g?d.appendChild(g):d.textContent=l,d.addEventListener("click",f=>{f.preventDefault(),f.stopPropagation(),p()}),d},s=i=>{let l=kp(i.text??"",90);if(l)return l;let c=i.contentParts?.length??0;return c>0?c===1?"1 attachment":`${c} attachments`:(i.mentionRefs?.length??0)>0?i.mentionRefs.map(d=>d.label).join(", "):"Queued message"};return{element:t,render:i=>{if(o||i===n)return;if(n=i,!i){t.replaceChildren(),t.style.display="none";return}let l=x("span","persona-composer-pending-badge");l.textContent=e.label??"Sends next";let c=Q("div",{className:"persona-composer-pending-text",attrs:{"data-persona-composer-pending-text":""}});c.textContent=s(i),t.replaceChildren(l,c,r("pencil",e.editLabel??"Edit queued message","data-persona-composer-pending-edit",e.onEdit),r("x",e.removeLabel??"Remove queued message","data-persona-composer-pending-remove",e.onRemove)),t.style.display="flex"},destroy:()=>{o=!0,t.replaceChildren(),t.remove()}}}Je();function pS(e){let t=Q("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":e.messageId,"data-preserve-runtime":""}}),n=Q("textarea",{className:"persona-message-edit-input",attrs:{rows:"1",dir:"auto","aria-label":"Edit message","data-persona-message-edit-input":""}});n.value=e.initialText;let o=()=>{n.style.height="auto",n.style.height=`${n.scrollHeight}px`};n.addEventListener("input",o);let r=x("div","persona-message-edit-actions"),s=(l,c,p,d)=>{let g=Q("button",{className:`persona-message-edit-button ${c}`,attrs:{type:"button",[p]:""},text:l});return g.addEventListener("click",f=>{f.preventDefault(),f.stopPropagation(),d()}),g},i=()=>{let l=n.value.trim();l&&e.onSave(l)};return r.append(s(e.cancelLabel??"Cancel","persona-message-edit-cancel","data-persona-message-edit-cancel",e.onCancel),s(e.saveLabel??"Send","persona-message-edit-save","data-persona-message-edit-save",i)),n.addEventListener("keydown",l=>{if(l.key==="Escape"){l.preventDefault(),l.stopPropagation(),e.onCancel();return}l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),i())}),t.append(n,r),{element:t,getValue:()=>n.value,focus:()=>{n.focus();let l=n.value.length;n.setSelectionRange(l,l),o()},destroy:()=>{t.replaceChildren(),t.remove()}}}function uS(e){let t=e.text??"";if(t.trim().length>0||(e.mentionRefs?.length??0)>0||(e.activeModeIds?.length??0)>0||e.quote||e.selectedModelId)return{text:t,...e.mentionRefs?.length?{mentionRefs:[...e.mentionRefs]}:{},...e.contentSegments?.length?{contentSegments:[...e.contentSegments]}:{},...e.selectedModelId?{selectedModelId:e.selectedModelId}:{},...e.activeModeIds?.length?{activeModeIds:[...e.activeModeIds]}:{},...e.quote?{quote:{...e.quote}}:{}}}function gS(e,t){if(!e||typeof e.text!="string")return;let n=new Set(t.mentionSourceIds),o=(e.mentionRefs??[]).filter(c=>n.has(c.sourceId)),r=o.length===(e.mentionRefs?.length??0)&&o.length>0,s=new Set(t.modes.map(c=>c.id)),i=(e.activeModeIds??[]).filter(c=>s.has(c)),l=e.selectedModelId&&t.modelIds.includes(e.selectedModelId)?e.selectedModelId:void 0;return{text:e.text,...r?{mentionRefs:o}:{},...r&&e.contentSegments?.length?{contentSegments:e.contentSegments}:{},...l?{selectedModelId:l}:{},...i.length?{activeModeIds:i}:{},...e.quote?.text?{quote:e.quote}:{}}}function fS(e){let t=e.delay??500,n=null,o=!1,r=()=>{n!==null&&(clearTimeout(n),n=null)};return{schedule:()=>{o||(r(),n=setTimeout(()=>{n=null,e.write()},t))},flush:()=>{o||n===null||(r(),e.write())},cancel:r,destroy:()=>{o=!0,r()}}}function mS(e){return e.wrapped||e.text.includes(`
|
|
29
|
-
`)?!1:!(e.hasAttachments||e.hasChips||e.hasQuote||e.hasPendingSubmission)}function hS(){let e=!1;return{observe:(t,n)=>n?(t&&(e=!0),e):(e=!1,!1),release:()=>{e=!1}}}function yS(e){if(!e)return!1;let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return!1;let n=t.getComputedStyle(e),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 i=(Number.parseFloat(n.paddingTop)||0)+(Number.parseFloat(n.paddingBottom)||0);return e.scrollHeight-i>s*1.5}function bS(e){e&&(typeof e.requestSubmit=="function"?e.requestSubmit():e.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})))}Jd();function Cm(e){return Object.freeze({text:e.text,contentParts:e.contentParts?Object.freeze([...e.contentParts]):void 0,mentionRefs:Object.freeze([...e.mentionRefs]),contentSegments:e.contentSegments?Object.freeze([...e.contentSegments]):void 0,options:Object.freeze({...e.options}),viaVoice:e.viaVoice})}function CS(e){return e.inputDisabled===!0||e.sendDisabled===!0||e.hasAttachments&&!e.attachmentsReady?!1:!!e.text||e.hasAttachments||e.hasMentions||e.hasServerMentions}var jk=e=>typeof e?.then=="function";function vS(e,t){return t===!1?{status:"canceled"}:!t||typeof t!="object"?{status:"proceed"}:(typeof t.text=="string"&&(e.text=t.text),t.options&&(e.options={...e.options,...t.options}),{status:"proceed"})}function wS(e,t,n){let o;try{o=e(Cm(t),{signal:n})}catch(r){return{status:"error",error:r}}return jk(o)?Promise.resolve(o).then(r=>n.aborted?{status:"aborted"}:vS(t,r),r=>n.aborted?{status:"aborted"}:{status:"error",error:r}):vS(t,o)}$f();Uf();Ff();Nr();var _p=e=>e?.launcher?.variant??(e?.future?.v5Defaults===!0?"circle":"pill"),Dp={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"};wo();wo();var Fp="16px",$p="transparent",qk=(()=>{let e={};for(let t of[0,1,2,3,4,5,6,8,10,12,16,20,24,32,40,48,56,64])e[t]=t===0?"0px":`${t/4}rem`;return e})(),Kl={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:qk,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"}},Np={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"}},so={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:vi,maxWidth:"none",height:"min(640px, max(200px, calc(100vh - 64px)))",maxHeight:"none",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:Fp,canvasBackground:$p,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"}}},zk=Kl.colors.gray,Kk={50:"#fafafa",100:"#f5f5f5",200:"#e5e5e5",300:"#d4d4d4",400:"#a3a3a3",500:"#737373",600:"#525252",700:"#404040",800:"#262626",900:"#171717",950:"#0a0a0a"},AS={...Kl,colors:{...Kl.colors,gray:zk}},Gk={...Kl,colors:{...Kl.colors,gray:Kk},radius:{none:"0px",sm:"4px",md:"8px",lg:"12px",xl:"16px","2xl":"24px",full:"9999px"}},xS=AS,MS=Np,Yk={...Np,colors:{...Np.colors,surface:"#ffffff",background:"#ffffff",container:"semantic.colors.surface",textInverse:"#ffffff"},typography:{...Np.typography,fontSize:"14px",lineHeight:"1.5"}},ES=MS,Up=so,Xk={...so,launcher:Dp,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:{...so.input,borderRadius:"palette.radius.full"},introCard:{...so.introCard,title:{fontSize:"22px",fontWeight:"500"}},suggestion:{chip:{...so.suggestion.chip,fontWeight:"400"},card:{...so.suggestion.card,fontWeight:"400"},list:{...so.suggestion.list,fontWeight:"400"}},panel:{...so.panel,width:"min(400px, calc(100vw - 24px))",height:"min(704px, calc(100dvh - 104px))",borderRadius:"palette.radius.xl"},header:{...so.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:{...so.message,gap:"20px",fullscreenGap:"28px",topFadeHeight:"18px",user:{...so.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:{...so.message.assistant,background:"transparent",border:"transparent",borderWidth:"0px",borderRadius:"0px",shadow:"none",padding:"0px",fontSize:"14px",lineHeight:"1.55"}},composer:{...so.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)"}},TS=Up,Qk=e=>Ms({future:e}),Sm=e=>Qk(e)==="v5"?{palette:Gk,semantic:Yk,components:Xk}:{palette:AS,semantic:MS,components:Up};function wn(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),o=e;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."))?wn(e,o):o}function Vp(e){let t={};function n(o,r){for(let[s,i]of Object.entries(o)){let l=`${r}.${s}`;if(typeof i=="string"){let c=wn(e,i);c!==void 0&&(t[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 i=="object"&&i!==null&&n(i,l)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function Am(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function PS(e,t){let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];s&&typeof s=="object"&&!Array.isArray(s)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=PS(s,r):n[o]=r}return n}function Jk(e,t){return t?PS(e,t):e}function Gl(e,t={}){let n=Sm(t.future),o={palette:n.palette,semantic:n.semantic,components:n.components},r={palette:{...o.palette,...e?.palette,colors:{...o.palette.colors,...e?.palette?.colors},spacing:{...o.palette.spacing,...e?.palette?.spacing},typography:{...o.palette.typography,...e?.palette?.typography},shadows:{...o.palette.shadows,...e?.palette?.shadows},borders:{...o.palette.borders,...e?.palette?.borders},radius:{...o.palette.radius,...e?.palette?.radius}},semantic:{...o.semantic,...e?.semantic,colors:{...o.semantic.colors,...e?.semantic?.colors,interactive:{...o.semantic.colors.interactive,...e?.semantic?.colors?.interactive},feedback:{...o.semantic.colors.feedback,...e?.semantic?.colors?.feedback}},spacing:{...o.semantic.spacing,...e?.semantic?.spacing},typography:{...o.semantic.typography,...e?.semantic?.typography}},components:Jk(o.components,e?.components)},s=e?.components?.activity;for(let p of["toolBubble","reasoningBubble"])for(let d of["rowHeight","labelSize","iconSize","indent","bodySurface"])s?.[d]!==void 0&&(r.components[p][d]=s[d]);let i=e?.components?.collapsibleWidget?.surface;i!==void 0&&s?.bodySurface===void 0&&(r.components.activity={...r.components.activity,bodySurface:i});let l=e?.components?.header;l?.padding!==void 0&&l.minimalPadding===void 0&&(r.components.header.minimalPadding=r.components.header.padding);let c=e?.components?.message;if(c?.gap!==void 0&&c.fullscreenGap===void 0&&(r.components.message.fullscreenGap=r.components.message.gap),t.validate!==!1){let p=Am(r);if(!p.valid)throw new Error(`Theme validation failed: ${p.errors.map(d=>d.message).join(", ")}`)}if(t.plugins)for(let p of t.plugins)r=p.transform(r);return r}var wm=e=>e.trim()==="0"?"0px":e,SS="--persona-",Zk=e=>{if(!e)return;let t=e.trim().toLowerCase(),n;if(t.charCodeAt(0)===35){let i=t.slice(1);if(!/^[0-9a-f]+$/.test(i))return;i.length===3||i.length===4?n=[0,1,2].map(l=>parseInt(i[l]+i[l],16)):(i.length===6||i.length===8)&&(n=[0,2,4].map(l=>parseInt(i.slice(l,l+2),16)))}else{let i=t.match(/^rgba?\(([^)]+)\)$/);if(i){let l=i[1].split(/[,/\s]+/).filter(Boolean);l.length>=3&&(n=l.slice(0,3).map(c=>{let p=c.endsWith("%"),d=parseFloat(p?c.slice(0,-1):c);return p?d/100*255:d}))}}if(!n||n.some(i=>!Number.isFinite(i)))return;let[o,r,s]=n.map(i=>{let l=Math.max(0,Math.min(255,i))/255;return l<=.03928?l/12.92:Math.pow((l+.055)/1.055,2.4)});return .2126*o+.7152*r+.0722*s},e0=.179,Cn=(e,t)=>{for(let[n,...o]of t){let r;for(let s of o)if(r=s.charCodeAt(0)===61?s.slice(1):e[SS+s],r!==void 0)break;r!==void 0&&(e[SS+n]=r)}};function jp(e){let t=Vp(e),n={};for(let[$,Be]of Object.entries(t)){let ye=$.replace(/\./g,"-");n[`--persona-${ye}`]=Be.value}Cn(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"],Cn(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"]]),Cn(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"]}`,Cn(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"]??Fp,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??$p,Cn(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"]]),Cn(n,[["header-bg","components-header-background","surface"]]);let r=n["--persona-header-bg"],s=n["--persona-components-header-foreground"],i=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"],Cn(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"]??i??n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=n["--persona-components-header-actionIconForeground"]??i??n["--persona-muted"],Cn(n,[["header-control-size","components-header-controlSize","=32px"],["header-control-icon-size","components-header-controlIconSize","=20px"]]);let l=e.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 d=n["--persona-components-history-railHeader-minHeight"];d&&(n["--persona-history-rail-header-min-height"]=d);for(let[$,Be]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let ye=n[`--persona-components-history-overlay-${$}`];ye&&(n[`--persona-history-overlay-${Be}`]=ye)}for(let[$,Be]of[["background","bg"],["borderRadius","radius"]]){let ye=n[`--persona-components-history-menu-${$}`];ye&&(n[`--persona-history-menu-${Be}`]=ye)}let g=e.components?.history?.motion;if(g){let $=ut=>{if(ut===void 0)return;let Zt=String(ut).trim();return/^\d+(\.\d+)?$/.test(Zt)?`${Zt}ms`:Zt},Be=$(g.enterDurationMs);Be!==void 0&&(n["--persona-history-enter-ms"]=Be);let ye=$(g.exitDurationMs);ye!==void 0&&(n["--persona-history-exit-ms"]=ye),g.enterEasing&&(n["--persona-history-enter-easing"]=g.enterEasing),g.exitEasing&&(n["--persona-history-exit-easing"]=g.exitEasing)}let f=n["--persona-components-history-dangerForeground"];f&&(n["--persona-history-danger-fg"]=f),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 Be=n[`--persona-components-history-confirm-${$}`];Be&&(n[`--persona-history-confirm-${$}`]=Be)}for(let[$,Be]of[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]]){let ye=n[`--persona-components-tooltip-${$}`];ye&&(n[`--persona-tooltip-${Be}`]=ye)}e.components?.tooltip?.arrow===!1&&(n["--persona-tooltip-arrow-display"]="none");for(let[$,Be]of[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let ye=n[`--persona-components-messageActions-${$}`];ye&&(n[`--persona-message-action-${Be}`]=ye)}Cn(n,[["intro-card-bg","components-introCard-background","=transparent"],["intro-card-radius","components-introCard-borderRadius","=1rem"]]);let h=n["--persona-components-introCard-background"],y=n["--persona-components-introCard-shadow"],v=(!h||h==="transparent"||h==="none")&&(!y||y==="none"),C=n["--persona-components-introCard-padding"]??"1.5rem";n["--persona-intro-card-padding"]=v&&C==="1.5rem"?"1.5rem 0":C,Cn(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"]]),Cn(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 A=n["--persona-components-markdown-heading-h1-fontSize"];A&&(n["--persona-md-h1-size"]=A);let L=n["--persona-components-markdown-heading-h1-fontWeight"];L&&(n["--persona-md-h1-weight"]=L);let I=n["--persona-components-markdown-heading-h2-fontSize"];I&&(n["--persona-md-h2-size"]=I);let H=n["--persona-components-markdown-heading-h2-fontWeight"];H&&(n["--persona-md-h2-weight"]=H);let _=n["--persona-components-markdown-prose-fontFamily"];_&&_!=="inherit"&&(n["--persona-md-prose-font-family"]=_),Cn(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"]]),Cn(n,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),Cn(n,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),Cn(n,[["md-hr-color","components-markdown-hr-color","divider"]]),Cn(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 V=[["container","surface"],["surface","surface"],["border","border"]];for(let[$,Be]of V){let ye=n[`--persona-components-collapsibleWidget-${$}`]??n[`--persona-${Be}`];ye!==void 0&&(n[`--persona-cw-${$}`]=ye,n[`--cw-${$}`]=ye)}Cn(n,[["message-border","components-message-border","border"]]),Cn(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 oe=e.components,W=oe?.iconButton;W&&(W.background&&(n["--persona-icon-btn-bg"]=W.background),W.border&&(n["--persona-icon-btn-border"]=W.border),W.color&&(n["--persona-icon-btn-color"]=W.color),W.padding&&(n["--persona-icon-btn-padding"]=W.padding),W.borderRadius&&(n["--persona-icon-btn-radius"]=W.borderRadius),W.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=W.hoverBackground),W.hoverColor&&(n["--persona-icon-btn-hover-color"]=W.hoverColor),W.activeBackground&&(n["--persona-icon-btn-active-bg"]=W.activeBackground),W.activeBorder&&(n["--persona-icon-btn-active-border"]=W.activeBorder));let j=oe?.labelButton;j&&(j.background&&(n["--persona-label-btn-bg"]=j.background),j.border&&(n["--persona-label-btn-border"]=j.border),j.color&&(n["--persona-label-btn-color"]=j.color),j.padding&&(n["--persona-label-btn-padding"]=j.padding),j.borderRadius&&(n["--persona-label-btn-radius"]=j.borderRadius),j.hoverBackground&&(n["--persona-label-btn-hover-bg"]=j.hoverBackground),j.fontSize&&(n["--persona-label-btn-font-size"]=j.fontSize),j.gap&&(n["--persona-label-btn-gap"]=j.gap));let X=oe?.toggleGroup;X&&(X.gap&&(n["--persona-toggle-group-gap"]=X.gap),X.borderRadius&&(n["--persona-toggle-group-radius"]=X.borderRadius));let E=oe?.artifact;if(E?.toolbar){let $=E.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"]=wm($.toggleGroupGap)),$.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=$.toggleBorderRadius),$.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=wm($.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"]=wn(e,$.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"]=wm($.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(E?.tab){let $=E.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(E?.pane){let $=E.pane;if($.toolbarBackground){let Be=wn(e,$.toolbarBackground)??$.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Be}}if(E?.card){let $=E.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(E?.inline){let $=E.inline;$.background&&(n["--persona-artifact-inline-bg"]=wn(e,$.background)??$.background),$.border&&(n["--persona-artifact-inline-border"]=$.border),$.borderRadius&&(n["--persona-artifact-inline-radius"]=$.borderRadius),$.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=wn(e,$.chromeBackground)??$.chromeBackground),$.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=wn(e,$.chromeBorder)??$.chromeBorder),$.titleColor&&(n["--persona-artifact-inline-title-color"]=wn(e,$.titleColor)??$.titleColor),$.mutedColor&&(n["--persona-artifact-inline-muted-color"]=wn(e,$.mutedColor)??$.mutedColor),$.frameHeight&&(n["--persona-artifact-inline-frame-height"]=$.frameHeight)}let T=oe?.code;T&&(T.keywordColor&&(n["--persona-code-keyword-color"]=T.keywordColor),T.stringColor&&(n["--persona-code-string-color"]=T.stringColor),T.commentColor&&(n["--persona-code-comment-color"]=T.commentColor),T.numberColor&&(n["--persona-code-number-color"]=T.numberColor),T.tagColor&&(n["--persona-code-tag-color"]=T.tagColor),T.attrColor&&(n["--persona-code-attr-color"]=T.attrColor),T.propertyColor&&(n["--persona-code-property-color"]=T.propertyColor),T.lineNumberColor&&(n["--persona-code-line-number-color"]=T.lineNumberColor),T.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=T.gutterBorderColor),T.background&&(n["--persona-code-bg"]=wn(e,T.background)??T.background));let B=n["--persona-surface"],P=n["--persona-container"],J=n["--persona-palette-colors-gray-100"]??"#f3f4f6",U=n["--persona-palette-colors-gray-200"]??"#e5e7eb",ue=n["--persona-palette-colors-gray-300"]??"#d1d5db",fe=!P||P===B,me=Zk(B??n["--persona-background"]),He=fe&&me!==void 0&&me<e0,Ee=He?"rgba(255, 255, 255, 0.08)":J,Ie=He?"rgba(255, 255, 255, 0.12)":U,yt=He?"rgba(255, 255, 255, 0.16)":ue,qe=fe?Ee:P,Oe=fe?Ie:P;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??qe,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??Oe,fe&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??yt),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??qe,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??qe,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??qe,n}var kS={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar","artifact-inline":"Inline artifact block","artifact-inline-chrome":"Inline artifact title bar"};Vd();var t0=e=>!!e&&"launcher"in e&&(e.launcher?.sidebarMode===!0||e.launcher?.mountMode==="docked"),LS=(e,t)=>{if(!t||!t0(t))return e;let n=t.theme?.components?.panel?.width,o=t.darkTheme?.components?.panel?.width;return(xi(t)==="dark"?o??n:n)!=null?e:{...e,components:{...e.components,panel:{...e.components.panel,width:Ms(t)==="v5"?"400px":"420px"}}}},n0={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"}}},Yl={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)"}}}},xm=n0,o0={...xm,colors:{...xm.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"}}},r0=Yl,s0={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:{...Yl.components,button:{...Yl.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:{...Yl.components?.eventStream,badge:{...Yl.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"}}}}},i0=e=>Ms({future:e})==="v5"?{palette:o0,components:s0}:{palette:xm,components:r0},HS=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Xl=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",a0=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":Xl()},xi=e=>a0(e),l0=(e,t={})=>Gl(e,t),c0=(e,t={})=>{let n=i0(t.future),o=_o(n.components,e??{})??{};return Gl({...o,palette:{...o.palette,colors:Ms(t)==="v5"?_o(n.palette.colors,o.palette?.colors):{...n.palette.colors,...o.palette?.colors}}},{validate:!1,future:t.future})},No=e=>{let t=xi(e),n=HS(e?.theme),o=_p(e)==="circle"?Dp:{...Up.launcher,...e?.future?.v5Defaults?{offset:"1.5rem"}:{}},r=_o({components:{launcher:o}},n),s=HS(e?.darkTheme);return LS(t==="dark"?c0(_o(r??{},s??{}),{future:e?.future}):l0(r,{future:e?.future}),e)},d0=e=>jp(e),Mi=(e,t)=>{let n=No(t),o=d0(n);for(let[r,s]of Object.entries(o))e.style.setProperty(r,s);e.setAttribute("data-persona-color-scheme",xi(t)),e.setAttribute("data-persona-defaults",Ms(t))},Oa=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e(Xl())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window<"u"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>e(Xl());n.addEventListener?(n.addEventListener("change",o),t.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),t.push(()=>n.removeListener(o)))}return()=>{t.forEach(n=>n())}};Vd();var Kr=require("lucide");kt();Lr();Je();var Hs=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");var qp="24px",Mm=(e,t)=>t||e?.composer?.placement!=="overlay"?"block":"overlay",Ql=e=>{if(typeof e!="string")return null;let t=/^\s*(\d+(?:\.\d+)?)\s*%\s*$/.exec(e);if(!t)return null;let n=Number(t[1])/100;return n>0&&n<1?n:null},IS=e=>Math.max(0,Math.round(e.columnHeight*(1-e.fraction))-e.footerHeight);xa();Fd();mp();var RS=require("idiomorph"),zp=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;RS.Idiomorph.morph(e,t.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 i=r.textContent??"",l=s.textContent??"";if(i!==l)return}return!1}}}}})};var WS=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var Em={index:-1,draft:""};function OS(e){let{direction:t,history:n,currentValue:o,atStart:r,state:s}=e,i=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="up"){if(!i&&!r)return{handled:!1,state:s};if(!i){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(!i)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 BS(e,t){return[e.id,e.role,e.content?.length??0,e.content?.slice(-32)??"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",e.variant??"",e.rawContent?.length??0,e.llmContent?.length??0,e.approval?.status??"",e.toolCall?.status??"",e.toolCall?.name??"",e.toolCall?.chunks?.length??0,e.toolCall?.chunks?.[e.toolCall.chunks.length-1]?.slice(-32)??"",typeof e.toolCall?.args=="string"?e.toolCall.args.length:e.toolCall?.args?JSON.stringify(e.toolCall.args).length:0,e.reasoning?.chunks?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.slice(-32)??"",e.contentParts?.length??0,e.stopReason??"",t].join("\0")}function _S(){return new Map}function DS(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function NS(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function FS(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function $S(e){return e.role!=="assistant"||e.variant==="tool"||e.variant==="reasoning"?!1:e.variant==="approval"?!0:!!(e.content?.trim()||e.rawContent?.trim()||e.contentParts?.length)}function US(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function ir(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Ei(e,t){return ir(e)-e.scrollTop<=t}function VS(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:i=!1,pauseOnUpwardScroll:l=!1,pauseWhenAwayFromBottom:c=!0,resumeRequiresDownwardScroll:p=!1}=e,d=n-o;return i||Math.abs(d)<s?{action:"none",delta:d,nextLastScrollTop:n}:!t&&r&&(!p||d>0)?{action:"resume",delta:d,nextLastScrollTop:n}:t&&l&&d<0?{action:"pause",delta:d,nextLastScrollTop:n}:t&&c&&!r?{action:"pause",delta:d,nextLastScrollTop:n}:{action:"none",delta:d,nextLastScrollTop:n}}function jS(e){let{following:t,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:r=!1}=e;return t&&n<0?"pause":!t&&r&&n>0&&o?"resume":"none"}function qS(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function Tm(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),n=Math.max(0,t+e.viewportHeight-e.contentHeight+(e.slack??0));return{targetScrollTop:t,spacerHeight:n}}function zS(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}Bo();var Jl={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},p0=["pre","code","a","script","style"],Kp=e=>({type:e?.type??Jl.type,placeholder:e?.placeholder??Jl.placeholder,speed:e?.speed??Jl.speed,duration:e?.duration??Jl.duration,buffer:e?.buffer??Jl.buffer}),GS=[{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"}],Zl=new Map;for(let e of GS)Zl.set(e.name,e);var YS=["wipe","glyph-cycle"],ec=e=>{Zl.set(e.name,e)},XS=e=>{GS.some(t=>t.name===e)||Zl.delete(e)},QS=()=>Array.from(Zl.keys()),tc=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:Zl.get(e)??null,Gp=(e,t,n,o,r)=>{if(!r)return e;if(n?.bufferContent)return n.bufferContent(e,o);if(!e)return e;if(t==="word"){let s=e.search(/\s(?=\S*$)/);return s<0?"":e.slice(0,s)}if(t==="line"){let s=e.lastIndexOf(`
|
|
30
|
-
`);return s<0?"":e.slice(0,s)}return e},u0=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-char",r.id=`stream-c-${n}-${o}`,r.style.setProperty("--char-index",String(o)),r.textContent=t,r},g0=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${n}-${o}`,r.style.setProperty("--word-index",String(o)),r.textContent=t,r},Pm=/\s/,f0=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let o=n;if(t.has(o.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},m0=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let i=o.createDocumentFragment(),l=0;for(;l<s.length;)if(Pm.test(s[l])){let c=l;for(;c<s.length&&Pm.test(s[c]);)c+=1;i.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&&!Pm.test(s[p]);)c.appendChild(u0(o,s[p],t,n.value)),n.value+=1,p+=1;i.appendChild(c),l=p}r.replaceChild(i,e)},h0=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let i=o.createDocumentFragment(),l=s.split(/(\s+)/);for(let c of l)c&&(/^\s+$/.test(c)?i.appendChild(o.createTextNode(c)):(i.appendChild(g0(o,c,t,n.value)),n.value+=1));r.replaceChild(i,e)},nc=(e,t,n,o)=>{if(!e||typeof document>"u")return e;let r=document.createElement("div");r.innerHTML=e;let s=new Set((o?.skipTags??p0).map(g=>g.toLowerCase())),i=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],c=i.nextNode();for(;c;)f0(c,s)||l.push(c),c=i.nextNode();let p={value:o?.startIndex??0},d=t==="char"?m0:h0;for(let g of l)d(g,n,p);return r.innerHTML},Yp=(e=document)=>{let t=e.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},oc=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let n=e.createElement("div");return n.className="persona-stream-skeleton-line",t.appendChild(n),t},KS=new WeakMap,y0=(e,t)=>{if(!e.styles)return;let n=KS.get(t);if(n||(n=new Set,KS.set(t,n)),n.has(e.name)){let s=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${s}"]`))return;n.delete(e.name)}n.add(e.name);let r=(t instanceof ShadowRoot?t.ownerDocument:t.ownerDocument??document).createElement("style");r.setAttribute("data-persona-animation",e.name),r.textContent=e.styles,t.appendChild(r)},km=new WeakMap,b0=(e,t)=>{if(!e.onAttach)return;let n=km.get(t);if(n||(n=new Map,km.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},JS=e=>{let t=km.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},rc=(e,t)=>{y0(e,t),b0(e,t)};dn();var{setLoader:B_,load:v0}=lt({fallbackImport:()=>import("@runtypelabs/persona/animations-extra")});var ZS=v0;Bo();function Lm(e,t=kn){let n=e.style.position,o=e.style.zIndex,r=e.style.isolation,s=getComputedStyle(e),i=s.position==="static"||s.position==="";return i&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{i&&(e.style.position=n),e.style.zIndex=o,e.style.isolation=r}}var sc=0,Is=null;function Hm(e=document){if(sc++,sc===1){let n=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;Is={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 t=!1;return()=>{if(!t&&(t=!0,sc=Math.max(0,sc-1),sc===0&&Is)){let n=e.body,o=e.defaultView??window;n.style.overflow=Is.originalOverflow,n.style.position=Is.originalPosition,n.style.top=Is.originalTop,n.style.width=Is.originalWidth,o.scrollTo(0,Is.scrollY),Is=null}}}Ma();var ic={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Lt=e=>(e?.launcher?.mountMode??"floating")==="docked",Rs=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",Jn=e=>{let t=e?.launcher?.dock,n=Br(e).dockWidth?t?.width:wn(No(e),"components.panel.width");return{side:t?.side??ic.side,width:n??ic.width,animate:t?.animate??ic.animate,reveal:t?.reveal??ic.reveal,maxHeight:t?.maxHeight??ic.maxHeight}};Je();Je();var tA=require("lucide");kt();Lr();var Im=e=>e==="followUp"?"follow-up":e,Rm=(e,t=0)=>{if(typeof e=="string"){let r=e.trim();return r?{id:r,label:r,prompt:r,emphasis:"default"}:null}let n=e.label.trim();if(!n)return null;let o=e.prompt?.trim()||n;return{id:e.id?.trim()||o||`suggestion-${t}`,label:n,prompt:o,description:e.description?.trim()||void 0,icon:e.icon,iconColor:e.iconColor?.trim()||void 0,behavior:e.behavior,emphasis:e.emphasis??"default"}},eA=new WeakSet,C0=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,w0=e=>{C0()||e.forEach((t,n)=>{typeof t.animate=="function"&&t.animate([{opacity:"0",transform:"translateY(4px)"},{opacity:"1",transform:"none"}],{duration:250,delay:n*60,easing:"ease-out",fill:"backwards"})})},Wm=e=>{let{item:t,index:n,surface:o,source:r,variant:s,streaming:i,config:l,plugins:c,chipsConfig:p,session:d,getTextarea:g,eventTarget:f,submitPrompt:h}=e,y=o==="followUp",v=t.behavior,C=()=>{if(d.isStreaming())return;let I={suggestion:{...t},surface:o,source:r,behavior:v},H=f.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:I,bubbles:!0,composed:!0,cancelable:!0}));if(y&&f.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:t.prompt},bubbles:!0,composed:!0})),!H)return;for(let V of c)if(V.onSuggestionSelect?.({suggestion:{...t},surface:o,source:r,variant:s,config:l})===!1)return;let _=g();if(v==="fill"){_.value=t.prompt,_.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),_.focus();return}if(h){h(t.prompt);return}_.value="",d.sendMessage(t.prompt)},A=()=>{let I=x("button",`persona-suggestion persona-suggestion--${s}`);if(I.type="button",I.disabled=i,I.dataset.suggestionId=t.id,I.dataset.emphasis=t.emphasis,I.dataset.behavior=v,s==="chip"&&(p?.fontWeight&&(I.style.fontWeight=p.fontWeight),p?.paddingX&&(I.style.paddingLeft=p.paddingX,I.style.paddingRight=p.paddingX),p?.paddingY&&(I.style.paddingTop=p.paddingY,I.style.paddingBottom=p.paddingY)),t.icon){let _=ge(t.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);_&&(_.classList.add("persona-suggestion__icon"),t.iconColor&&(_.style.color=t.iconColor),I.appendChild(_))}let H=x("span","persona-suggestion__copy");if(H.appendChild(Q("span",{className:"persona-suggestion__label",text:t.label})),t.description&&s!=="chip"&&H.appendChild(Q("span",{className:"persona-suggestion__description",text:t.description})),I.appendChild(H),s!=="chip"){let _=Nt(tA.ArrowRight,16,"currentColor",1.8);_&&(_.classList.add("persona-suggestion__arrow"),I.appendChild(_))}return I.addEventListener("click",C),I},L=null;for(let I of c)if(I.renderSuggestion&&(L=I.renderSuggestion({suggestion:{...t},index:n,surface:o,source:r,variant:s,streaming:i,config:l,defaultRenderer:A,select:C}),L))break;return L??=A(),L.dataset.suggestionId||=t.id,L.dataset.behavior||=v,L.dataset.emphasis||=t.emphasis,L instanceof HTMLButtonElement||L.setAttribute("aria-disabled",i?"true":"false"),L},ac=e=>{let t=[],n=[],o=null,r=null,s=()=>{e.removeAttribute("data-scroll-left"),e.removeAttribute("data-scroll-right")},i=()=>{if(r=null,e.hidden||e.dataset.variant!=="chip"||e.dataset.overflow!=="scroll"){s();return}let d=Math.max(0,e.scrollWidth-e.clientWidth);if(d<=1){s();return}let g=getComputedStyle(e).direction==="rtl",f=Math.min(d,Math.max(0,Math.abs(e.scrollLeft))),h=4,y=f<=h,v=f>=d-h,C=g?!v:!y,A=g?!y:!v;e.toggleAttribute("data-scroll-left",C),e.toggleAttribute("data-scroll-right",A)},l=()=>{if(r!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&i();return}r=requestAnimationFrame(i)};e.addEventListener("scroll",l,{passive:!0});let c=typeof ResizeObserver=="function"?new ResizeObserver(l):null;return c?.observe(e),{buttons:t,elements:n,destroy:()=>{e.removeEventListener("scroll",l),c?.disconnect(),r!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(r),r=null},render:(d,g,f,h,y,v)=>{e.replaceChildren(),t.length=0,n.length=0;let C=v?.source??"config",A=v?.surface??(C==="config"?"starter":"followUp"),L=A==="followUp",I=v?.variant??"chip",H=v?.behavior??"send",_=v?.overflow??"wrap",V=v?.config??{},oe=v?.plugins??[],W=typeof v?.maxItems=="number"?Math.max(0,Math.floor(v.maxItems)):void 0,j=L?"followUps":"starters";!eA.has(V)&&V.debug===!0&&I!=="chip"&&V.suggestions?.[j]?.overflow!==void 0&&(eA.add(V),console.info(`[persona] suggestions.${j}.overflow applies to the "chip" variant only; the "${I}" variant manages its own stacking.`));let X=U=>U.map(Rm).filter(ue=>ue!==null).map(ue=>({...ue,behavior:ue.behavior??H})),E=X(d??[]);oe.forEach(U=>{U.transformSuggestions&&(E=X(U.transformSuggestions({suggestions:E.map(ue=>({...ue})),surface:A,source:C,config:V})))});let T=W===void 0?E:E.slice(0,W);if(!T.length){e.hidden=!0,o=null,s();return}if(!L&&(h??g.getMessages()).some(ue=>ue.role==="user")){e.hidden=!0,o=null;return}e.hidden=!1,e.classList.add("persona-suggestions"),e.dataset.personaSuggestionSurface=Im(A),e.dataset.variant=I,e.dataset.overflow=_;let B=document.createDocumentFragment(),P=g.isStreaming();T.forEach((U,ue)=>{let fe=Wm({item:U,index:ue,surface:A,source:C,variant:I,streaming:P,config:V,plugins:oe,chipsConfig:y,session:g,getTextarea:()=>f,eventTarget:e,submitPrompt:v?.submitPrompt});B.appendChild(fe),n.push(fe),[...fe instanceof HTMLButtonElement?[fe]:[],...Array.from(fe.querySelectorAll("button"))].forEach(He=>{t.includes(He)||(He.disabled=P,t.push(He))})}),e.appendChild(B),i(),l();let J=JSON.stringify({normalized:T,surface:A,variant:I,source:C});J!==o&&(o=J,w0(n),e.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:T.map(U=>({...U})),surface:A,source:C,variant:I},bubbles:!0,composed:!0})),L&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:T.map(U=>U.prompt)},bubbles:!0,composed:!0})))}}};var io={"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"};Bo();Je();kt();wo();Je();kt();xa();var S0="persona-header-control",A0="persona-header-control--glyph",x0="persona-header-control--sparse",M0=20,E0={x:[1.4,1.05]},nA="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",T0="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Xp=(e,t,n={})=>{let{iconSize:o,iconText:r}=n,[s,i]=E0[t]??[1,1.5],l=!o;e.classList.toggle(A0,l),e.classList.toggle(x0,l&&s!==1);let c=parseFloat(o??"")||M0,p=ge(t,`${Math.round(c*s)}px`,"currentColor",i);p?(p.style.display="block",l||(p.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((i/1.5).toFixed(4))})`),e.replaceChildren(p)):r&&(e.textContent=r)},Ba=e=>{let{ariaLabel:t,tooltip:n=!0,tooltipHint:o,iconName:r,iconText:s,wrapperClassName:i=nA,size:l,iconSize:c,color:p,backgroundColor:d,borderWidth:g,borderColor:f,borderRadius:h,paddingX:y,paddingY:v,hidden:C,extraClassName:A,attrs:L}=e,I=x("div",i),H=!!(g||f),_=Q("button",{className:_n(S0,"persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!d&&"persona-bg-transparent hover:persona-bg-gray-100",!H&&"persona-border-none",!h&&"persona-rounded-full",A),attrs:{type:"button","aria-label":t,...L},style:{width:l,height:l,minWidth:l,minHeight:l,display:C?"none":void 0,color:p||Nn.actionIconColor,backgroundColor:d,border:H?`${g||"0px"} solid ${f||"transparent"}`:void 0,borderRadius:h,paddingLeft:y,paddingRight:y,paddingTop:v,paddingBottom:v}});return r?Xp(_,r,{iconSize:c,iconText:s}):s&&(_.textContent=s),I.appendChild(_),vn({anchor:_,trigger:I,text:()=>_.getAttribute("aria-label")??t,hint:o,enabled:n}),{button:_,wrapper:I}},_a=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=nA,buttonSize:r,iconSize:s}=t,i=e?.launcher??{},l=i.closeButtonTooltipText??"Close chat",c=i.closeButtonShowTooltip??!0,{button:p,wrapper:d}=Ba({ariaLabel:l,tooltip:c,iconName:i.closeButtonIconName??"x",iconText:i.closeButtonIconText??"\xD7",wrapperClassName:o,size:r??i.closeButtonSize,iconSize:s,color:i.closeButtonColor,backgroundColor:i.closeButtonBackgroundColor,borderWidth:i.closeButtonBorderWidth,borderColor:i.closeButtonBorderColor,borderRadius:i.closeButtonBorderRadius,paddingX:i.closeButtonPaddingX,paddingY:i.closeButtonPaddingY,hidden:!n});return{button:p,wrapper:d}},Da=(e,t={})=>{let{wrapperClassName:n=T0,buttonSize:o,iconSize:r}=t,i=(e?.launcher??{}).clearChat??{},l=i.tooltipText??"Clear chat",c=i.showTooltip??!0,{button:p,wrapper:d}=Ba({ariaLabel:l,tooltip:c,iconName:i.iconName??"refresh-cw",wrapperClassName:n,size:o??i.size,iconSize:r,color:i.iconColor,backgroundColor:i.backgroundColor,borderWidth:i.borderWidth,borderColor:i.borderColor,borderRadius:i.borderRadius,paddingX:i.paddingX,paddingY:i.paddingY});return{button:p,wrapper:d}};var Nn={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)"},Om={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)"},P0={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)"},jr=e=>{let{config:t,showClose:n=!0}=e,o=Q("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:Nn.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=t?.launcher??{},s=r.headerIconSize??Bl,i=r.closeButtonPlacement??"inline",l=r.headerIconHidden??!1,c=r.headerIconName,p=Q("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 _=parseFloat(s)||24,V=ge(c,_*.6,"currentColor",1);V?(V.style.width=`calc(${_}px * var(--persona-components-header-iconScale, 0.6))`,V.style.height=`calc(${_}px * var(--persona-components-header-iconScale, 0.6))`,p.replaceChildren(V)):p.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let _=x("img");_.src=t.launcher.iconUrl,_.alt="",_.className="persona-rounded-xl persona-object-cover",_.style.height=s,_.style.width=s,p.replaceChildren(_)}else p.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let d=x("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),g=Q("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:Nn.titleColor,...Om}}),f=Q("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Nn.subtitleColor,...P0}});d.append(g,f),l?o.append(d):o.append(p,d);let h=r.clearChat??{},y=h.enabled??!0,v=h.placement??"inline",C=null,A=null;if(y){let V=Da(t,{wrapperClassName:v==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});C=V.button,A=V.wrapper,v==="top-right"&&(A.style.right="48px"),v==="inline"&&o.appendChild(A)}let L=i==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":y&&v==="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:I,wrapper:H}=_a(t,{showClose:n,wrapperClassName:L});return i!=="top-right"&&o.appendChild(H),{header:o,iconHolder:p,headerTitle:g,headerSubtitle:f,closeButton:I,closeButtonWrapper:H,clearChatButton:C,clearChatButtonWrapper:A}},Ti=(e,t,n)=>{let o=n?.launcher??{},r=o.closeButtonPlacement??"inline",s=o.clearChat?.placement??"inline";e.appendChild(t.header),r==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};Je();Je();kt();Bo();function Pi(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:s,onOpenChange:i}=e,l=x("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(wa)):(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 y of t){if(y.dividerBefore){let A=document.createElement("hr");l.appendChild(A)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",y.id),y.destructive&&v.setAttribute("data-destructive",""),y.icon){let A=ge(y.icon,16,"currentColor",1.5);A&&v.appendChild(A)}let C=document.createElement("span");C.textContent=y.label,v.appendChild(C),v.addEventListener("click",A=>{A.stopPropagation(),g(),n(y.id)}),l.appendChild(v)}let c=null;function p(){if(!s)return;let y=o.getBoundingClientRect();l.style.top=`${y.bottom+4}px`,r==="bottom-right"?(l.style.right=`${window.innerWidth-y.right}px`,l.style.left="auto"):(l.style.left=`${y.left}px`,l.style.right="auto")}function d(){let y=l.classList.contains("persona-hidden");p(),l.classList.remove("persona-hidden"),y&&i?.(!0),requestAnimationFrame(()=>{let v=C=>{!l.contains(C.target)&&!o.contains(C.target)&&g()};document.addEventListener("click",v,!0),c=()=>document.removeEventListener("click",v,!0)})}function g(){let y=!l.classList.contains("persona-hidden");l.classList.add("persona-hidden"),c?.(),c=null,y&&i?.(!1)}function f(){l.classList.contains("persona-hidden")?d():g()}function h(){g(),l.remove()}return s&&s.appendChild(l),{element:l,show:d,hide:g,toggle:f,destroy:h}}Je();kt();function Zn(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,chromeless:i,onClick:l,aria:c}=e,p=x("button",_n(!i&&"persona-icon-btn",s));p.type="button",p.setAttribute("aria-label",n),p.title=n;let d=ge(t,o??16,"currentColor",r??2);if(d&&p.appendChild(d),l&&p.addEventListener("click",l),c)for(let[g,f]of Object.entries(c))p.setAttribute(g,f);return p}function Bm(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:s,className:i,onClick:l,aria:c}=e,p="persona-label-btn";o!=="default"&&(p+=" persona-label-btn--"+o),p+=" persona-label-btn--"+r,i&&(p+=" "+i);let d=x("button",p);if(d.type="button",d.setAttribute("aria-label",n),t){let f=ge(t,s??14,"currentColor",2);f&&d.appendChild(f)}let g=x("span");if(g.textContent=n,d.appendChild(g),l&&d.addEventListener("click",l),c)for(let[f,h]of Object.entries(c))d.setAttribute(f,h);return d}function lc(e){let{items:t,selectedId:n,onSelect:o,className:r}=e,s=x("div","persona-toggle-group"+(r?" "+r:""));s.setAttribute("role","group");let i=n,l=[];function c(){for(let d of l)d.btn.setAttribute("aria-pressed",d.id===i?"true":"false")}for(let d of t){let g;d.icon?g=Zn({icon:d.icon,label:d.label,className:d.className,onClick:()=>{i=d.id,c(),o(d.id)}}):(g=x("button","persona-icon-btn"+(d.className?" "+d.className:"")),g.type="button",g.setAttribute("aria-label",d.label),g.title=d.label,g.textContent=d.label,g.addEventListener("click",()=>{i=d.id,c(),o(d.id)})),g.setAttribute("aria-pressed",d.id===i?"true":"false"),l.push({id:d.id,btn:g}),s.appendChild(g)}function p(d){i=d,c()}return{element:s,setSelected:p}}function oA(e){let{label:t,icon:n,iconSize:o,iconOnly:r,menuItems:s,onSelect:i,onPrimary:l,position:c="bottom-left",portal:p,chevronLabel:d="More options",chevronIconSize:g,className:f,primaryClassName:h,chevronClassName:y}=e,v=x("div","persona-split-btn"+(f?" "+f:"")),C={label:t,className:"persona-split-btn-primary"+(h?" "+h:""),onClick:l},A=r&&n?Zn({...C,icon:n,size:o??14}):Bm({...C,icon:n,iconSize:o??14}),L=Zn({icon:"chevron-down",label:d,size:g??14,className:"persona-split-btn-chevron"+(y?" "+y:""),aria:{"aria-haspopup":"true","aria-expanded":"false"}});v.append(A,L);let I=null,H=()=>{if(I)return I;let _=(typeof p=="function"?p():p)??void 0;return I=Pi({items:s,onSelect:i,anchor:v,position:c,portal:_,onOpenChange:V=>{L.setAttribute("aria-expanded",V?"true":"false")}}),_||v.appendChild(I.element),I};return v.isConnected?H():requestAnimationFrame(()=>{I||H()}),L.addEventListener("click",_=>{_.stopPropagation(),H().toggle()}),{element:v,primaryButton:A,chevronButton:L,openMenu:()=>H().show(),closeMenu:()=>I?.hide(),toggleMenu:()=>H().toggle(),destroy:()=>{I?.destroy(),v.remove()}}}function Qp(e){let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:i,className:l,hover:c}=e,p=x("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",t);let d=x("span","persona-combo-btn-label");d.textContent=t,p.appendChild(d);let g=ge(n,14,"currentColor",2);g&&(g.style.marginLeft="4px",g.style.opacity="0.6",p.appendChild(g)),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 f=Pi({items:o,onSelect:y=>{p.setAttribute("aria-expanded","false"),r(y)},anchor:p,position:s,portal:i});i||p.appendChild(f.element);let h=()=>p.getAttribute("data-persona-menu-locked")==="true";return p.addEventListener("click",y=>{if(y.stopPropagation(),h())return;let v=!f.element.classList.contains("persona-hidden");p.setAttribute("aria-expanded",v?"false":"true"),f.toggle()}),p.addEventListener("keydown",y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),p.click())}),{element:p,setLabel:y=>{d.textContent=y,p.setAttribute("aria-label",y)},open:()=>{p.setAttribute("aria-expanded","true"),f.show()},close:()=>{p.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let y=!f.element.classList.contains("persona-hidden");p.setAttribute("aria-expanded",y?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),p.remove()}}}mp();var _m=e=>{let t=jr({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=e.layoutHeaderConfig?.onTitleClick;if(n){let o=t.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 t};function k0(e,t,n){if(t?.length)for(let o of t){let{button:r,wrapper:s}=Ba({ariaLabel:o.ariaLabel??o.label??o.id,iconName:o.icon,iconText:o.icon?void 0:o.label,tooltipHint:o.shortcut?fp(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 i=Nl(o.shortcut);i&&r.setAttribute("aria-keyshortcuts",i)}if(o.menuItems?.length){let i=Pi({items:o.menuItems,onSelect:l=>n?.(l),anchor:s,position:"bottom-right"});s.appendChild(i.element),r.addEventListener("click",l=>{l.stopPropagation(),i.toggle()})}else r.addEventListener("click",()=>n?.(o.id));e.appendChild(s)}}var Dm=e=>{let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=e,i=t?.launcher??{},l=x("div","persona-flex persona-items-center persona-justify-between");l.setAttribute("data-persona-theme-zone","header"),l.style.minHeight=Nn.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,d;if(c){let H=Qp({label:i.title??"Chat Assistant",menuItems:c.menuItems,onSelect:_=>{let V=W=>{W===!1&&H.element.dispatchEvent(new CustomEvent("persona:title-menu-builtin",{bubbles:!0,composed:!0,detail:{actionId:_}}))},oe=c.onSelect(_);oe instanceof Promise?oe.then(V,()=>{}):V(oe)},hover:c.hover,className:""});p=H.element,p.style.color=Nn.titleColor,d=p.querySelector(".persona-combo-btn-label")??p}else{if(p=x("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),d=x("span","persona-text-base persona-font-semibold persona-truncate"),d.style.color=Nn.titleColor,Object.assign(d.style,Om),d.textContent=i.title??"Chat Assistant",p.appendChild(d),r?.onTitleClick){p.style.cursor="pointer",p.setAttribute("role","button"),p.setAttribute("tabindex","0");let _=r.onTitleClick;p.addEventListener("click",V=>{V.target.closest("button")||_()}),p.addEventListener("keydown",V=>{(V.key==="Enter"||V.key===" ")&&(V.preventDefault(),_())})}let H=r?.titleRowHover;H&&(p.style.borderRadius=H.borderRadius??"10px",p.style.padding=H.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=H.background??"",p.style.borderColor=H.border??""}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="",p.style.borderColor="transparent"}))}l.appendChild(p);let g="persona-relative persona-inline-flex persona-items-center persona-justify-center",{button:f,wrapper:h}=_a(t,{showClose:n,wrapperClassName:g});o&&f.addEventListener("click",o);let y=x("div","persona-flex persona-items-center persona-gap-1");c||k0(y,r?.trailingActions,r?.onAction??s);let v=i.clearChat??{},C=null,A=null;if(v.enabled??!0){let H=v.placement??"inline",_=Da(t,{wrapperClassName:H==="top-right"?"persona-absolute persona-top-4 persona-z-50":g});C=_.button,A=_.wrapper,H==="top-right"?A.style.right="48px":y.appendChild(A)}y.appendChild(h),l.appendChild(y);let L=x("div");L.style.display="none";let I=x("span");return I.style.display="none",{header:l,iconHolder:L,headerTitle:d,headerSubtitle:I,closeButton:f,closeButtonWrapper:h,clearChatButton:C,clearChatButtonWrapper:A}},Jp={default:_m,minimal:Dm},Nm=e=>Jp[e]??Jp.default,Na=(e,t,n)=>{if(t?.render){let i=t.render({config:e,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),l=x("div");l.style.display="none";let c=x("span"),p=x("span"),d=x("button");d.style.display="none";let g=x("div");return g.style.display="none",{header:i,iconHolder:l,headerTitle:c,headerSubtitle:p,closeButton:d,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}}let o=t?.layout??"default",s=Nm(o)({config:e,showClose:t?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:t,onHeaderAction:t?.onAction});return t&&(t.showIcon===!1&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};Je();Es();var ki=e=>{let{config:t}=e,n=Q("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=rp(),r=Q("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:i}=ep(t);i();let l=tp(t),c=ka(t),p=np(t),d=op(t),g=Q("div",{className:"persona-widget-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});r.append(g),p&&(p.previewsContainer.style.gap="8px",g.append(p.previewsContainer),r.append(p.input)),r.append(s);let f=Q("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),h=Q("div",{className:"persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-start":""}}),y=Q("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&&y.append(c.wrapper),y.append(l.wrapper),f.append(h,y),r.append(f),r.addEventListener("click",v=>{v.target!==l.button&&v.target!==l.wrapper&&v.target!==c?.button&&v.target!==c?.wrapper&&v.target!==p?.button&&v.target!==p?.wrapper&&s.focus()}),t?.statusIndicator?.mode==="transient"?n.append(o,d,r):n.append(o,r,d),{footer:n,suggestions:o,composerForm:r,header:g,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:c?.button??null,micButtonWrapper:c?.wrapper??null,statusText:d,attachmentButton:p?.button??null,attachmentButtonWrapper:p?.wrapper??null,attachmentInput:p?.input??null,attachmentPreviewsContainer:p?.previewsContainer??null,actionsRow:f,leftActions:h,rightActions:y,setSendButtonMode:l.setMode}};Je();var Zp=require("lucide");Lr();Es();Jd();var rA=()=>{let e=Q("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=x("span","persona-pill-peek__icon"),n=Nt(Zp.MessageSquare,16,"currentColor",1.5);n&&t.appendChild(n);let o=x("span","persona-pill-peek__text"),r=x("span","persona-pill-peek__caret"),s=Nt(Zp.ChevronUp,16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},eu=e=>{let{config:t}=e,n=Q("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=rp(),r=op(t);r.style.display="none";let{textarea:s,attachAutoResize:i}=ep(t,{defaultMaxLines:5});i();let l=tp(t),c=ka(t),p=np(t);p&&p.previewsContainer.classList.add("persona-pill-composer__previews");let d=Q("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""}}),g=Q("div",{className:"persona-widget-composer__left-actions persona-pill-composer__left",attrs:{"data-persona-composer-actions-start":""}});p&&g.append(p.wrapper);let f=Q("div",{className:"persona-widget-composer__right-actions persona-pill-composer__right",attrs:{"data-persona-composer-actions-end":""}});c&&f.append(c.wrapper),f.append(l.wrapper),d.addEventListener("click",v=>{v.target!==l.button&&v.target!==l.wrapper&&v.target!==c?.button&&v.target!==c?.wrapper&&v.target!==p?.button&&v.target!==p?.wrapper&&s.focus()}),p&&d.append(p.input),d.append(g,s,f);let h=Q("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,d,r);let y=d;return{footer:n,suggestions:o,composerForm:d,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:y,leftActions:g,rightActions:f,setSendButtonMode:l.setMode}};Je();kt();Je();Vf();kt();Nr();var L0=e=>{switch(e){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}},H0=(e,t)=>{if(!e)return null;let n=L0(e);if(n===null)return null;let o=t?.[e],r=o!==void 0?o:n;return r||null},I0=(e,t)=>{let n=x("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},R0=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},$m=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},Um=320,cA=320,W0=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),O0=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),B0=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),_0=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),D0=e=>{if(!e||e.length===0)return null;let t=Q("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let n of e){let o=Q("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=x("span","persona-mention-chip-icon"),s=ge(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild(Q("span",{className:"persona-mention-chip-label",text:n.label})),t.appendChild(o)}return t},N0=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(Dl(o.ref,{readonly:!0,render:t}))}return n},sA="\uE000",iA="\uE001",F0=(e,t,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=f=>`${sA}${r}:${f}${iA}`,i=t.map((f,h)=>f.kind==="text"?f.text:s(h)).join(""),l=n(i);if(!t.every((f,h)=>f.kind==="text"||l.includes(s(h)))){e.replaceChildren(N0(t,o));return}e.innerHTML=l;let p=new RegExp(`${sA}${r}:(\\d+)${iA}`),d=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),g=[];for(let f=d.nextNode();f;f=d.nextNode())g.push(f);for(let f of g){let h=f;for(let y=p.exec(h.data);y;y=p.exec(h.data)){let v=t[Number(y[1])],C=h.splitText(y.index);C.data=C.data.slice(y[0].length),v?.kind==="mention"&&C.parentNode?.insertBefore(Dl(v.ref,{readonly:!0,render:o}),C),h=C}}},$0=(e,t,n)=>{if(e.length===0)return null;try{let o=x("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let r=0,s=!1,i=()=>{s||(s=!0,o.remove(),n?.())};return e.forEach((l,c)=>{let p=x("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=`${Um}px`,p.style.maxHeight=`${cA}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 d=!1;r+=1,p.addEventListener("error",()=>{d||(d=!0,r=Math.max(0,r-1),p.remove(),r===0&&i())}),p.addEventListener("load",()=>{d=!0}),R0(l.image)?(p.src=l.image,o.appendChild(p)):(d=!0,r=Math.max(0,r-1),p.remove())}),r===0?(i(),null):o}catch{return n?.(),null}},U0=e=>{if(e.length===0)return null;try{let t=x("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!$m(o.audio))return;let r=x("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Um}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},V0=e=>{if(e.length===0)return null;try{let t=x("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!$m(o.video))return;let r=x("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Um}px`,r.style.maxHeight=`${cA}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},j0=e=>{if(e.length===0)return null;try{let t=x("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!$m(o.data))return;let r=x("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",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Li=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.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",e.appendChild(t),e.appendChild(n),e.appendChild(o),e.appendChild(r),e},Vm=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:Li};if(t){let r=t(o);if(r!==null)return r}return Li()},q0=(e,t)=>{let n=x("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=t==="user"?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=x("img");r.src=o,r.alt=t==="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(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},aA=(e,t,n="div")=>{let o=x(n,"persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return t.format?o.textContent=t.format(r):o.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},cc=(e,t="bubble")=>{let n=["persona-message-bubble"];switch(t){case"flat":e==="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"),e==="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"),e==="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},lA={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"}},z0=(e,t,n="bubble",o)=>{if(!o)return;let r=t==="user"?"user":"assistant",s=lA[n??"bubble"]??lA.bubble;o.padding&&(e.style.padding=`var(--persona-message-${r}-padding, ${s.padding})`),o.fontSize&&(e.style.fontSize=`var(--persona-message-${r}-font-size, ${s.fontSize})`),o.lineHeight&&(e.style.lineHeight=`var(--persona-message-${r}-line-height, ${s.lineHeight})`),o.fontFamily&&(e.style.fontFamily=`var(--persona-message-${r}-font-family, inherit)`)},tu="custom:",K0=e=>`${tu}${e}`,dA=(e,t)=>t!=="user"&&t!=="assistant"?[]:(e?.custom??[]).filter(n=>(n.roles??["assistant"]).includes(t)),jm=(e,t,n,o)=>{let r=t.showCopy??!0,s=t.showUpvote??!1,i=t.showDownvote??!1,l=t.showReadAloud??!1,c=(t.showRegenerate??!1)&&o?.canRegenerate===!0,p=(t.showEdit??!1)&&o?.canEdit===!0,d=(t.showQuote??!1)&&o?.canQuote!==!1,g=dA(t,e.role);if(!r&&!s&&!i&&!l&&!c&&!p&&!d&&g.length===0){let I=x("div");return I.style.display="none",I.id=`actions-${e.id}`,I.setAttribute("data-actions-for",e.id),I}let f=t.visibility??"hover",h=t.align??"right",y=t.layout??"pill-inside",v={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[h],C={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[y],A=x("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${v} ${C} ${f==="hover"?"persona-message-actions-hover":""}`);A.id=`actions-${e.id}`,A.setAttribute("data-actions-for",e.id);let L=(I,H,_)=>{let V=Zn({icon:I,label:H,size:14,className:"persona-message-action-btn",chromeless:!0});return V.setAttribute("data-action",_),V};r&&A.appendChild(L("copy","Copy message","copy")),l&&A.appendChild(L("volume-2","Read aloud","read-aloud")),s&&A.appendChild(L("thumbs-up","Upvote","upvote")),i&&A.appendChild(L("thumbs-down","Downvote","downvote")),c&&A.appendChild(L("refresh-cw","Regenerate response","regenerate")),p&&A.appendChild(L("pencil","Edit message","edit")),d&&A.appendChild(L("quote","Quote message","quote"));for(let I of g)A.appendChild(L(I.iconName??"ellipsis",I.label,K0(I.id)));return A},Fa=(e,t,n,o,r,s)=>{let i=n??{},l=i.layout??"bubble",c=i.avatar,p=i.timestamp,d=c?.show??!1,g=p?.show??!1,f=c?.position??"left",h=p?.position??"below",y=cc(e.role,l),v=x("div",y.join(" "));v.id=`bubble-${e.id}`,v.setAttribute("data-message-id",e.id),v.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message");let C=Sm(s?.widgetConfig?.future).components.message,A=s?.widgetConfig?.theme?.components?.message;z0(v,e.role,l,e.role==="user"?{...C.user,...A?.user,...s?.widgetConfig?.darkTheme?.components?.message?.user}:{...C.assistant,...A?.assistant,...s?.widgetConfig?.darkTheme?.components?.message?.assistant}),l==="flat"?(v.style.backgroundColor="transparent",v.style.color=e.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):e.role==="user"?(v.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",v.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(v.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",v.style.color="var(--persona-message-assistant-text, var(--persona-text))");let L=W0(e),I=e.content?.trim()??"",_=L.length>0&&I===Ta,V=Kp(s?.widgetConfig?.features?.streamAnimation),oe=s?.widgetConfig?.features?.streamAnimation?.plugins,W=e.role==="assistant"&&V.type!=="none"?tc(V.type,oe):null,j=e.role==="assistant"&&W?.isAnimating?.(e)===!0,X=e.role==="assistant"&&W!==null&&(!!e.streaming||j);X&&W?.bubbleClass&&v.classList.add(W.bubbleClass);let E=document.createElement("div");E.classList.add("persona-message-content"),e.streaming&&E.classList.add("persona-content-streaming"),X&&W&&(W.containerClass&&E.classList.add(W.containerClass),E.style.setProperty("--persona-stream-step",`${V.speed}ms`),E.style.setProperty("--persona-stream-duration",`${V.duration}ms`));let T=X?Gp(e.content??"",V.buffer,W,e,!!e.streaming):e.content??"",B=()=>{let Oe=t({text:T,message:e,streaming:!!e.streaming,raw:e.rawContent});return X&&W?.wrap==="char"?nc(Oe,"char",e.id,{skipTags:W.skipTags}):X&&W?.wrap==="word"?nc(Oe,"word",e.id,{skipTags:W.skipTags}):Oe},P=null;if(_?(P=document.createElement("div"),P.innerHTML=B(),P.style.display="none",E.appendChild(P)):e.contentSegments?.length?F0(E,e.contentSegments,Oe=>t({text:Oe,message:e,streaming:!!e.streaming,raw:e.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):E.innerHTML=B(),X&&W?.useCaret&&!_&&I){let Oe=Yp(),$=E.querySelectorAll(".persona-stream-char, .persona-stream-word"),Be=$[$.length-1];if(Be?.parentNode)Be.parentNode.insertBefore(Oe,Be.nextSibling);else{let ye=E.lastElementChild;ye?ye.appendChild(Oe):E.appendChild(Oe)}}if(g&&h==="inline"&&e.createdAt){let Oe=aA(e,p,"span");Oe.classList.add("persona-timestamp-inline");let $=E.lastElementChild;$?$.appendChild(Oe):E.appendChild(Oe)}if(L.length>0){let Oe=$0(L,!_&&!!I,()=>{_&&P&&(P.style.display="")});Oe?v.appendChild(Oe):_&&P&&(P.style.display="")}let J=O0(e);if(J.length>0){let Oe=U0(J);Oe&&v.appendChild(Oe)}let U=B0(e);if(U.length>0){let Oe=V0(U);Oe&&v.appendChild(Oe)}let ue=_0(e);if(ue.length>0){let Oe=j0(ue);Oe&&v.appendChild(Oe)}let fe=e.contentSegments?.length?null:D0(e.contextMentions);if(fe&&v.appendChild(fe),v.appendChild(E),g&&h==="below"&&e.createdAt){let Oe=aA(e,p);Oe.classList.add("persona-mt-1"),v.appendChild(Oe)}let me=e.role==="assistant"?H0(e.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let Oe=!!(T&&T.trim()),$=V.placeholder==="skeleton",Be=$&&V.buffer==="line"&&Oe;if(Oe)Be&&v.appendChild(oc());else if($)v.appendChild(oc());else{let ye=Vm("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);ye&&v.appendChild(ye)}}me&&e.stopReason&&!e.streaming&&(I||(E.style.display="none"),v.appendChild(I0(e.stopReason,me)));let He=e.role==="assistant"&&!e.streaming&&!e.voiceCaption&&e.content&&e.content.trim()&&o?.enabled!==!1,Ee=s?.actionEligibility,Ie=e.role==="user"&&!e.streaming&&o?.enabled!==!1&&(o?.showEdit===!0&&Ee?.canEdit===!0||o?.showQuote===!0&&Ee?.canQuote===!0||dA(o,"user").length>0);if((He||Ie)&&o){let Oe=jm(e,Ie?{...o,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:o,r,Ee);v.appendChild(Oe)}if(!d||e.role==="system")return v;let yt=x("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),qe=q0(c,e.role);return f==="right"||f==="left"&&e.role==="user"?yt.append(v,qe):yt.append(qe,v),yt},pA=(e,t,n,o,r,s)=>{let i=n??{};return e.role==="user"&&i.renderUserMessage?i.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&i.renderAssistantMessage?i.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Fa(e,t,n,o,r,s)};var G0=40,Y0=(e,t)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}if(typeof t=="function"){let n=null;try{n=t()}catch(o){console.warn("[persona] welcome.icon renderer threw",o)}if(!n){e.hidden=!0;return}e.appendChild(n),e.hidden=!1;return}if(t.type==="lucide"){let n=ge(t.name,G0);if(!n){e.hidden=!0;return}e.appendChild(n)}else t.type==="image"?e.appendChild(Q("img",{className:"persona-welcome-icon-image",attrs:{src:t.url,alt:t.alt}})):e.appendChild(Q("span",{className:"persona-welcome-icon-text",text:t.text}));e.hidden=!1},uA=(e,t,n={})=>{let o=Q("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});o.hidden=!0;let r=x("p","persona-welcome-kicker");r.hidden=!0;let s=x("h2","persona-welcome-title"),i=x("p","persona-welcome-subtitle"),l=Q("div",{className:"persona-welcome-head-text"},r,s),c=Q("div",{className:"persona-welcome-title-row"},o,l);return{host:Q("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,i,t),iconHolder:o,kicker:r,title:s,subtitle:i,starterSuggestions:t}},$a=(e,t,n)=>{t.hidden=!n,t.style.display=n?"":"none",e.classList.toggle("persona-gap-6",n),e.classList.toggle("persona-gap-3",!n)},ou=(e,t)=>{e.title.textContent=t.title,e.kicker.textContent=t.kicker??"",e.kicker.hidden=!t.kicker,e.subtitle.textContent=t.subtitle,e.subtitle.hidden=t.subtitle==="",Y0(e.iconHolder,t.icon),e.host.setAttribute("data-persona-welcome-variant",t.variant),e.host.setAttribute("data-persona-welcome-dismiss",t.dismiss),e.host.setAttribute("data-persona-welcome-layout",t.layout??"top"),e.host.setAttribute("data-persona-welcome-anchor",t.anchor??"bottom"),t.iconPlacement==="inline"?e.host.setAttribute("data-persona-welcome-icon-placement","inline"):e.host.removeAttribute("data-persona-welcome-icon-placement"),t.align?e.host.setAttribute("data-persona-welcome-align",t.align):e.host.removeAttribute("data-persona-welcome-align")},X0="data-persona-welcome-plugin",gA="data-persona-welcome-overlay",nu="persona-welcome-overlay-active",qm=new WeakMap,zm=(e,t,n)=>{n.setAttribute(X0,""),t.appendChild(n),t.setAttribute("data-persona-welcome-content","plugin"),t.setAttribute(gA,""),e.classList.contains(nu)||(qm.set(e,e.scrollTop),e.classList.add(nu),e.scrollTop=0)},Km=(e,t,n)=>{n&&n!==t&&n.remove(),t.removeAttribute("data-persona-welcome-content"),t.removeAttribute(gA),e.classList.contains(nu)&&(e.classList.remove(nu),e.scrollTop=qm.get(e)??e.scrollTop,qm.delete(e))},fA=()=>{let e=Q("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return e.hidden=!0,e},ru=(e,t,n)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}let o=n?.layout?.messages?.layout??"bubble",r=Q("div",{className:cc("assistant",o).join(" "),attrs:{"data-persona-theme-zone":"assistant-message"},text:t,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))"}});e.appendChild(Q("div",{className:"persona-flex"},r)),e.hidden=!1},mA=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,hA=(e,t)=>{if(mA()||typeof e.animate!="function"||!e.isConnected)return t(null),null;let n=e.getBoundingClientRect(),o=e.parentElement,r=0,s=0,i=0;if(o){let y=getComputedStyle(o);r=parseFloat(y.rowGap)||0;let v=e.previousElementSibling,C=e.nextElementSibling,L=o.getBoundingClientRect().top+(parseFloat(y.borderTopWidth)||0)+(parseFloat(y.paddingTop)||0)-o.scrollTop;s=Math.max(0,v?n.top-v.getBoundingClientRect().bottom-r:n.top-L),i=Math.max(0,C?C.getBoundingClientRect().top-n.bottom-r:0)}let l=e.style.overflow;e.style.overflow="hidden";let c=getComputedStyle(e),p=parseFloat(c.paddingTop)||0,d=parseFloat(c.paddingBottom)||0,g=e.animate([{opacity:"1",transform:"none",height:`${n.height}px`,minHeight:"0px",paddingTop:`${p}px`,paddingBottom:`${d}px`,marginTop:`${s}px`,marginBottom:`${i}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"}),f=!1,h=()=>{f||(f=!0,e.style.overflow=l,t(g))};return g.finished.then(h).catch(h),g},yA=(e,t,n,o=260)=>{if(t<=1||mA()||typeof e.animate!="function"||!e.isConnected)return null;let r=n==="drop"?-t:t;return e.animate([{transform:`translateY(${r}px)`},{transform:"none"}],{duration:o,easing:"cubic-bezier(0.2, 0, 0, 1)",fill:"none"})};var Q0="Hello \u{1F44B}",J0="I can answer questions and help you get things done here.",bA=new WeakSet,Fn=(e,t)=>!!e&&e[t]!==void 0,Z0=(e,t)=>{!e||e.debug!==!0||!t.length||bA.has(e)||(bA.add(e),t.forEach(n=>console.warn(`[persona] ${n}`)))},Ua=(e,t=e?.launcher?.fullHeight===!0&&!e.launcher.sidebarMode&&e.launcher.mountMode!=="docked")=>{let n=e?.welcome,o=e?.copy,r=e?.future?.v5Defaults===!0,s=n?.layout??(r?"centered":"top"),i=Fn(n,"variant")?n.variant:o?.showWelcomeCard===!1?"none":"card",l=i==="hero"&&!r&&n?.layout===void 0?"on-first-message":Fn(n,"dismiss")?n.dismiss:r||i==="hero"?"on-first-message":"never",c=[];Fn(n,"title")&&Fn(o,"welcomeTitle")&&c.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),Fn(n,"subtitle")&&Fn(o,"welcomeSubtitle")&&c.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),Fn(n,"variant")&&Fn(o,"showWelcomeCard")&&c.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),i==="hero"&&Fn(n,"message")&&c.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),!r&&n?.layout===void 0&&i==="hero"&&Fn(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"&&t?"center":"bottom"),d=Ql(n?.anchorComposerTop)!==null;return Fn(n,"anchorComposerTop")&&!d&&c.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),p!=="center"&&(Fn(n,"anchorComposerTop")||Fn(n,"composerGap"))&&c.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),Z0(e,c),{title:Fn(n,"title")?n.title:o?.welcomeTitle??(r?"What can I help with?":Q0),kicker:n?.kicker??"",subtitle:Fn(n,"subtitle")?n.subtitle:o?.welcomeSubtitle??(r?"":J0),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:i,dismiss:l,message:i==="hero"?void 0:n?.message,layout:s,anchor:p,anchorComposerTop:d?n.anchorComposerTop:"44%",composerGap:n?.composerGap?.trim()||qp}},vA=e=>(e??[]).some(t=>t.role==="user")?"active":"empty",Ws=(e,t)=>e.variant==="none"?!1:e.dismiss==="never"?!0:!(t??[]).some(n=>n.role==="user");Ma();var eL="var(--persona-components-panel-maxWidth)",CA="var(--persona-components-panel-height)",tL="var(--persona-components-panel-maxHeight)",Hi=e=>{let t=Br(e),n=t.launcherWidth?e?.launcher?.width:t.legacyLauncherWidth?e?.launcherWidth:void 0,o=e?.launcher?.heightOffset??0,r=o===0?`max(200px, ${CA})`:`max(200px, calc(${CA} - ${o}px))`;return{width:n??hC,maxWidth:n??eL,height:r,maxHeight:tL}},wA="16px",Ym="10px",Xm="14px",SA=e=>{let t=e?.launcher?.enabled??!0,n=Lt(e);if(Rs(e)){let p=e?.launcher?.composerBar??{},d=x("div","persona-widget-wrapper persona-fixed persona-transition");d.setAttribute("data-persona-composer-bar",""),d.dataset.state="collapsed",d.dataset.expandedSize=p.expandedSize??"anchored",d.style.zIndex=String(e?.launcher?.zIndex??kn);let g=x("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");g.style.width="100%",d.appendChild(g);let f=x("div","persona-widget-pill-root");return f.setAttribute("data-persona-composer-bar",""),f.dataset.state="collapsed",f.dataset.expandedSize=p.expandedSize??"anchored",f.style.zIndex=String(e?.launcher?.zIndex??kn),{wrapper:d,panel:g,pillRoot:f}}if(n){let p=x("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),d=x("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return p.appendChild(d),{wrapper:p,panel:d}}if(!t){let p=x("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),d=x("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),g=Br(e),h=g.launcherWidth||g.legacyLauncherWidth||e?.theme?.components?.panel?.width!==void 0?Hi(e).width:"100%";return p.style.width=h,d.style.width="100%",p.appendChild(d),{wrapper:p,panel:d}}let r=e?.launcher??{},s=r.position&&io[r.position]?io[r.position]:io["bottom-right"],i=x("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);i.style.zIndex=String(e?.launcher?.zIndex??kn);let l=x("div","persona-widget-panel persona-relative persona-min-h-[320px]"),c=Hi(e);return l.style.width=c.width,l.style.maxWidth=c.maxWidth,i.appendChild(l),{wrapper:i,panel:l}},Qm=e=>{let t=Q("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":Im(e)}});return t.hidden=!0,t},AA=(e,t)=>{let n=Qm("starter"),o=uA(e,n,{flatShadow:Lt(e)}),r=Ua(e);ou(o,r),$a(t,o.host,Ws(r,e?.initialMessages));let s=fA();return ru(s,r.message,e),{welcome:o,greetingHost:s}},nL=(e,t)=>{let n=x("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}=_a(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:wA,iconSize:Ym});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let s=e?.launcher?.clearChat?.enabled??!0,i=null,l=null;if(s){let oe=Da(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:wA,iconSize:Xm});i=oe.button,l=oe.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let c=Q("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),p=Q("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:d,greetingHost:g}=AA(e,p),{host:f,title:h,subtitle:y}=d,v=d.starterSuggestions,C=x("div","persona-widget-messages persona-flex persona-flex-col");C.style.gap="var(--persona-components-message-gap, 12px)";let A=Qm("followUp"),L=Hs(e,!0);L&&(C.style.maxWidth=L,C.style.marginLeft="auto",C.style.marginRight="auto",C.style.width="100%"),p.append(f,g,C,A);let I=Q("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"}}),H=eu({config:e}),{root:_,textNode:V}=rA();return n.append(c,r,p,I),l&&n.appendChild(l),{container:n,body:p,messagesWrapper:C,starterSuggestions:v,transcriptSuggestions:A,composerOverlay:I,suggestions:H.suggestions,textarea:H.textarea,sendButton:H.sendButton,sendButtonWrapper:H.sendButtonWrapper,micButton:H.micButton,micButtonWrapper:H.micButtonWrapper,composerForm:H.composerForm,statusText:H.statusText,welcomeHost:f,welcomeIconHolder:d.iconHolder,greetingHost:g,introKicker:d.kicker,introTitle:h,introSubtitle:y,closeButton:o,closeButtonWrapper:r,clearChatButton:i,clearChatButtonWrapper:l,iconHolder:x("span"),headerTitle:x("span"),headerSubtitle:x("span"),header:c,footer:H.footer,attachmentButton:H.attachmentButton,attachmentButtonWrapper:H.attachmentButtonWrapper,attachmentInput:H.attachmentInput,attachmentPreviewsContainer:H.attachmentPreviewsContainer,actionsRow:H.actionsRow,leftActions:H.leftActions,rightActions:H.rightActions,setSendButtonMode:H.setSendButtonMode,peekBanner:_,peekTextNode:V}},xA=(e,t=!0)=>{if(Rs(e))return nL(e,t);let n=Q("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=e?.layout?.header,r=e?.layout?.showHeader!==!1,s=o?Na(e,o,{showClose:t}):jr({config:e,showClose:t}),i=Q("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"}});i.style.setProperty("scrollbar-gutter","stable");let{welcome:l,greetingHost:c}=AA(e,i),{host:p,title:d,subtitle:g}=l,f=l.starterSuggestions,h=x("div","persona-widget-messages persona-flex persona-flex-col");h.style.gap="var(--persona-components-message-gap, 12px)";let y=Qm("followUp"),v=Hs(e,!1);v&&(h.style.maxWidth=v,h.style.marginLeft="auto",h.style.marginRight="auto",h.style.width="100%"),i.append(p,c,h,y);let C=ki({config:e}),A=e?.layout?.showFooter!==!1;r?Ti(n,s,e):(s.header.style.display="none",Ti(n,s,e)),n.append(i);let L=Q("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 A||(C.footer.style.display="none"),n.append(C.footer),n.append(L),{container:n,body:i,messagesWrapper:h,starterSuggestions:f,transcriptSuggestions:y,composerOverlay:L,suggestions:C.suggestions,textarea:C.textarea,sendButton:C.sendButton,sendButtonWrapper:C.sendButtonWrapper,micButton:C.micButton,micButtonWrapper:C.micButtonWrapper,composerForm:C.composerForm,statusText:C.statusText,welcomeHost:p,welcomeIconHolder:l.iconHolder,greetingHost:c,introKicker:l.kicker,introTitle:d,introSubtitle:g,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:C.footer,attachmentButton:C.attachmentButton,attachmentButtonWrapper:C.attachmentButtonWrapper,attachmentInput:C.attachmentInput,attachmentPreviewsContainer:C.attachmentPreviewsContainer,actionsRow:C.actionsRow,leftActions:C.leftActions,rightActions:C.rightActions,setSendButtonMode:C.setSendButtonMode}};Es();Je();kt();Bo();var Jm=(e,t)=>{let n=x("button");n.type="button",n.innerHTML=`
|
|
28
|
+
`),l=Array.isArray(t.contentParts)&&t.contentParts.length>0,c=r.contentParts.length>0;if(l){let p=[];s&&p.push(Ao(s)),p.push(...r.contentParts),p.push(...t.contentParts),t.contentParts=p}else if(c){let p=[];i&&p.push(Ao(i)),p.push(...r.contentParts),t.contentParts=p}else s&&(t.llmContent=i);Object.keys(r.context).length>0&&(t.mentionContext=r.context)}async sendMessage(t,n){let o=t.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.#_&&!n?.voiceTurn&&(this.#_.failed=!0,this.#_=null),(this.#H||this.#C||this.#v||this.#W)&&await this.#Ne(),this.stopSpeaking(),this.abortController?.abort(),this.#me(),this.#le++,this.#ye();let s=n?.voiceTurn?.userMessageId,i=s?this.messages.find(h=>h.id===s&&h.role==="user"):void 0,l=i?.id??Ha(),c=Ps();this.#s=null;let p=n?.contentParts&&Pa(n.contentParts)?Ta:"",d={id:l,role:"user",content:o||p,createdAt:new Date().toISOString(),sequence:this.#F(),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??{}};i?(i.viaVoice=!0,delete i.voiceCaption,i.content.trim()!==o&&(i.llmContent=o),this.callbacks.onMessagesChanged([...this.messages])):this.#te(d),this.#k(!0);let g=new AbortController;if(this.abortController=g,n?.mentions){let h=this.messages.find(y=>y.id===l)??d;if(await this.#Qe(h,o,n.mentions.finalize),g.signal.aborted||this.abortController!==g)return;this.callbacks.onMessagesChanged([...this.messages])}if(n?.quote&&!n.replayFields){let h=this.messages.find(v=>v.id===l)??d,y=Rw({quote:n.quote,text:h.llmContent??h.content,contentParts:h.contentParts});y.contentParts&&(h.contentParts=y.contentParts),y.llmContent!==void 0&&(h.llmContent=y.llmContent),(y.contentParts||y.llmContent!==void 0)&&(h.quote={...n.quote},this.callbacks.onMessagesChanged([...this.messages]))}let f=i?[...this.messages.filter(h=>h!==i),{...i,createdAt:new Date().toISOString()}]:[...this.messages];try{await this.#Ye(f,g,c,l,{composerOptions:n?.composerOptions,interrupt:n?.interrupt})}catch(h){if(this.status==="resuming"||this.#r)return;this.#_&&(this.#_.failed=!0);let y=h instanceof Error&&(h.name==="AbortError"||h.message.includes("aborted")||h.message.includes("abort"));if(!y){let v=mm(h,this.config.errorMessage);if(v){let C={id:c,role:"assistant",createdAt:new Date().toISOString(),content:v,sequence:this.#F()};this.#te(C)}}this.#q("idle"),this.#k(!1),this.abortController=null,y||(h instanceof Error?this.callbacks.onError?.(h):this.callbacks.onError?.(new Error(String(h))))}}resubmitFrom(t,n){let o=Ww(this.messages,t);if(!o)return!1;let r=this.messages[o.start],s=n.replacement,i=s?s.text:r.content,l=s?s.contentParts:r.contentParts;if(!(!!i?.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}},d=s?this.#Je(s.options):r.composerOptions,g=s?s.contentSegments:r.contentSegments,f=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(i??"",{...l?.length?{contentParts:[...l]}:{},...g?.length?{contentSegments:[...g]}:{},...d?{composerOptions:d}:{},...f?{quote:f}:{},...p&&Object.keys(p).length>0?{replayFields:p}:{},viaVoice:h===!0}),!0}#Je(t){if(!t)return;let n={};return t.selectedModelId&&(n.selectedModelId=t.selectedModelId),t.activeModeIds?.length&&(n.activeModeIds=[...t.activeModeIds]),Object.keys(n).length>0?n:void 0}async continueConversation(){if(this.streaming)return;(this.#H||this.#C||this.#v||this.#W)&&await this.#Ne(),this.abortController?.abort(),this.#ye();let t=Ps();this.#s=null,this.#k(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(r){if(this.status==="resuming"||this.#r)return;let s=r instanceof Error&&(r.name==="AbortError"||r.message.includes("aborted")||r.message.includes("abort"));if(!s){let i=mm(r,this.config.errorMessage);if(i){let l={id:t,role:"assistant",createdAt:new Date().toISOString(),content:i,sequence:this.#F()};this.#te(l)}}this.#q("idle"),this.#k(!1),this.abortController=null,s||(r instanceof Error?this.callbacks.onError?.(r):this.callbacks.onError?.(new Error(String(r))))}}async connectStream(t,n){if(this.streaming&&!n?.allowReentry)return;n?.allowReentry||this.abortController?.abort(),n?.preserveAssistantId&&n.assistantMessageId&&(this.#s=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,r=!1;for(let i of this.messages)i.streaming&&i.id!==o&&(i.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.#k(!0);let s={};try{await this.client.processStream(t,i=>{let l=this.#n;this.#n=s;try{this.handleEvent(i)}finally{this.#n=l}},n?.assistantMessageId,n?.seedContent),this.#We(s)}catch(i){if(this.status==="resuming"||this.#r){this.#pt(s);return}this.#We(s),this.#q("error"),this.webMcpResolveControllers.size===0&&(this.#k(!1),this.abortController=null),this.callbacks.onError?.(i instanceof Error?i:new Error(String(i)))}}#Fe(){let t=this.config.webmcp;t?.enabled===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){try{if(this.config.webmcp?.autoApprove?.(t)===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.#l}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:t.description??`Allow the assistant to run ${t.toolName}?`,parameters:t.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(t,n){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let r=this.messages.find(s=>s.id===t);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}#Ze;#le;#Me(t){let n=this.#Ze??={s:this,setStreaming:s=>this.#k(s),appendMessage:s=>this.#te(s),nextSequence:()=>this.#F(),settleApprovalPausedToolCall:s=>this.#Ve(s),resumeAfter:s=>this.#t?.executionId===s?this.#t.lastEventId:void 0},o=jC();if(o)return t(o,n);let r=this.#le;return Qf().then(s=>r===this.#le?t(s,n):void 0,s=>{this.callbacks.onError?.(s instanceof Error?s:new Error(String(s)))})}resolveApproval(t,n,o){return this.#Me((r,s)=>r.resolveApproval(s,t,n,o))}resolveAskUserQuestion(t,n){return this.#Me((o,r)=>o.resolveAskUserQuestion(r,t,n))}resolveWebMcpToolCall(t){return this.#Me((n,o)=>n.resolveWebMcpToolCall(o,t))}persistAskUserQuestionProgress(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}#et(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.id;if(!n||!o){let s=this.#c;queueMicrotask(()=>{s===this.#c&&this.resolveWebMcpToolCall(t)});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(t))}#tt(){if(this.webMcpAwaitBatches.size===0)return;let t=this.#c;queueMicrotask(()=>{if(t===this.#c)for(let n of[...this.webMcpAwaitBatches.keys()])this.#nt(n)})}#nt(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.#Me((r,s)=>r.resolveWebMcpToolCallBatch(s,t,o))}#me(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.#c++}cancel(){this.abortController?.abort(),this.abortController=null,this.#ye(),this.#me(),this.#le++,this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.#k(!1),this.#q("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#ye(),this.#me(),this.#le++,this.messages=[],this.agentExecution=null,this.#Ie(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#k(!1),this.#q("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.#u}selectArtifact(t){this.#u=t,this.#he()}clearArtifacts(){this.#Ie()}upsertArtifact(t){let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=t.artifactType==="markdown"?{id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{}}:{id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:t.props??{},...t.presentation?{presentation:t.presentation}:{}};return this.artifacts.set(n,o),this.#u=n,this.#he(),t.transcript!==!1&&this.#ot(o),o}#ot(t){let n=`artifact-ref-${t.id}`,o=or(this.config.features?.artifacts,t),r=Ml(o,{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:"complete",...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...t.component?{component:t.component}:{},...t.props?{componentProps:t.props}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}),s=this.messages.find(i=>i.id===n);if(s){s.rawContent=r,s.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:n,content:"",rawContent:r})}#$e(){let t=!1;for(let n of this.artifacts.values()){let o=this.messages.find(i=>i.id===`artifact-ref-${n.id}`);if(!o)continue;let r=or(this.config.features?.artifacts,n),s=Ml(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",t=!0)}t&&this.callbacks.onMessagesChanged([...this.messages])}#Ie(){this.artifacts.size===0&&this.#u===null||(this.artifacts.clear(),this.#u=null,this.#he())}#he(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.#u})}#rt(t){switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:"",...t.file?{file:t.file}:{}}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:t.component??"",props:{}}),this.#u=t.id;break}case"artifact_delta":{let n=this.artifacts.get(t.id);n?.artifactType==="markdown"&&(n.markdown=(n.markdown??"")+t.artDelta);break}case"artifact_update":{let n=this.artifacts.get(t.id);n?.artifactType==="component"&&(n.props={...n.props,...t.props},t.component&&(n.component=t.component));break}case"artifact_complete":{let n=this.artifacts.get(t.id);n&&(n.status="complete");break}default:return}this.#he()}hydrateMessages(t){this.abortController?.abort(),this.abortController=null,this.#ye(),this.#me(),this.#le++,this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.#ce(t.map(n=>({...n,streaming:!1,sequence:n.sequence??this.#F()}))),this.#k(!1),this.#q("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let o of t)this.artifacts.set(o.id,{...o,status:"complete"});this.#u=n,this.#he()}#st(t){let n=this.agentExecution?.executionId;if(!n||!this.#s||this.agentExecution?.status!=="running")return;let o=this.#t===null;this.#t={executionId:n,lastEventId:t,assistantMessageId:this.#s,status:"running"},this.#dt(o)}#it(){return this.#t!==null&&typeof this.config.reconnectStream=="function"&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.#Ue()}#Ue(){return this.messages.some(t=>t.agentMetadata?.awaitingLocalTool===!0&&t.agentMetadata?.askUserQuestionAnswered!==!0||t.variant==="approval"&&t.approval?.status==="pending")}#Re(){this.#r||!this.#t||typeof this.config.reconnectStream!="function"||(this.#r=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.#t}),this.#k(!0),this.#q("resuming"),this.#at().then(t=>{this.#r&&this.#t&&t.begin()}))}#at(){return this.#p?Promise.resolve(this.#p):(this.#f||(this.#f=Vw().then(({createReconnectController:t})=>{let n=t(this.#lt());return this.#p=n,n}),this.#f.catch(()=>{this.#f=null})),this.#f)}#lt(){let t=this;return{get config(){return t.config},getResumable:()=>t.#t,clearResumable:()=>t.#Te(),getStatus:()=>t.status,setStatus:n=>t.#q(n),setStreaming:n=>t.#k(n),setReconnecting:n=>{t.#r=n},setAbortController:n=>{t.abortController=n},getMessages:()=>t.messages,notifyMessagesChanged:()=>t.callbacks.onMessagesChanged([...t.messages]),resumeConnect:(n,o,r)=>t.connectStream(n,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:n=>t.#te(n),nextSequence:()=>t.#F(),emitReconnect:n=>t.callbacks.onReconnect?.(n),buildErrorContent:n=>mm(new Error(n),t.config.errorMessage),onError:n=>t.callbacks.onError?.(n)}}reconnectNow(){if(this.#r){this.#p?.wake();return}this.#Re()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.#r)return;let n=this.#ct();n||(n=Ps(),this.#te({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.#F()})),this.#s=n,this.agentExecution||(this.agentExecution={executionId:t.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.#t={executionId:t.executionId,lastEventId:t.after,assistantMessageId:n,status:"running"},this.#Re()}#ct(){for(let t=this.messages.length-1;t>=0;t--){let n=this.messages[t];if(n.role==="assistant"&&!n.variant)return n.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),n.id;if(n.role==="user")break}return null}#ye(){this.#r=!1,this.#p?.teardown(),this.#Te()}#Te(){this.#i&&(clearTimeout(this.#i),this.#i=null);let t=this.#t!==null;this.#t=null,t&&this.config.onExecutionState?.(null)}#dt(t){let n=this.config.onExecutionState;if(n){if(t){this.#i&&(clearTimeout(this.#i),this.#i=null),n(this.#t);return}this.#i||(this.#i=setTimeout(()=>{this.#i=null,this.config.onExecutionState?.(this.#t)},500))}}getResumableHandle(){return this.#t}#q(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}#k(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&(this.#We(void 0),this.speakLatestAssistantMessage())}speakLatestAssistantMessage(t){let n=this.config.textToSpeech;if(!n?.enabled||!(!n.provider||n.provider==="browser"||n.provider==="runtype"&&n.browserFallback))return;let r=[...this.messages].reverse().find(i=>i.role==="assistant"&&i.content&&!i.voiceProcessing);if(!r||t&&!t.includes(r.id))return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let s=um(r.content);s.trim()&&this.readAloud.play(r.id,{text:s,voice:n.voice,rate:n.rate,pitch:n.pitch})}static pickBestVoice(t){return Ia(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let o=um(n.content||"");if(!o.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(t,{text:o,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}#We(t){for(let[n,o]of[...this.#e])o===t&&(this.#e.delete(n),this.#Ve(n))}#pt(t){for(let[n,o]of this.#e)o===t&&this.#e.set(n,void 0)}#Ve(t){let n=this.messages.find(l=>l.id===t)?.approval,o=n?.toolCallId,r=o&&this.messages.find(l=>l.toolCall?.id===o),s=r&&r.toolCall;if(!s||s.status==="complete"||n.status==="pending")return;let i={...s,status:"complete",approvalStatus:n.status,completedAt:Date.now(),...n.status==="approved"?{superseded:!0}:{success:!1,error:n.status==="denied"?"Denied":"Approval timed out"}};this.upsertMessage({...r,streaming:!1,toolCall:i})}#te(t){let n=this.#Ae(t);this.messages=this.#ce([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.#Ae(t),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.#te(n);return}this.messages=this.messages.map((r,s)=>{if(s!==o)return r;let i={...r,...n};r.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(i.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(i.agentMetadata={...i.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1});let l=r.agentMetadata?.clientToolAnswer;if(l&&i.agentMetadata&&!i.agentMetadata.clientToolAnswer&&(i.agentMetadata={...i.agentMetadata,clientToolAnswer:l}),r.approval&&n.approval&&r.approval.id===n.approval.id){let g=r.approval,f=n.approval;i.approval={...g,...f,executionId:f.executionId||g.executionId,toolName:f.toolName||g.toolName,description:f.description||g.description,toolType:f.toolType??g.toolType,reason:f.reason??g.reason,parameters:f.parameters??g.parameters,toolCallId:f.toolCallId??g.toolCallId}}let c=n.toolCall?.name,p=n.agentMetadata?.executionId,d=n.toolCall?.id;if(c&&jw(c)&&p&&d&&n.agentMetadata?.awaitingLocalTool===!0){let g=`${p}:${d}`,f=this.webMcpInflightKeys.has(g),h=this.webMcpResolvedKeys.has(g),y=r.toolCall?.name,v=r.agentMetadata?.executionId===p&&r.toolCall?.id===d&&y!==void 0&&jw(y)&&r.toolCall?.status==="complete";(f||h||v)&&(i.agentMetadata={...i.agentMetadata??{},awaitingLocalTool:!1},i.toolCall=r.toolCall,i.streaming=r.streaming)}return i}),this.messages=this.#ce(this.messages),this.callbacks.onMessagesChanged([...this.messages])}#Ae(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.#F()}}#F(){return this.#o++}#ce(t){return[...t].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 i=n.sequence??0,l=o.sequence??0;return i!==l?i-l:n.id.localeCompare(o.id)})}};Ze();var xo=require("lucide");Lr();kt();Nr();var wk={add:e=>IC(e)},Sk=e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0,Wp={allowedTypes:Dr,maxFileSize:10*1024*1024,maxFiles:4};function Ak(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function xk(e){return e==="application/pdf"?xo.FileText:e.startsWith("text/")?xo.FileText:e.includes("word")?xo.FileText:e.includes("excel")||e.includes("spreadsheet")?xo.FileSpreadsheet:e==="application/json"?xo.FileCode:xo.File}var Ai=class e{constructor(t={}){this.attachments=[];this.#e=null;this.#n=new Map;this.#o=!1;this.config={allowedTypes:t.allowedTypes??Wp.allowedTypes,maxFileSize:t.maxFileSize??Wp.maxFileSize,maxFiles:t.maxFiles??Wp.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange,adapter:t.adapter}}#e;#n;#o;#t(){return typeof this.config.adapter?.add=="function"}#s(){return this.#t()?this.config.adapter:wk}setPreviewsContainer(t){this.#e=t}remountPreviews(t){if(this.#e=t,t){t.innerHTML="";for(let n of this.attachments)this.#u(n)}this.#a()}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:Wp.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange),t.adapter!==void 0&&(this.config.adapter=t.adapter)}isReady(){return this.attachments.every(t=>t.status==="ready")}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart).filter(t=>t!==null)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){if(!t.length||this.#o)return;let n=[];for(let o of t){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(o,"count");continue}let r=RC(o,this.config.allowedTypes,this.config.maxFileSize);if(!r.valid){let i=r.error?.includes("type")?"type":"size";this.config.onFileRejected?.(o,i);continue}let s={id:Ak(),file:o,previewUrl:Xd(o)?URL.createObjectURL(o):null,contentPart:null,status:this.#t()?"uploading":"processing",progress:this.#t()?0:void 0};this.attachments.push(s),this.#u(s),n.push(s)}this.#a(),this.#i(),await Promise.all(n.map(o=>this.#r(o)))}async#r(t){let n=new AbortController;this.#n.set(t.id,n);let o=()=>this.#o||n.signal.aborted||this.#n.get(t.id)!==n||!this.attachments.includes(t);try{let r=await this.#s().add(t.file,{signal:n.signal,onProgress:s=>{o()||t.status!=="uploading"||(t.progress=Sk(s),this.#c(t),this.#i())}});if(o())return;t.contentPart=r,t.status="ready",t.progress=void 0,t.error=void 0}catch(r){if(o())return;t.status="error",t.progress=void 0,t.error=r instanceof Error?r.message:String(r??"Upload failed")}finally{this.#n.get(t.id)===n&&this.#n.delete(t.id)}this.#c(t),this.#i()}retryAttachment(t){let n=this.attachments.find(o=>o.id===t);!n||n.status!=="error"||this.#o||(n.status=this.#t()?"uploading":"processing",n.progress=this.#t()?0:void 0,n.error=void 0,this.#c(n),this.#i(),this.#r(n))}#p(t){let n=this.#n.get(t);n&&(this.#n.delete(t),n.abort())}removeAttachment(t){let n=this.attachments.findIndex(s=>s.id===t);if(n===-1)return;let o=this.attachments[n];this.#p(t),o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let r=this.#e?.querySelector(`[data-attachment-id="${t}"]`);r&&r.remove(),o.status==="ready"&&o.contentPart&&this.#f(o.contentPart),this.#a(),this.#i()}#f(t){let n=this.config.adapter?.remove;if(n)try{let o=n(t,{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 t of this.attachments)this.#p(t.id),t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.#n.clear(),this.#e&&(this.#e.innerHTML=""),this.#a(),this.#i()}destroy(){if(!this.#o){this.#o=!0;for(let t of this.#n.values())t.abort();this.#n.clear();for(let t of this.attachments)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.#e=null}}#i(){this.#o||this.config.onAttachmentsChange?.(this.getAttachments())}#u(t){if(!this.#e)return;let n=Xd(t.file),o=x("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",t.id),o.style.width="48px",o.style.height="48px",n&&t.previewUrl){let d=x("img");d.src=t.previewUrl,d.alt=t.file.name,d.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",d.style.width="48px",d.style.height="48px",d.style.objectFit="cover",d.style.borderRadius="8px",o.appendChild(d)}else{let d=x("div");d.style.width="48px",d.style.height="48px",d.style.borderRadius="8px",d.style.backgroundColor="var(--persona-container, #f3f4f6)",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.display="flex",d.style.flexDirection="column",d.style.alignItems="center",d.style.justifyContent="center",d.style.gap="2px",d.style.overflow="hidden";let g=xk(t.file.type),f=Nt(g,20,"var(--persona-muted, #6b7280)",1.5);f&&d.appendChild(f);let h=x("span");h.textContent=WC(t.file.type,t.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",d.appendChild(h),o.appendChild(d)}let r=Q("div",{className:"persona-attachment-status",attrs:{"data-persona-attachment-status":""}}),s=x("div","persona-attachment-progress");s.appendChild(x("div","persona-attachment-progress__bar"));let i=Q("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),l=ge("rotate-cw",12,"var(--persona-text-inverse, #ffffff)",2);l?i.appendChild(l):i.textContent="\u21BB",i.addEventListener("click",d=>{d.preventDefault(),d.stopPropagation(),this.retryAttachment(t.id)}),r.append(s,i),o.appendChild(r);let c=x("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=Nt(xo.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",d=>{d.preventDefault(),d.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(c),this.#e.appendChild(o),this.#l(o,t)}#c(t){let n=this.#e?.querySelector(`[data-attachment-id="${t.id}"]`);n&&this.#l(n,t)}#l(t,n){t.dataset.status=n.status;let o=n.status!=="ready"&&n.status!=="error";t.setAttribute("aria-busy",o?"true":"false"),t.title=n.status==="error"?`${n.file.name}: ${n.error??"Upload failed"}`:n.file.name;let r=t.querySelector(".persona-attachment-progress__bar");if(r){let s=n.progress;r.style.width=typeof s=="number"?`${Math.round(s*100)}%`:""}}#a(){this.#e&&(this.#e.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t?.allowedTypes,maxFileSize:t?.maxFileSize,maxFiles:t?.maxFiles,onFileRejected:t?.onFileRejected,onAttachmentsChange:n,adapter:t?.adapter})}};var qw=(e,t)=>e.length===t.length&&e.every((n,o)=>n===t[o]),Ek=(e,t)=>e.length===t.length&&e.every((n,o)=>{let r=t[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 zw(){let e={text:"",attachments:[],mentionRefs:[],selectedModelId:void 0,activeModeIds:[],quote:void 0,pendingSubmission:void 0,preparing:!1,streaming:!1,inputDisabled:!1,sendDisabled:!1},t=new Set,n=null,o=!1,r=!1,s=()=>e.preparing?"preparing":e.streaming?"streaming":"idle",i=()=>{let d=s();return Object.freeze({text:e.text,attachments:Object.freeze(e.attachments.map(g=>Object.freeze({...g}))),mentionRefs:Object.freeze([...e.mentionRefs]),selectedModelId:e.selectedModelId,activeModeIds:Object.freeze([...e.activeModeIds]),quote:e.quote?Object.freeze({...e.quote}):void 0,pendingSubmission:e.pendingSubmission,phase:d,inputDisabled:e.inputDisabled,sendDisabled:d!=="idle"||e.sendDisabled||e.inputDisabled})},l=()=>(n||(n=i()),n),c=()=>{if(o=!1,r||t.size===0)return;let d=l();for(let g of[...t])try{g(d)}catch(f){typeof console<"u"&&console.error("[AgentWidget] composer state listener failed:",f)}},p=()=>{n=null,!(r||o)&&(o=!0,queueMicrotask(c))};return{getState:l,subscribe:d=>(t.add(d),()=>t.delete(d)),setText:d=>{e.text!==d&&(e.text=d,p())},setAttachments:d=>{Ek(e.attachments,d)||(e.attachments=[...d],p())},setMentionRefs:d=>{qw(e.mentionRefs,d)||(e.mentionRefs=[...d],p())},setSelectedModelId:d=>{e.selectedModelId!==d&&(e.selectedModelId=d,p())},setActiveModeIds:d=>{qw(e.activeModeIds,d)||(e.activeModeIds=[...d],p())},setQuote:d=>{let g=e.quote;g?.text===d?.text&&g?.messageId===d?.messageId&&g?.sourceLabel===d?.sourceLabel||(e.quote=d?{...d}:void 0,p())},setPendingSubmission:d=>{e.pendingSubmission!==d&&(e.pendingSubmission=d,p())},setPreparing:d=>{e.preparing!==d&&(e.preparing=d,p())},setStreaming:d=>{e.streaming!==d&&(e.streaming=d,p())},setInputDisabled:d=>{e.inputDisabled!==d&&(e.inputDisabled=d,p())},setSendDisabled:d=>{e.sendDisabled!==d&&(e.sendDisabled=d,p())},flush:()=>{o&&c()},destroy:()=>{r=!0,o=!1,t.clear()}}}Ze();var Jn=(e,...t)=>{for(let n of t){let o=e.querySelector(n);if(o)return o}return null},Kw=(e,t)=>{let n=x("div",e);return n.setAttribute(t,""),n.setAttribute("data-persona-composer-synthesized",""),n.style.display="contents",n};function Gw(e,t={}){let n=Jn(e,"[data-persona-composer-form]"),o=Jn(e,"[data-persona-composer-input]");if(!n||!o){let A=`[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(t.debug&&(n||o))throw new Error(A);return typeof console<"u"&&console.warn(A),null}let r={header:Jn(e,"[data-persona-composer-header]"),body:Jn(e,"[data-persona-composer-body]"),actionsStart:Jn(e,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:Jn(e,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:Jn(e,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:Jn(e,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:Jn(e,"[data-persona-composer-status]")},s=new Set,i=r.header;i||(s.add("header"),i=Kw("persona-widget-composer__header","data-persona-composer-header"),n.parentNode?n.parentNode.insertBefore(i,n):e.appendChild(i));let l=r.body??o.parentElement??n,c=(C,A,L,I,H)=>{if(A)return A;s.add(C);let B=Kw(L,I);return H.appendChild(B),B},p=c("actionsStart",r.actionsStart,"persona-widget-composer__left-actions","data-persona-composer-actions-start",n),d=c("actionsEnd",r.actionsEnd,"persona-widget-composer__right-actions","data-persona-composer-actions-end",n),g=c("suggestions",r.suggestions,"persona-widget-composer__suggestions","data-persona-composer-suggestions",e),f=c("status",r.status,"persona-widget-composer__status","data-persona-composer-status",e),h=[],y=(C,A)=>C.target===A.target&&C.type===A.type&&C.handler===A.handler,v=Jn(e,"[data-persona-composer-attachment-input]",'input[type="file"]')??void 0;return{footer:e,form:n,input:o,header:i,body:l,actionsStart:p,actionsEnd:d,suggestions:g,status:f,attachmentInput:v,attachmentPreviews:Jn(e,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:Jn(e,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:Jn(e,"[data-persona-composer-submit]")??void 0,micButton:Jn(e,"[data-persona-composer-mic]")??void 0,synthesized:s,found:r,addListener:(C,A,L,I)=>{C.addEventListener(A,L,I),h.push({target:C,type:A,handler:L,options:I})},removeListener:(C,A,L,I)=>{C.removeEventListener(A,L,I),h=h.filter(H=>!y(H,{target:C,type:A,handler:L}))},destroy:()=>{for(let C of h)C.target.removeEventListener(C.type,C.handler,C.options);h=[]}}}Ze();kt();xa();Ms();function Mk(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function Op(e){let{anchor:t,content:n,placement:o="bottom-start",offset:r=6,matchAnchorWidth:s=!1,horizontalOffset:i,verticalOffset:l,zIndex:c=2147483e3,onOpen:p,onDismiss:d}=e,g=e.container??Mk(t),f=!1,h=null,y=()=>{if(!f)return;let A=t.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${A.width}px`),i&&(n.style.maxWidth=`${A.width}px`);let L=n.getBoundingClientRect(),I=l?.()??null,H=I!=null?A.top+I:A.top,B=o==="top-start"||o==="top-end"?H-r-L.height:A.bottom+r,oe=o==="bottom-end"||o==="top-end"?A.right-L.width:A.left,W=i?.()??null;if(W!=null){let j=Math.max(A.left,A.right-L.width);oe=Math.min(Math.max(A.left+W,A.left),j)}n.style.top=`${B}px`,n.style.left=`${oe}px`},v=()=>{f&&(f=!1,h&&(h(),h=null),n.remove())},C=()=>{if(f)return;f=!0,c!=null&&(n.style.zIndex=String(c)),g.appendChild(n),y();let A=(t.ownerDocument??document).defaultView??window,L=t.ownerDocument??document,I=()=>{if(!t.isConnected){v(),d?.("anchor-removed");return}y()},H=V=>{let oe=typeof V.composedPath=="function"?V.composedPath():[];oe.includes(n)||oe.includes(t)||(v(),d?.("outside"))},B=A.setTimeout(()=>{L.addEventListener("pointerdown",H,!0)},0);A.addEventListener("scroll",I,!0),A.addEventListener("resize",I),h=()=>{A.clearTimeout(B),L.removeEventListener("pointerdown",H,!0),A.removeEventListener("scroll",I,!0),A.removeEventListener("resize",I)},p?.()};return{get isOpen(){return f},open:C,close:v,toggle:()=>f?v():C(),reposition:y,destroy:v}}Ze();kt();Ms();var Tk='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',Pk=["--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"],hm="data-persona-menu-focus",kk=new Set(["ArrowDown","ArrowUp","Home","End"]);function Yw(e){return e.getAttribute("role")==="menuitem"?e:e.querySelector(Tk)??e}var Lk=e=>e.disabled===!0||e.getAttribute("aria-disabled")==="true";function Xw(e){let t=e.label,n=!1,o=x("div","persona-send-button-wrapper"),r=Q("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${so} ${Do}`,attrs:{type:"button","aria-haspopup":"menu","aria-expanded":"false","data-persona-composer-overflow-trigger":""}});o.appendChild(r);let s=Q("div",{className:"persona-composer-overflow-menu",attrs:{role:"menu",tabindex:"-1","data-persona-composer-overflow-menu":""}}),i=()=>{let P=e.getButtonSize?.()??"";r.style.width=P,r.style.height=P,r.style.minWidth=P,r.style.minHeight=P,r.style.lineHeight="1",r.replaceChildren();let J=ge("plus",Qn,"currentColor",1.5);J?r.appendChild(J):r.textContent="+"},l=()=>{r.setAttribute("aria-label",t),r.setAttribute("title",t),s.setAttribute("aria-label",t)};l(),i();let c=[],p=-1,d=!1,g=()=>{let J=s.getRootNode().activeElement;return J instanceof HTMLElement?J:null},f=()=>{let P=g();for(let J of c){let U=!!P&&Yw(J)===P;J.toggleAttribute(hm,U&&d)}},h=()=>c.filter(P=>P.isConnected||s.contains(P)).map(Yw).filter(P=>!Lk(P)),y=(P,J)=>{P.forEach((U,ue)=>{U.setAttribute("tabindex",ue===J?"0":"-1")})},v=P=>{let J=h();if(J.length===0)return;let U=(P%J.length+J.length)%J.length;p=U,y(J,U),J[U].focus(),f()},C=()=>o.ownerDocument??document,A=null,L=null,I=null,H=()=>{A&&(C().removeEventListener("focusin",A,!0),A=null)},B=()=>{L&&(s.removeEventListener("focusin",L),L=null),I&&(s.removeEventListener("pointerdown",I,!0),I=null)},V=null,oe=()=>(V||(V=Op({anchor:r,content:s,placement:"top-start",offset:6,onDismiss:()=>{r.setAttribute("aria-expanded","false"),H()}})),V),W=()=>V?.isOpen===!0,j=(P=!1)=>{if(W()){V?.close(),r.setAttribute("aria-expanded","false"),H(),B(),p=-1,d=!1;for(let J of c)J.removeAttribute(hm);P&&r.focus()}},X=(P=0,J=!1)=>{if(n||W())return;d=J,tp(r,s,Pk),oe().open(),r.setAttribute("aria-expanded","true");let U=h();y(U,-1),v(P<0?U.length-1:P),A=ue=>{let fe=typeof ue.composedPath=="function"?ue.composedPath():[];fe.includes(s)||fe.includes(o)||j()},C().addEventListener("focusin",A,!0),L=()=>f(),s.addEventListener("focusin",L),I=()=>{d=!1},s.addEventListener("pointerdown",I,!0)},M=P=>{P.preventDefault(),P.stopPropagation(),W()?j(!0):X(0)},T=P=>{if(P.key==="ArrowDown"||P.key==="Enter"||P.key===" "){P.preventDefault(),d=!0,W()?v(0):X(0,!0);return}P.key==="ArrowUp"&&(P.preventDefault(),d=!0,W()?v(-1):X(-1,!0))},_=P=>{switch(kk.has(P.key)&&(d=!0),P.key){case"ArrowDown":P.preventDefault(),v(p+1);return;case"ArrowUp":P.preventDefault(),v(p-1);return;case"Home":P.preventDefault(),v(0);return;case"End":P.preventDefault(),v(h().length-1);return;case"Escape":P.preventDefault(),P.stopPropagation(),j(!0);return;case"Tab":j(!0);return;default:}};return r.addEventListener("click",M),r.addEventListener("keydown",T),s.addEventListener("keydown",_),{trigger:o,triggerButton:r,panel:s,setItems:P=>{for(let U of c)P.includes(U)||U.removeAttribute(hm);if(c=[...P],!W())return;let J=h();y(J,Math.min(p,J.length-1)),f()},isOpen:W,open:()=>X(0),close:j,setLabel:P=>{P!==t&&(t=P,l())},applyButtonSize:i,destroy:()=>{n=!0,H(),B(),r.removeEventListener("click",M),r.removeEventListener("keydown",T),s.removeEventListener("keydown",_),V?.destroy(),V=null,o.remove(),s.remove(),c=[]}}}var sr={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},Qw="data-persona-composer-action",ym="data-persona-composer-disable-when-streaming",Hk="core:overflow",Ik=e=>e==="core:attachment"?"attachments":e.startsWith("core:mention")?"mentions":null;function Rk(e,t){if(e===void 0)return null;if(typeof e=="number")return Number.isFinite(e)?e:null;let n=Number.parseFloat(e);if(/^\s*-?\d*\.?\d+(px)?\s*$/.test(e)&&Number.isFinite(n))return n;let o=x("div");o.style.position="absolute",o.style.visibility="hidden",o.style.pointerEvents="none",o.style.height="0",o.style.width=e,t.appendChild(o);let r=o.getBoundingClientRect().width;return o.remove(),Number.isFinite(r)&&r>0?r:Number.isFinite(n)?n:null}function bm(e){let t=e.clientWidth;if(!t)return 0;let n=e.ownerDocument?.defaultView;if(!n?.getComputedStyle)return t;let o=n.getComputedStyle(e),r=(Number.parseFloat(o.paddingLeft)||0)+(Number.parseFloat(o.paddingRight)||0);return Math.max(0,t-r)}var Jw=(e,t)=>{!e||typeof console>"u"||console.warn(t)},Wk=(e,t)=>t.includes(":")?t:`${e}:${t}`;function Ok(e){let{debug:t}=e,n=[],o=new Map,r=0,s=l=>{let c=o.get(l.id);if(c){Jw(t,`[Persona] composer action "${l.id}" is already contributed by ${Zw(c)}; the ${Zw(l)} copy is ignored.`);return}o.set(l.id,l),n.push(l)};for(let l of e.builtIns)s({id:l.id,placement:l.placement,presentation:"bar",order:l.order,sequence:r++,source:"core",builtIn:l});let i=(l,c,p)=>{let d=p?Wk(p,l.id):l.id,g=l.order??sr.custom;l.placement==="end"&&g>=sr.send&&(Jw(t,`[Persona] composer action "${d}" ordered at ${g} would render after send; clamped to ${sr.send-1}.`),g=sr.send-1),s({id:d,placement:l.placement,presentation:l.presentation??"bar",order:g,sequence:r++,source:c,pluginId:p,action:l})};for(let l of e.configActions??[])i(l,"config");for(let l of e.plugins){if(!l.contributeComposerActions)continue;let c;try{c=l.contributeComposerActions(e.contributionContext)}catch(p){typeof console<"u"&&console.error(`[Persona] plugin "${l.id}" contributeComposerActions failed:`,p);continue}for(let p of c??[])i(p,"plugin",l.id)}return n.sort((l,c)=>l.order===c.order?l.sequence-c.sequence:l.order-c.order)}var Zw=e=>e.source==="plugin"?`plugin "${e.pluginId}"`:e.source==="config"?"composer.actions":"a core built-in",eS=(e,t,n)=>e===void 0?n:typeof e=="function"?e(t)===!0:e===!0,_k=e=>e.phase==="streaming"||e.text.trim().length>0||e.attachments.length>0;function Bk(e,t){if(!e||e==="always")return!0;let n=_k(t);return e==="when-text"?n:!n}var Ls=e=>e.kind==="custom",vm=e=>e instanceof HTMLButtonElement?e:e.querySelector("button")??e,Dk=e=>{let t=vm(e);return t.getAttribute("aria-label")?.trim()||t.getAttribute("title")?.trim()||""},Nk='.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]';function Fk(e){let t="",n=o=>{if(o.nodeType===Node.TEXT_NODE){t+=o.nodeValue??"";return}if(o.nodeType!==Node.ELEMENT_NODE)return;let r=o;typeof r.matches=="function"&&r.matches(Nk)||o.childNodes.forEach(n)};return n(e),t.trim()}var $k=e=>Fk(e).length===0;function tS(e){let t=new Map,n=[],o=!1,r=()=>e.getButtonSize?.(),s=(M,T)=>{let _=M.button;if(!_)return;_.setAttribute("role","menuitem"),_.setAttribute("tabindex","-1"),_.className="persona-composer-overflow-menu__item";for(let U of["width","height","minWidth","minHeight","fontSize","color","backgroundColor"])_.style[U]="";_.style.lineHeight="1",T.tooltipText?_.setAttribute("title",T.tooltipText):_.removeAttribute("title"),_.replaceChildren();let P=x("span","persona-composer-overflow-menu__icon");if(T.iconName){let U=ge(T.iconName,16,"currentColor",1.5);U&&P.appendChild(U)}let J=x("span","persona-composer-overflow-menu__label");J.textContent=T.shortLabel??T.label,_.append(P,J)},i=(M,T)=>{let _=M.button;if(!_)return;if(_.setAttribute("aria-label",T.label),T.pressed===void 0?_.removeAttribute("aria-pressed"):_.setAttribute("aria-pressed",T.pressed?"true":"false"),_.toggleAttribute(ym,T.disableWhenStreaming===!0),M.mode==="menu"){M.tooltip?.destroy(),M.tooltip=void 0,s(M,T);return}_.removeAttribute("role"),_.removeAttribute("tabindex"),_.removeAttribute("title");let P=r(),J=!!T.shortLabel;if(_.className=Dn("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",so,Do,J&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),_.style.width=P&&!J?P:"",_.style.height=P??"",_.style.minWidth=P&&!J?P:"",_.style.minHeight=P??"",_.style.fontSize=J?"":"18px",_.style.lineHeight="1",_.style.color=T.iconColor??"",_.style.backgroundColor=T.backgroundColor??"",_.replaceChildren(),T.iconName){let U=ge(T.iconName,Qn,"currentColor",1.5);U&&_.appendChild(U)}if(J){let U=x("span","persona-composer-action-button__label");U.textContent=T.shortLabel,_.appendChild(U)}else _.firstChild||(_.textContent=T.label);M.tooltip?.destroy(),M.tooltip=vn({anchor:_,trigger:M.element,text:()=>T.tooltipText??T.label,enabled:!!T.tooltipText})},l=(M,T)=>{let _=M.action,P=Q("button",{attrs:{type:"button"}}),J=P;if(T==="bar"){let fe=x("div","persona-send-button-wrapper");fe.appendChild(P),J=fe}J.setAttribute(Qw,M.id);let U={resolved:M,element:J,button:P,owned:!0,managed:!0,busy:!1,visible:!0,mode:T},ue=fe=>{if(fe.preventDefault(),fe.stopPropagation(),U.busy||P.disabled)return;let me=U.resolved.action;U.mode==="menu"&&h?.close(!0);let He;try{He=me.onSelect(e.actionContext,fe)}catch(Ee){e.reportError(Ee,{actionId:U.resolved.id});return}!He||typeof He.then!="function"||(U.busy=!0,P.setAttribute("aria-busy","true"),He.catch(Ee=>{e.reportError(Ee,{actionId:U.resolved.id})}).finally(()=>{U.busy=!1,P.removeAttribute("aria-busy")}))};return P.addEventListener("click",ue),U.detach=()=>P.removeEventListener("click",ue),i(U,_),U},c=M=>{let T=M.action,_;try{_=T.render({...e.actionContext,id:M.id,action:T})}catch(P){return e.reportError(P,{actionId:M.id}),null}return _?.element?(_.element.setAttribute(Qw,M.id),_.element.toggleAttribute(ym,T.disableWhenStreaming===!0),{resolved:M,element:_.element,owned:!0,managed:!0,destroy:_.destroy,busy:!1,visible:!0,mode:"bar"}):null},p=(M,T)=>{if(M.builtIn){let P=M.builtIn.element;return P?{resolved:M,element:P,owned:!1,managed:M.builtIn.managed===!0,busy:!1,visible:!0,mode:"bar"}:null}let _=M.action;return _?Ls(_)?c(M):l(M,T):null},d=M=>{if(M.detach?.(),M.tooltip?.destroy(),M.detachMenuSlot?.(),M.detachMenuSlot=void 0,M.menuLabel?.remove(),M.menuLabel=void 0,M.menuSlot?.remove(),M.menuSlot=void 0,M.owned){try{M.destroy?.()}catch(T){e.reportError(T,{actionId:M.resolved.id})}M.element.remove()}},g=(M,T)=>{for(let _=0;_<T.length;_++){let P=T[_];if(!P.managed)continue;let J=null;for(let U=_+1;U<T.length;U++){let ue=T[U];if(!ue.managed&&ue.element.parentElement===M){J=ue.element;break}}J?(P.element.parentElement!==M||P.element.nextSibling!==J)&&M.insertBefore(P.element,J):M.lastChild!==P.element&&M.appendChild(P.element)}},f=(M,T)=>{if(M.button){M.button.disabled=T;return}if(!M.owned)return;let _=M.element;_.toggleAttribute("data-disabled",T),_.setAttribute("aria-disabled",T?"true":"false");let P=_ instanceof HTMLButtonElement||_ instanceof HTMLSelectElement||_ instanceof HTMLInputElement||_ instanceof HTMLTextAreaElement?_:_.querySelector("button, select, input, textarea");P&&(P.disabled=T)},h=null,y=null,v=null,C=0,A=()=>{let M=e.getOverflow?.();return M?.enabled===!0?M:void 0},L=()=>(h?h.setLabel(e.getOverflowLabel?.()??"More actions"):h=Xw({label:e.getOverflowLabel?.()??"More actions",getButtonSize:r}),h),I=M=>{y!==M&&(v?.disconnect(),y=M,C=bm(M),!(typeof ResizeObserver>"u")&&(v=new ResizeObserver(T=>{let P=T[T.length-1]?.contentRect?.width??bm(M);P!==C&&(C=P,j())}),v.observe(M)))},H=(M,T)=>{let _=Rk(M.collapseAutoActionsBelow,T);if(_===null)return!1;let P=C||bm(T);return P>0&&P<_},B=(M,T,_)=>{if(!T)return"bar";if(M.resolved.builtIn){let J=Ik(M.resolved.id);return J&&T.includeBuiltIns?.includes(J)?"menu":"bar"}let P=M.resolved.presentation;return P==="overflow"||P==="auto"&&_?"menu":"bar"},V=M=>{let T=M.menuSlot;if(!T)return;if(!$k(M.element)){M.menuLabel?.remove(),M.menuLabel=void 0;return}let _=Dk(M.element);if(!_){M.menuLabel?.remove(),M.menuLabel=void 0;return}M.menuLabel||(M.menuLabel=x("span","persona-composer-overflow-menu__label")),M.menuLabel.textContent!==_&&(M.menuLabel.textContent=_),M.menuLabel.parentElement!==T&&T.appendChild(M.menuLabel)},oe=(M,T)=>{if(M.mode===T)return M;let _=M.resolved.action;if(_&&!Ls(_)){d(M),t.delete(M.resolved.id);let P=l(M.resolved,T);return t.set(M.resolved.id,P),P}if(T==="menu"){let P=Q("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none",[Mf]:""}});P.appendChild(M.element),gC(vm(M.element)),M.menuSlot=P;let J=U=>{let ue=vm(M.element);if(ue.disabled)return;let fe=U.target===ue||ue.contains(U.target);h?.close(!0),fe||ue.click()};P.addEventListener("click",J,!0),M.detachMenuSlot=()=>P.removeEventListener("click",J,!0),M.managed=!0,V(M)}else M.detachMenuSlot?.(),M.detachMenuSlot=void 0,M.menuLabel?.remove(),M.menuLabel=void 0,M.menuSlot?.remove(),M.menuSlot=void 0;return M.mode=T,M},W=(M,T)=>{let _=T.map(P=>P.menuSlot??P.element);for(_.forEach((P,J)=>{let U=M.children[J];U!==P&&(U?M.insertBefore(P,U):M.appendChild(P))});M.children.length>_.length;)M.lastElementChild?.remove()},j=()=>{if(o)return;let M=e.getBindings();if(!M)return;let T=e.getState(),_=T.phase==="streaming",P=A();P&&I(M.footer);let J=P?H(P,M.footer):!1,U={start:[],end:[]},ue=[];for(let fe of n){let me=t.get(fe.id);if(!me)continue;let He=fe.action,Ee=He?eS(He.visible,T,!0)&&Bk(He.visibility,T):!0;if(me.visible!==Ee&&(me.visible=Ee,!Ee&&me.managed&&(me.menuSlot??me.element).remove()),!!Ee){if(me=oe(me,B(me,P,J)),He){let Ie=eS(He.disabled,T,!1)||He.disableWhenStreaming===!0&&_;f(me,Ie),!Ls(He)&&He.pressed!==void 0&&me.button?.setAttribute("aria-pressed",He.pressed?"true":"false")}me.mode==="menu"?(V(me),ue.push(me)):U[fe.placement].push(me)}}if(ue.length>0){let fe=L();W(fe.panel,ue),fe.setItems(ue.map(Ie=>Ie.menuSlot??Ie.element)),fe.applyButtonSize();let me=Number.isFinite(P?.order)?P?.order:sr.overflow,He=U.start.findIndex(Ie=>Ie.resolved.order>me),Ee={resolved:{id:Hk,placement:"start",presentation:"bar",order:me,sequence:-1,source:"core"},element:fe.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};U.start.splice(He<0?U.start.length:He,0,Ee)}else h&&(h.close(),h.trigger.remove(),h.setItems([]));g(M.actionsStart,U.start),g(M.actionsEnd,U.end)};return{resolve:()=>{if(o)return;let M=Ok(e.collect()),T=new Set(M.map(_=>_.id));for(let[_,P]of t)T.has(_)||(d(P),t.delete(_));for(let _ of M){let P=t.get(_.id);if(!P){let fe=p(_,"bar");fe&&t.set(_.id,fe);continue}let J=P.resolved.action,U=_.action;if(!!J!=!!U||J&&U&&Ls(J)!==Ls(U)||J&&U&&Ls(J)&&Ls(U)&&J.render!==U.render){d(P),t.delete(_.id);let fe=p(_,P.mode);fe&&t.set(_.id,fe);continue}P.resolved=_,_.builtIn?(P.managed=_.builtIn.managed===!0||P.mode==="menu",_.builtIn.element&&P.mode==="bar"&&(P.element=_.builtIn.element)):U&&!Ls(U)?i(P,U):U&&P.element.toggleAttribute(ym,U.disableWhenStreaming===!0)}n=M,j()},sync:j,getResolved:()=>n,getOverflowMenu:()=>h,destroy:()=>{if(!o){o=!0,v?.disconnect(),v=null,y=null;for(let M of t.values())d(M);t.clear(),h?.destroy(),h=null,n=[]}}}}Ze();kt();Ms();var Uk="core:model",Vk=700,nS=16,jk=["--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"],oS=()=>{let e=Q("span",{className:"persona-composer-model-picker-wrapper",attrs:{"data-persona-composer-model-picker-wrapper":""}}),t=Q("span",{className:"persona-composer-model-picker-chevron",attrs:{"aria-hidden":"true"}});return{wrapper:e,chevron:t}};function rS(e){let t=e.label??"Model",n=e.presentation??"native",o=null,r=c=>{let p=e.getSelectedModelId();return c.find(d=>d.id===p)??c[0]},s=()=>{let c=Q("select",{className:"persona-composer-model-picker",attrs:{"aria-label":t,"data-persona-composer-model-picker":""}}),p="",d=()=>{let v=e.getModels(),C=v.map(A=>`${A.id}:${A.label}`).join("|");C!==p&&(p=C,c.replaceChildren(...v.map(A=>{let L=Q("option",{attrs:{value:A.id}});return L.textContent=A.label,L}))),c.value=r(v)?.id??""};d(),o=d;let g=()=>{c.value&&e.onSelect(c.value)};c.addEventListener("change",g);let f=v=>v.stopPropagation();c.addEventListener("click",f);let{wrapper:h,chevron:y}=oS();return h.append(c,y),{element:h,destroy:()=>{o===d&&(o=null),c.removeEventListener("change",g),c.removeEventListener("click",f)}}},i=()=>{let c=Q("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=x("span","persona-composer-model-picker-label"),d=x("span","persona-composer-model-picker-suffix");c.append(p,d);let g=Q("div",{className:"persona-composer-model-menu",attrs:{role:"listbox",tabindex:"-1","aria-label":t,"data-persona-composer-model-menu":""}}),f=new Map,h="",y=null,v=()=>y?.isOpen===!0,C=(T=!1)=>{v()&&(y?.close(),c.setAttribute("aria-expanded","false"),T&&c.focus())},A=T=>{let _=[...f.values()];if(_.length===0)return;let P=(T%_.length+_.length)%_.length;_[P].focus()},L=T=>{if(v())return;y||(y=Op({anchor:c,content:g,placement:"top-start",offset:6,onDismiss:()=>c.setAttribute("aria-expanded","false")})),tp(c,g,jk),y.open(),c.setAttribute("aria-expanded","true");let P=[...f.keys()].indexOf(r(e.getModels())?.id??"");A(T??(P>=0?P:0))},I=T=>{C(!0),e.onSelect(T)},H=T=>{T.preventDefault(),T.stopPropagation();let _=T.currentTarget.getAttribute("data-persona-model-option");_&&I(_)},B=T=>{let _=Q("button",{className:"persona-composer-model-option",attrs:{type:"button",role:"option",tabindex:"-1","aria-selected":"false","data-persona-model-option":T.id}});if(T.icon){let fe=ge(T.icon,nS,"currentColor",1.5);if(fe){let me=x("span","persona-composer-model-option-icon");me.appendChild(fe),_.appendChild(me)}}let P=x("span","persona-composer-model-option-body"),J=x("span","persona-composer-model-option-label");if(J.textContent=T.label,P.appendChild(J),T.description){let fe=x("span","persona-composer-model-option-description");fe.textContent=T.description,P.appendChild(fe)}_.appendChild(P);let U=x("span","persona-composer-model-option-check");U.setAttribute("aria-hidden","true");let ue=ge("check",nS,"currentColor",2);return ue&&U.appendChild(ue),_.appendChild(U),_.addEventListener("click",H),_},V=()=>{let T=e.getModels(),_=T.map(U=>`${U.id}:${U.label}:${U.icon??""}:${U.description??""}`).join("|");if(_!==h){h=_;for(let U of f.values())U.removeEventListener("click",H);f.clear(),g.replaceChildren(...T.map(U=>{let ue=B(U);return f.set(U.id,ue),ue}))}let P=r(T);for(let[U,ue]of f)ue.setAttribute("aria-selected",String(U===P?.id));p.textContent=P?.label??"";let J=e.getSuffix?.()??"";d.textContent=J,c.setAttribute("aria-label",[t,[P?.label,J].filter(Boolean).join(" ")].filter(Boolean).join(": "))};V(),o=V;let oe=T=>{T.preventDefault(),T.stopPropagation(),v()?C(!0):L()},W=T=>{if(T.key==="ArrowDown"){T.preventDefault(),v()?A(0):L(0);return}T.key==="ArrowUp"&&(T.preventDefault(),v()?A(-1):L(-1))},j=T=>{let _=[...f.values()],P=_.indexOf(T.target?.closest?.(".persona-composer-model-option"));switch(T.key){case"ArrowDown":T.preventDefault(),A(P+1);return;case"ArrowUp":T.preventDefault(),A(P-1);return;case"Home":T.preventDefault(),A(0);return;case"End":T.preventDefault(),A(_.length-1);return;case"Escape":T.preventDefault(),T.stopPropagation(),C(!0);return;case"Tab":C(!0);return;default:}};c.addEventListener("click",oe),c.addEventListener("keydown",W),g.addEventListener("keydown",j);let{wrapper:X,chevron:M}=oS();return X.append(c,M),{element:X,destroy:()=>{o===V&&(o=null),c.removeEventListener("click",oe),c.removeEventListener("keydown",W),g.removeEventListener("keydown",j);for(let T of f.values())T.removeEventListener("click",H);f.clear(),y?.destroy(),y=null,g.remove()}}};return{action:{id:Uk,kind:"custom",placement:"end",order:Vk,presentation:n==="popover"?"bar":"auto",label:t,render:()=>n==="popover"?i():s()},repaint:()=>o?.()}}Ze();kt();Ze();var Cm="[data-persona-composer-chip-row]";function _p(e){e.style.display=e.childElementCount>0?"flex":"none"}function wm(e){let t=e.querySelector(Cm);if(t)return t;let n=Q("div",{className:"persona-composer-chip-row",attrs:{"data-persona-composer-chip-row":""}});n.style.display="none";let o=e.querySelector("[data-persona-composer-quote], [data-persona-composer-pending]");return o?.parentElement===e?e.insertBefore(n,o):e.appendChild(n),n}var qk=":scope > [data-persona-composer-mode]";function sS(e){let t=e.row,n="",o=!1,r=new Set(e.initialIds??[]),s=p=>{let d=Q("span",{className:"persona-mention-chip persona-composer-mode-chip",attrs:{"data-persona-composer-mode":p.id}});if(p.iconName){let y=x("span","persona-mention-chip-icon"),v=ge(p.iconName,12,"currentColor",1.5);v&&y.appendChild(v),d.appendChild(y)}let g=x("span","persona-mention-chip-label");g.textContent=p.shortLabel??p.label,d.appendChild(g);let f=Q("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${p.label}`}}),h=ge("x",12,"currentColor",2);return h?f.appendChild(h):f.textContent="\xD7",f.addEventListener("click",y=>{y.preventDefault(),y.stopPropagation(),e.onRemove(p.id)}),d.appendChild(f),d},i=()=>Array.from(t.querySelectorAll(qk)),l=p=>{p.setAttribute("data-persona-chip-exit",""),p.setAttribute("aria-hidden","true"),p.style.pointerEvents="none";let d=()=>{p.remove(),_p(t)},g=t.ownerDocument.defaultView,f=typeof g?.getComputedStyle=="function"?g.getComputedStyle(p).animationName:"";if(!f||f==="none"){d();return}p.addEventListener("animationend",d,{once:!0}),p.addEventListener("animationcancel",d,{once:!0})},c=()=>{for(let p of i())p.remove()};return{element:t,render:(p,d)=>{if(o)return;let g=d.filter(v=>p.includes(v.id)),f=g.map(v=>`${v.id}:${v.shortLabel??v.label}`).join("|");if(f===n)return;n=f;let h=new Map;for(let v of i()){let C=v.getAttribute("data-persona-composer-mode");C&&g.some(L=>L.id===C)&&!v.hasAttribute("data-persona-chip-exit")?h.set(C,v):v.hasAttribute("data-persona-chip-exit")||l(v)}let y=t.firstChild;for(let v of g){let C=h.get(v.id);C||(C=s(v),r.has(v.id)||(C.setAttribute("data-persona-chip-enter",""),C.addEventListener("animationend",()=>C?.removeAttribute("data-persona-chip-enter"),{once:!0}))),r.delete(v.id),C!==y&&t.insertBefore(C,y),y=C.nextSibling}_p(t)},destroy:()=>{o=!0,c(),_p(t)}}}Ze();kt();var iS=e=>`core:mode:${e}`;var Sm=e=>Math.min(300+e,499),aS=e=>`core:mode-group:${e}`;function Bp(e,t){return e?t?.find(n=>n.id===e)?.presentation==="segmented":!1}function zk(e,t){return e?t?.find(n=>n.id===e)?.chipVisibility==="hidden":!1}function lS(e,t){return e?.length?e.filter(n=>!Bp(n.groupId,t)&&!zk(n.groupId,t)):[]}var Kk=(e,t)=>e.groupId?t?.find(n=>n.id===e.groupId)?.selection??null:null;function cS(e,t,n,o){let r=n.find(l=>l.id===t);if(!r)return[...e];let s=e.includes(t),i=new Set(e);if(s)i.delete(t);else{if(Kk(r,o)==="single"){let l=n.filter(c=>c.groupId===r.groupId).map(c=>c.id);i=new Set([...i].filter(c=>!l.includes(c)))}i.add(t)}return n.filter(l=>i.has(l.id)).map(l=>l.id)}function Dp(e,t){return t?.length?t.filter(n=>e.includes(n.id)).map(n=>n.id):[]}function dS(e,t){return t?.length?t.filter(n=>e.includes(n.id)&&(n.persistence??"sticky")!=="once").map(n=>n.id):[]}function pS(e,t){if(!(!t?.length||e.length===0))return t.find(n=>e.includes(n.id)&&n.placeholder)?.placeholder}var Gk=16;function uS(e){let t=null;return{action:{id:aS(e.groupId),kind:"custom",placement:"start",presentation:"bar",label:e.getGroup()?.label??e.groupId,render:()=>{let o=Q("div",{className:"persona-composer-segmented",attrs:{"data-persona-composer-mode-group":e.groupId}}),r=new Map,s="",i=p=>{p.preventDefault(),p.stopPropagation();let g=p.currentTarget.getAttribute("data-persona-composer-mode");!g||e.getActiveIds().includes(g)&&e.getGroup()?.selection==="single"||e.onSelect(g)},l=p=>{let d=Q("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":p.id,"aria-label":p.label}});if(p.iconName){let f=ge(p.iconName,Gk,"currentColor",1.5);f&&d.appendChild(f)}let g=x("span","persona-composer-segmented-label");return g.textContent=p.shortLabel??p.label,d.appendChild(g),d.addEventListener("click",i),d},c=()=>{let p=e.getGroup();p?.label?(o.setAttribute("role","group"),o.setAttribute("aria-label",p.label)):(o.removeAttribute("role"),o.removeAttribute("aria-label"));let d=e.getModes(),g=d.map(h=>`${h.id}:${h.shortLabel??h.label}:${h.iconName??""}`).join("|");if(g!==s){s=g;for(let y of r.values())y.removeEventListener("click",i);r.clear();let h=d.map(y=>{let v=l(y);return r.set(y.id,v),v});o.replaceChildren(...h)}let f=e.getActiveIds();for(let[h,y]of r)y.setAttribute("aria-pressed",String(f.includes(h)))};return c(),t=c,{element:o,destroy:()=>{t===c&&(t=null);for(let p of r.values())p.removeEventListener("click",i);r.clear()}}}},repaint:()=>t?.()}}Ze();kt();function gS(e){let t=Q("div",{className:"persona-composer-quote",attrs:{"data-persona-composer-quote":""}});t.style.display="none";let n="",o=!1,r=s=>{let i=x("span","persona-composer-quote-bar"),l=x("div","persona-composer-quote-content");if(s.sourceLabel){let g=x("div","persona-composer-quote-source");g.textContent=s.sourceLabel,l.appendChild(g)}let c=Q("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});c.textContent=Hp(s.text),l.appendChild(c);let p=Q("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":e.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),d=ge("x",12,"currentColor",2);d?p.appendChild(d):p.textContent="\xD7",p.addEventListener("click",g=>{g.preventDefault(),g.stopPropagation(),e.onDismiss()}),t.replaceChildren(i,l,p)};return{element:t,render:s=>{if(o)return;let i=s?`${s.sourceLabel??""}\0${s.text}`:"";if(i!==n){if(n=i,!s){t.replaceChildren(),t.style.display="none";return}r(s),t.style.display="flex"}},destroy:()=>{o=!0,t.replaceChildren(),t.remove()}}}Ze();kt();function fS(e){let t=Q("div",{className:"persona-composer-pending",attrs:{"data-persona-composer-pending":""}});t.style.display="none";let n,o=!1,r=(i,l,c,p)=>{let d=Q("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":l,[c]:""}}),g=ge(i,12,"currentColor",2);return g?d.appendChild(g):d.textContent=l,d.addEventListener("click",f=>{f.preventDefault(),f.stopPropagation(),p()}),d},s=i=>{let l=Hp(i.text??"",90);if(l)return l;let c=i.contentParts?.length??0;return c>0?c===1?"1 attachment":`${c} attachments`:(i.mentionRefs?.length??0)>0?i.mentionRefs.map(d=>d.label).join(", "):"Queued message"};return{element:t,render:i=>{if(o||i===n)return;if(n=i,!i){t.replaceChildren(),t.style.display="none";return}let l=x("span","persona-composer-pending-badge");l.textContent=e.label??"Sends next";let c=Q("div",{className:"persona-composer-pending-text",attrs:{"data-persona-composer-pending-text":""}});c.textContent=s(i),t.replaceChildren(l,c,r("pencil",e.editLabel??"Edit queued message","data-persona-composer-pending-edit",e.onEdit),r("x",e.removeLabel??"Remove queued message","data-persona-composer-pending-remove",e.onRemove)),t.style.display="flex"},destroy:()=>{o=!0,t.replaceChildren(),t.remove()}}}Ze();function mS(e){let t=Q("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":e.messageId,"data-preserve-runtime":""}}),n=Q("textarea",{className:"persona-message-edit-input",attrs:{rows:"1",dir:"auto","aria-label":"Edit message","data-persona-message-edit-input":""}});n.value=e.initialText;let o=()=>{n.style.height="auto",n.style.height=`${n.scrollHeight}px`};n.addEventListener("input",o);let r=x("div","persona-message-edit-actions"),s=(l,c,p,d)=>{let g=Q("button",{className:`persona-message-edit-button ${c}`,attrs:{type:"button",[p]:""},text:l});return g.addEventListener("click",f=>{f.preventDefault(),f.stopPropagation(),d()}),g},i=()=>{let l=n.value.trim();l&&e.onSave(l)};return r.append(s(e.cancelLabel??"Cancel","persona-message-edit-cancel","data-persona-message-edit-cancel",e.onCancel),s(e.saveLabel??"Send","persona-message-edit-save","data-persona-message-edit-save",i)),n.addEventListener("keydown",l=>{if(l.key==="Escape"){l.preventDefault(),l.stopPropagation(),e.onCancel();return}l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),i())}),t.append(n,r),{element:t,getValue:()=>n.value,focus:()=>{n.focus();let l=n.value.length;n.setSelectionRange(l,l),o()},destroy:()=>{t.replaceChildren(),t.remove()}}}function hS(e){let t=e.text??"";if(t.trim().length>0||(e.mentionRefs?.length??0)>0||(e.activeModeIds?.length??0)>0||e.quote||e.selectedModelId)return{text:t,...e.mentionRefs?.length?{mentionRefs:[...e.mentionRefs]}:{},...e.contentSegments?.length?{contentSegments:[...e.contentSegments]}:{},...e.selectedModelId?{selectedModelId:e.selectedModelId}:{},...e.activeModeIds?.length?{activeModeIds:[...e.activeModeIds]}:{},...e.quote?{quote:{...e.quote}}:{}}}function yS(e,t){if(!e||typeof e.text!="string")return;let n=new Set(t.mentionSourceIds),o=(e.mentionRefs??[]).filter(c=>n.has(c.sourceId)),r=o.length===(e.mentionRefs?.length??0)&&o.length>0,s=new Set(t.modes.map(c=>c.id)),i=(e.activeModeIds??[]).filter(c=>s.has(c)),l=e.selectedModelId&&t.modelIds.includes(e.selectedModelId)?e.selectedModelId:void 0;return{text:e.text,...r?{mentionRefs:o}:{},...r&&e.contentSegments?.length?{contentSegments:e.contentSegments}:{},...l?{selectedModelId:l}:{},...i.length?{activeModeIds:i}:{},...e.quote?.text?{quote:e.quote}:{}}}function bS(e){let t=e.delay??500,n=null,o=!1,r=()=>{n!==null&&(clearTimeout(n),n=null)};return{schedule:()=>{o||(r(),n=setTimeout(()=>{n=null,e.write()},t))},flush:()=>{o||n===null||(r(),e.write())},cancel:r,destroy:()=>{o=!0,r()}}}function vS(e){return e.wrapped||e.text.includes(`
|
|
29
|
+
`)?!1:!(e.hasAttachments||e.hasChips||e.hasQuote||e.hasPendingSubmission)}function CS(){let e=!1;return{observe:(t,n)=>n?(t&&(e=!0),e):(e=!1,!1),release:()=>{e=!1}}}function wS(e){if(!e)return!1;let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return!1;let n=t.getComputedStyle(e),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 i=(Number.parseFloat(n.paddingTop)||0)+(Number.parseFloat(n.paddingBottom)||0);return e.scrollHeight-i>s*1.5}function SS(e){e&&(typeof e.requestSubmit=="function"?e.requestSubmit():e.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})))}ep();function Am(e){return Object.freeze({text:e.text,contentParts:e.contentParts?Object.freeze([...e.contentParts]):void 0,mentionRefs:Object.freeze([...e.mentionRefs]),contentSegments:e.contentSegments?Object.freeze([...e.contentSegments]):void 0,options:Object.freeze({...e.options}),viaVoice:e.viaVoice})}function xS(e){return e.inputDisabled===!0||e.sendDisabled===!0||e.hasAttachments&&!e.attachmentsReady?!1:!!e.text||e.hasAttachments||e.hasMentions||e.hasServerMentions}var Yk=e=>typeof e?.then=="function";function AS(e,t){return t===!1?{status:"canceled"}:!t||typeof t!="object"?{status:"proceed"}:(typeof t.text=="string"&&(e.text=t.text),t.options&&(e.options={...e.options,...t.options}),{status:"proceed"})}function ES(e,t,n){let o;try{o=e(Am(t),{signal:n})}catch(r){return{status:"error",error:r}}return Yk(o)?Promise.resolve(o).then(r=>n.aborted?{status:"aborted"}:AS(t,r),r=>n.aborted?{status:"aborted"}:{status:"error",error:r}):AS(t,o)}jf();qf();Vf();Nr();var Np=e=>e?.launcher?.variant??(e?.future?.v5Defaults===!0?"circle":"pill"),Fp={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"};So();So();var Up="16px",Vp="transparent",Xk=(()=>{let e={};for(let t of[0,1,2,3,4,5,6,8,10,12,16,20,24,32,40,48,56,64])e[t]=t===0?"0px":`${t/4}rem`;return e})(),Kl={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:Xk,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"}},$p={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"}},io={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:vi,maxWidth:"none",height:"min(640px, max(200px, calc(100vh - 64px)))",maxHeight:"none",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:Up,canvasBackground:Vp,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"}}},Qk=Kl.colors.gray,Jk={50:"#fafafa",100:"#f5f5f5",200:"#e5e5e5",300:"#d4d4d4",400:"#a3a3a3",500:"#737373",600:"#525252",700:"#404040",800:"#262626",900:"#171717",950:"#0a0a0a"},TS={...Kl,colors:{...Kl.colors,gray:Qk}},Zk={...Kl,colors:{...Kl.colors,gray:Jk},radius:{none:"0px",sm:"4px",md:"8px",lg:"12px",xl:"16px","2xl":"24px",full:"9999px"}},PS=TS,kS=$p,e0={...$p,colors:{...$p.colors,surface:"#ffffff",background:"#ffffff",container:"semantic.colors.surface",textInverse:"#ffffff"},typography:{...$p.typography,fontSize:"14px",lineHeight:"1.5"}},LS=kS,jp=io,t0={...io,launcher:Fp,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:{...io.input,borderRadius:"palette.radius.full"},introCard:{...io.introCard,title:{fontSize:"22px",fontWeight:"500"}},suggestion:{chip:{...io.suggestion.chip,fontWeight:"400"},card:{...io.suggestion.card,fontWeight:"400"},list:{...io.suggestion.list,fontWeight:"400"}},panel:{...io.panel,width:"min(400px, calc(100vw - 24px))",height:"min(704px, calc(100dvh - 104px))",borderRadius:"palette.radius.xl"},header:{...io.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:{...io.message,gap:"20px",fullscreenGap:"28px",topFadeHeight:"18px",user:{...io.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:{...io.message.assistant,background:"transparent",border:"transparent",borderWidth:"0px",borderRadius:"0px",shadow:"none",padding:"0px",fontSize:"14px",lineHeight:"1.55"}},composer:{...io.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)"}},HS=jp,n0=e=>Es({future:e}),Em=e=>n0(e)==="v5"?{palette:Zk,semantic:e0,components:t0}:{palette:TS,semantic:kS,components:jp};function wn(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),o=e;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."))?wn(e,o):o}function qp(e){let t={};function n(o,r){for(let[s,i]of Object.entries(o)){let l=`${r}.${s}`;if(typeof i=="string"){let c=wn(e,i);c!==void 0&&(t[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 i=="object"&&i!==null&&n(i,l)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function Mm(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function IS(e,t){let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];s&&typeof s=="object"&&!Array.isArray(s)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=IS(s,r):n[o]=r}return n}function o0(e,t){return t?IS(e,t):e}function Gl(e,t={}){let n=Em(t.future),o={palette:n.palette,semantic:n.semantic,components:n.components},r={palette:{...o.palette,...e?.palette,colors:{...o.palette.colors,...e?.palette?.colors},spacing:{...o.palette.spacing,...e?.palette?.spacing},typography:{...o.palette.typography,...e?.palette?.typography},shadows:{...o.palette.shadows,...e?.palette?.shadows},borders:{...o.palette.borders,...e?.palette?.borders},radius:{...o.palette.radius,...e?.palette?.radius}},semantic:{...o.semantic,...e?.semantic,colors:{...o.semantic.colors,...e?.semantic?.colors,interactive:{...o.semantic.colors.interactive,...e?.semantic?.colors?.interactive},feedback:{...o.semantic.colors.feedback,...e?.semantic?.colors?.feedback}},spacing:{...o.semantic.spacing,...e?.semantic?.spacing},typography:{...o.semantic.typography,...e?.semantic?.typography}},components:o0(o.components,e?.components)},s=e?.components?.activity;for(let p of["toolBubble","reasoningBubble"])for(let d of["rowHeight","labelSize","iconSize","indent","bodySurface"])s?.[d]!==void 0&&(r.components[p][d]=s[d]);let i=e?.components?.collapsibleWidget?.surface;i!==void 0&&s?.bodySurface===void 0&&(r.components.activity={...r.components.activity,bodySurface:i});let l=e?.components?.header;l?.padding!==void 0&&l.minimalPadding===void 0&&(r.components.header.minimalPadding=r.components.header.padding);let c=e?.components?.message;if(c?.gap!==void 0&&c.fullscreenGap===void 0&&(r.components.message.fullscreenGap=r.components.message.gap),t.validate!==!1){let p=Mm(r);if(!p.valid)throw new Error(`Theme validation failed: ${p.errors.map(d=>d.message).join(", ")}`)}if(t.plugins)for(let p of t.plugins)r=p.transform(r);return r}var xm=e=>e.trim()==="0"?"0px":e,MS="--persona-",r0=e=>{if(!e)return;let t=e.trim().toLowerCase(),n;if(t.charCodeAt(0)===35){let i=t.slice(1);if(!/^[0-9a-f]+$/.test(i))return;i.length===3||i.length===4?n=[0,1,2].map(l=>parseInt(i[l]+i[l],16)):(i.length===6||i.length===8)&&(n=[0,2,4].map(l=>parseInt(i.slice(l,l+2),16)))}else{let i=t.match(/^rgba?\(([^)]+)\)$/);if(i){let l=i[1].split(/[,/\s]+/).filter(Boolean);l.length>=3&&(n=l.slice(0,3).map(c=>{let p=c.endsWith("%"),d=parseFloat(p?c.slice(0,-1):c);return p?d/100*255:d}))}}if(!n||n.some(i=>!Number.isFinite(i)))return;let[o,r,s]=n.map(i=>{let l=Math.max(0,Math.min(255,i))/255;return l<=.03928?l/12.92:Math.pow((l+.055)/1.055,2.4)});return .2126*o+.7152*r+.0722*s},s0=.179,Cn=(e,t)=>{for(let[n,...o]of t){let r;for(let s of o)if(r=s.charCodeAt(0)===61?s.slice(1):e[MS+s],r!==void 0)break;r!==void 0&&(e[MS+n]=r)}};function zp(e){let t=qp(e),n={};for(let[$,_e]of Object.entries(t)){let ye=$.replace(/\./g,"-");n[`--persona-${ye}`]=_e.value}Cn(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"],Cn(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"]]),Cn(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"]}`,Cn(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"]??Up,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??Vp,Cn(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"]]),Cn(n,[["header-bg","components-header-background","surface"]]);let r=n["--persona-header-bg"],s=n["--persona-components-header-foreground"],i=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"],Cn(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"]??i??n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=n["--persona-components-header-actionIconForeground"]??i??n["--persona-muted"],Cn(n,[["header-control-size","components-header-controlSize","=32px"],["header-control-icon-size","components-header-controlIconSize","=20px"]]);let l=e.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 d=n["--persona-components-history-railHeader-minHeight"];d&&(n["--persona-history-rail-header-min-height"]=d);for(let[$,_e]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let ye=n[`--persona-components-history-overlay-${$}`];ye&&(n[`--persona-history-overlay-${_e}`]=ye)}for(let[$,_e]of[["background","bg"],["borderRadius","radius"]]){let ye=n[`--persona-components-history-menu-${$}`];ye&&(n[`--persona-history-menu-${_e}`]=ye)}let g=e.components?.history?.motion;if(g){let $=ut=>{if(ut===void 0)return;let Zt=String(ut).trim();return/^\d+(\.\d+)?$/.test(Zt)?`${Zt}ms`:Zt},_e=$(g.enterDurationMs);_e!==void 0&&(n["--persona-history-enter-ms"]=_e);let ye=$(g.exitDurationMs);ye!==void 0&&(n["--persona-history-exit-ms"]=ye),g.enterEasing&&(n["--persona-history-enter-easing"]=g.enterEasing),g.exitEasing&&(n["--persona-history-exit-easing"]=g.exitEasing)}let f=n["--persona-components-history-dangerForeground"];f&&(n["--persona-history-danger-fg"]=f),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 _e=n[`--persona-components-history-confirm-${$}`];_e&&(n[`--persona-history-confirm-${$}`]=_e)}for(let[$,_e]of[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]]){let ye=n[`--persona-components-tooltip-${$}`];ye&&(n[`--persona-tooltip-${_e}`]=ye)}e.components?.tooltip?.arrow===!1&&(n["--persona-tooltip-arrow-display"]="none");for(let[$,_e]of[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let ye=n[`--persona-components-messageActions-${$}`];ye&&(n[`--persona-message-action-${_e}`]=ye)}Cn(n,[["intro-card-bg","components-introCard-background","=transparent"],["intro-card-radius","components-introCard-borderRadius","=1rem"]]);let h=n["--persona-components-introCard-background"],y=n["--persona-components-introCard-shadow"],v=(!h||h==="transparent"||h==="none")&&(!y||y==="none"),C=n["--persona-components-introCard-padding"]??"1.5rem";n["--persona-intro-card-padding"]=v&&C==="1.5rem"?"1.5rem 0":C,Cn(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"]]),Cn(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 A=n["--persona-components-markdown-heading-h1-fontSize"];A&&(n["--persona-md-h1-size"]=A);let L=n["--persona-components-markdown-heading-h1-fontWeight"];L&&(n["--persona-md-h1-weight"]=L);let I=n["--persona-components-markdown-heading-h2-fontSize"];I&&(n["--persona-md-h2-size"]=I);let H=n["--persona-components-markdown-heading-h2-fontWeight"];H&&(n["--persona-md-h2-weight"]=H);let B=n["--persona-components-markdown-prose-fontFamily"];B&&B!=="inherit"&&(n["--persona-md-prose-font-family"]=B),Cn(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"]]),Cn(n,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),Cn(n,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),Cn(n,[["md-hr-color","components-markdown-hr-color","divider"]]),Cn(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 V=[["container","surface"],["surface","surface"],["border","border"]];for(let[$,_e]of V){let ye=n[`--persona-components-collapsibleWidget-${$}`]??n[`--persona-${_e}`];ye!==void 0&&(n[`--persona-cw-${$}`]=ye,n[`--cw-${$}`]=ye)}Cn(n,[["message-border","components-message-border","border"]]),Cn(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 oe=e.components,W=oe?.iconButton;W&&(W.background&&(n["--persona-icon-btn-bg"]=W.background),W.border&&(n["--persona-icon-btn-border"]=W.border),W.color&&(n["--persona-icon-btn-color"]=W.color),W.padding&&(n["--persona-icon-btn-padding"]=W.padding),W.borderRadius&&(n["--persona-icon-btn-radius"]=W.borderRadius),W.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=W.hoverBackground),W.hoverColor&&(n["--persona-icon-btn-hover-color"]=W.hoverColor),W.activeBackground&&(n["--persona-icon-btn-active-bg"]=W.activeBackground),W.activeBorder&&(n["--persona-icon-btn-active-border"]=W.activeBorder));let j=oe?.labelButton;j&&(j.background&&(n["--persona-label-btn-bg"]=j.background),j.border&&(n["--persona-label-btn-border"]=j.border),j.color&&(n["--persona-label-btn-color"]=j.color),j.padding&&(n["--persona-label-btn-padding"]=j.padding),j.borderRadius&&(n["--persona-label-btn-radius"]=j.borderRadius),j.hoverBackground&&(n["--persona-label-btn-hover-bg"]=j.hoverBackground),j.fontSize&&(n["--persona-label-btn-font-size"]=j.fontSize),j.gap&&(n["--persona-label-btn-gap"]=j.gap));let X=oe?.toggleGroup;X&&(X.gap&&(n["--persona-toggle-group-gap"]=X.gap),X.borderRadius&&(n["--persona-toggle-group-radius"]=X.borderRadius));let M=oe?.artifact;if(M?.toolbar){let $=M.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"]=xm($.toggleGroupGap)),$.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=$.toggleBorderRadius),$.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=xm($.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"]=wn(e,$.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"]=xm($.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(M?.tab){let $=M.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(M?.pane){let $=M.pane;if($.toolbarBackground){let _e=wn(e,$.toolbarBackground)??$.toolbarBackground;n["--persona-artifact-toolbar-bg"]=_e}}if(M?.card){let $=M.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(M?.inline){let $=M.inline;$.background&&(n["--persona-artifact-inline-bg"]=wn(e,$.background)??$.background),$.border&&(n["--persona-artifact-inline-border"]=$.border),$.borderRadius&&(n["--persona-artifact-inline-radius"]=$.borderRadius),$.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=wn(e,$.chromeBackground)??$.chromeBackground),$.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=wn(e,$.chromeBorder)??$.chromeBorder),$.titleColor&&(n["--persona-artifact-inline-title-color"]=wn(e,$.titleColor)??$.titleColor),$.mutedColor&&(n["--persona-artifact-inline-muted-color"]=wn(e,$.mutedColor)??$.mutedColor),$.frameHeight&&(n["--persona-artifact-inline-frame-height"]=$.frameHeight)}let T=oe?.code;T&&(T.keywordColor&&(n["--persona-code-keyword-color"]=T.keywordColor),T.stringColor&&(n["--persona-code-string-color"]=T.stringColor),T.commentColor&&(n["--persona-code-comment-color"]=T.commentColor),T.numberColor&&(n["--persona-code-number-color"]=T.numberColor),T.tagColor&&(n["--persona-code-tag-color"]=T.tagColor),T.attrColor&&(n["--persona-code-attr-color"]=T.attrColor),T.propertyColor&&(n["--persona-code-property-color"]=T.propertyColor),T.lineNumberColor&&(n["--persona-code-line-number-color"]=T.lineNumberColor),T.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=T.gutterBorderColor),T.background&&(n["--persona-code-bg"]=wn(e,T.background)??T.background));let _=n["--persona-surface"],P=n["--persona-container"],J=n["--persona-palette-colors-gray-100"]??"#f3f4f6",U=n["--persona-palette-colors-gray-200"]??"#e5e7eb",ue=n["--persona-palette-colors-gray-300"]??"#d1d5db",fe=!P||P===_,me=r0(_??n["--persona-background"]),He=fe&&me!==void 0&&me<s0,Ee=He?"rgba(255, 255, 255, 0.08)":J,Ie=He?"rgba(255, 255, 255, 0.12)":U,yt=He?"rgba(255, 255, 255, 0.16)":ue,qe=fe?Ee:P,Oe=fe?Ie:P;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??qe,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??Oe,fe&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??yt),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??qe,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??qe,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??qe,n}var RS={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar","artifact-inline":"Inline artifact block","artifact-inline-chrome":"Inline artifact title bar"};qd();var i0=e=>!!e&&"launcher"in e&&(e.launcher?.sidebarMode===!0||e.launcher?.mountMode==="docked"),WS=(e,t)=>{if(!t||!i0(t))return e;let n=t.theme?.components?.panel?.width,o=t.darkTheme?.components?.panel?.width;return(xi(t)==="dark"?o??n:n)!=null?e:{...e,components:{...e.components,panel:{...e.components.panel,width:Es(t)==="v5"?"400px":"420px"}}}},a0={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"}}},Yl={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)"}}}},Tm=a0,l0={...Tm,colors:{...Tm.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"}}},c0=Yl,d0={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:{...Yl.components,button:{...Yl.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:{...Yl.components?.eventStream,badge:{...Yl.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"}}}}},p0=e=>Es({future:e})==="v5"?{palette:l0,components:d0}:{palette:Tm,components:c0},OS=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Xl=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",u0=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":Xl()},xi=e=>u0(e),g0=(e,t={})=>Gl(e,t),f0=(e,t={})=>{let n=p0(t.future),o=Bo(n.components,e??{})??{};return Gl({...o,palette:{...o.palette,colors:Es(t)==="v5"?Bo(n.palette.colors,o.palette?.colors):{...n.palette.colors,...o.palette?.colors}}},{validate:!1,future:t.future})},No=e=>{let t=xi(e),n=OS(e?.theme),o=Np(e)==="circle"?Fp:{...jp.launcher,...e?.future?.v5Defaults?{offset:"1.5rem"}:{}},r=Bo({components:{launcher:o}},n),s=OS(e?.darkTheme);return WS(t==="dark"?f0(Bo(r??{},s??{}),{future:e?.future}):g0(r,{future:e?.future}),e)},m0=e=>zp(e),Ei=(e,t)=>{let n=No(t),o=m0(n);for(let[r,s]of Object.entries(o))e.style.setProperty(r,s);e.setAttribute("data-persona-color-scheme",xi(t)),e.setAttribute("data-persona-defaults",Es(t))},Oa=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e(Xl())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window<"u"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>e(Xl());n.addEventListener?(n.addEventListener("change",o),t.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),t.push(()=>n.removeListener(o)))}return()=>{t.forEach(n=>n())}};qd();var Kr=require("lucide");kt();Lr();Ze();var Hs=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");var Kp="24px",Pm=(e,t)=>t||e?.composer?.placement!=="overlay"?"block":"overlay",Ql=e=>{if(typeof e!="string")return null;let t=/^\s*(\d+(?:\.\d+)?)\s*%\s*$/.exec(e);if(!t)return null;let n=Number(t[1])/100;return n>0&&n<1?n:null},_S=e=>Math.max(0,Math.round(e.columnHeight*(1-e.fraction))-e.footerHeight);xa();Ud();yp();var BS=require("idiomorph"),Gp=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;BS.Idiomorph.morph(e,t.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 i=r.textContent??"",l=s.textContent??"";if(i!==l)return}return!1}}}}})};var DS=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var km={index:-1,draft:""};function NS(e){let{direction:t,history:n,currentValue:o,atStart:r,state:s}=e,i=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="up"){if(!i&&!r)return{handled:!1,state:s};if(!i){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(!i)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 FS(e,t){return[e.id,e.role,e.content?.length??0,e.content?.slice(-32)??"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",e.variant??"",e.rawContent?.length??0,e.llmContent?.length??0,e.approval?.status??"",e.toolCall?.status??"",e.toolCall?.name??"",e.toolCall?.chunks?.length??0,e.toolCall?.chunks?.[e.toolCall.chunks.length-1]?.slice(-32)??"",typeof e.toolCall?.args=="string"?e.toolCall.args.length:e.toolCall?.args?JSON.stringify(e.toolCall.args).length:0,e.reasoning?.chunks?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.slice(-32)??"",e.contentParts?.length??0,e.stopReason??"",t].join("\0")}function $S(){return new Map}function US(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function VS(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function jS(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function qS(e){return e.role!=="assistant"||e.variant==="tool"||e.variant==="reasoning"?!1:e.variant==="approval"?!0:!!(e.content?.trim()||e.rawContent?.trim()||e.contentParts?.length)}function zS(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function ir(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Mi(e,t){return ir(e)-e.scrollTop<=t}function KS(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:i=!1,pauseOnUpwardScroll:l=!1,pauseWhenAwayFromBottom:c=!0,resumeRequiresDownwardScroll:p=!1}=e,d=n-o;return i||Math.abs(d)<s?{action:"none",delta:d,nextLastScrollTop:n}:!t&&r&&(!p||d>0)?{action:"resume",delta:d,nextLastScrollTop:n}:t&&l&&d<0?{action:"pause",delta:d,nextLastScrollTop:n}:t&&c&&!r?{action:"pause",delta:d,nextLastScrollTop:n}:{action:"none",delta:d,nextLastScrollTop:n}}function GS(e){let{following:t,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:r=!1}=e;return t&&n<0?"pause":!t&&r&&n>0&&o?"resume":"none"}function YS(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function Lm(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),n=Math.max(0,t+e.viewportHeight-e.contentHeight+(e.slack??0));return{targetScrollTop:t,spacerHeight:n}}function XS(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}_o();var Jl={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},h0=["pre","code","a","script","style"],Yp=e=>({type:e?.type??Jl.type,placeholder:e?.placeholder??Jl.placeholder,speed:e?.speed??Jl.speed,duration:e?.duration??Jl.duration,buffer:e?.buffer??Jl.buffer}),JS=[{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"}],Zl=new Map;for(let e of JS)Zl.set(e.name,e);var ZS=["wipe","glyph-cycle"],ec=e=>{Zl.set(e.name,e)},eA=e=>{JS.some(t=>t.name===e)||Zl.delete(e)},tA=()=>Array.from(Zl.keys()),tc=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:Zl.get(e)??null,Xp=(e,t,n,o,r)=>{if(!r)return e;if(n?.bufferContent)return n.bufferContent(e,o);if(!e)return e;if(t==="word"){let s=e.search(/\s(?=\S*$)/);return s<0?"":e.slice(0,s)}if(t==="line"){let s=e.lastIndexOf(`
|
|
30
|
+
`);return s<0?"":e.slice(0,s)}return e},y0=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-char",r.id=`stream-c-${n}-${o}`,r.style.setProperty("--char-index",String(o)),r.textContent=t,r},b0=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${n}-${o}`,r.style.setProperty("--word-index",String(o)),r.textContent=t,r},Hm=/\s/,v0=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let o=n;if(t.has(o.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},C0=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let i=o.createDocumentFragment(),l=0;for(;l<s.length;)if(Hm.test(s[l])){let c=l;for(;c<s.length&&Hm.test(s[c]);)c+=1;i.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&&!Hm.test(s[p]);)c.appendChild(y0(o,s[p],t,n.value)),n.value+=1,p+=1;i.appendChild(c),l=p}r.replaceChild(i,e)},w0=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let i=o.createDocumentFragment(),l=s.split(/(\s+)/);for(let c of l)c&&(/^\s+$/.test(c)?i.appendChild(o.createTextNode(c)):(i.appendChild(b0(o,c,t,n.value)),n.value+=1));r.replaceChild(i,e)},nc=(e,t,n,o)=>{if(!e||typeof document>"u")return e;let r=document.createElement("div");r.innerHTML=e;let s=new Set((o?.skipTags??h0).map(g=>g.toLowerCase())),i=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],c=i.nextNode();for(;c;)v0(c,s)||l.push(c),c=i.nextNode();let p={value:o?.startIndex??0},d=t==="char"?C0:w0;for(let g of l)d(g,n,p);return r.innerHTML},Qp=(e=document)=>{let t=e.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},oc=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let n=e.createElement("div");return n.className="persona-stream-skeleton-line",t.appendChild(n),t},QS=new WeakMap,S0=(e,t)=>{if(!e.styles)return;let n=QS.get(t);if(n||(n=new Set,QS.set(t,n)),n.has(e.name)){let s=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${s}"]`))return;n.delete(e.name)}n.add(e.name);let r=(t instanceof ShadowRoot?t.ownerDocument:t.ownerDocument??document).createElement("style");r.setAttribute("data-persona-animation",e.name),r.textContent=e.styles,t.appendChild(r)},Im=new WeakMap,A0=(e,t)=>{if(!e.onAttach)return;let n=Im.get(t);if(n||(n=new Map,Im.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},nA=e=>{let t=Im.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},rc=(e,t)=>{S0(e,t),A0(e,t)};dn();var{setLoader:jB,load:x0}=lt({fallbackImport:()=>import("@runtypelabs/persona/animations-extra")});var oA=x0;_o();function Rm(e,t=kn){let n=e.style.position,o=e.style.zIndex,r=e.style.isolation,s=getComputedStyle(e),i=s.position==="static"||s.position==="";return i&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{i&&(e.style.position=n),e.style.zIndex=o,e.style.isolation=r}}var sc=0,Is=null;function Wm(e=document){if(sc++,sc===1){let n=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;Is={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 t=!1;return()=>{if(!t&&(t=!0,sc=Math.max(0,sc-1),sc===0&&Is)){let n=e.body,o=e.defaultView??window;n.style.overflow=Is.originalOverflow,n.style.position=Is.originalPosition,n.style.top=Is.originalTop,n.style.width=Is.originalWidth,o.scrollTo(0,Is.scrollY),Is=null}}}Ea();var ic={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Lt=e=>(e?.launcher?.mountMode??"floating")==="docked",Rs=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",Zn=e=>{let t=e?.launcher?.dock,n=_r(e).dockWidth?t?.width:wn(No(e),"components.panel.width");return{side:t?.side??ic.side,width:n??ic.width,animate:t?.animate??ic.animate,reveal:t?.reveal??ic.reveal,maxHeight:t?.maxHeight??ic.maxHeight}};Ze();Ze();var sA=require("lucide");kt();Lr();var Om=e=>e==="followUp"?"follow-up":e,_m=(e,t=0)=>{if(typeof e=="string"){let r=e.trim();return r?{id:r,label:r,prompt:r,emphasis:"default"}:null}let n=e.label.trim();if(!n)return null;let o=e.prompt?.trim()||n;return{id:e.id?.trim()||o||`suggestion-${t}`,label:n,prompt:o,description:e.description?.trim()||void 0,icon:e.icon,iconColor:e.iconColor?.trim()||void 0,behavior:e.behavior,emphasis:e.emphasis??"default"}},rA=new WeakSet,E0=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,M0=e=>{E0()||e.forEach((t,n)=>{typeof t.animate=="function"&&t.animate([{opacity:"0",transform:"translateY(4px)"},{opacity:"1",transform:"none"}],{duration:250,delay:n*60,easing:"ease-out",fill:"backwards"})})},Bm=e=>{let{item:t,index:n,surface:o,source:r,variant:s,streaming:i,config:l,plugins:c,chipsConfig:p,session:d,getTextarea:g,eventTarget:f,submitPrompt:h}=e,y=o==="followUp",v=t.behavior,C=()=>{if(d.isStreaming())return;let I={suggestion:{...t},surface:o,source:r,behavior:v},H=f.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:I,bubbles:!0,composed:!0,cancelable:!0}));if(y&&f.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:t.prompt},bubbles:!0,composed:!0})),!H)return;for(let V of c)if(V.onSuggestionSelect?.({suggestion:{...t},surface:o,source:r,variant:s,config:l})===!1)return;let B=g();if(v==="fill"){B.value=t.prompt,B.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),B.focus();return}if(h){h(t.prompt);return}B.value="",d.sendMessage(t.prompt)},A=()=>{let I=x("button",`persona-suggestion persona-suggestion--${s}`);if(I.type="button",I.disabled=i,I.dataset.suggestionId=t.id,I.dataset.emphasis=t.emphasis,I.dataset.behavior=v,s==="chip"&&(p?.fontWeight&&(I.style.fontWeight=p.fontWeight),p?.paddingX&&(I.style.paddingLeft=p.paddingX,I.style.paddingRight=p.paddingX),p?.paddingY&&(I.style.paddingTop=p.paddingY,I.style.paddingBottom=p.paddingY)),t.icon){let B=ge(t.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);B&&(B.classList.add("persona-suggestion__icon"),t.iconColor&&(B.style.color=t.iconColor),I.appendChild(B))}let H=x("span","persona-suggestion__copy");if(H.appendChild(Q("span",{className:"persona-suggestion__label",text:t.label})),t.description&&s!=="chip"&&H.appendChild(Q("span",{className:"persona-suggestion__description",text:t.description})),I.appendChild(H),s!=="chip"){let B=Nt(sA.ArrowRight,16,"currentColor",1.8);B&&(B.classList.add("persona-suggestion__arrow"),I.appendChild(B))}return I.addEventListener("click",C),I},L=null;for(let I of c)if(I.renderSuggestion&&(L=I.renderSuggestion({suggestion:{...t},index:n,surface:o,source:r,variant:s,streaming:i,config:l,defaultRenderer:A,select:C}),L))break;return L??=A(),L.dataset.suggestionId||=t.id,L.dataset.behavior||=v,L.dataset.emphasis||=t.emphasis,L instanceof HTMLButtonElement||L.setAttribute("aria-disabled",i?"true":"false"),L},ac=e=>{let t=[],n=[],o=null,r=null,s=()=>{e.removeAttribute("data-scroll-left"),e.removeAttribute("data-scroll-right")},i=()=>{if(r=null,e.hidden||e.dataset.variant!=="chip"||e.dataset.overflow!=="scroll"){s();return}let d=Math.max(0,e.scrollWidth-e.clientWidth);if(d<=1){s();return}let g=getComputedStyle(e).direction==="rtl",f=Math.min(d,Math.max(0,Math.abs(e.scrollLeft))),h=4,y=f<=h,v=f>=d-h,C=g?!v:!y,A=g?!y:!v;e.toggleAttribute("data-scroll-left",C),e.toggleAttribute("data-scroll-right",A)},l=()=>{if(r!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&i();return}r=requestAnimationFrame(i)};e.addEventListener("scroll",l,{passive:!0});let c=typeof ResizeObserver=="function"?new ResizeObserver(l):null;return c?.observe(e),{buttons:t,elements:n,destroy:()=>{e.removeEventListener("scroll",l),c?.disconnect(),r!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(r),r=null},render:(d,g,f,h,y,v)=>{e.replaceChildren(),t.length=0,n.length=0;let C=v?.source??"config",A=v?.surface??(C==="config"?"starter":"followUp"),L=A==="followUp",I=v?.variant??"chip",H=v?.behavior??"send",B=v?.overflow??"wrap",V=v?.config??{},oe=v?.plugins??[],W=typeof v?.maxItems=="number"?Math.max(0,Math.floor(v.maxItems)):void 0,j=L?"followUps":"starters";!rA.has(V)&&V.debug===!0&&I!=="chip"&&V.suggestions?.[j]?.overflow!==void 0&&(rA.add(V),console.info(`[persona] suggestions.${j}.overflow applies to the "chip" variant only; the "${I}" variant manages its own stacking.`));let X=U=>U.map(_m).filter(ue=>ue!==null).map(ue=>({...ue,behavior:ue.behavior??H})),M=X(d??[]);oe.forEach(U=>{U.transformSuggestions&&(M=X(U.transformSuggestions({suggestions:M.map(ue=>({...ue})),surface:A,source:C,config:V})))});let T=W===void 0?M:M.slice(0,W);if(!T.length){e.hidden=!0,o=null,s();return}if(!L&&(h??g.getMessages()).some(ue=>ue.role==="user")){e.hidden=!0,o=null;return}e.hidden=!1,e.classList.add("persona-suggestions"),e.dataset.personaSuggestionSurface=Om(A),e.dataset.variant=I,e.dataset.overflow=B;let _=document.createDocumentFragment(),P=g.isStreaming();T.forEach((U,ue)=>{let fe=Bm({item:U,index:ue,surface:A,source:C,variant:I,streaming:P,config:V,plugins:oe,chipsConfig:y,session:g,getTextarea:()=>f,eventTarget:e,submitPrompt:v?.submitPrompt});_.appendChild(fe),n.push(fe),[...fe instanceof HTMLButtonElement?[fe]:[],...Array.from(fe.querySelectorAll("button"))].forEach(He=>{t.includes(He)||(He.disabled=P,t.push(He))})}),e.appendChild(_),i(),l();let J=JSON.stringify({normalized:T,surface:A,variant:I,source:C});J!==o&&(o=J,M0(n),e.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:T.map(U=>({...U})),surface:A,source:C,variant:I},bubbles:!0,composed:!0})),L&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:T.map(U=>U.prompt)},bubbles:!0,composed:!0})))}}};var ao={"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"};_o();Ze();kt();So();Ze();kt();xa();var T0="persona-header-control",P0="persona-header-control--glyph",k0="persona-header-control--sparse",L0=20,H0={x:[1.4,1.05]},iA="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",I0="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Jp=(e,t,n={})=>{let{iconSize:o,iconText:r}=n,[s,i]=H0[t]??[1,1.5],l=!o;e.classList.toggle(P0,l),e.classList.toggle(k0,l&&s!==1);let c=parseFloat(o??"")||L0,p=ge(t,`${Math.round(c*s)}px`,"currentColor",i);p?(p.style.display="block",l||(p.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((i/1.5).toFixed(4))})`),e.replaceChildren(p)):r&&(e.textContent=r)},_a=e=>{let{ariaLabel:t,tooltip:n=!0,tooltipHint:o,iconName:r,iconText:s,wrapperClassName:i=iA,size:l,iconSize:c,color:p,backgroundColor:d,borderWidth:g,borderColor:f,borderRadius:h,paddingX:y,paddingY:v,hidden:C,extraClassName:A,attrs:L}=e,I=x("div",i),H=!!(g||f),B=Q("button",{className:Dn(T0,"persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!d&&"persona-bg-transparent hover:persona-bg-gray-100",!H&&"persona-border-none",!h&&"persona-rounded-full",A),attrs:{type:"button","aria-label":t,...L},style:{width:l,height:l,minWidth:l,minHeight:l,display:C?"none":void 0,color:p||Nn.actionIconColor,backgroundColor:d,border:H?`${g||"0px"} solid ${f||"transparent"}`:void 0,borderRadius:h,paddingLeft:y,paddingRight:y,paddingTop:v,paddingBottom:v}});return r?Jp(B,r,{iconSize:c,iconText:s}):s&&(B.textContent=s),I.appendChild(B),vn({anchor:B,trigger:I,text:()=>B.getAttribute("aria-label")??t,hint:o,enabled:n}),{button:B,wrapper:I}},Ba=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=iA,buttonSize:r,iconSize:s}=t,i=e?.launcher??{},l=i.closeButtonTooltipText??"Close chat",c=i.closeButtonShowTooltip??!0,{button:p,wrapper:d}=_a({ariaLabel:l,tooltip:c,iconName:i.closeButtonIconName??"x",iconText:i.closeButtonIconText??"\xD7",wrapperClassName:o,size:r??i.closeButtonSize,iconSize:s,color:i.closeButtonColor,backgroundColor:i.closeButtonBackgroundColor,borderWidth:i.closeButtonBorderWidth,borderColor:i.closeButtonBorderColor,borderRadius:i.closeButtonBorderRadius,paddingX:i.closeButtonPaddingX,paddingY:i.closeButtonPaddingY,hidden:!n});return{button:p,wrapper:d}},Da=(e,t={})=>{let{wrapperClassName:n=I0,buttonSize:o,iconSize:r}=t,i=(e?.launcher??{}).clearChat??{},l=i.tooltipText??"Clear chat",c=i.showTooltip??!0,{button:p,wrapper:d}=_a({ariaLabel:l,tooltip:c,iconName:i.iconName??"refresh-cw",wrapperClassName:n,size:o??i.size,iconSize:r,color:i.iconColor,backgroundColor:i.backgroundColor,borderWidth:i.borderWidth,borderColor:i.borderColor,borderRadius:i.borderRadius,paddingX:i.paddingX,paddingY:i.paddingY});return{button:p,wrapper:d}};var Nn={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)"},Dm={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)"},R0={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)"},jr=e=>{let{config:t,showClose:n=!0}=e,o=Q("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:Nn.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=t?.launcher??{},s=r.headerIconSize??_l,i=r.closeButtonPlacement??"inline",l=r.headerIconHidden??!1,c=r.headerIconName,p=Q("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 B=parseFloat(s)||24,V=ge(c,B*.6,"currentColor",1);V?(V.style.width=`calc(${B}px * var(--persona-components-header-iconScale, 0.6))`,V.style.height=`calc(${B}px * var(--persona-components-header-iconScale, 0.6))`,p.replaceChildren(V)):p.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let B=x("img");B.src=t.launcher.iconUrl,B.alt="",B.className="persona-rounded-xl persona-object-cover",B.style.height=s,B.style.width=s,p.replaceChildren(B)}else p.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let d=x("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),g=Q("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:Nn.titleColor,...Dm}}),f=Q("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Nn.subtitleColor,...R0}});d.append(g,f),l?o.append(d):o.append(p,d);let h=r.clearChat??{},y=h.enabled??!0,v=h.placement??"inline",C=null,A=null;if(y){let V=Da(t,{wrapperClassName:v==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});C=V.button,A=V.wrapper,v==="top-right"&&(A.style.right="48px"),v==="inline"&&o.appendChild(A)}let L=i==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":y&&v==="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:I,wrapper:H}=Ba(t,{showClose:n,wrapperClassName:L});return i!=="top-right"&&o.appendChild(H),{header:o,iconHolder:p,headerTitle:g,headerSubtitle:f,closeButton:I,closeButtonWrapper:H,clearChatButton:C,clearChatButtonWrapper:A}},Ti=(e,t,n)=>{let o=n?.launcher??{},r=o.closeButtonPlacement??"inline",s=o.clearChat?.placement??"inline";e.appendChild(t.header),r==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};Ze();Ze();kt();_o();function Pi(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:s,onOpenChange:i}=e,l=x("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(wa)):(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 y of t){if(y.dividerBefore){let A=document.createElement("hr");l.appendChild(A)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",y.id),y.destructive&&v.setAttribute("data-destructive",""),y.icon){let A=ge(y.icon,16,"currentColor",1.5);A&&v.appendChild(A)}let C=document.createElement("span");C.textContent=y.label,v.appendChild(C),v.addEventListener("click",A=>{A.stopPropagation(),g(),n(y.id)}),l.appendChild(v)}let c=null;function p(){if(!s)return;let y=o.getBoundingClientRect();l.style.top=`${y.bottom+4}px`,r==="bottom-right"?(l.style.right=`${window.innerWidth-y.right}px`,l.style.left="auto"):(l.style.left=`${y.left}px`,l.style.right="auto")}function d(){let y=l.classList.contains("persona-hidden");p(),l.classList.remove("persona-hidden"),y&&i?.(!0),requestAnimationFrame(()=>{let v=C=>{!l.contains(C.target)&&!o.contains(C.target)&&g()};document.addEventListener("click",v,!0),c=()=>document.removeEventListener("click",v,!0)})}function g(){let y=!l.classList.contains("persona-hidden");l.classList.add("persona-hidden"),c?.(),c=null,y&&i?.(!1)}function f(){l.classList.contains("persona-hidden")?d():g()}function h(){g(),l.remove()}return s&&s.appendChild(l),{element:l,show:d,hide:g,toggle:f,destroy:h}}Ze();kt();function eo(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,chromeless:i,onClick:l,aria:c}=e,p=x("button",Dn(!i&&"persona-icon-btn",s));p.type="button",p.setAttribute("aria-label",n),p.title=n;let d=ge(t,o??16,"currentColor",r??2);if(d&&p.appendChild(d),l&&p.addEventListener("click",l),c)for(let[g,f]of Object.entries(c))p.setAttribute(g,f);return p}function Nm(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:s,className:i,onClick:l,aria:c}=e,p="persona-label-btn";o!=="default"&&(p+=" persona-label-btn--"+o),p+=" persona-label-btn--"+r,i&&(p+=" "+i);let d=x("button",p);if(d.type="button",d.setAttribute("aria-label",n),t){let f=ge(t,s??14,"currentColor",2);f&&d.appendChild(f)}let g=x("span");if(g.textContent=n,d.appendChild(g),l&&d.addEventListener("click",l),c)for(let[f,h]of Object.entries(c))d.setAttribute(f,h);return d}function lc(e){let{items:t,selectedId:n,onSelect:o,className:r}=e,s=x("div","persona-toggle-group"+(r?" "+r:""));s.setAttribute("role","group");let i=n,l=[];function c(){for(let d of l)d.btn.setAttribute("aria-pressed",d.id===i?"true":"false")}for(let d of t){let g;d.icon?g=eo({icon:d.icon,label:d.label,className:d.className,onClick:()=>{i=d.id,c(),o(d.id)}}):(g=x("button","persona-icon-btn"+(d.className?" "+d.className:"")),g.type="button",g.setAttribute("aria-label",d.label),g.title=d.label,g.textContent=d.label,g.addEventListener("click",()=>{i=d.id,c(),o(d.id)})),g.setAttribute("aria-pressed",d.id===i?"true":"false"),l.push({id:d.id,btn:g}),s.appendChild(g)}function p(d){i=d,c()}return{element:s,setSelected:p}}function aA(e){let{label:t,icon:n,iconSize:o,iconOnly:r,menuItems:s,onSelect:i,onPrimary:l,position:c="bottom-left",portal:p,chevronLabel:d="More options",chevronIconSize:g,className:f,primaryClassName:h,chevronClassName:y}=e,v=x("div","persona-split-btn"+(f?" "+f:"")),C={label:t,className:"persona-split-btn-primary"+(h?" "+h:""),onClick:l},A=r&&n?eo({...C,icon:n,size:o??14}):Nm({...C,icon:n,iconSize:o??14}),L=eo({icon:"chevron-down",label:d,size:g??14,className:"persona-split-btn-chevron"+(y?" "+y:""),aria:{"aria-haspopup":"true","aria-expanded":"false"}});v.append(A,L);let I=null,H=()=>{if(I)return I;let B=(typeof p=="function"?p():p)??void 0;return I=Pi({items:s,onSelect:i,anchor:v,position:c,portal:B,onOpenChange:V=>{L.setAttribute("aria-expanded",V?"true":"false")}}),B||v.appendChild(I.element),I};return v.isConnected?H():requestAnimationFrame(()=>{I||H()}),L.addEventListener("click",B=>{B.stopPropagation(),H().toggle()}),{element:v,primaryButton:A,chevronButton:L,openMenu:()=>H().show(),closeMenu:()=>I?.hide(),toggleMenu:()=>H().toggle(),destroy:()=>{I?.destroy(),v.remove()}}}function Zp(e){let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:i,className:l,hover:c}=e,p=x("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",t);let d=x("span","persona-combo-btn-label");d.textContent=t,p.appendChild(d);let g=ge(n,14,"currentColor",2);g&&(g.style.marginLeft="4px",g.style.opacity="0.6",p.appendChild(g)),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 f=Pi({items:o,onSelect:y=>{p.setAttribute("aria-expanded","false"),r(y)},anchor:p,position:s,portal:i});i||p.appendChild(f.element);let h=()=>p.getAttribute("data-persona-menu-locked")==="true";return p.addEventListener("click",y=>{if(y.stopPropagation(),h())return;let v=!f.element.classList.contains("persona-hidden");p.setAttribute("aria-expanded",v?"false":"true"),f.toggle()}),p.addEventListener("keydown",y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),p.click())}),{element:p,setLabel:y=>{d.textContent=y,p.setAttribute("aria-label",y)},open:()=>{p.setAttribute("aria-expanded","true"),f.show()},close:()=>{p.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let y=!f.element.classList.contains("persona-hidden");p.setAttribute("aria-expanded",y?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),p.remove()}}}yp();var Fm=e=>{let t=jr({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=e.layoutHeaderConfig?.onTitleClick;if(n){let o=t.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 t};function W0(e,t,n){if(t?.length)for(let o of t){let{button:r,wrapper:s}=_a({ariaLabel:o.ariaLabel??o.label??o.id,iconName:o.icon,iconText:o.icon?void 0:o.label,tooltipHint:o.shortcut?hp(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 i=Nl(o.shortcut);i&&r.setAttribute("aria-keyshortcuts",i)}if(o.menuItems?.length){let i=Pi({items:o.menuItems,onSelect:l=>n?.(l),anchor:s,position:"bottom-right"});s.appendChild(i.element),r.addEventListener("click",l=>{l.stopPropagation(),i.toggle()})}else r.addEventListener("click",()=>n?.(o.id));e.appendChild(s)}}var $m=e=>{let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=e,i=t?.launcher??{},l=x("div","persona-flex persona-items-center persona-justify-between");l.setAttribute("data-persona-theme-zone","header"),l.style.minHeight=Nn.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,d;if(c){let H=Zp({label:i.title??"Chat Assistant",menuItems:c.menuItems,onSelect:B=>{let V=W=>{W===!1&&H.element.dispatchEvent(new CustomEvent("persona:title-menu-builtin",{bubbles:!0,composed:!0,detail:{actionId:B}}))},oe=c.onSelect(B);oe instanceof Promise?oe.then(V,()=>{}):V(oe)},hover:c.hover,className:""});p=H.element,p.style.color=Nn.titleColor,d=p.querySelector(".persona-combo-btn-label")??p}else{if(p=x("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),d=x("span","persona-text-base persona-font-semibold persona-truncate"),d.style.color=Nn.titleColor,Object.assign(d.style,Dm),d.textContent=i.title??"Chat Assistant",p.appendChild(d),r?.onTitleClick){p.style.cursor="pointer",p.setAttribute("role","button"),p.setAttribute("tabindex","0");let B=r.onTitleClick;p.addEventListener("click",V=>{V.target.closest("button")||B()}),p.addEventListener("keydown",V=>{(V.key==="Enter"||V.key===" ")&&(V.preventDefault(),B())})}let H=r?.titleRowHover;H&&(p.style.borderRadius=H.borderRadius??"10px",p.style.padding=H.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=H.background??"",p.style.borderColor=H.border??""}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="",p.style.borderColor="transparent"}))}l.appendChild(p);let g="persona-relative persona-inline-flex persona-items-center persona-justify-center",{button:f,wrapper:h}=Ba(t,{showClose:n,wrapperClassName:g});o&&f.addEventListener("click",o);let y=x("div","persona-flex persona-items-center persona-gap-1");c||W0(y,r?.trailingActions,r?.onAction??s);let v=i.clearChat??{},C=null,A=null;if(v.enabled??!0){let H=v.placement??"inline",B=Da(t,{wrapperClassName:H==="top-right"?"persona-absolute persona-top-4 persona-z-50":g});C=B.button,A=B.wrapper,H==="top-right"?A.style.right="48px":y.appendChild(A)}y.appendChild(h),l.appendChild(y);let L=x("div");L.style.display="none";let I=x("span");return I.style.display="none",{header:l,iconHolder:L,headerTitle:d,headerSubtitle:I,closeButton:f,closeButtonWrapper:h,clearChatButton:C,clearChatButtonWrapper:A}},eu={default:Fm,minimal:$m},Um=e=>eu[e]??eu.default,Na=(e,t,n)=>{if(t?.render){let i=t.render({config:e,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),l=x("div");l.style.display="none";let c=x("span"),p=x("span"),d=x("button");d.style.display="none";let g=x("div");return g.style.display="none",{header:i,iconHolder:l,headerTitle:c,headerSubtitle:p,closeButton:d,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}}let o=t?.layout??"default",s=Um(o)({config:e,showClose:t?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:t,onHeaderAction:t?.onAction});return t&&(t.showIcon===!1&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};Ze();Ms();var ki=e=>{let{config:t}=e,n=Q("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=ip(),r=Q("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:i}=np(t);i();let l=op(t),c=ka(t),p=rp(t),d=sp(t),g=Q("div",{className:"persona-widget-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});r.append(g),p&&(p.previewsContainer.style.gap="8px",g.append(p.previewsContainer),r.append(p.input)),r.append(s);let f=Q("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),h=Q("div",{className:"persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-start":""}}),y=Q("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&&y.append(c.wrapper),y.append(l.wrapper),f.append(h,y),r.append(f),r.addEventListener("click",v=>{v.target!==l.button&&v.target!==l.wrapper&&v.target!==c?.button&&v.target!==c?.wrapper&&v.target!==p?.button&&v.target!==p?.wrapper&&s.focus()}),t?.statusIndicator?.mode==="transient"?n.append(o,d,r):n.append(o,r,d),{footer:n,suggestions:o,composerForm:r,header:g,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:c?.button??null,micButtonWrapper:c?.wrapper??null,statusText:d,attachmentButton:p?.button??null,attachmentButtonWrapper:p?.wrapper??null,attachmentInput:p?.input??null,attachmentPreviewsContainer:p?.previewsContainer??null,actionsRow:f,leftActions:h,rightActions:y,setSendButtonMode:l.setMode}};Ze();var tu=require("lucide");Lr();Ms();ep();var lA=()=>{let e=Q("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=x("span","persona-pill-peek__icon"),n=Nt(tu.MessageSquare,16,"currentColor",1.5);n&&t.appendChild(n);let o=x("span","persona-pill-peek__text"),r=x("span","persona-pill-peek__caret"),s=Nt(tu.ChevronUp,16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},nu=e=>{let{config:t}=e,n=Q("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=ip(),r=sp(t);r.style.display="none";let{textarea:s,attachAutoResize:i}=np(t,{defaultMaxLines:5});i();let l=op(t),c=ka(t),p=rp(t);p&&p.previewsContainer.classList.add("persona-pill-composer__previews");let d=Q("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""}}),g=Q("div",{className:"persona-widget-composer__left-actions persona-pill-composer__left",attrs:{"data-persona-composer-actions-start":""}});p&&g.append(p.wrapper);let f=Q("div",{className:"persona-widget-composer__right-actions persona-pill-composer__right",attrs:{"data-persona-composer-actions-end":""}});c&&f.append(c.wrapper),f.append(l.wrapper),d.addEventListener("click",v=>{v.target!==l.button&&v.target!==l.wrapper&&v.target!==c?.button&&v.target!==c?.wrapper&&v.target!==p?.button&&v.target!==p?.wrapper&&s.focus()}),p&&d.append(p.input),d.append(g,s,f);let h=Q("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,d,r);let y=d;return{footer:n,suggestions:o,composerForm:d,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:y,leftActions:g,rightActions:f,setSendButtonMode:l.setMode}};Ze();kt();Ze();zf();kt();Nr();var O0=e=>{switch(e){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}},_0=(e,t)=>{if(!e)return null;let n=O0(e);if(n===null)return null;let o=t?.[e],r=o!==void 0?o:n;return r||null},B0=(e,t)=>{let n=x("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},D0=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},jm=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},qm=320,gA=320,N0=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),F0=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),$0=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),U0=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),V0=e=>{if(!e||e.length===0)return null;let t=Q("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let n of e){let o=Q("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=x("span","persona-mention-chip-icon"),s=ge(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild(Q("span",{className:"persona-mention-chip-label",text:n.label})),t.appendChild(o)}return t},j0=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(Dl(o.ref,{readonly:!0,render:t}))}return n},cA="\uE000",dA="\uE001",q0=(e,t,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=f=>`${cA}${r}:${f}${dA}`,i=t.map((f,h)=>f.kind==="text"?f.text:s(h)).join(""),l=n(i);if(!t.every((f,h)=>f.kind==="text"||l.includes(s(h)))){e.replaceChildren(j0(t,o));return}e.innerHTML=l;let p=new RegExp(`${cA}${r}:(\\d+)${dA}`),d=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),g=[];for(let f=d.nextNode();f;f=d.nextNode())g.push(f);for(let f of g){let h=f;for(let y=p.exec(h.data);y;y=p.exec(h.data)){let v=t[Number(y[1])],C=h.splitText(y.index);C.data=C.data.slice(y[0].length),v?.kind==="mention"&&C.parentNode?.insertBefore(Dl(v.ref,{readonly:!0,render:o}),C),h=C}}},z0=(e,t,n)=>{if(e.length===0)return null;try{let o=x("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let r=0,s=!1,i=()=>{s||(s=!0,o.remove(),n?.())};return e.forEach((l,c)=>{let p=x("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=`${qm}px`,p.style.maxHeight=`${gA}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 d=!1;r+=1,p.addEventListener("error",()=>{d||(d=!0,r=Math.max(0,r-1),p.remove(),r===0&&i())}),p.addEventListener("load",()=>{d=!0}),D0(l.image)?(p.src=l.image,o.appendChild(p)):(d=!0,r=Math.max(0,r-1),p.remove())}),r===0?(i(),null):o}catch{return n?.(),null}},K0=e=>{if(e.length===0)return null;try{let t=x("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!jm(o.audio))return;let r=x("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${qm}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},G0=e=>{if(e.length===0)return null;try{let t=x("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!jm(o.video))return;let r=x("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${qm}px`,r.style.maxHeight=`${gA}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Y0=e=>{if(e.length===0)return null;try{let t=x("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!jm(o.data))return;let r=x("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",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Li=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.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",e.appendChild(t),e.appendChild(n),e.appendChild(o),e.appendChild(r),e},zm=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:Li};if(t){let r=t(o);if(r!==null)return r}return Li()},X0=(e,t)=>{let n=x("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=t==="user"?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=x("img");r.src=o,r.alt=t==="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(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},pA=(e,t,n="div")=>{let o=x(n,"persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return t.format?o.textContent=t.format(r):o.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},cc=(e,t="bubble")=>{let n=["persona-message-bubble"];switch(t){case"flat":e==="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"),e==="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"),e==="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},uA={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"}},Q0=(e,t,n="bubble",o)=>{if(!o)return;let r=t==="user"?"user":"assistant",s=uA[n??"bubble"]??uA.bubble;o.padding&&(e.style.padding=`var(--persona-message-${r}-padding, ${s.padding})`),o.fontSize&&(e.style.fontSize=`var(--persona-message-${r}-font-size, ${s.fontSize})`),o.lineHeight&&(e.style.lineHeight=`var(--persona-message-${r}-line-height, ${s.lineHeight})`),o.fontFamily&&(e.style.fontFamily=`var(--persona-message-${r}-font-family, inherit)`)},ou="custom:",J0=e=>`${ou}${e}`,fA=(e,t)=>t!=="user"&&t!=="assistant"?[]:(e?.custom??[]).filter(n=>(n.roles??["assistant"]).includes(t)),Km=(e,t,n,o)=>{let r=t.showCopy??!0,s=t.showUpvote??!1,i=t.showDownvote??!1,l=t.showReadAloud??!1,c=(t.showRegenerate??!1)&&o?.canRegenerate===!0,p=(t.showEdit??!1)&&o?.canEdit===!0,d=(t.showQuote??!1)&&o?.canQuote!==!1,g=fA(t,e.role);if(!r&&!s&&!i&&!l&&!c&&!p&&!d&&g.length===0){let I=x("div");return I.style.display="none",I.id=`actions-${e.id}`,I.setAttribute("data-actions-for",e.id),I}let f=t.visibility??"hover",h=t.align??"right",y=t.layout??"pill-inside",v={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[h],C={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[y],A=x("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${v} ${C} ${f==="hover"?"persona-message-actions-hover":""}`);A.id=`actions-${e.id}`,A.setAttribute("data-actions-for",e.id);let L=(I,H,B)=>{let V=eo({icon:I,label:H,size:14,className:"persona-message-action-btn",chromeless:!0});return V.setAttribute("data-action",B),V};r&&A.appendChild(L("copy","Copy message","copy")),l&&A.appendChild(L("volume-2","Read aloud","read-aloud")),s&&A.appendChild(L("thumbs-up","Upvote","upvote")),i&&A.appendChild(L("thumbs-down","Downvote","downvote")),c&&A.appendChild(L("refresh-cw","Regenerate response","regenerate")),p&&A.appendChild(L("pencil","Edit message","edit")),d&&A.appendChild(L("quote","Quote message","quote"));for(let I of g)A.appendChild(L(I.iconName??"ellipsis",I.label,J0(I.id)));return A},Fa=(e,t,n,o,r,s)=>{let i=n??{},l=i.layout??"bubble",c=i.avatar,p=i.timestamp,d=c?.show??!1,g=p?.show??!1,f=c?.position??"left",h=p?.position??"below",y=cc(e.role,l),v=x("div",y.join(" "));v.id=`bubble-${e.id}`,v.setAttribute("data-message-id",e.id),v.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message");let C=Em(s?.widgetConfig?.future).components.message,A=s?.widgetConfig?.theme?.components?.message;Q0(v,e.role,l,e.role==="user"?{...C.user,...A?.user,...s?.widgetConfig?.darkTheme?.components?.message?.user}:{...C.assistant,...A?.assistant,...s?.widgetConfig?.darkTheme?.components?.message?.assistant}),l==="flat"?(v.style.backgroundColor="transparent",v.style.color=e.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):e.role==="user"?(v.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",v.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(v.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",v.style.color="var(--persona-message-assistant-text, var(--persona-text))");let L=N0(e),I=e.content?.trim()??"",B=L.length>0&&I===Ta,V=Yp(s?.widgetConfig?.features?.streamAnimation),oe=s?.widgetConfig?.features?.streamAnimation?.plugins,W=e.role==="assistant"&&V.type!=="none"?tc(V.type,oe):null,j=e.role==="assistant"&&W?.isAnimating?.(e)===!0,X=e.role==="assistant"&&W!==null&&(!!e.streaming||j);X&&W?.bubbleClass&&v.classList.add(W.bubbleClass);let M=document.createElement("div");M.classList.add("persona-message-content"),e.streaming&&M.classList.add("persona-content-streaming"),X&&W&&(W.containerClass&&M.classList.add(W.containerClass),M.style.setProperty("--persona-stream-step",`${V.speed}ms`),M.style.setProperty("--persona-stream-duration",`${V.duration}ms`));let T=X?Xp(e.content??"",V.buffer,W,e,!!e.streaming):e.content??"",_=()=>{let Oe=t({text:T,message:e,streaming:!!e.streaming,raw:e.rawContent});return X&&W?.wrap==="char"?nc(Oe,"char",e.id,{skipTags:W.skipTags}):X&&W?.wrap==="word"?nc(Oe,"word",e.id,{skipTags:W.skipTags}):Oe},P=null;if(B?(P=document.createElement("div"),P.innerHTML=_(),P.style.display="none",M.appendChild(P)):e.contentSegments?.length?q0(M,e.contentSegments,Oe=>t({text:Oe,message:e,streaming:!!e.streaming,raw:e.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):M.innerHTML=_(),X&&W?.useCaret&&!B&&I){let Oe=Qp(),$=M.querySelectorAll(".persona-stream-char, .persona-stream-word"),_e=$[$.length-1];if(_e?.parentNode)_e.parentNode.insertBefore(Oe,_e.nextSibling);else{let ye=M.lastElementChild;ye?ye.appendChild(Oe):M.appendChild(Oe)}}if(g&&h==="inline"&&e.createdAt){let Oe=pA(e,p,"span");Oe.classList.add("persona-timestamp-inline");let $=M.lastElementChild;$?$.appendChild(Oe):M.appendChild(Oe)}if(L.length>0){let Oe=z0(L,!B&&!!I,()=>{B&&P&&(P.style.display="")});Oe?v.appendChild(Oe):B&&P&&(P.style.display="")}let J=F0(e);if(J.length>0){let Oe=K0(J);Oe&&v.appendChild(Oe)}let U=$0(e);if(U.length>0){let Oe=G0(U);Oe&&v.appendChild(Oe)}let ue=U0(e);if(ue.length>0){let Oe=Y0(ue);Oe&&v.appendChild(Oe)}let fe=e.contentSegments?.length?null:V0(e.contextMentions);if(fe&&v.appendChild(fe),v.appendChild(M),g&&h==="below"&&e.createdAt){let Oe=pA(e,p);Oe.classList.add("persona-mt-1"),v.appendChild(Oe)}let me=e.role==="assistant"?_0(e.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let Oe=!!(T&&T.trim()),$=V.placeholder==="skeleton",_e=$&&V.buffer==="line"&&Oe;if(Oe)_e&&v.appendChild(oc());else if($)v.appendChild(oc());else{let ye=zm("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);ye&&v.appendChild(ye)}}me&&e.stopReason&&!e.streaming&&(I||(M.style.display="none"),v.appendChild(B0(e.stopReason,me)));let He=e.role==="assistant"&&!e.streaming&&!e.voiceCaption&&e.content&&e.content.trim()&&o?.enabled!==!1,Ee=s?.actionEligibility,Ie=e.role==="user"&&!e.streaming&&o?.enabled!==!1&&(o?.showEdit===!0&&Ee?.canEdit===!0||o?.showQuote===!0&&Ee?.canQuote===!0||fA(o,"user").length>0);if((He||Ie)&&o){let Oe=Km(e,Ie?{...o,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:o,r,Ee);v.appendChild(Oe)}if(!d||e.role==="system")return v;let yt=x("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),qe=X0(c,e.role);return f==="right"||f==="left"&&e.role==="user"?yt.append(v,qe):yt.append(qe,v),yt},mA=(e,t,n,o,r,s)=>{let i=n??{};return e.role==="user"&&i.renderUserMessage?i.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&i.renderAssistantMessage?i.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Fa(e,t,n,o,r,s)};var Z0=40,eL=(e,t)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}if(typeof t=="function"){let n=null;try{n=t()}catch(o){console.warn("[persona] welcome.icon renderer threw",o)}if(!n){e.hidden=!0;return}e.appendChild(n),e.hidden=!1;return}if(t.type==="lucide"){let n=ge(t.name,Z0);if(!n){e.hidden=!0;return}e.appendChild(n)}else t.type==="image"?e.appendChild(Q("img",{className:"persona-welcome-icon-image",attrs:{src:t.url,alt:t.alt}})):e.appendChild(Q("span",{className:"persona-welcome-icon-text",text:t.text}));e.hidden=!1},hA=(e,t,n={})=>{let o=Q("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});o.hidden=!0;let r=x("p","persona-welcome-kicker");r.hidden=!0;let s=x("h2","persona-welcome-title"),i=x("p","persona-welcome-subtitle"),l=Q("div",{className:"persona-welcome-head-text"},r,s),c=Q("div",{className:"persona-welcome-title-row"},o,l);return{host:Q("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,i,t),iconHolder:o,kicker:r,title:s,subtitle:i,starterSuggestions:t}},$a=(e,t,n)=>{t.hidden=!n,t.style.display=n?"":"none",e.classList.toggle("persona-gap-6",n),e.classList.toggle("persona-gap-3",!n)},su=(e,t)=>{e.title.textContent=t.title,e.kicker.textContent=t.kicker??"",e.kicker.hidden=!t.kicker,e.subtitle.textContent=t.subtitle,e.subtitle.hidden=t.subtitle==="",eL(e.iconHolder,t.icon),e.host.setAttribute("data-persona-welcome-variant",t.variant),e.host.setAttribute("data-persona-welcome-dismiss",t.dismiss),e.host.setAttribute("data-persona-welcome-layout",t.layout??"top"),e.host.setAttribute("data-persona-welcome-anchor",t.anchor??"bottom"),t.iconPlacement==="inline"?e.host.setAttribute("data-persona-welcome-icon-placement","inline"):e.host.removeAttribute("data-persona-welcome-icon-placement"),t.align?e.host.setAttribute("data-persona-welcome-align",t.align):e.host.removeAttribute("data-persona-welcome-align")},tL="data-persona-welcome-plugin",yA="data-persona-welcome-overlay",ru="persona-welcome-overlay-active",Gm=new WeakMap,Ym=(e,t,n)=>{n.setAttribute(tL,""),t.appendChild(n),t.setAttribute("data-persona-welcome-content","plugin"),t.setAttribute(yA,""),e.classList.contains(ru)||(Gm.set(e,e.scrollTop),e.classList.add(ru),e.scrollTop=0)},Xm=(e,t,n)=>{n&&n!==t&&n.remove(),t.removeAttribute("data-persona-welcome-content"),t.removeAttribute(yA),e.classList.contains(ru)&&(e.classList.remove(ru),e.scrollTop=Gm.get(e)??e.scrollTop,Gm.delete(e))},bA=()=>{let e=Q("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return e.hidden=!0,e},iu=(e,t,n)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}let o=n?.layout?.messages?.layout??"bubble",r=Q("div",{className:cc("assistant",o).join(" "),attrs:{"data-persona-theme-zone":"assistant-message"},text:t,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))"}});e.appendChild(Q("div",{className:"persona-flex"},r)),e.hidden=!1},vA=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,CA=(e,t)=>{if(vA()||typeof e.animate!="function"||!e.isConnected)return t(null),null;let n=e.getBoundingClientRect(),o=e.parentElement,r=0,s=0,i=0;if(o){let y=getComputedStyle(o);r=parseFloat(y.rowGap)||0;let v=e.previousElementSibling,C=e.nextElementSibling,L=o.getBoundingClientRect().top+(parseFloat(y.borderTopWidth)||0)+(parseFloat(y.paddingTop)||0)-o.scrollTop;s=Math.max(0,v?n.top-v.getBoundingClientRect().bottom-r:n.top-L),i=Math.max(0,C?C.getBoundingClientRect().top-n.bottom-r:0)}let l=e.style.overflow;e.style.overflow="hidden";let c=getComputedStyle(e),p=parseFloat(c.paddingTop)||0,d=parseFloat(c.paddingBottom)||0,g=e.animate([{opacity:"1",transform:"none",height:`${n.height}px`,minHeight:"0px",paddingTop:`${p}px`,paddingBottom:`${d}px`,marginTop:`${s}px`,marginBottom:`${i}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"}),f=!1,h=()=>{f||(f=!0,e.style.overflow=l,t(g))};return g.finished.then(h).catch(h),g},wA=(e,t,n,o=260)=>{if(t<=1||vA()||typeof e.animate!="function"||!e.isConnected)return null;let r=n==="drop"?-t:t;return e.animate([{transform:`translateY(${r}px)`},{transform:"none"}],{duration:o,easing:"cubic-bezier(0.2, 0, 0, 1)",fill:"none"})};var nL="Hello \u{1F44B}",oL="I can answer questions and help you get things done here.",SA=new WeakSet,Fn=(e,t)=>!!e&&e[t]!==void 0,rL=(e,t)=>{!e||e.debug!==!0||!t.length||SA.has(e)||(SA.add(e),t.forEach(n=>console.warn(`[persona] ${n}`)))},Ua=(e,t=e?.launcher?.fullHeight===!0&&!e.launcher.sidebarMode&&e.launcher.mountMode!=="docked")=>{let n=e?.welcome,o=e?.copy,r=e?.future?.v5Defaults===!0,s=n?.layout??(r?"centered":"top"),i=Fn(n,"variant")?n.variant:o?.showWelcomeCard===!1?"none":"card",l=i==="hero"&&!r&&n?.layout===void 0?"on-first-message":Fn(n,"dismiss")?n.dismiss:r||i==="hero"?"on-first-message":"never",c=[];Fn(n,"title")&&Fn(o,"welcomeTitle")&&c.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),Fn(n,"subtitle")&&Fn(o,"welcomeSubtitle")&&c.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),Fn(n,"variant")&&Fn(o,"showWelcomeCard")&&c.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),i==="hero"&&Fn(n,"message")&&c.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),!r&&n?.layout===void 0&&i==="hero"&&Fn(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"&&t?"center":"bottom"),d=Ql(n?.anchorComposerTop)!==null;return Fn(n,"anchorComposerTop")&&!d&&c.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),p!=="center"&&(Fn(n,"anchorComposerTop")||Fn(n,"composerGap"))&&c.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),rL(e,c),{title:Fn(n,"title")?n.title:o?.welcomeTitle??(r?"What can I help with?":nL),kicker:n?.kicker??"",subtitle:Fn(n,"subtitle")?n.subtitle:o?.welcomeSubtitle??(r?"":oL),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:i,dismiss:l,message:i==="hero"?void 0:n?.message,layout:s,anchor:p,anchorComposerTop:d?n.anchorComposerTop:"44%",composerGap:n?.composerGap?.trim()||Kp}},AA=e=>(e??[]).some(t=>t.role==="user")?"active":"empty",Ws=(e,t)=>e.variant==="none"?!1:e.dismiss==="never"?!0:!(t??[]).some(n=>n.role==="user");Ea();var sL="var(--persona-components-panel-maxWidth)",xA="var(--persona-components-panel-height)",iL="var(--persona-components-panel-maxHeight)",Hi=e=>{let t=_r(e),n=t.launcherWidth?e?.launcher?.width:t.legacyLauncherWidth?e?.launcherWidth:void 0,o=e?.launcher?.heightOffset??0,r=o===0?`max(200px, ${xA})`:`max(200px, calc(${xA} - ${o}px))`;return{width:n??CC,maxWidth:n??sL,height:r,maxHeight:iL}},EA="16px",Jm="10px",Zm="14px",MA=e=>{let t=e?.launcher?.enabled??!0,n=Lt(e);if(Rs(e)){let p=e?.launcher?.composerBar??{},d=x("div","persona-widget-wrapper persona-fixed persona-transition");d.setAttribute("data-persona-composer-bar",""),d.dataset.state="collapsed",d.dataset.expandedSize=p.expandedSize??"anchored",d.style.zIndex=String(e?.launcher?.zIndex??kn);let g=x("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");g.style.width="100%",d.appendChild(g);let f=x("div","persona-widget-pill-root");return f.setAttribute("data-persona-composer-bar",""),f.dataset.state="collapsed",f.dataset.expandedSize=p.expandedSize??"anchored",f.style.zIndex=String(e?.launcher?.zIndex??kn),{wrapper:d,panel:g,pillRoot:f}}if(n){let p=x("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),d=x("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return p.appendChild(d),{wrapper:p,panel:d}}if(!t){let p=x("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),d=x("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),g=_r(e),h=g.launcherWidth||g.legacyLauncherWidth||e?.theme?.components?.panel?.width!==void 0?Hi(e).width:"100%";return p.style.width=h,d.style.width="100%",p.appendChild(d),{wrapper:p,panel:d}}let r=e?.launcher??{},s=r.position&&ao[r.position]?ao[r.position]:ao["bottom-right"],i=x("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);i.style.zIndex=String(e?.launcher?.zIndex??kn);let l=x("div","persona-widget-panel persona-relative persona-min-h-[320px]"),c=Hi(e);return l.style.width=c.width,l.style.maxWidth=c.maxWidth,i.appendChild(l),{wrapper:i,panel:l}},eh=e=>{let t=Q("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":Om(e)}});return t.hidden=!0,t},TA=(e,t)=>{let n=eh("starter"),o=hA(e,n,{flatShadow:Lt(e)}),r=Ua(e);su(o,r),$a(t,o.host,Ws(r,e?.initialMessages));let s=bA();return iu(s,r.message,e),{welcome:o,greetingHost:s}},aL=(e,t)=>{let n=x("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}=Ba(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:EA,iconSize:Jm});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let s=e?.launcher?.clearChat?.enabled??!0,i=null,l=null;if(s){let oe=Da(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:EA,iconSize:Zm});i=oe.button,l=oe.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let c=Q("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),p=Q("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:d,greetingHost:g}=TA(e,p),{host:f,title:h,subtitle:y}=d,v=d.starterSuggestions,C=x("div","persona-widget-messages persona-flex persona-flex-col");C.style.gap="var(--persona-components-message-gap, 12px)";let A=eh("followUp"),L=Hs(e,!0);L&&(C.style.maxWidth=L,C.style.marginLeft="auto",C.style.marginRight="auto",C.style.width="100%"),p.append(f,g,C,A);let I=Q("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"}}),H=nu({config:e}),{root:B,textNode:V}=lA();return n.append(c,r,p,I),l&&n.appendChild(l),{container:n,body:p,messagesWrapper:C,starterSuggestions:v,transcriptSuggestions:A,composerOverlay:I,suggestions:H.suggestions,textarea:H.textarea,sendButton:H.sendButton,sendButtonWrapper:H.sendButtonWrapper,micButton:H.micButton,micButtonWrapper:H.micButtonWrapper,composerForm:H.composerForm,statusText:H.statusText,welcomeHost:f,welcomeIconHolder:d.iconHolder,greetingHost:g,introKicker:d.kicker,introTitle:h,introSubtitle:y,closeButton:o,closeButtonWrapper:r,clearChatButton:i,clearChatButtonWrapper:l,iconHolder:x("span"),headerTitle:x("span"),headerSubtitle:x("span"),header:c,footer:H.footer,attachmentButton:H.attachmentButton,attachmentButtonWrapper:H.attachmentButtonWrapper,attachmentInput:H.attachmentInput,attachmentPreviewsContainer:H.attachmentPreviewsContainer,actionsRow:H.actionsRow,leftActions:H.leftActions,rightActions:H.rightActions,setSendButtonMode:H.setSendButtonMode,peekBanner:B,peekTextNode:V}},PA=(e,t=!0)=>{if(Rs(e))return aL(e,t);let n=Q("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=e?.layout?.header,r=e?.layout?.showHeader!==!1,s=o?Na(e,o,{showClose:t}):jr({config:e,showClose:t}),i=Q("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"}});i.style.setProperty("scrollbar-gutter","stable");let{welcome:l,greetingHost:c}=TA(e,i),{host:p,title:d,subtitle:g}=l,f=l.starterSuggestions,h=x("div","persona-widget-messages persona-flex persona-flex-col");h.style.gap="var(--persona-components-message-gap, 12px)";let y=eh("followUp"),v=Hs(e,!1);v&&(h.style.maxWidth=v,h.style.marginLeft="auto",h.style.marginRight="auto",h.style.width="100%"),i.append(p,c,h,y);let C=ki({config:e}),A=e?.layout?.showFooter!==!1;r?Ti(n,s,e):(s.header.style.display="none",Ti(n,s,e)),n.append(i);let L=Q("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 A||(C.footer.style.display="none"),n.append(C.footer),n.append(L),{container:n,body:i,messagesWrapper:h,starterSuggestions:f,transcriptSuggestions:y,composerOverlay:L,suggestions:C.suggestions,textarea:C.textarea,sendButton:C.sendButton,sendButtonWrapper:C.sendButtonWrapper,micButton:C.micButton,micButtonWrapper:C.micButtonWrapper,composerForm:C.composerForm,statusText:C.statusText,welcomeHost:p,welcomeIconHolder:l.iconHolder,greetingHost:c,introKicker:l.kicker,introTitle:d,introSubtitle:g,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:C.footer,attachmentButton:C.attachmentButton,attachmentButtonWrapper:C.attachmentButtonWrapper,attachmentInput:C.attachmentInput,attachmentPreviewsContainer:C.attachmentPreviewsContainer,actionsRow:C.actionsRow,leftActions:C.leftActions,rightActions:C.rightActions,setSendButtonMode:C.setSendButtonMode}};Ms();Ze();kt();_o();var th=(e,t)=>{let n=x("button");n.type="button",n.innerHTML=`
|
|
31
31
|
<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>
|
|
32
32
|
<img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
|
|
33
33
|
<span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
|
|
@@ -35,15 +35,15 @@ _Details: ${n.message}_`:o}var Fw=e=>bs(e)||e===Oo,Wa=class e{constructor(t={},n
|
|
|
35
35
|
<span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-launcher-muted" data-role="launcher-subtitle"></span>
|
|
36
36
|
</span>
|
|
37
37
|
<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>
|
|
38
|
-
`,n.addEventListener("click",t);let o=s=>{let i=s.launcher??{},l=Lt(s),c=
|
|
39
|
-
`):""},
|
|
40
|
-
`).length>7?{tabindex:"0","aria-label":`${l} content`}:{},style:{color:r.codeBlockTextColor??r.contentTextColor}}),h=Q("button",{className:"persona-tool-detail-copy",attrs:{type:"button","data-persona-copy-tool-detail":"","aria-label":`Copy ${l.toLowerCase()}`,title:`Copy ${l.toLowerCase()}`}}),y=ge("copy",14,"currentColor",1.7);y&&h.appendChild(y),p.append(d,f,h),e.appendChild(p)};
|
|
38
|
+
`,n.addEventListener("click",t);let o=s=>{let i=s.launcher??{},l=Lt(s),c=Np(s)==="circle";c?(n.dataset.personaLauncherVariant="circle",n.setAttribute("aria-label",i.title??"Open chat")):(n.removeAttribute("data-persona-launcher-variant"),n.removeAttribute("aria-label"));let p=n.querySelector("[data-role='launcher-title']");if(p){let H=i.title??"Chat Assistant";p.textContent=H,p.setAttribute("title",H)}let d=n.querySelector("[data-role='launcher-subtitle']");if(d){let H=i.subtitle??"Here to help you get answers fast";d.textContent=H,d.setAttribute("title",H)}let g=n.querySelector(".persona-flex-col");g&&(i.textHidden||l||c?g.style.display="none":g.style.display="");let f=n.querySelector("[data-role='launcher-icon']");if(f)if(i.agentIconHidden)f.style.display="none";else{let H=i.agentIconSize??"40px";if(f.style.height=H,f.style.width=H,i.agentIconBackgroundColor?(f.style.backgroundColor=i.agentIconBackgroundColor,f.classList.remove("persona-bg-persona-primary")):(f.style.backgroundColor="",f.classList.add("persona-bg-persona-primary")),f.innerHTML="",i.agentIconName){let B=parseFloat(H)||24,V=ge(i.agentIconName,B*.6,"var(--persona-text-inverse, #ffffff)",1.5);V?(f.appendChild(V),f.style.display=""):(f.textContent=i.agentIconText??"\u{1F4AC}",f.style.display="")}else i.iconUrl?f.style.display="none":(f.textContent=i.agentIconText??"\u{1F4AC}",f.style.display="")}let h=n.querySelector("[data-role='launcher-image']");if(h){let H=i.agentIconSize??"40px";h.style.height=H,h.style.width=H,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(h.src=i.iconUrl,h.style.display="block"):h.style.display="none"}let y=n.querySelector("[data-role='launcher-call-to-action-icon']");if(y){let H=i.callToActionIconSize??"32px";y.style.height=H,y.style.width=H,i.callToActionIconBackgroundColor?(y.style.backgroundColor=i.callToActionIconBackgroundColor,y.classList.remove("persona-bg-persona-primary")):(y.style.backgroundColor="",y.classList.add("persona-bg-persona-primary")),i.callToActionIconColor?(y.style.color=i.callToActionIconColor,y.classList.remove("persona-text-persona-call-to-action")):(y.style.color="",y.classList.add("persona-text-persona-call-to-action"));let B=0;if(i.callToActionIconPadding?(y.style.boxSizing="border-box",y.style.padding=i.callToActionIconPadding,B=(parseFloat(i.callToActionIconPadding)||0)*2):(y.style.boxSizing="",y.style.padding=""),i.callToActionIconHidden||c)y.style.display="none";else if(y.style.display=l?"none":"",y.innerHTML="",i.callToActionIconName){let V=parseFloat(H)||24,oe=Math.max(V-B,8),W=ge(i.callToActionIconName,oe,"currentColor",1.5);W?y.appendChild(W):y.textContent=i.callToActionIconText??"\u2197"}else y.textContent=i.callToActionIconText??"\u2197"}let v=i.position&&ao[i.position]?ao[i.position]:ao["bottom-right"],C="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",A="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?A:`${C} ${v}`,l||(n.style.zIndex=String(i.zIndex??kn));let L="1px solid var(--persona-launcher-border, var(--persona-border, #e5e7eb))",I="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=i.border??L,n.style.boxShadow=i.shadow!==void 0?i.shadow.trim()===""?"none":i.shadow:I,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=i.collapsedMaxWidth??"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},r=()=>{n.removeEventListener("click",t),n.remove()};return e&&o(e),{element:n,update:o,destroy:r}},lL="teaser-dismissed",LA=new Set,kA=e=>{let t=e?.persistState;return`${(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"}${lL}`},cL=(e,t)=>{if(LA.has(e))return!0;if(!t)return!1;try{return window.localStorage.getItem(e)==="1"}catch{return!1}},dL=(e,t)=>{if(LA.add(e),!!t)try{window.localStorage.setItem(e,"1")}catch{}},pL=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,uL=e=>{let t=e?.launcher?.teaser;return!t||!t.text||e?.launcher?.enabled===!1||Lt(e??{})?null:t},HA=(e,t)=>{let n=x("div","persona-launcher-surface");n.setAttribute("data-persona-launcher-surface","true");let o=e??{},r=null,s=null,i=null,l=null,c=null,p=!1,d=!1,g=!1,f=!1,h=()=>(r?.frequency??"once")==="once"&&o.persistState!==!1,y=()=>{c!==null&&(clearTimeout(c),c=null)},v=()=>{!s||!p||(p=!1,s.hidden=!0)},C=J=>{y(),g=!0,v(),dL(kA(o),J&&h())},A=J=>{!r||g||C(J==="user"&&p)},L=()=>{c=null,!(!s||g||f)&&(d=!0,p=!0,s.hidden=!1,!(pL()||typeof s.animate!="function")&&s.animate([{opacity:"0",transform:"translateY(6px)"},{opacity:"1",transform:"none"}],{duration:220,easing:"ease-out",fill:"backwards"}))},I=()=>{!r||!s||g||d||f||cL(kA(o),h())||(y(),c=setTimeout(L,Math.max(0,r.delayMs??0)))},H=()=>{C(h()),t()},B=J=>{J.stopPropagation(),C(h())},oe=th(e,()=>{A("user"),t()}),W=()=>{y(),l?.removeEventListener("click",H),i?.removeEventListener("click",B),s?.remove(),s=null,l=null,i=null,p=!1},j=()=>{l=Q("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),l.addEventListener("click",H),i=Q("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"\xD7"}),i.addEventListener("click",B),s=Q("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},l,i),n.insertBefore(s,oe.element)},X=()=>{let J=o.launcher?.position??"bottom-right",U=ao[J]??ao["bottom-right"];if(!s){n.className="persona-launcher-surface",n.removeAttribute("data-teaser"),n.style.zIndex="",oe.element.style.position="";return}n.className=Dn("persona-launcher-surface",U),n.setAttribute("data-teaser",J),n.style.zIndex=String(o.launcher?.zIndex??kn),oe.element.style.position="static"},M=J=>{let U=uL(J);if(r=U,!U){W();return}s||j(),l.textContent=U.text,i.hidden=U.dismissible===!1,i.setAttribute("aria-label",U.dismissLabel??"Dismiss message"),I()},T=J=>{o=J,oe.update(J),M(J),X()},_=(J,U="user")=>{f=J,J&&A(U)},P=()=>{W(),oe.destroy(),n.remove()};return n.appendChild(oe.element),e&&(M(e),X()),{element:n,launcher:oe,get teaser(){return s?{element:s,show:L,dismiss:C}:null},setPanelOpen:_,update:T,destroy:P}};var IA=({config:e,showClose:t})=>{let{wrapper:n,panel:o,pillRoot:r}=MA(e),s=PA(e,t),i={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:i,panelElements:s,transcript:l,header:c,composer:p,replaceHeader:f=>(c.element.replaceWith(f.header),c.element=f.header,c.iconHolder=f.iconHolder,c.headerTitle=f.headerTitle,c.headerSubtitle=f.headerSubtitle,c.closeButton=f.closeButton,c.closeButtonWrapper=f.closeButtonWrapper,c.clearChatButton=f.clearChatButton,c.clearChatButtonWrapper=f.clearChatButtonWrapper,f),replaceComposer:f=>{p.footer.replaceWith(f),p.footer=f}}},nh=({config:e,plugins:t,onToggle:n})=>{let o=t.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:e,defaultRenderer:()=>th(e,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=HA(e,n);return{instance:r,element:r.element}};var gL=e=>{let t=e?.persistState;return(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"},fL=(e,t,n)=>`${gL(e)}plugin:${t}:${n}`,RA=e=>{let t=new Map,n=!1,o=()=>{if(n||e()?.persistState===!1)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return n=!0,null}};return r=>{let s=i=>fL(e(),r,i);return{get:i=>{let l=s(i),c=o();if(c)try{return c.getItem(l)}catch{n=!0}return t.get(l)??null},set:(i,l)=>{let c=s(i),p=o();if(p)try{p.setItem(c,l);return}catch{n=!0}t.set(c,l)},remove:i=>{let l=s(i);t.delete(l);let c=o();if(c)try{c.removeItem(l)}catch{n=!0}}}}};Ze();kt();So();Cs();Ze();var Va=(e,t,n)=>{let o=n;for(let r of t){let s=x("span","persona-tool-char");s.style.setProperty("--char-index",String(o)),s.textContent=r===" "?"\xA0":r,e.appendChild(s),o++}return o};var mL=(e,t)=>{let n=e.reasoning?.chunks.join("").trim()??"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,t).join(`
|
|
39
|
+
`):""},oh=(e,t,n)=>{Tp(e,t,{stateSet:n,previewKind:"reasoning",iconColor:"currentColor"})},rh=(e,t,n=new Set)=>{t=kp(t,"reasoning");let o=e.reasoning,r=Ap("persona-reasoning-bubble",e.id);if(!o)return $r(r,e,t,"reasoning");let s=t?.features?.reasoningDisplay??{},i=s.expandable??Ci.expandable,l=i&&n.has(e.id),c=o.status!=="complete",p=mL(e,s.previewMaxLines??Ci.previewMaxLines),d=xp({expandable:i,expanded:l,bubbleType:"reasoning"}),g=x("div","persona-flex persona-flex-col persona-text-left"),f=x("span","persona-text-xs persona-text-persona-primary"),h=Ts(t,"reasoning")==="row",y=h&&!c?`Thought for ${Ul(o.durationMs??(o.completedAt!==void 0&&o.startedAt!==void 0?o.completedAt-o.startedAt:void 0))}`:"Thinking...",v=t?.reasoning??{},C=String(o.startedAt??Date.now()),A=()=>{let U=x("span","");return U.setAttribute("data-tool-elapsed",C),U.textContent=Md(o),U},L=v.renderCollapsedSummary?.({message:e,reasoning:o,defaultSummary:y,previewText:p,isActive:c,config:t??{},elapsed:Md(o),createElapsedElement:A});typeof L=="string"&&L.trim()?(f.textContent=L,g.appendChild(f)):L instanceof HTMLElement?g.appendChild(L):(f.textContent=y,g.appendChild(f));let I=x("span","persona-text-xs persona-text-persona-primary");I.textContent=bv(o),h||g.appendChild(I);let H=s.loadingAnimation??Ci.loadingAnimation,B=v.activeTextTemplate,V=v.completeTextTemplate,oe=c?B:V,W=L instanceof HTMLElement,j=(U,ue)=>{f.textContent="";let fe=Td(U,""),me=0;for(let He of fe){let Ee=He.styles.length>0?(()=>{let Ie=x("span",He.styles.map(yt=>`persona-tool-text-${yt}`).join(" "));return f.appendChild(Ie),Ie})():f;if(He.isDuration&&c)Ee.appendChild(A());else{let Ie=He.isDuration?Md(o):He.text;ue?me=Va(Ee,Ie,me):Ee.appendChild(document.createTextNode(Ie))}}};if(!W&&oe)if(I.style.display="none",f.style.display="",c&&H!=="none"){let U=v.loadingAnimationDuration??2e3;f.setAttribute("data-preserve-animation","true"),H==="pulse"?(f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${U}ms`),j(oe,!1)):(f.classList.add(`persona-tool-loading-${H}`),f.style.setProperty("--persona-tool-anim-duration",`${U}ms`),H==="shimmer-color"&&(v.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",v.loadingAnimationColor),v.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",v.loadingAnimationSecondaryColor)),j(oe,!0))}else j(oe,!1);else if(!W&&c&&H!=="none"){f.style.display="";let U=v.loadingAnimationDuration??2e3;if(f.setAttribute("data-preserve-animation","true"),H==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${U}ms`);else{f.classList.add(`persona-tool-loading-${H}`),f.style.setProperty("--persona-tool-anim-duration",`${U}ms`),H==="shimmer-color"&&(v.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",v.loadingAnimationColor),v.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",v.loadingAnimationSecondaryColor));let ue=f.textContent||y;f.textContent="",Va(f,ue,0)}o.status==="complete"&&!h&&(f.style.display="none")}else W||(o.status==="complete"&&!h?f.style.display="none":f.style.display="");if(s.iconName&&!W){let U=x("span","persona-reasoning-header-icon"),ue=ge(s.iconName,16,"currentColor",2);ue&&(U.appendChild(ue),d.appendChild(U))}let X="currentColor",M=La(d,g,{expandable:i,expanded:l,iconColor:X,metaGap:!1}),T=Ep({bubble:r,previewKind:"reasoning",expanded:l,isActive:c,previewText:p,activePreview:s.activePreview,activeMinHeight:s.activeMinHeight,renderPreview:()=>t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:o,defaultPreview:p,isActive:c,config:t??{}})});if(!i)return r.append(d,T),$r(r,e,t,"reasoning");let _=x("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");_.style.display=l?"":"none";let P=o.chunks.join(""),J=x("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return J.textContent=P||(o.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),_.appendChild(J),Mp({expanded:l,header:d,toggleIcon:M,content:_,collapsedPreview:T,iconColor:X}),r.append(d,T,_),$r(r,e,t,"reasoning")};Ze();Cs();kt();var WA=e=>{if(e==null)return!0;if(typeof e=="string"){if(!e.trim())return!0;try{return WA(JSON.parse(e))}catch{return!1}}return typeof e=="object"&&Object.keys(e).length===0},hL=e=>{if(e!==null&&typeof e=="object")return!0;if(typeof e!="string")return!1;try{let t=JSON.parse(e);return t!==null&&typeof t=="object"}catch{return!1}};function OA(e,t,n){let o=t.toolCall;if(!o)return;let r=n.toolCall??{},s=(l,c)=>{let p=Q("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}}),d=Q("div",{className:"persona-tool-detail-label",text:l,style:{color:r.labelTextColor}}),g=ya(c),f=Q("pre",{className:`persona-tool-detail-value${hL(c)?" persona-tool-detail-code":""}`,text:g,attrs:g.length>420||g.split(`
|
|
40
|
+
`).length>7?{tabindex:"0","aria-label":`${l} content`}:{},style:{color:r.codeBlockTextColor??r.contentTextColor}}),h=Q("button",{className:"persona-tool-detail-copy",attrs:{type:"button","data-persona-copy-tool-detail":"","aria-label":`Copy ${l.toLowerCase()}`,title:`Copy ${l.toLowerCase()}`}}),y=ge("copy",14,"currentColor",1.7);y&&h.appendChild(y),p.append(d,f,h),e.appendChild(p)};WA(o.args)||s("Request",o.args);let i=o.status==="complete"&&o.result!==void 0?o.result:o.chunks?.join("");i!==void 0&&(typeof i!="string"||i.trim())&&s("Response",i),o.success===!1&&e.appendChild(Q("div",{className:"persona-text-sm persona-whitespace-pre-wrap",text:o.error||"Tool failed",attrs:{"data-persona-tool-error":"",role:"status"}}))}var sh=new WeakMap;async function _A(e){let t=e.closest("[data-persona-tool-detail]"),n=t?.querySelector("pre");if(!n)return;let o=`Copy ${t?.getAttribute("data-persona-tool-detail")}`;clearTimeout(sh.get(e));try{await navigator.clipboard.writeText(n.textContent??""),e.dataset.copied="true",e.setAttribute("aria-label","Copied"),e.title="Copied";let r=ge("check",14,"currentColor",2);r&&e.replaceChildren(r)}catch{e.setAttribute("aria-label","Copy failed \u2014 try again"),e.title="Copy failed \u2014 try again"}sh.set(e,setTimeout(()=>{delete e.dataset.copied,e.setAttribute("aria-label",o),e.title=o;let r=ge("copy",14,"currentColor",1.7);r&&e.replaceChildren(r),sh.delete(e)},1800))}Ze();So();Cs();var BA=(e,t=!1)=>e.toggleTextColor||e.headerTextColor||(t?"currentColor":"var(--persona-primary, #171717)"),yL=(e,t)=>{let n=e.toolCall;if(!n)return"";let o=(n.chunks??[]).join("").trim();if(o)return o.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
|
|
41
41
|
`);let r=ya(n.args).trim();return r?r.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
|
|
42
|
-
`):""},oh=(e,t)=>{e.style.backgroundColor=t.codeBlockBackgroundColor??"var(--persona-container, #f3f4f6)",e.style.borderColor=t.codeBlockBorderColor??"var(--persona-border, #e5e7eb)",e.style.color=t.codeBlockTextColor??"var(--persona-text, #171717)"},gL=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,r=o?.collapsedMode??_r.collapsedMode,s=n?.success===!1?n.error||"Tool failed":uL(e,o?.previewMaxLines??_r.previewMaxLines),i=n?Ts(t,"tool")==="row"?`${n.status==="complete"?"Used":"Using"} ${n.name?.trim()||"tool"}`:hv(n):"";if(!n)return{summary:i,previewText:s,isActive:!1};let l=n.status!=="complete",c=t?.toolCall??{},p=i;return r==="tool-name"?p=n.name?.trim()||i:r==="tool-preview"&&s&&(p=s),l&&c.activeTextTemplate?p=sf(n,c.activeTextTemplate,p):!l&&c.completeTextTemplate&&(p=sf(n,c.completeTextTemplate,p)),n.success===!1?p+=" \xB7 Failed":n.superseded&&(p+=" \xB7 Approved, ran again below"),{summary:p,previewText:s,isActive:l}},rh=(e,t,n,o)=>{Mp(e,t,{stateSet:n,previewKind:"tool",iconColor:RA(o?.toolCall??{},t.classList.contains("persona-activity-row"))})},sh=(e,t,n=new Set)=>{t=Tp(t,"tool");let o=e.toolCall,r=t?.toolCall??{},s=wp("persona-tool-bubble",e.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 $r(s,e,t,"tool");let i=t?.features?.toolCallDisplay??{},l=i.expandable??_r.expandable,c=l&&n.has(e.id),{summary:p,previewText:d,isActive:g}=gL(e,t),f=Sp({expandable:l,expanded:c,bubbleType:"tool"});r.headerBackgroundColor&&(f.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(f.style.paddingLeft=r.headerPaddingX,f.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(f.style.paddingTop=r.headerPaddingY,f.style.paddingBottom=r.headerPaddingY);let h=x("div","persona-flex persona-flex-col persona-text-left"),y=x("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(y.style.color=r.headerTextColor);let v=String(o.startedAt??Date.now()),C=()=>{let T=x("span","");return T.setAttribute("data-tool-elapsed",v),T.textContent=Pl(o),T},A=r.renderCollapsedSummary?.({message:e,toolCall:o,defaultSummary:p,previewText:d,collapsedMode:i.collapsedMode??_r.collapsedMode,isActive:g,config:t??{},elapsed:Pl(o),createElapsedElement:C});typeof A=="string"&&A.trim()?(y.textContent=A,h.appendChild(y)):A instanceof HTMLElement?h.appendChild(A):(y.textContent=p,h.appendChild(y));let L=i.loadingAnimation??_r.loadingAnimation,I=r.activeTextTemplate,H=r.completeTextTemplate,_=g?I:H,V=A instanceof HTMLElement,oe=(T,B)=>{y.textContent="";let P=o.name?.trim()||"tool",J=Md(T,P),U=0;for(let ue of J){let fe=ue.styles.length>0?(()=>{let me=x("span",ue.styles.map(He=>`persona-tool-text-${He}`).join(" "));return y.appendChild(me),me})():y;if(ue.isDuration&&g)fe.appendChild(C());else{let me=ue.isDuration?Pl(o):ue.text;B?U=Va(fe,me,U):fe.appendChild(document.createTextNode(me))}}};if(!V)if(g&&L!=="none"){let T=r.loadingAnimationDuration??2e3;if(y.setAttribute("data-preserve-animation","true"),L==="pulse")y.classList.add("persona-tool-loading-pulse"),y.style.setProperty("--persona-tool-anim-duration",`${T}ms`),_&&oe(_,!1);else if(y.classList.add(`persona-tool-loading-${L}`),y.style.setProperty("--persona-tool-anim-duration",`${T}ms`),L==="shimmer-color"&&(r.loadingAnimationColor&&y.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&y.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),_)oe(_,!0);else{let B=y.textContent||p;y.textContent="",Va(y,B,0)}}else _&&oe(_,!1);let W=RA(r,Ts(t,"tool")==="row"),j=La(f,h,{expandable:l,expanded:c,iconColor:W,metaGap:!0}),X=Ap({bubble:s,previewKind:"tool",expanded:c,isActive:g,previewText:d,activePreview:i.activePreview,activeMinHeight:i.activeMinHeight,renderPreview:()=>r.renderCollapsedPreview?.({message:e,toolCall:o,defaultPreview:d,isActive:g,config:t??{}})});if(!l)return s.append(f,X),$r(s,e,t,"tool");let E=x("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(E.style.display=c?"":"none",r.contentBackgroundColor&&(E.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(E.style.color=r.contentTextColor),r.contentPaddingX&&(E.style.paddingLeft=r.contentPaddingX,E.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(E.style.paddingTop=r.contentPaddingY,E.style.paddingBottom=r.contentPaddingY),t.future?.v5Defaults===!0)HA(E,e,t);else{if(o.name){let T=x("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?T.style.color=r.contentTextColor:r.headerTextColor&&(T.style.color=r.headerTextColor),T.textContent=o.name,E.appendChild(T)}if(o.args!==void 0){let T=x("div","persona-space-y-1"),B=x("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(B.style.color=r.labelTextColor),B.textContent="Arguments";let P=x("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");P.style.fontSize="0.75rem",P.style.lineHeight="1rem",oh(P,r),P.textContent=ya(o.args),T.append(B,P),E.appendChild(T)}if(o.chunks&&o.chunks.length){let T=x("div","persona-space-y-1"),B=x("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(B.style.color=r.labelTextColor),B.textContent="Activity";let P=x("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");P.style.fontSize="0.75rem",P.style.lineHeight="1rem",oh(P,r),P.textContent=o.chunks.join(""),T.append(B,P),E.appendChild(T)}if(o.success===!1&&E.appendChild(Q("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 T=x("div","persona-space-y-1"),B=x("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(B.style.color=r.labelTextColor),B.textContent="Result";let P=x("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");P.style.fontSize="0.75rem",P.style.lineHeight="1rem",oh(P,r),P.textContent=ya(o.result),T.append(B,P),E.appendChild(T)}if(o.status==="complete"&&typeof o.duration=="number"){let T=x("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(T.style.color=r.contentTextColor),T.textContent=`Duration: ${o.duration}ms`,E.appendChild(T)}}return xp({expanded:c,header:f,toggleIcon:j,content:E,collapsedPreview:X,iconColor:W}),s.append(f,X,E),$r(s,e,t,"tool")};Rl();Ca();Cs();dn();var{setLoader:qN,load:fL,provide:zN,getSync:mL}=lt({fallbackImport:()=>import("@runtypelabs/persona/approval-ui")});var WA=fL;var OA=mL;pi();dn();var{setLoader:YN,load:hL}=lt({fallbackImport:()=>import("@runtypelabs/persona/event-stream-view")});var ih=hL;dn();var ah=class{constructor(){this.components=new Map;this.#e=new Map}#e;register(t,n,o){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n),o?this.#e.set(t,o):this.#e.delete(t)}unregister(t){this.components.delete(t),this.#e.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getOptions(t){return this.#e.get(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.#e.clear()}registerAll(t){Object.entries(t).forEach(([n,o])=>{this.register(n,o)})}},Fo=new ah;Jg();var lh=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:n1,load:yL,provide:o1,getSync:bL}=lt({fallbackImport:()=>import("@runtypelabs/persona/artifacts-ui")}),ja=null,su=new Set,BA=e=>{if(ja)return ja;ja=e,e.initArtifactsUi({componentRegistry:Fo});for(let o of lh)Fo.has(o)||Fo.register(o,o==="PersonaArtifactCard"?e.PersonaArtifactCard:e.PersonaArtifactInline,{bubbleChrome:!1});let t=nr();t?e.__provideMarkdownParsers(t):ua(()=>{let o=nr();o&&e.__provideMarkdownParsers(o)}),e.__setIconsExtraLoader(()=>bd());let n=[...su];su.clear();for(let o of n)try{o()}catch{}return e};var iu=()=>yL().then(BA);var qr=()=>{if(ja)return ja;let e=bL();return e?BA(e):null},ch=e=>ja?()=>{}:(su.add(e),()=>{su.delete(e)});function $n(e){return e?.features?.artifacts?.enabled===!0}function _A(e,t){if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!$n(t))return;let n=t.features?.artifacts?.layout,o=n?.paneBorder?.trim(),r=n?.paneBorderLeft?.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):r&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",r))}function vL(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}var DA=["panel","seamless","detached"];function dh(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&DA.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function ph(e){return!e||!$n(e)?!1:dh(e)==="detached"}function dc(e,t){if(!$n(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-drawer-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),vL(e),_A(e,t);return}let n=t.features?.artifacts?.layout,o=dh(t)==="detached"?"var(--persona-panel-inset)":"0";e.style.setProperty("--persona-artifact-split-gap",n?.splitGap??o),e.style.setProperty("--persona-artifact-pane-width",n?.paneWidth??"40%"),e.style.setProperty("--persona-artifact-pane-max-width",n?.paneMaxWidth??"28rem"),n?.drawerWidth?e.style.setProperty("--persona-artifact-drawer-width",n.drawerWidth):e.style.removeProperty("--persona-artifact-drawer-width"),n?.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=n?.paneBackground?.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let s=n?.panePadding?.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let i=[[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 i){let p=l?.trim();p?e.style.setProperty(c,p):e.style.removeProperty(c)}_A(e,t)}function pc(e,t){for(let l of DA)e.classList.remove(`persona-artifact-appearance-${l}`);if(e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-chat-shadow"),!$n(t))return;let n=t.features?.artifacts?.layout,o=dh(t);e.classList.add(`persona-artifact-appearance-${o}`);let r=n?.paneBorderRadius?.trim();r&&e.style.setProperty("--persona-artifact-pane-radius",r);let s=n?.paneShadow?.trim();s&&e.style.setProperty("--persona-artifact-pane-shadow",s);let i=n?.chatShadow?.trim();i&&e.style.setProperty("--persona-artifact-chat-shadow",i)}function NA(e,t){return!t||!$n(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}ha();ha();var CL=new Set(["__proto__","prototype","constructor"]),wL=new Set(["collapsed","card","panel","inline"]),FA=new Set(["markdown","component"]),SL=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,Ii=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),lu=e=>!CL.has(e),uh=e=>typeof e=="string"&&wL.has(e),Ri=e=>Object.keys(e).length>0;function ar(e,t,n,o){e.push({path:t,code:n,message:o})}var AL="Ignored because this key is not part of the persisted preference schema.",au="Ignored an unsupported value.",xL="Expected collapsed, panel, or inline.",ML='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',$A={kind:"mode",message:au},qa={kind:"string",message:"Expected a CSS length string."},zr={kind:"boolean"},EL={paneWidth:qa,paneMaxWidth:qa,paneMinWidth:qa,expandedPanelWidth:qa,resizableMinWidth:qa,resizableMaxWidth:qa,expandLauncherPanelWhenOpen:zr,resizable:zr},TL={kind:"object",message:"Expected a preference object.",children:{showToolCalls:zr,showReasoning:zr,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:au},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:au},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:au},expandable:zr,grouped:zr}},reasoningDisplay:{kind:"object",children:{expandable:zr,activePreview:zr}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:$A,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:$A,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:FA,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:FA}}},filePreview:{kind:"object",children:{enabled:zr}},layout:{kind:"object",children:EL}}}}};function UA(e,t,n,o){if(e!==void 0)switch(t.kind){case"boolean":return typeof e=="boolean"?e:ar(o,n,"invalid_type","Expected a boolean.");case"string":return typeof e=="string"?e:ar(o,n,"invalid_type",t.message);case"enum":return typeof e=="string"&&t.values.has(e)?e:ar(o,n,"invalid_value",t.message);case"mode":return uh(e)?Gn(e):ar(o,n,"invalid_value",t.message);case"modeMap":{if(!Ii(e))return ar(o,n,"invalid_type","Expected an object.");let r=t.keys==="mediaType"?void 0:t.keys,s={};for(let[i,l]of Object.entries(e)){let c=r?i:vs(i);lu(i)&&(r?r.has(i):SL.test(c))?uh(l)?s[c]=Gn(l):ar(o,`${n}.${i}`,"invalid_value",xL):ar(o,`${n}.${i}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":ML)}return Ri(s)?s:void 0}case"object":{if(t.bareMode&&uh(e))return Gn(e);if(!Ii(e))return ar(o,n,"invalid_type",t.message??"Expected an object.");let r=Object.keys(t.children),s=l=>n?`${n}.${l}`:l;for(let l of Object.keys(e))(!lu(l)||!r.includes(l))&&ar(o,s(l),"unknown_key",AL);let i={};for(let l of r){let c=t.children[l],p=UA(e[l],c,s(l),o);if(c.deprecated&&e[l]!==void 0&&ar(o,s(l),"deprecated_key",c.deprecated),p===void 0)continue;let d=c.alias??l,g=i[d];i[d]=Ii(g)&&Ii(p)?{...g,...p}:p}return Ri(i)?i:void 0}}}function gh(e){let t=[];return{preferences:(e===null?void 0:UA(e,TL,"",t))??{},issues:t}}function za(e){if(Array.isArray(e))return e.map(za);if(!Ii(e))return e;let t={};for(let[n,o]of Object.entries(e))lu(n)&&o!==void 0&&(t[n]=za(o));return t}function VA(e,t){let n=za(e);for(let[o,r]of Object.entries(t)){if(!lu(o)||r===void 0)continue;let s=n[o];n[o]=Ii(s)&&Ii(r)?VA(s,r):za(r)}return n}function PL(e){let t={},n;for(let r of e){let s=gh(r).preferences;n=jA(n,s.artifacts?.display),t=VA(t,s)}let o=t;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function kL(e,t){if(t===void 0)return e===void 0?void 0:za(e);if(typeof t=="string")return t;let n=typeof e=="string"?{default:e}:e??{},o=t.default??n.default,r={...n.byMediaType,...t.byMediaType},s={...o?{default:o}:{},...Ri(r)?{byMediaType:r}:{}};return Ri(s)?s:void 0}function jA(e,t){if(t===void 0)return e===void 0?void 0:za(e);if(typeof t=="string")return t;let n=typeof e=="string"?{default:e}:e??{},o=t.default??n.default,r={...n.byType,...n.byKind,...t.byType,...t.byKind},s=kL(n.files,t.files),i={...o?{default:o}:{},...Ri(r)?{byKind:r}:{},...s!==void 0?{files:s}:{}};return Ri(i)?i:void 0}function fh(e={},t){let n=PL(t),o={...e};if(n.showToolCalls!==void 0&&(o.showToolCalls=n.showToolCalls),n.showReasoning!==void 0&&(o.showReasoning=n.showReasoning),n.toolCallDisplay&&(o.toolCallDisplay={...e.toolCallDisplay,...n.toolCallDisplay}),n.reasoningDisplay&&(o.reasoningDisplay={...e.reasoningDisplay,...n.reasoningDisplay}),n.artifacts){let r=e.artifacts??{},s={...r};if(n.artifacts.display!==void 0){let i=jA(r.display,n.artifacts.display);i!==void 0&&(s.display=i)}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 uc(e){let t=e.preferences;return!t||!Ri(t)?e:{...e,features:fh(e.features??{},[t])}}function LL(e,t){if(!e?.trim())return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function HL(e){if(!e?.trim())return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function IL(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function RL(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function mh(e,t){let o=(t.getComputedStyle(e).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 qA(e,t,n,o,r,s,i=200){let l=LL(r,200),c=RL(t,n,o,i);c=Math.max(l,c);let p=HL(s);return p!==null&&(c=Math.min(c,p)),IL(e,l,c)}dn();var{setLoader:d1,load:WL,provide:p1,getSync:OL}=lt({fallbackImport:()=>import("@runtypelabs/persona/forms-ui")});var zA=WL;var KA=OL;var hh=class{#e=new Map;register(t){this.#e.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.#e.set(t.id,t),t.onRegister?.()}unregister(t){let n=this.#e.get(t);n&&(n.onUnregister?.(),this.#e.delete(t))}getAll(){return Array.from(this.#e.values()).sort((t,n)=>(n.priority??0)-(t.priority??0))}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let o=new Set(t.map(s=>s.id));return[...n.filter(s=>!o.has(s.id)),...t].sort((s,i)=>(i.priority??0)-(s.priority??0))}clear(){this.#e.forEach(t=>t.onUnregister?.()),this.#e.clear()}},gc=new hh;wo();wo();Ma();Lf();var GA=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),BL=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),YA=(e,t,n)=>{if(!GA(e)||!GA(t)||BL.has(n))return t;let o={...e};for(let r of Object.keys(t)){if(t[r]===void 0){delete o[r];continue}let s=n?`${n}.${r}`:r;o[r]=YA(e[r],t[r],s)}return o};function cu(e,t){let n=jd(bi),o=fC(e,t,n),r=Pf(mC(YA(e,t,""),n,o),o);return If(Ea(r),yC(e,t))}Ma();var XA=()=>{let e=new Map,t=(r,s)=>(e.has(r)||e.set(r,new Set),e.get(r).add(s),()=>n(r,s)),n=(r,s)=>{e.get(r)?.delete(s)};return{on:t,off:n,emit:(r,s)=>{e.get(r)?.forEach(i=>{try{i(s)}catch(l){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",l)}})}}};var _L=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},DL=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let o=0;for(let r=n;r<t.length;r+=1){let s=t[r];if(s==="{"&&(o+=1),s==="}"&&(o-=1,o===0))return t.slice(n,r+1)}return null},fc=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=_L(e),n=DL(t);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}},yh=e=>typeof e=="string"?e:e==null?"":String(e),Wi={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:yh(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let n=e.payload,o=yh(n.element);if(o&&t.document?.querySelector){let r=t.document.querySelector(o);r?setTimeout(()=>{r.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:yh(n.text)}}},QA=e=>Array.isArray(e)?e.map(t=>String(t)):[],mc=e=>{let t=new Set(QA(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(QA(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(t);e.updateSessionMetadata(i=>({...i,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let i=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!i&&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=i?e.parsers.reduce((p,d)=>p||d?.({text:i,message:s.message})||null,null):null;if(!l)return null;t.add(s.message.id),o();let c={action:l,message:s.message};e.emit("action:detected",c);for(let p of e.handlers)if(p)try{let d=()=>{e.emit("action:resubmit",c)},g=p(l,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:d});if(!g)continue;if(g.handled){let f=g.persistMessage!==!1;return{text:g.displayText!==void 0?g.displayText:"",persist:f,resubmit:g.resubmit}}}catch(d){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",d)}return{text:"",persist:!0}},syncFromMetadata:n}};var NL=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},FL=e=>e.map(t=>({...t,streaming:!1})),$L=e=>e.map(t=>({...t,status:"complete"})),du=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?NL(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?FL(n.messages):void 0,artifacts:n.artifacts?$L(n.artifacts):void 0};o.setItem(e,JSON.stringify(r))}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(o){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};var UL=e=>{let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")},JA=async e=>{let t=globalThis.crypto?.subtle;if(t)try{let n=await t.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(n)).map(o=>o.toString(16).padStart(2,"0")).join("")}catch{}return UL(e)},VL=async(e,t)=>{let n=await JA(e);return{storageKey:`${t}visitor:${n}`,leaseKey:`${t}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await JA(`${e}\0${t}`)}`}};var ZA=(e,t,n)=>{let o="",r="",s="",i=!1,l=!1,c=0,p=null,d=null,g=new Set,f=()=>{if(n||i)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return i=!0,null}},h=()=>{let W=f();if(!W)return p;try{return W.getItem(o)}catch{return i=!0,p}},y=(W,j)=>{if(l||W===p)return;let X=p;p=W,c+=1;let E={previousToken:X,token:W,source:j,revision:c};for(let T of g)T(E)},v=W=>{l||W.key!==null&&W.key!==o||y(W.key===null?null:W.newValue??null,"external")},C=(async()=>{let W=await VL(e,t);o=W.storageKey,r=W.leaseKey,s=W.lockName,p=h(),!n&&typeof window<"u"&&window.addEventListener("storage",v)})(),A=W=>new Promise(j=>setTimeout(j,W)),L=()=>{let W=f();if(!W)return null;try{let j=W.getItem(r);if(!j)return null;let X=JSON.parse(j);return typeof X?.expiresAt=="number"&&typeof X?.ownerNonce=="string"?X:null}catch{return null}},I=W=>{let j=f();if(j)try{L()?.ownerNonce===W&&j.removeItem(r)}catch{}},H=new Set,_=W=>l?Promise.reject(new Error("Visitor store destroyed before its first init could start")):W(),V=W=>new Promise(j=>{let X=setTimeout(E,W);function E(){clearTimeout(X),H.delete(E),window.removeEventListener("storage",T),j()}function T(B){(B.key===null||B.key===r)&&E()}H.add(E),window.addEventListener("storage",T)}),oe=async W=>{let j=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,X=Date.now()+15e3;for(;!l&&Date.now()<X;){let E=f();if(!E)break;let T=Date.now(),B=L();if(B&&B.expiresAt>T&&B.ownerNonce!==j){await V(Math.min(B.expiresAt-T,500));continue}try{E.setItem(r,JSON.stringify({ownerNonce:j,expiresAt:T+1e4}))}catch{i=!0;break}if(await A(20+Math.random()*40),L()?.ownerNonce!==j){await V(500);continue}d=j;try{return await _(W)}finally{d=null,I(j)}}return _(W)};return{ready:C,async get(){return await C,y(h(),"external"),p},async set(W){await C;let j=f();if(j)try{j.setItem(o,W)}catch{i=!0}y(W,"local")},async clear(){await C;let W=f();if(W)try{W.removeItem(o)}catch{i=!0}y(null,"local")},revision(){return c},subscribe(W){return g.add(W),()=>{g.delete(W)}},async withFirstInitLock(W){await C;let j=globalThis.navigator?.locks;return j?.request?j.request(s,()=>_(W)):f()?oe(W):_(W)},matches(W,j,X){return W===e&&j===t&&X===n},destroy(){l=!0,g.clear(),typeof window<"u"&&window.removeEventListener("storage",v),d&&I(d);for(let W of[...H])W()}}};dn();var{setLoader:A1,load:jL}=lt({fallbackImport:()=>import("@runtypelabs/persona/history-view")});var ex=jL;var qL=null;function tx(){return qL}var Ka=require("partial-json");function zL(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function KL(e,t){if(!zL(e))return null;let n=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:n,raw:t}}function pu(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e;try{let r=(0,Ka.parse)(n,Ka.STR|Ka.OBJ),s=KL(r,n);s&&(e=s)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function nx(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}Je();function uu(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=Fo.get(e.component);if(!s){if(lh.includes(e.component)){iu().catch(()=>{});let l=x("div","persona-w-full");return l.setAttribute("data-persona-artifact-pending","true"),l}return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null}let i={message:o,config:n,updateProps:l=>{r&&r(l)}};try{return s(e.props,i)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,l),null}}function ox(){let e=pu();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function rx(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let t=e.content.trim();if(t.startsWith("{")||t.startsWith("["))return e.content}return null}function hc(e){let t=rx(e);if(!t)return!1;try{let n=JSON.parse(t);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function gu(e){let t=rx(e);if(!t)return null;try{let n=JSON.parse(t);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:t}}}catch{}return null}var GL=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function fu(e){let{onSubmit:t,onDismiss:n,title:o="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:i="Submit",skipText:l="Skip",showComment:c=!0,ratingLabels:p=GL}=e,d=document.createElement("div");d.className="persona-feedback-container persona-feedback-csat",d.setAttribute("role","dialog"),d.setAttribute("aria-label","Customer satisfaction feedback");let g=null,f=document.createElement("div");f.className="persona-feedback-content";let h=document.createElement("div");h.className="persona-feedback-header";let y=document.createElement("h3");y.className="persona-feedback-title",y.textContent=o,h.appendChild(y);let v=document.createElement("p");v.className="persona-feedback-subtitle",v.textContent=r,h.appendChild(v),f.appendChild(h);let C=document.createElement("div");C.className="persona-feedback-rating persona-feedback-rating-csat",C.setAttribute("role","radiogroup"),C.setAttribute("aria-label","Satisfaction rating from 1 to 5");let A=[];for(let V=1;V<=5;V++){let oe=document.createElement("button");oe.type="button",oe.className="persona-feedback-rating-btn persona-feedback-star-btn",oe.setAttribute("role","radio"),oe.setAttribute("aria-checked","false"),oe.setAttribute("aria-label",`${V} star${V>1?"s":""}: ${p[V-1]}`),oe.title=p[V-1],oe.dataset.rating=String(V),oe.innerHTML=`
|
|
42
|
+
`):""},ih=(e,t)=>{e.style.backgroundColor=t.codeBlockBackgroundColor??"var(--persona-container, #f3f4f6)",e.style.borderColor=t.codeBlockBorderColor??"var(--persona-border, #e5e7eb)",e.style.color=t.codeBlockTextColor??"var(--persona-text, #171717)"},bL=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,r=o?.collapsedMode??Br.collapsedMode,s=n?.success===!1?n.error||"Tool failed":yL(e,o?.previewMaxLines??Br.previewMaxLines),i=n?Ts(t,"tool")==="row"?`${n.status==="complete"?"Used":"Using"} ${n.name?.trim()||"tool"}`:Cv(n):"";if(!n)return{summary:i,previewText:s,isActive:!1};let l=n.status!=="complete",c=t?.toolCall??{},p=i;return r==="tool-name"?p=n.name?.trim()||i:r==="tool-preview"&&s&&(p=s),l&&c.activeTextTemplate?p=cf(n,c.activeTextTemplate,p):!l&&c.completeTextTemplate&&(p=cf(n,c.completeTextTemplate,p)),n.success===!1?p+=" \xB7 Failed":n.superseded&&(p+=" \xB7 Approved, ran again below"),{summary:p,previewText:s,isActive:l}},ah=(e,t,n,o)=>{Tp(e,t,{stateSet:n,previewKind:"tool",iconColor:BA(o?.toolCall??{},t.classList.contains("persona-activity-row"))})},lh=(e,t,n=new Set)=>{t=kp(t,"tool");let o=e.toolCall,r=t?.toolCall??{},s=Ap("persona-tool-bubble",e.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 $r(s,e,t,"tool");let i=t?.features?.toolCallDisplay??{},l=i.expandable??Br.expandable,c=l&&n.has(e.id),{summary:p,previewText:d,isActive:g}=bL(e,t),f=xp({expandable:l,expanded:c,bubbleType:"tool"});r.headerBackgroundColor&&(f.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(f.style.paddingLeft=r.headerPaddingX,f.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(f.style.paddingTop=r.headerPaddingY,f.style.paddingBottom=r.headerPaddingY);let h=x("div","persona-flex persona-flex-col persona-text-left"),y=x("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(y.style.color=r.headerTextColor);let v=String(o.startedAt??Date.now()),C=()=>{let T=x("span","");return T.setAttribute("data-tool-elapsed",v),T.textContent=Pl(o),T},A=r.renderCollapsedSummary?.({message:e,toolCall:o,defaultSummary:p,previewText:d,collapsedMode:i.collapsedMode??Br.collapsedMode,isActive:g,config:t??{},elapsed:Pl(o),createElapsedElement:C});typeof A=="string"&&A.trim()?(y.textContent=A,h.appendChild(y)):A instanceof HTMLElement?h.appendChild(A):(y.textContent=p,h.appendChild(y));let L=i.loadingAnimation??Br.loadingAnimation,I=r.activeTextTemplate,H=r.completeTextTemplate,B=g?I:H,V=A instanceof HTMLElement,oe=(T,_)=>{y.textContent="";let P=o.name?.trim()||"tool",J=Td(T,P),U=0;for(let ue of J){let fe=ue.styles.length>0?(()=>{let me=x("span",ue.styles.map(He=>`persona-tool-text-${He}`).join(" "));return y.appendChild(me),me})():y;if(ue.isDuration&&g)fe.appendChild(C());else{let me=ue.isDuration?Pl(o):ue.text;_?U=Va(fe,me,U):fe.appendChild(document.createTextNode(me))}}};if(!V)if(g&&L!=="none"){let T=r.loadingAnimationDuration??2e3;if(y.setAttribute("data-preserve-animation","true"),L==="pulse")y.classList.add("persona-tool-loading-pulse"),y.style.setProperty("--persona-tool-anim-duration",`${T}ms`),B&&oe(B,!1);else if(y.classList.add(`persona-tool-loading-${L}`),y.style.setProperty("--persona-tool-anim-duration",`${T}ms`),L==="shimmer-color"&&(r.loadingAnimationColor&&y.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&y.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),B)oe(B,!0);else{let _=y.textContent||p;y.textContent="",Va(y,_,0)}}else B&&oe(B,!1);let W=BA(r,Ts(t,"tool")==="row"),j=La(f,h,{expandable:l,expanded:c,iconColor:W,metaGap:!0}),X=Ep({bubble:s,previewKind:"tool",expanded:c,isActive:g,previewText:d,activePreview:i.activePreview,activeMinHeight:i.activeMinHeight,renderPreview:()=>r.renderCollapsedPreview?.({message:e,toolCall:o,defaultPreview:d,isActive:g,config:t??{}})});if(!l)return s.append(f,X),$r(s,e,t,"tool");let M=x("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(M.style.display=c?"":"none",r.contentBackgroundColor&&(M.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(M.style.color=r.contentTextColor),r.contentPaddingX&&(M.style.paddingLeft=r.contentPaddingX,M.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(M.style.paddingTop=r.contentPaddingY,M.style.paddingBottom=r.contentPaddingY),t.future?.v5Defaults===!0)OA(M,e,t);else{if(o.name){let T=x("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?T.style.color=r.contentTextColor:r.headerTextColor&&(T.style.color=r.headerTextColor),T.textContent=o.name,M.appendChild(T)}if(o.args!==void 0){let T=x("div","persona-space-y-1"),_=x("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(_.style.color=r.labelTextColor),_.textContent="Arguments";let P=x("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");P.style.fontSize="0.75rem",P.style.lineHeight="1rem",ih(P,r),P.textContent=ya(o.args),T.append(_,P),M.appendChild(T)}if(o.chunks&&o.chunks.length){let T=x("div","persona-space-y-1"),_=x("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(_.style.color=r.labelTextColor),_.textContent="Activity";let P=x("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");P.style.fontSize="0.75rem",P.style.lineHeight="1rem",ih(P,r),P.textContent=o.chunks.join(""),T.append(_,P),M.appendChild(T)}if(o.success===!1&&M.appendChild(Q("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 T=x("div","persona-space-y-1"),_=x("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(_.style.color=r.labelTextColor),_.textContent="Result";let P=x("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");P.style.fontSize="0.75rem",P.style.lineHeight="1rem",ih(P,r),P.textContent=ya(o.result),T.append(_,P),M.appendChild(T)}if(o.status==="complete"&&typeof o.duration=="number"){let T=x("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(T.style.color=r.contentTextColor),T.textContent=`Duration: ${o.duration}ms`,M.appendChild(T)}}return Mp({expanded:c,header:f,toggleIcon:j,content:M,collapsedPreview:X,iconColor:W}),s.append(f,X,M),$r(s,e,t,"tool")};Rl();Ca();Cs();dn();var{setLoader:ZN,load:vL,provide:e1,getSync:CL}=lt({fallbackImport:()=>import("@runtypelabs/persona/approval-ui")});var DA=vL;var NA=CL;pi();dn();var{setLoader:o1,load:wL}=lt({fallbackImport:()=>import("@runtypelabs/persona/event-stream-view")});var ch=wL;dn();var dh=class{constructor(){this.components=new Map;this.#e=new Map}#e;register(t,n,o){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n),o?this.#e.set(t,o):this.#e.delete(t)}unregister(t){this.components.delete(t),this.#e.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getOptions(t){return this.#e.get(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.#e.clear()}registerAll(t){Object.entries(t).forEach(([n,o])=>{this.register(n,o)})}},Fo=new dh;tf();var ph=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:d1,load:SL,provide:p1,getSync:AL}=lt({fallbackImport:()=>import("@runtypelabs/persona/artifacts-ui")}),ja=null,au=new Set,FA=e=>{if(ja)return ja;ja=e,e.initArtifactsUi({componentRegistry:Fo});for(let o of ph)Fo.has(o)||Fo.register(o,o==="PersonaArtifactCard"?e.PersonaArtifactCard:e.PersonaArtifactInline,{bubbleChrome:!1});let t=nr();t?e.__provideMarkdownParsers(t):ua(()=>{let o=nr();o&&e.__provideMarkdownParsers(o)}),e.__setIconsExtraLoader(()=>Cd());let n=[...au];au.clear();for(let o of n)try{o()}catch{}return e};var lu=()=>SL().then(FA);var qr=()=>{if(ja)return ja;let e=AL();return e?FA(e):null},uh=e=>ja?()=>{}:(au.add(e),()=>{au.delete(e)});function $n(e){return e?.features?.artifacts?.enabled===!0}function $A(e,t){if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!$n(t))return;let n=t.features?.artifacts?.layout,o=n?.paneBorder?.trim(),r=n?.paneBorderLeft?.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):r&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",r))}function xL(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}var UA=["panel","seamless","detached"];function gh(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&UA.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function fh(e){return!e||!$n(e)?!1:gh(e)==="detached"}function dc(e,t){if(!$n(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-drawer-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),xL(e),$A(e,t);return}let n=t.features?.artifacts?.layout,o=gh(t)==="detached"?"var(--persona-panel-inset)":"0";e.style.setProperty("--persona-artifact-split-gap",n?.splitGap??o),e.style.setProperty("--persona-artifact-pane-width",n?.paneWidth??"40%"),e.style.setProperty("--persona-artifact-pane-max-width",n?.paneMaxWidth??"28rem"),n?.drawerWidth?e.style.setProperty("--persona-artifact-drawer-width",n.drawerWidth):e.style.removeProperty("--persona-artifact-drawer-width"),n?.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=n?.paneBackground?.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let s=n?.panePadding?.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let i=[[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 i){let p=l?.trim();p?e.style.setProperty(c,p):e.style.removeProperty(c)}$A(e,t)}function pc(e,t){for(let l of UA)e.classList.remove(`persona-artifact-appearance-${l}`);if(e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-chat-shadow"),!$n(t))return;let n=t.features?.artifacts?.layout,o=gh(t);e.classList.add(`persona-artifact-appearance-${o}`);let r=n?.paneBorderRadius?.trim();r&&e.style.setProperty("--persona-artifact-pane-radius",r);let s=n?.paneShadow?.trim();s&&e.style.setProperty("--persona-artifact-pane-shadow",s);let i=n?.chatShadow?.trim();i&&e.style.setProperty("--persona-artifact-chat-shadow",i)}function VA(e,t){return!t||!$n(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}ha();ha();var EL=new Set(["__proto__","prototype","constructor"]),ML=new Set(["collapsed","card","panel","inline"]),jA=new Set(["markdown","component"]),TL=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,Ii=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),du=e=>!EL.has(e),mh=e=>typeof e=="string"&&ML.has(e),Ri=e=>Object.keys(e).length>0;function ar(e,t,n,o){e.push({path:t,code:n,message:o})}var PL="Ignored because this key is not part of the persisted preference schema.",cu="Ignored an unsupported value.",kL="Expected collapsed, panel, or inline.",LL='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',qA={kind:"mode",message:cu},qa={kind:"string",message:"Expected a CSS length string."},zr={kind:"boolean"},HL={paneWidth:qa,paneMaxWidth:qa,paneMinWidth:qa,expandedPanelWidth:qa,resizableMinWidth:qa,resizableMaxWidth:qa,expandLauncherPanelWhenOpen:zr,resizable:zr},IL={kind:"object",message:"Expected a preference object.",children:{showToolCalls:zr,showReasoning:zr,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:cu},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:cu},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:cu},expandable:zr,grouped:zr}},reasoningDisplay:{kind:"object",children:{expandable:zr,activePreview:zr}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:qA,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:qA,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:jA,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:jA}}},filePreview:{kind:"object",children:{enabled:zr}},layout:{kind:"object",children:HL}}}}};function zA(e,t,n,o){if(e!==void 0)switch(t.kind){case"boolean":return typeof e=="boolean"?e:ar(o,n,"invalid_type","Expected a boolean.");case"string":return typeof e=="string"?e:ar(o,n,"invalid_type",t.message);case"enum":return typeof e=="string"&&t.values.has(e)?e:ar(o,n,"invalid_value",t.message);case"mode":return mh(e)?Yn(e):ar(o,n,"invalid_value",t.message);case"modeMap":{if(!Ii(e))return ar(o,n,"invalid_type","Expected an object.");let r=t.keys==="mediaType"?void 0:t.keys,s={};for(let[i,l]of Object.entries(e)){let c=r?i:vs(i);du(i)&&(r?r.has(i):TL.test(c))?mh(l)?s[c]=Yn(l):ar(o,`${n}.${i}`,"invalid_value",kL):ar(o,`${n}.${i}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":LL)}return Ri(s)?s:void 0}case"object":{if(t.bareMode&&mh(e))return Yn(e);if(!Ii(e))return ar(o,n,"invalid_type",t.message??"Expected an object.");let r=Object.keys(t.children),s=l=>n?`${n}.${l}`:l;for(let l of Object.keys(e))(!du(l)||!r.includes(l))&&ar(o,s(l),"unknown_key",PL);let i={};for(let l of r){let c=t.children[l],p=zA(e[l],c,s(l),o);if(c.deprecated&&e[l]!==void 0&&ar(o,s(l),"deprecated_key",c.deprecated),p===void 0)continue;let d=c.alias??l,g=i[d];i[d]=Ii(g)&&Ii(p)?{...g,...p}:p}return Ri(i)?i:void 0}}}function hh(e){let t=[];return{preferences:(e===null?void 0:zA(e,IL,"",t))??{},issues:t}}function za(e){if(Array.isArray(e))return e.map(za);if(!Ii(e))return e;let t={};for(let[n,o]of Object.entries(e))du(n)&&o!==void 0&&(t[n]=za(o));return t}function KA(e,t){let n=za(e);for(let[o,r]of Object.entries(t)){if(!du(o)||r===void 0)continue;let s=n[o];n[o]=Ii(s)&&Ii(r)?KA(s,r):za(r)}return n}function RL(e){let t={},n;for(let r of e){let s=hh(r).preferences;n=GA(n,s.artifacts?.display),t=KA(t,s)}let o=t;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function WL(e,t){if(t===void 0)return e===void 0?void 0:za(e);if(typeof t=="string")return t;let n=typeof e=="string"?{default:e}:e??{},o=t.default??n.default,r={...n.byMediaType,...t.byMediaType},s={...o?{default:o}:{},...Ri(r)?{byMediaType:r}:{}};return Ri(s)?s:void 0}function GA(e,t){if(t===void 0)return e===void 0?void 0:za(e);if(typeof t=="string")return t;let n=typeof e=="string"?{default:e}:e??{},o=t.default??n.default,r={...n.byType,...n.byKind,...t.byType,...t.byKind},s=WL(n.files,t.files),i={...o?{default:o}:{},...Ri(r)?{byKind:r}:{},...s!==void 0?{files:s}:{}};return Ri(i)?i:void 0}function yh(e={},t){let n=RL(t),o={...e};if(n.showToolCalls!==void 0&&(o.showToolCalls=n.showToolCalls),n.showReasoning!==void 0&&(o.showReasoning=n.showReasoning),n.toolCallDisplay&&(o.toolCallDisplay={...e.toolCallDisplay,...n.toolCallDisplay}),n.reasoningDisplay&&(o.reasoningDisplay={...e.reasoningDisplay,...n.reasoningDisplay}),n.artifacts){let r=e.artifacts??{},s={...r};if(n.artifacts.display!==void 0){let i=GA(r.display,n.artifacts.display);i!==void 0&&(s.display=i)}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 uc(e){let t=e.preferences;return!t||!Ri(t)?e:{...e,features:yh(e.features??{},[t])}}function OL(e,t){if(!e?.trim())return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function _L(e){if(!e?.trim())return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function BL(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function DL(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function bh(e,t){let o=(t.getComputedStyle(e).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 YA(e,t,n,o,r,s,i=200){let l=OL(r,200),c=DL(t,n,o,i);c=Math.max(l,c);let p=_L(s);return p!==null&&(c=Math.min(c,p)),BL(e,l,c)}dn();var{setLoader:b1,load:NL,provide:v1,getSync:FL}=lt({fallbackImport:()=>import("@runtypelabs/persona/forms-ui")});var XA=NL;var QA=FL;var vh=class{#e=new Map;register(t){this.#e.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.#e.set(t.id,t),t.onRegister?.()}unregister(t){let n=this.#e.get(t);n&&(n.onUnregister?.(),this.#e.delete(t))}getAll(){return Array.from(this.#e.values()).sort((t,n)=>(n.priority??0)-(t.priority??0))}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let o=new Set(t.map(s=>s.id));return[...n.filter(s=>!o.has(s.id)),...t].sort((s,i)=>(i.priority??0)-(s.priority??0))}clear(){this.#e.forEach(t=>t.onUnregister?.()),this.#e.clear()}},gc=new vh;So();So();Ea();Rf();var JA=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),$L=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),ZA=(e,t,n)=>{if(!JA(e)||!JA(t)||$L.has(n))return t;let o={...e};for(let r of Object.keys(t)){if(t[r]===void 0){delete o[r];continue}let s=n?`${n}.${r}`:r;o[r]=ZA(e[r],t[r],s)}return o};function pu(e,t){let n=zd(bi),o=bC(e,t,n),r=Hf(vC(ZA(e,t,""),n,o),o);return Of(Ma(r),wC(e,t))}Ea();var ex=()=>{let e=new Map,t=(r,s)=>(e.has(r)||e.set(r,new Set),e.get(r).add(s),()=>n(r,s)),n=(r,s)=>{e.get(r)?.delete(s)};return{on:t,off:n,emit:(r,s)=>{e.get(r)?.forEach(i=>{try{i(s)}catch(l){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",l)}})}}};var UL=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},VL=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let o=0;for(let r=n;r<t.length;r+=1){let s=t[r];if(s==="{"&&(o+=1),s==="}"&&(o-=1,o===0))return t.slice(n,r+1)}return null},fc=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=UL(e),n=VL(t);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}},Ch=e=>typeof e=="string"?e:e==null?"":String(e),Wi={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Ch(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let n=e.payload,o=Ch(n.element);if(o&&t.document?.querySelector){let r=t.document.querySelector(o);r?setTimeout(()=>{r.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:Ch(n.text)}}},tx=e=>Array.isArray(e)?e.map(t=>String(t)):[],mc=e=>{let t=new Set(tx(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(tx(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(t);e.updateSessionMetadata(i=>({...i,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let i=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!i&&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=i?e.parsers.reduce((p,d)=>p||d?.({text:i,message:s.message})||null,null):null;if(!l)return null;t.add(s.message.id),o();let c={action:l,message:s.message};e.emit("action:detected",c);for(let p of e.handlers)if(p)try{let d=()=>{e.emit("action:resubmit",c)},g=p(l,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:d});if(!g)continue;if(g.handled){let f=g.persistMessage!==!1;return{text:g.displayText!==void 0?g.displayText:"",persist:f,resubmit:g.resubmit}}}catch(d){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",d)}return{text:"",persist:!0}},syncFromMetadata:n}};var jL=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},qL=e=>e.map(t=>({...t,streaming:!1})),zL=e=>e.map(t=>({...t,status:"complete"})),uu=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?jL(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?qL(n.messages):void 0,artifacts:n.artifacts?zL(n.artifacts):void 0};o.setItem(e,JSON.stringify(r))}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(o){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};var KL=e=>{let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")},nx=async e=>{let t=globalThis.crypto?.subtle;if(t)try{let n=await t.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(n)).map(o=>o.toString(16).padStart(2,"0")).join("")}catch{}return KL(e)},GL=async(e,t)=>{let n=await nx(e);return{storageKey:`${t}visitor:${n}`,leaseKey:`${t}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await nx(`${e}\0${t}`)}`}};var ox=(e,t,n)=>{let o="",r="",s="",i=!1,l=!1,c=0,p=null,d=null,g=new Set,f=()=>{if(n||i)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return i=!0,null}},h=()=>{let W=f();if(!W)return p;try{return W.getItem(o)}catch{return i=!0,p}},y=(W,j)=>{if(l||W===p)return;let X=p;p=W,c+=1;let M={previousToken:X,token:W,source:j,revision:c};for(let T of g)T(M)},v=W=>{l||W.key!==null&&W.key!==o||y(W.key===null?null:W.newValue??null,"external")},C=(async()=>{let W=await GL(e,t);o=W.storageKey,r=W.leaseKey,s=W.lockName,p=h(),!n&&typeof window<"u"&&window.addEventListener("storage",v)})(),A=W=>new Promise(j=>setTimeout(j,W)),L=()=>{let W=f();if(!W)return null;try{let j=W.getItem(r);if(!j)return null;let X=JSON.parse(j);return typeof X?.expiresAt=="number"&&typeof X?.ownerNonce=="string"?X:null}catch{return null}},I=W=>{let j=f();if(j)try{L()?.ownerNonce===W&&j.removeItem(r)}catch{}},H=new Set,B=W=>l?Promise.reject(new Error("Visitor store destroyed before its first init could start")):W(),V=W=>new Promise(j=>{let X=setTimeout(M,W);function M(){clearTimeout(X),H.delete(M),window.removeEventListener("storage",T),j()}function T(_){(_.key===null||_.key===r)&&M()}H.add(M),window.addEventListener("storage",T)}),oe=async W=>{let j=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,X=Date.now()+15e3;for(;!l&&Date.now()<X;){let M=f();if(!M)break;let T=Date.now(),_=L();if(_&&_.expiresAt>T&&_.ownerNonce!==j){await V(Math.min(_.expiresAt-T,500));continue}try{M.setItem(r,JSON.stringify({ownerNonce:j,expiresAt:T+1e4}))}catch{i=!0;break}if(await A(20+Math.random()*40),L()?.ownerNonce!==j){await V(500);continue}d=j;try{return await B(W)}finally{d=null,I(j)}}return B(W)};return{ready:C,async get(){return await C,y(h(),"external"),p},async set(W){await C;let j=f();if(j)try{j.setItem(o,W)}catch{i=!0}y(W,"local")},async clear(){await C;let W=f();if(W)try{W.removeItem(o)}catch{i=!0}y(null,"local")},revision(){return c},subscribe(W){return g.add(W),()=>{g.delete(W)}},async withFirstInitLock(W){await C;let j=globalThis.navigator?.locks;return j?.request?j.request(s,()=>B(W)):f()?oe(W):B(W)},matches(W,j,X){return W===e&&j===t&&X===n},destroy(){l=!0,g.clear(),typeof window<"u"&&window.removeEventListener("storage",v),d&&I(d);for(let W of[...H])W()}}};dn();var{setLoader:H1,load:YL}=lt({fallbackImport:()=>import("@runtypelabs/persona/history-view")});var rx=YL;var XL=null;function sx(){return XL}var Ka=require("partial-json");function QL(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function JL(e,t){if(!QL(e))return null;let n=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:n,raw:t}}function gu(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e;try{let r=(0,Ka.parse)(n,Ka.STR|Ka.OBJ),s=JL(r,n);s&&(e=s)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function ix(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}Ze();function fu(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=Fo.get(e.component);if(!s){if(ph.includes(e.component)){lu().catch(()=>{});let l=x("div","persona-w-full");return l.setAttribute("data-persona-artifact-pending","true"),l}return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null}let i={message:o,config:n,updateProps:l=>{r&&r(l)}};try{return s(e.props,i)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,l),null}}function ax(){let e=gu();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function lx(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let t=e.content.trim();if(t.startsWith("{")||t.startsWith("["))return e.content}return null}function hc(e){let t=lx(e);if(!t)return!1;try{let n=JSON.parse(t);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function mu(e){let t=lx(e);if(!t)return null;try{let n=JSON.parse(t);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:t}}}catch{}return null}var ZL=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function hu(e){let{onSubmit:t,onDismiss:n,title:o="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:i="Submit",skipText:l="Skip",showComment:c=!0,ratingLabels:p=ZL}=e,d=document.createElement("div");d.className="persona-feedback-container persona-feedback-csat",d.setAttribute("role","dialog"),d.setAttribute("aria-label","Customer satisfaction feedback");let g=null,f=document.createElement("div");f.className="persona-feedback-content";let h=document.createElement("div");h.className="persona-feedback-header";let y=document.createElement("h3");y.className="persona-feedback-title",y.textContent=o,h.appendChild(y);let v=document.createElement("p");v.className="persona-feedback-subtitle",v.textContent=r,h.appendChild(v),f.appendChild(h);let C=document.createElement("div");C.className="persona-feedback-rating persona-feedback-rating-csat",C.setAttribute("role","radiogroup"),C.setAttribute("aria-label","Satisfaction rating from 1 to 5");let A=[];for(let V=1;V<=5;V++){let oe=document.createElement("button");oe.type="button",oe.className="persona-feedback-rating-btn persona-feedback-star-btn",oe.setAttribute("role","radio"),oe.setAttribute("aria-checked","false"),oe.setAttribute("aria-label",`${V} star${V>1?"s":""}: ${p[V-1]}`),oe.title=p[V-1],oe.dataset.rating=String(V),oe.innerHTML=`
|
|
43
43
|
<svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
44
44
|
<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>
|
|
45
45
|
</svg>
|
|
46
|
-
`,oe.addEventListener("click",()=>{g=V,A.forEach((W,j)=>{let X=j<V;W.classList.toggle("selected",X),W.setAttribute("aria-checked",j===V-1?"true":"false")})}),A.push(oe),C.appendChild(oe)}f.appendChild(C);let L=null;if(c){let V=document.createElement("div");V.className="persona-feedback-comment-container",L=document.createElement("textarea"),L.className="persona-feedback-comment",L.placeholder=s,L.rows=3,L.setAttribute("aria-label","Additional comments"),V.appendChild(L),f.appendChild(V)}let I=document.createElement("div");I.className="persona-feedback-actions";let H=document.createElement("button");H.type="button",H.className="persona-feedback-btn persona-feedback-btn-skip",H.textContent=l,H.addEventListener("click",()=>{n?.(),d.remove()});let _=document.createElement("button");return _.type="button",_.className="persona-feedback-btn persona-feedback-btn-submit",_.textContent=i,_.addEventListener("click",async()=>{if(g===null){C.classList.add("persona-feedback-shake"),setTimeout(()=>C.classList.remove("persona-feedback-shake"),500);return}_.disabled=!0,_.textContent="Submitting...";try{let V=L?.value.trim()||void 0;await t(g,V),d.remove()}catch(V){_.disabled=!1,_.textContent=i,console.error("[CSAT Feedback] Failed to submit:",V)}}),I.appendChild(H),I.appendChild(_),f.appendChild(I),d.appendChild(f),d}function mu(e){let{onSubmit:t,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:i="Submit",skipText:l="Skip",showComment:c=!0,lowLabel:p="Not likely",highLabel:d="Very likely"}=e,g=document.createElement("div");g.className="persona-feedback-container persona-feedback-nps",g.setAttribute("role","dialog"),g.setAttribute("aria-label","Net Promoter Score feedback");let f=null,h=document.createElement("div");h.className="persona-feedback-content";let y=document.createElement("div");y.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=o,y.appendChild(v);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=r,y.appendChild(C),h.appendChild(y);let A=document.createElement("div");A.className="persona-feedback-rating persona-feedback-rating-nps",A.setAttribute("role","radiogroup"),A.setAttribute("aria-label","Likelihood rating from 0 to 10");let L=document.createElement("div");L.className="persona-feedback-labels";let I=document.createElement("span");I.className="persona-feedback-label-low",I.textContent=p;let H=document.createElement("span");H.className="persona-feedback-label-high",H.textContent=d,L.appendChild(I),L.appendChild(H);let _=document.createElement("div");_.className="persona-feedback-numbers";let V=[];for(let E=0;E<=10;E++){let T=document.createElement("button");T.type="button",T.className="persona-feedback-rating-btn persona-feedback-number-btn",T.setAttribute("role","radio"),T.setAttribute("aria-checked","false"),T.setAttribute("aria-label",`Rating ${E} out of 10`),T.textContent=String(E),T.dataset.rating=String(E),E<=6?T.classList.add("persona-feedback-detractor"):E<=8?T.classList.add("persona-feedback-passive"):T.classList.add("persona-feedback-promoter"),T.addEventListener("click",()=>{f=E,V.forEach((B,P)=>{B.classList.toggle("selected",P===E),B.setAttribute("aria-checked",P===E?"true":"false")})}),V.push(T),_.appendChild(T)}A.appendChild(L),A.appendChild(_),h.appendChild(A);let oe=null;if(c){let E=document.createElement("div");E.className="persona-feedback-comment-container",oe=document.createElement("textarea"),oe.className="persona-feedback-comment",oe.placeholder=s,oe.rows=3,oe.setAttribute("aria-label","Additional comments"),E.appendChild(oe),h.appendChild(E)}let W=document.createElement("div");W.className="persona-feedback-actions";let j=document.createElement("button");j.type="button",j.className="persona-feedback-btn persona-feedback-btn-skip",j.textContent=l,j.addEventListener("click",()=>{n?.(),g.remove()});let X=document.createElement("button");return X.type="button",X.className="persona-feedback-btn persona-feedback-btn-submit",X.textContent=i,X.addEventListener("click",async()=>{if(f===null){_.classList.add("persona-feedback-shake"),setTimeout(()=>_.classList.remove("persona-feedback-shake"),500);return}X.disabled=!0,X.textContent="Submitting...";try{let E=oe?.value.trim()||void 0;await t(f,E),g.remove()}catch(E){X.disabled=!1,X.textContent=i,console.error("[NPS Feedback] Failed to submit:",E)}}),W.appendChild(j),W.appendChild(X),h.appendChild(W),g.appendChild(h),g}var Ga="persona-chat-history",QL=30*1e3,JL=641,Ya="data-persona-composer-reason",ZL={"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 eH(e){if(!e)return[];let t=[],n=Array.from(e.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){t.push(r);continue}let s=ZL[r.type]??"png";t.push(new File([r],`clipboard-image-${Date.now()}.${s}`,{type:r.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let o of Array.from(e.files??[]))o.type.startsWith("image/")&&t.push(o);return t}function hu(e){if(!e)return!1;let t=e.types;return t?typeof t.contains=="function"?t.contains("Files"):Array.from(t).includes("Files"):!1}function tH(e){return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:e.storage??"session",keyPrefix:e.keyPrefix??"persona-",persist:{openState:e.persist?.openState??!0,voiceState:e.persist?.voiceState??!0,focusInput:e.persist?.focusInput??!0},clearOnChatClear:e.clearOnChatClear??!0}:null}function nH(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var bh=e=>!e||typeof e!="object"?{}:{...e},sx=e=>e.map(t=>({...t,streaming:!1})),ix=(e,t,n)=>{let o=e?.markdown?jl(e.markdown):null,r=Pp(e?.sanitize);e?.postprocessMessage&&r&&e?.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,i=l=>{let c=l.text??"",p=l.message.rawContent??null;if(t){let f=t.process({text:c,raw:p??c,message:l.message,streaming:l.streaming});f!==null&&(c=f.text,f.persist||(l.message.__skipPersist=!0),f.resubmit&&!l.streaming&&n&&n())}let d=nr()!==null,g;if(e?.postprocessMessage){let f=e.postprocessMessage({...l,text:c,raw:p??l.text??""});g=r?r(f):f}else if(o){let f=l.streaming?fw(c):c,h=o(f);g=r&&d?r(h):h}else g=Ur(c);return g};return l=>{try{return i(l)}catch(c){return s||(s=!0,console.error("[Persona] markdown rendering failed; falling back to plain text:",c)),Ur(l.text??"")}}};function ax(e){let t=x("div","persona-attachment-drop-overlay");e?.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),e?.backdropBlur!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e?.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e?.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e?.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e?.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e?.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=e?.iconName??"upload",o=e?.iconSize??"48px",r=e?.iconColor??"rgba(59, 130, 246, 0.6)",s=e?.iconStrokeWidth??.5,i=ge(n,o,r,s);if(i&&t.appendChild(i),e?.label){let l=x("span","persona-drop-overlay-label");l.textContent=e.label,t.appendChild(l)}return t}var oH=(e,t)=>{let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];n[o]=s?{...s,...r}:r}return n},rH=e=>e.reduce((t,n)=>({blocks:[...t.blocks,...n.blocks],contentParts:[...t.contentParts,...n.contentParts],context:oH(t.context,n.context)}),{blocks:[],contentParts:[],context:{}}),yu=(e,t,n)=>{if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let o=Ea(t),r=new Set,s=new Set,i=nw((a,u)=>{En.delete(a);let m=Array.from(Te.querySelectorAll("[data-message-id]")).find(b=>b.dataset.messageId===a);m&&(u==="tool"?rh(a,m,r,o):eh(a,m,s))}),l=new Map,c=()=>{lC({delayMs:o.tooltip?.delayMs??200,skipDelayMs:o.tooltip?.skipDelayMs??300})};c();let p=o.features;o=uc(o);let d=gc.getForInstance(o.plugins),g=YC(e),f=[],h=!1,y=kA(()=>o),v=null,C=null,A=null,L=!1,I=null,H=a=>{v=a,a.initApprovalUi({webMcpToolTitle:ma});let u=a.createBuiltInApprovalPlugin(l);C=u.plugin,A=u.teardown},_=()=>{if(v)return v;let a=OA();return a?(H(a),a):(WA().then(u=>{L||v||(H(u),I?.())}).catch(()=>{}),null)},V=!1,oe=!1,W=null,j=(a,u,m,b)=>{if(!a.querySelector("[data-tv-form]"))return;let w=KA();if(w){w.enhanceWithForms(a,u,m,b);return}zA().then(()=>{V||oe||!W||(oe=!0,W())}).catch(()=>{})};o.components&&Fo.registerAll(o.components);let X=XA(),T=o.persistState===!1?null:o.storageAdapter??du(),B=!!o.clientToken&&typeof o.reconnectStream!="function",P={},J=null,U,ue=new Promise(a=>{U=a}),fe=()=>{},me=new Promise(a=>{fe=a}),He,Ee=!1,Ie=a=>{if(o.onStateLoaded)try{let u=o.onStateLoaded(a);if(u&&typeof u=="object"&&"state"in u){let{state:m,open:b}=u;return b&&(Ee=!0),m}return u}catch(u){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",u)}return a};if(T?.load)try{let a=T.load();if(a&&typeof a.then=="function")J=a.then(u=>Ie(u??{messages:[],metadata:{}}));else{let m=Ie(a??{messages:[],metadata:{}});m.metadata&&(P=bh(m.metadata)),m.messages?.length&&(o={...o,initialMessages:m.messages}),m.artifacts?.length&&(o={...o,initialArtifacts:m.artifacts,initialSelectedArtifactId:m.selectedArtifactId??null}),He=m.draft}}catch(a){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",a)}else if(o.onStateLoaded)try{let a=Ie({messages:[],metadata:{}});a.messages?.length&&(o={...o,initialMessages:a.messages})}catch(a){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",a)}J||U();let yt=()=>P,qe=a=>{P=a({...P})??{},Ji()},Oe=o.actionParsers&&o.actionParsers.length?o.actionParsers:[fc],$=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Wi.message,Wi.messageAndClick],Be=mc({parsers:Oe,handlers:$,getSessionMetadata:yt,updateSessionMetadata:qe,emit:X.emit,documentRef:typeof document<"u"?document:null});Be.syncFromMetadata();let ye=o.launcher?.enabled??!0,ut=o.launcher?.autoExpand??!1,Zt=o.autoFocusInput??!1,xt=ut,xe=ye,Wt=o.layout?.header?.layout,vt=!1,Le=()=>Rs(o),Ye=()=>ye||Le(),D=Le()?!1:ye?ut:!0,S=!1,F=null,z=()=>{S=!0,F&&clearTimeout(F),F=setTimeout(()=>{S&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),S=!1)},1e4)},K=ix(o,Be,z),te=o.features?.showReasoning??!0,ve=o.features?.showToolCalls??!0,Ce=o.features?.showEventStreamToggle??!1,Me=o.features?.scrollToBottom??{},ot=o.features?.scrollBehavior??{},Ct=()=>(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-",Xe=`${Ct()}event-stream`,pn=null,xo=o.features?.eventStream?.maxEvents??2e3,ft=null,bt=null,Ft=null,Bi=!1,rn=null,Sn=!1,ao=null,_i=0,Di=(a,u)=>{ft?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:a,timestamp:Date.now(),payload:JSON.stringify(u)})},Qa=(a,u)=>{bt?.processEvent(a,u),ft?Di(a,u):Ft&&(Ft.length>=xo&&Ft.shift(),Ft.push({type:a,payload:u}))},cr=()=>{ft||!Ce||(Ft??=[],ih().then(a=>{if(Bi||ft||!Ce)return;pn=new a.EventStreamStore(Xe),ft=new a.EventStreamBuffer(xo,pn),bt=bt??new a.ThroughputTracker,pn.open().then(()=>ft?.restore()).catch(m=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",m)});let u=Ft??[];Ft=null;for(let m of u)bt?.processEvent(m.type,m.payload),Di(m.type,m.payload)}).catch(()=>{}))};Ce&&cr();let un=!1,Un=null,dr=()=>{},Vn=()=>{},pr=()=>{},Uo=()=>{},Yr=()=>{},Cc=()=>Sn||un&&Un==="panel",eo={onCopy:a=>{X.emit("message:copy",a),R?.isClientTokenMode()&&R.submitMessageFeedback(a.id,"copy").catch(u=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",u)}),o.messageActions?.onCopy?.(a)},onFeedback:a=>{X.emit("message:feedback",a),R?.isClientTokenMode()&&R.submitMessageFeedback(a.messageId,a.type).catch(u=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",u)}),o.messageActions?.onFeedback?.(a)}},Dh=o.statusIndicator??{},ur=(a,u=o.statusIndicator??{})=>a==="idle"?u.idleText??Yt.idle:a==="connecting"?u.connectingText??Yt.connecting:a==="connected"?u.connectedText??Yt.connected:a==="error"?u.errorText??Yt.error:a==="paused"?u.pausedText??Yt.paused:a==="resuming"?u.resumingText??Yt.resuming:Yt[a];function Bs(a,u,m,b){if(!Le()&&(m.mode==="transient"||a.classList.contains("persona-mb-2"))&&(xf(a,An,m),hi(a,m,b)),!a.hasAttribute(Ya))if(b==="idle"&&m.idleLink){a.textContent="";let w=document.createElement("a");w.href=m.idleLink,w.target="_blank",w.rel="noopener noreferrer",w.textContent=u,w.style.color="inherit",w.style.textDecoration="none",a.appendChild(w)}else a.textContent=u}let Ln=PA({config:o,showClose:Ye()}),{wrapper:Qe,panel:Ae,pillRoot:Xt}=Ln.shell,Ze=Ln.panelElements,{container:we,body:ae,messagesWrapper:Te,starterSuggestions:gr,transcriptSuggestions:Xr,suggestions:lo,textarea:ce,sendButton:Pe,composerForm:An,statusText:rt,welcomeHost:en,welcomeIconHolder:wc,greetingHost:In,introKicker:Sc,introTitle:Wu,introSubtitle:Ni,closeButton:ze,iconHolder:Ht,headerTitle:Vo,headerSubtitle:jo,header:mt,footer:Ke,actionsRow:Fi}=Ze,xn=Ze.leftActions,_s=Ze.rightActions,Rn=Ze.sendButtonWrapper,Ac=Ze.setSendButtonMode,he=Ze.micButton,gn=Ze.micButtonWrapper,It=Ze.attachmentButton,sn=Ze.attachmentButtonWrapper,Mt=Ze.attachmentInput,fn=Ze.attachmentPreviewsContainer;we.classList.add("persona-relative"),ae.classList.add("persona-relative");let xc=12,Qr=()=>Me.label??"",Ou=()=>Me.iconName??"arrow-down",Bu=()=>Me.enabled!==!1,Mn=()=>ot.mode??"anchor-top",Mo=()=>Mn()==="follow"||Mn()==="anchor-top"&&ll,Ds=()=>ot.anchorTopOffset??16,Mc=()=>ot.restorePosition??"bottom",Ja=()=>ot.pauseOnInteraction===!0,Za=()=>ot.showActivityWhilePinned!==!1,$i=()=>ot.announce===!0,Ns=()=>ot.scrollbar??"on-scroll",Vt=x("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");Vt.type="button",Vt.style.display="none",Vt.setAttribute("data-persona-scroll-to-bottom","true");let Fs=x("span","persona-flex persona-items-center"),el=x("span",""),tn=x("span","");tn.setAttribute("data-persona-scroll-to-bottom-count",""),tn.style.display="none",Vt.append(Fs,el,tn),we.appendChild(Vt);let Qt=x("div","persona-stream-anchor-spacer");Qt.setAttribute("aria-hidden","true"),Qt.setAttribute("data-persona-anchor-spacer",""),Qt.style.flexShrink="0",Qt.style.pointerEvents="none",Qt.style.height="0px",Qt.style.display="none",ae.appendChild(Qt);let Eo=x("div","persona-sr-only");Eo.setAttribute("aria-live","polite"),Eo.setAttribute("aria-atomic","true"),Eo.setAttribute("role","status"),Eo.setAttribute("data-persona-live-region",""),Object.assign(Eo.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"}),we.appendChild(Eo);let Jr=null,fr=null,$s=a=>{!$i()||!a||(fr=a,Jr===null&&(Jr=setTimeout(()=>{Jr=null,fr&&$i()&&(Eo.textContent=fr),fr=null},400)))},jn=()=>{let a=e.ownerDocument.defaultView??window;return(o.launcher?.mobileFullscreen??!0)&&a.innerWidth<=(o.launcher?.mobileBreakpoint??640)&&(ye||Lt(o))||o.launcher?.fullHeight===!0&&!o.launcher.sidebarMode&&!Lt(o)},M=()=>Ua(o,jn()),N="empty",ne=0,pe=()=>ne||parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,Re=()=>{let u=Ke.style.display==="none"?0:Ke.offsetHeight;Vt.style.bottom=`${u+pe()+xc}px`};Re();let $t=()=>{Ki||(Ke.style.marginBottom=ne>0?`${ne}px`:"")},Ot=()=>{let a=Mm(o,Le()),u=M();e.setAttribute("data-persona-welcome-fullscreen",String(jn())),e.setAttribute("data-persona-welcome-layout",u.layout??"top"),e.setAttribute("data-persona-welcome-layout-explicit",o.welcome?.layout??""),e.setAttribute("data-persona-welcome-anchor",u.anchor??"bottom");let b=Ke.style.display==="none"?0:Ke.offsetHeight,w=u.anchor==="center"&&N==="empty"?Ql(u.anchorComposerTop)??Ql("44%"):null,k=w!==null&&u.layout==="centered"&&o.welcome?.anchor===void 0&&o.welcome?.anchorComposerTop===void 0,q=k?getComputedStyle(ae):null,re=parseFloat(e.style.getPropertyValue("--persona-composer-overlay-height"))||0,Y=parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,ie=Math.max(0,(parseFloat(q?.paddingBottom??"")||0)-(a==="overlay"?re+Y:0)),le=k?ae.getBoundingClientRect().top-we.getBoundingClientRect().top:0,de=!k||en.hidden?0:(en.querySelector("[data-persona-welcome-plugin]")??en).offsetHeight,ke=w===null||Le()?0:k?Math.max(0,Math.round((we.clientHeight-le-de-ie-b)/2)):IS({columnHeight:we.clientHeight,footerHeight:b,fraction:w});e.style.setProperty("--persona-composer-overlay-height",`${b}px`),e.style.setProperty("--persona-composer-lift",`${a==="overlay"?ke:0}px`),ne=a==="block"?ke:0,$t(),Re()},Bt=()=>{let a=!!Qr();Vt.setAttribute("aria-label",Qr()||"Jump to latest"),Vt.title=Qr(),Vt.setAttribute("data-persona-scroll-to-bottom-has-label",a?"true":"false"),Fs.innerHTML="";let u=ge(Ou(),"14px","currentColor",2);u?(Fs.appendChild(u),Fs.style.display=""):Fs.style.display="none",el.textContent=Qr(),el.style.display=a?"":"none"};Bt();let je=null,at=null,be=Uw(),Ui=a=>{try{we.dispatchEvent(new CustomEvent("persona:composer:state",{detail:a,bubbles:!0,composed:!0}))}catch{}};be.subscribe(Ui);let co=()=>{be.setText(ce?.value??"")},mr=()=>{be.setMentionRefs(at?.getMentionRefs()??[])},nM=a=>({id:a.id,name:a.file.name,mimeType:a.file.type,size:a.file.size,status:a.status,progress:a.progress,error:a.error}),Nh=a=>{let u=Object.freeze(a.map(nM));be.setAttachments(u);try{o.attachments?.onChange?.(u)}catch(m){console.error("[AgentWidget] attachments.onChange failed:",m)}fg()};be.setSelectedModelId(o.composer?.selectedModelId);let tl=()=>o.composer?.modes??[],Vi=()=>rS(tl(),o.composer?.modeGroups);{let a=Bp(o.composer?.defaultActiveModeIds??[],tl());a.length&&be.setActiveModeIds(a)}function Fh(a){if(be.getState().selectedModelId!==a){be.setSelectedModelId(a),Zr?.repaint();try{o.composer?.onModelChange?.(a)}catch(u){console.error("[AgentWidget] composer.onModelChange failed:",u)}}}function Ec(a){be.setActiveModeIds(a),hr?.render(a,Vi()),ji.forEach(u=>u.repaint()),To?.resolve(),Zc(),Po()}function _u(a){Ec(sS(be.getState().activeModeIds,a,tl(),o.composer?.modeGroups))}let Zr=null,Du=null,hr=null,ji=new Map,es=null;function qo(a){be.setQuote(a),es?.render(be.getState().quote),Po(),Hy()}let $h=!1;function Nu(){let a=o.composer?.streamingSubmitBehavior??"block";return a!=="interrupt"?a:o.clientToken?"interrupt":(!$h&&o.debug===!0&&($h=!0,typeof console<"u"&&console.warn('[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".')),"block")}let ts=null;function qi(a){be.setPendingSubmission(a),ts?.render(be.getState().pendingSubmission),Po()}let oM=a=>{let u=ji.get(a);if(u)return u;let m=lS({groupId:a,getGroup:()=>o.composer?.modeGroups?.find(b=>b.id===a),getModes:()=>tl().filter(b=>b.groupId===a),getActiveIds:()=>be.getState().activeModeIds,onSelect:b=>_u(b)});return ji.set(a,m),m},rM=()=>{let a=[],u=be.getState().activeModeIds,m=new Set;if(tl().forEach((b,w)=>{if(Op(b.groupId,o.composer?.modeGroups)){let k=b.groupId;if(m.has(k))return;m.add(k);let q=oM(k);q.action.order=vm(w),q.action.label=o.composer?.modeGroups?.find(re=>re.id===k)?.label??k,a.push(q.action);return}a.push({id:nS(b.id),kind:"button",placement:"start",order:vm(w),presentation:b.presentation??"auto",label:b.label,shortLabel:b.shortLabel,iconName:b.iconName,pressed:u.includes(b.id),onSelect:()=>_u(b.id)})}),o.composer?.models?.length&&!d.some(b=>b.renderComposer)){let b=o.composer?.modelPicker?.presentation??"native";(!Zr||Du!==b)&&(Du=b,Zr=eS({getModels:()=>o.composer?.models??[],getSelectedModelId:()=>be.getState().selectedModelId,onSelect:w=>Fh(w),presentation:b,getSuffix:()=>o.composer?.modelPicker?.suffix})),a.push(Zr.action)}return a},Fu=null,Uh=d.find(a=>a.renderHeader);if(Uh?.renderHeader){let a=Uh.renderHeader({config:o,defaultRenderer:()=>{let u=jr({config:o,showClose:Ye()});return Ti(we,u,o),u.header},onClose:()=>Et(!1,"user")});if(a){let u=mt;u&&(u.replaceWith(a),mt=a,Ln.header.element=a)}}let Vh=()=>{rn&&(ae.style.display="none",Ke.parentNode?.insertBefore(rn.element,Ke),rn.update())},$u=()=>{if(!ft){cr();return}if(Sn=!0,rn?Vh():ih().then(u=>{rn||!Sn||!ft||(rn=u.createEventStreamView({buffer:ft,getFullHistory:()=>ft.getAllFromStore(),onClose:()=>zi(),config:o,plugins:d,getThroughput:()=>bt?.getMetric()??{status:"idle"},renderIconByName:ge}),Vh())}).catch(()=>{zi()}),ht){ht.style.boxShadow=`inset 0 0 0 1.5px ${Nn.actionIconColor}`;let u=o.features?.eventStream?.classNames?.toggleButtonActive;u&&u.split(/\s+/).forEach(m=>m&&ht.classList.add(m))}let a=()=>{if(!Sn)return;let u=Date.now();u-_i>=200&&(rn?.update(),_i=u),ao=requestAnimationFrame(a)};_i=0,ao=requestAnimationFrame(a),Tn(),X.emit("eventStream:opened",{timestamp:Date.now()})},zi=()=>{if(Sn){if(Sn=!1,rn&&rn.element.remove(),ae.style.display="",ht){ht.style.boxShadow="";let a=o.features?.eventStream?.classNames?.toggleButtonActive;a&&a.split(/\s+/).forEach(u=>u&&ht.classList.remove(u))}ao!==null&&(cancelAnimationFrame(ao),ao=null),Tn(),X.emit("eventStream:closed",{timestamp:Date.now()})}},ht=null;if(Ce){let a=o.features?.eventStream?.classNames,u="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"+(a?.toggleButton?" "+a.toggleButton:"");ht=x("button",u),ht.style.width="28px",ht.style.height="28px",ht.style.color=Nn.actionIconColor,ht.type="button",ht.setAttribute("aria-label","Event Stream"),ht.title="Event Stream";let m=Nt(Kr.Activity,"18px","currentColor",1.5);m&&ht.appendChild(m);let b=Ze.clearChatButtonWrapper,w=Ze.closeButtonWrapper,k=b||w;k&&k.parentNode===mt?mt.insertBefore(ht,k):mt.appendChild(ht),ht.addEventListener("click",()=>{Sn?zi():$u()})}let jh=a=>{let u=o.attachments;if(!u?.enabled)return;let m=a.querySelector("[data-persona-composer-attachment-previews]")??a.querySelector(".persona-attachment-previews");if(!m){m=x("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),m.setAttribute("data-persona-composer-attachment-previews",""),m.style.display="none";let w=a.querySelector("[data-persona-composer-form]");w?.parentNode?w.parentNode.insertBefore(m,w):a.insertBefore(m,a.firstChild)}if(!(a.querySelector("[data-persona-composer-attachment-input]")??a.querySelector('input[type="file"]'))){let w=x("input");w.type="file",w.setAttribute("data-persona-composer-attachment-input",""),w.accept=(u.allowedTypes??Dr).join(","),w.multiple=(u.maxFiles??4)>1,w.style.display="none",w.setAttribute("aria-label",u.buttonTooltipText??"Attach files"),a.appendChild(w)}},Ki=!1,qh=a=>{let u=d.find(w=>w.renderComposer);if(!u?.renderComposer)return null;let m=o.composer,b=h?R.isStreaming():!1;return u.renderComposer({config:o,defaultRenderer:a,requestRender:()=>$b(),storage:y(u.id),onSubmit:w=>{!R||R.isStreaming()||ad(w.trim(),{consumeDraft:!1})},streaming:b,disabled:b,openAttachmentPicker:()=>{Yo()||Mt?.click()},models:m?.models,selectedModelId:be.getState().selectedModelId??m?.selectedModelId,onModelChange:w=>Fh(w),onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{Fu?.()}:void 0})},zh=qh(()=>ki({config:o}).footer);zh&&(Ln.replaceComposer(zh),Ke=Ln.composer.footer,Ki=!0);let ct=null,sM=a=>{An=a.form,ce=a.input,Rn=a.sendButton?a.sendButton.parentElement:null,a.sendButton&&(Pe=a.sendButton),a.micButton&&(he=a.micButton,gn=a.micButton.parentElement),a.found.status&&(rt=a.found.status),a.found.suggestions&&(lo=a.found.suggestions),a.attachmentButton&&(It=a.attachmentButton,sn=a.attachmentButton.parentElement),Mt=a.attachmentInput??null,fn=a.attachmentPreviews??null,a.found.actionsRow&&(Fi=a.found.actionsRow),xn=a.found.actionsStart,_s=a.found.actionsEnd};function Uu(){let a=ce;if(!a)return;let u=o.composer?.inputAttributes,m=!u?.ariaLabel&&!(a instanceof HTMLTextAreaElement)?a.getAttribute("aria-label"):null;Qd(a,u),m&&a.setAttribute("aria-label",m),Xd(a,{submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:_l(a)}),HC(a,Yd(o.composer?.maxLines,Le()?5:3))}let Kh=a=>{ct=jw(a,{debug:o.debug===!0}),ct&&sM(ct),Uu()};jh(Ke),Kh(Ke),co();let nl=Hs(o,Le());nl&&(Te.style.maxWidth=nl,Te.style.marginLeft="auto",Te.style.marginRight="auto",Te.style.width="100%",In.style.maxWidth=nl,In.style.marginLeft="auto",In.style.marginRight="auto",In.style.width="100%",gr.style.maxWidth=nl,Xr.style.maxWidth=nl,Xr.style.marginLeft="auto",Xr.style.marginRight="auto",Xr.style.width="100%");let Gh=()=>{let a=Hs(o,Le());if(!(!a||Le()))for(let u of[An,lo,fn,rt])u&&(u.style.maxWidth=a,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%")};Gh();let Yh=()=>{!o.attachments?.enabled||!Mt||!fn||(je?je.remountPreviews(fn):(je=Ai.fromConfig(o.attachments,Nh),je.setPreviewsContainer(fn)),ct?.addListener(Mt,"change",a=>{let u=a.target;je?.handleFileSelect(u.files),u.value=""}),we.querySelector(".persona-attachment-drop-overlay")||we.appendChild(ax(o.attachments.dropOverlay)))};Yh();let iM=()=>at?.prefetch(),Vu=()=>{if(!o.contextMentions?.enabled||!ce)return;let a=qf();if(!a){let b=ce;cp().then(()=>{at||ce!==b||!b.isConnected||(Vu(),To?.resolve())},()=>{});return}let u=ct?.header??null,m=u?bm(u):void 0;if(at=a.createContextMentionOrchestrator({deps:{loadContextMentions:ip,loadContextMentionsInline:ap,renderLucideIcon:ge,createMentionButton:sp},config:o,textarea:ce,anchor:An??ce,getMessages:()=>R.getMessages(),liveRegionHost:we,chipRow:m}),at&&!m){let b=ce;b.parentElement?.insertBefore(at.contextRow,b)}};Vu();let To=null,aM={getState:()=>be.getState(),getValue:()=>ce?.value??"",setValue:a=>{ce&&(ce.value=a,ce.dispatchEvent(new Event("input",{bubbles:!0})),co())},submit:()=>{bS(ct?.form??null)},openAttachmentPicker:()=>{Yo()||Mt?.click()},toggleVoice:()=>{Fu?.()},requestRender:()=>To?.resolve()},lM=()=>{let a=[];return(at?.affordanceButtons??[]).forEach((m,b)=>{a.push({id:`core:mention-${b}`,placement:"start",order:sr.mention+b,element:m,managed:!0})}),sn&&a.push({id:"core:attachment",placement:"start",order:sr.attachment,element:sn}),gn&&a.push({id:"core:mic",placement:"end",order:sr.mic,element:gn}),Rn&&a.push({id:"core:send",placement:"end",order:sr.send,element:Rn}),a},Xh=()=>{To?.destroy(),To=Qw({getBindings:()=>ct,collect:()=>({builtIns:lM(),configActions:[...rM(),...o.composer?.actions??[]],plugins:d,contributionContext:{config:o,getState:()=>be.getState(),requestRender:()=>To?.resolve()},debug:o.debug===!0}),actionContext:aM,getState:()=>be.getState(),getOverflow:()=>o.composer?.actionOverflow,reportError:(a,u)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${u.actionId}" failed:`,a)}}),To.resolve()};Xh();let ju=()=>{if(hr?.destroy(),hr=null,!Vi().length)return;let a=ct?.header;a&&(hr=tS({row:bm(a),onRemove:u=>_u(u),initialIds:be.getState().activeModeIds}),hr.render(be.getState().activeModeIds,Vi()))};ju();let Qh=()=>{es?.destroy(),es=null,ts?.destroy(),ts=null;let a=ct?.header;a&&(es=cS({onDismiss:()=>qo(void 0)}),a.appendChild(es.element),es.render(be.getState().quote),Nu()==="defer-one"&&(ts=dS({onEdit:()=>rE(),onRemove:()=>qi(void 0)}),a.appendChild(ts.element),ts.render(be.getState().pendingSubmission)))};Qh();let qu=hS(),cM=()=>{let a=ct?.header?.querySelector(ym);if(a)return a.childElementCount>0;let u=be.getState();return u.mentionRefs.length>0||Bp(u.activeModeIds,Vi()).length>0};function Po(){let a=be.getState(),u=qu.observe(yS(ce),a.text);Ke.toggleAttribute("data-persona-composer-compact",mS({text:a.text,wrapped:u,hasAttachments:a.attachments.length>0,hasChips:cM(),hasQuote:a.quote!==void 0,hasPendingSubmission:a.pendingSubmission!==void 0}))}function Jh(){o.composer?.layout==="single-row"&&!Le()?Ke.setAttribute("data-persona-composer-layout","single-row"):Ke.removeAttribute("data-persona-composer-layout")}Jh(),be.subscribe(()=>{To?.sync(),fg(),Xc(),Po(),Hy()}),Xc();let Zh=!1,dM=a=>{if(Zh||o.debug!==!0)return;let u=["messages","composer"].filter(m=>a[m]);u.length&&(Zh=!0,console.warn(`[persona] layout.slots.${u.join(" and layout.slots.")} ${u.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 a=o.layout?.slots??{};dM(a);let u=b=>{switch(b){case"body-top":return ae.querySelector("[data-persona-intro-card]");case"messages":return Te;case"footer-top":return lo;case"composer":return An;case"footer-bottom":return rt;default:return null}},m=(b,w)=>{switch(b){case"header-left":case"header-center":case"header-right":if(b==="header-left")mt.insertBefore(w,mt.firstChild);else if(b==="header-right")mt.appendChild(w);else{let k=mt.querySelector(".persona-flex-col");k?k.parentNode?.insertBefore(w,k.nextSibling):mt.appendChild(w)}break;case"body-top":{let k=ae.querySelector("[data-persona-intro-card]");k?k.replaceWith(w):ae.insertBefore(w,ae.firstChild);break}case"body-bottom":ae.appendChild(w);break;case"footer-top":lo.replaceWith(w);break;case"footer-bottom":rt.replaceWith(w);break;default:break}};for(let[b,w]of Object.entries(a))if(w)try{let k=w({config:o,defaultContent:()=>u(b)});k&&m(b,k)}catch(k){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${b}":`,k)}})(),Te.addEventListener("click",a=>{let u=a.target;if(!(u instanceof Element))return;let m=u.closest("button[data-persona-copy-tool-detail]");m&&(a.preventDefault(),a.stopPropagation(),IA(m))});let zu=a=>{let m=a.target.closest('button[data-expand-header="true"]');if(!m)return;let b=m.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!b)return;let w=b.getAttribute("data-message-id");if(!w)return;is(),ta();let k=m.getAttribute("data-bubble-type");if(b.classList.contains("persona-activity-row")){i.manual(w);let q=b.parentElement?.closest("[data-persona-tool-group]");q?.dataset.messageId&&i.manual(q.dataset.messageId)}if(k==="reasoning")s.has(w)?s.delete(w):s.add(w),eh(w,b,s);else if(k==="tool")r.has(w)?r.delete(w):r.add(w),rh(w,b,r,o);else if(k==="approval"&&v){let re=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",Y=l.get(w)??re;l.set(w,!Y),v.updateApprovalDetailsUI(w,b,o,l)}En.delete(w)};Te.addEventListener("pointerdown",a=>{a.target.closest('button[data-expand-header="true"]')&&(a.preventDefault(),zu(a))}),Te.addEventListener("click",a=>{a.detail===0&&a.target.closest(".persona-activity-row")&&zu(a)}),Te.addEventListener("keydown",a=>{let u=a.target;(a.key==="Enter"||a.key===" ")&&u.closest('button[data-expand-header="true"]')&&(a.preventDefault(),zu(a))}),Te.addEventListener("copy",a=>{let{clipboardData:u}=a;if(!u)return;let m=Te.getRootNode(),b=typeof m.getSelection=="function"?m.getSelection():window.getSelection();if(!b||b.isCollapsed)return;let w=b.toString(),k=WS(w);!k||k===w||(u.setData("text/plain",k),a.preventDefault())});let Ku=new Map,ey=null,ty="idle",pM={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},uM=(a,u)=>{let{icon:m,label:b}=pM[u];a.setAttribute("aria-label",b),a.title=b,a.setAttribute("aria-pressed",u==="idle"?"false":"true"),a.classList.toggle("persona-message-action-active",u!=="idle"),a.classList.toggle("persona-message-action-loading",u==="loading");let w=ge(m,14,"currentColor",2);w&&(a.innerHTML="",a.appendChild(w))},ny=()=>{Te.querySelectorAll('[data-action="read-aloud"]').forEach(u=>{let b=u.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;uM(u,b&&b===ey?ty:"idle")})};Te.addEventListener("click",a=>{let m=a.target.closest(".persona-message-action-btn[data-action]");if(!m)return;a.preventDefault(),a.stopPropagation();let b=m.closest("[data-actions-for]");if(!b)return;let w=b.getAttribute("data-actions-for");if(!w)return;let k=m.getAttribute("data-action");if(k==="copy"){let re=R.getMessages().find(Y=>Y.id===w);if(re&&eo.onCopy){let Y=re.content||"";navigator.clipboard.writeText(Y).then(()=>{m.classList.add("persona-message-action-success");let ie=Nt(Kr.Check,14,"currentColor",2);ie&&(m.innerHTML="",m.appendChild(ie)),setTimeout(()=>{m.classList.remove("persona-message-action-success");let le=Nt(Kr.Copy,14,"currentColor",2);le&&(m.innerHTML="",m.appendChild(le))},2e3)}).catch(ie=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",ie)}),eo.onCopy(re)}}else if(k==="read-aloud")R.toggleReadAloud(w);else if(k==="upvote"||k==="downvote"){let re=(Ku.get(w)??null)===k,Y=k==="upvote"?"thumbs-up":"thumbs-down";if(re){Ku.delete(w),m.classList.remove("persona-message-action-active");let ie=ge(Y,14,"currentColor",2);ie&&(m.innerHTML="",m.appendChild(ie))}else{let ie=k==="upvote"?"downvote":"upvote",le=b.querySelector(`[data-action="${ie}"]`);if(le){le.classList.remove("persona-message-action-active");let dt=ge(ie==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);dt&&(le.innerHTML="",le.appendChild(dt))}Ku.set(w,k),m.classList.add("persona-message-action-active");let de=ge(Y,14,"currentColor",2);de&&(de.setAttribute("fill","currentColor"),m.innerHTML="",m.appendChild(de)),m.classList.remove("persona-message-action-pop"),m.offsetWidth,m.classList.add("persona-message-action-pop");let it=R.getMessages().find(gt=>gt.id===w);it&&eo.onFeedback&&eo.onFeedback({type:k,messageId:it.id,message:it})}}else if(k==="regenerate")Tc?.regenerate(w);else if(k==="edit")Tc?.edit(w);else if(k==="quote")Tc?.quote(w);else if(k?.startsWith(tu)){let q=k.slice(tu.length),re=o.messageActions?.custom?.find(ie=>ie.id===q),Y=R.getMessages().find(ie=>ie.id===w);if(!re||!Y)return;try{re.onSelect(Y)}catch(ie){console.error(`[AgentWidget] messageActions.custom "${q}" onSelect failed:`,ie)}}});let Tc=null;Te.addEventListener("click",a=>{let m=a.target.closest("button[data-approval-action]");if(!m)return;a.preventDefault(),a.stopPropagation();let b=m.closest(".persona-approval-bubble");if(!b)return;let w=b.getAttribute("data-message-id");if(!w)return;let k=m.getAttribute("data-approval-action");if(!k)return;let q=k==="approve"?"approved":"denied",Y=R.getMessages().find(le=>le.id===w);if(!Y?.approval)return;let ie=b.querySelector("[data-approval-buttons]");ie&&ie.querySelectorAll("button").forEach(de=>{de.disabled=!0,de.style.opacity="0.5",de.style.cursor="not-allowed"}),Y.approval.toolType==="webmcp"?R.resolveWebMcpApproval(w,q):R.resolveApproval(Y.approval,q)});let et=null,oy=!1,ol=null,Us=()=>{},rl="none",Pc=null,po={artifacts:[],selectedId:null},yr=!1,ko=!1,sl=!1,Gi=!1,ry=()=>Gi||po.artifacts.some(a=>or(o.features?.artifacts,a)==="panel"),kc=()=>po.artifacts.length>0&&!yr&&ry(),uo={current:null},Gu=(a,u)=>{let m=R.getArtifactById(u),b=m?.markdown,w=m?.title||"artifact",k=m?.file,q=m?.artifactType??"markdown";if(!b){let ie=a.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(ie){let de=R.getMessages().find(ke=>ke.id===ie);if(de?.rawContent)try{let ke=JSON.parse(de.rawContent);b=ke?.props?.markdown,w=ke?.props?.title||w,ke?.props?.file&&typeof ke.props.file=="object"&&(k=ke.props.file),!m&&typeof ke?.props?.artifactType=="string"&&(q=ke.props.artifactType)}catch{}}}return{markdown:b,title:w,file:k,artifactType:q}};Te.addEventListener("click",a=>{let m=a.target.closest("[data-download-artifact]");if(!m)return;a.preventDefault(),a.stopPropagation();let b=m.getAttribute("data-download-artifact");if(!b||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:b})===!0)return;let{markdown:k,title:q,file:re}=Gu(m,b);if(!k)return;let Y=qr();Y&&Y.triggerArtifactDownload(Y.downloadInfoFor({title:q,markdown:k,file:re}))}),Te.addEventListener("click",a=>{let m=a.target.closest("[data-artifact-custom-action]");if(!m)return;a.preventDefault(),a.stopPropagation();let b=m.getAttribute("data-artifact-custom-action");if(!b)return;let w=m.closest("[data-artifact-inline]"),k=w?null:m.closest("[data-open-artifact]"),q=w?w.getAttribute("data-artifact-inline"):k?.getAttribute("data-open-artifact")??null,Y=(w?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(gt=>gt.id===b);if(!Y)return;let{markdown:ie,title:le,file:de,artifactType:ke}=Gu(m,q??""),it={artifactId:q,title:le,artifactType:ke,markdown:ie,file:de};try{Promise.resolve(Y.onClick(it)).catch(()=>{})}catch{}}),Te.addEventListener("click",a=>{let m=a.target.closest("[data-copy-artifact]");if(!m)return;a.preventDefault(),a.stopPropagation();let b=m.getAttribute("data-copy-artifact");if(!b)return;let w=R.getArtifactById(b),k=qr();if(!k)return;let q="";if(w)q=k.artifactCopyText(w);else{let{markdown:re,file:Y,artifactType:ie}=Gu(m,b);ie==="markdown"&&(q=k.artifactCopyText({id:b,artifactType:"markdown",status:"complete",markdown:re??"",...Y?{file:Y}:{}}))}q&&navigator.clipboard.writeText(q).then(()=>{let re=Nt(Kr.Check,16,"currentColor",2);re&&(m.replaceChildren(re),setTimeout(()=>{let Y=Nt(Kr.Copy,16,"currentColor",2);Y&&m.replaceChildren(Y)},1500))}).catch(()=>{})}),Te.addEventListener("click",a=>{let m=a.target.closest("[data-expand-artifact-inline]");if(!m)return;a.preventDefault(),a.stopPropagation();let b=m.getAttribute("data-expand-artifact-inline");!b||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:b})===!0||(yr=!1,Gi=!0,ko=!0,sl=!0,R.selectArtifact(b),Lo())}),Te.addEventListener("click",a=>{let u=a.target;if(u.closest("[data-download-artifact]")||u.closest("[data-artifact-custom-action]"))return;let m=u.closest("[data-open-artifact]");if(!m)return;let b=m.getAttribute("data-open-artifact");!b||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:b})===!0||(a.preventDefault(),a.stopPropagation(),yr=!1,Gi=!0,R.selectArtifact(b),Lo())}),Te.addEventListener("keydown",a=>{if(a.key!=="Enter"&&a.key!==" ")return;let u=a.target;!u.hasAttribute("data-open-artifact")&&!u.hasAttribute("data-expand-artifact-inline")||(a.preventDefault(),u.click())});let il=Ze.composerOverlay,Yu=a=>{cp().catch(()=>{}),Id(a,o,il)},sy=null,gM={mount:e,overlay:il,sessionRef:uo,config:()=>o},Lc=!1,iy=a=>u=>{let m=u.target,b=m?.closest?.("[data-persona-ask-sheet-for]");if(!b||!(a==="click"?!!m?.closest("[data-ask-user-action]"):u.key==="Enter"&&!!m?.matches?.('[data-ask-free-text-input="true"]')))return;let k=re=>{sy??=re.createAskUserSheetHandlers(gM),sy[a](u)},q=qf();if(q){k(q);return}Lc||(Lc=!0,cp().then(re=>{Lc=!1,b.isConnected&&k(re)},()=>{Lc=!1}))};il.addEventListener("click",iy("click")),il.addEventListener("keydown",iy("keydown"));let ay=a=>{if(!/^[1-9]$/.test(a.key)||a.metaKey||a.ctrlKey||a.altKey)return;let u=a.target;if(u?.tagName==="INPUT"||u?.tagName==="TEXTAREA"||u?.isContentEditable)return;let m=il.querySelector("[data-persona-ask-sheet-for]");if(!m||m.getAttribute("data-ask-layout")!=="rows"||m.getAttribute("data-multi-select")==="true")return;let b=Number(a.key),k=m.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[b-1];k&&(a.preventDefault(),k.click())};document.addEventListener("keydown",ay);let br=null,Ut=null,al=null,Hc=null,Ic=()=>{},ly=!1,Rc="",Wc="";function Xu(){Hc?.(),Hc=null}let fM=()=>{let a=_t?.railShell?_t.railHost:null,u=a?.isConnected?a:null,m=u?u.getBoundingClientRect().width:0;return m<=0?200:m+360},cy=()=>{if(!br||!Ut)return;let a=e.classList.contains("persona-artifact-welded-split"),u=e.ownerDocument.defaultView??window,m=u.innerWidth<=640;if(!a||e.classList.contains("persona-artifact-narrow-host")||m){Ut.style.removeProperty("position"),Ut.style.removeProperty("left"),Ut.style.removeProperty("top"),Ut.style.removeProperty("bottom"),Ut.style.removeProperty("width"),Ut.style.removeProperty("z-index");return}let b=br.firstElementChild;if(!b||b===Ut)return;let w=10;Ut.style.position="absolute",Ut.style.top="0",Ut.style.bottom="0",Ut.style.width=`${w}px`,Ut.style.zIndex="5";let k=mh(br,u),q=b.offsetWidth+k/2-w/2;Ut.style.left=`${Math.max(0,q)}px`},Oc=()=>{},dy=()=>{let a=e.ownerDocument.defaultView??window,u=o.launcher?.mobileFullscreen??!0,m=o.launcher?.mobileBreakpoint??640;return!u||a.innerWidth>m?!1:ye||Lt(o)},Bc=()=>!$n(o)||!kc()||e.classList.contains("persona-artifact-narrow-host")||dy()||(e.ownerDocument.defaultView??window).innerWidth<JL?"none":ph(o)?"detached":"welded",Lo=()=>{if(!et||!$n(o))return;dc(e,o),pc(e,o),Oc();let a=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,u=Ae.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",u>0&&u<=a);let m=kc();et.setVisible(m),et.update(po),yr?(et.setMobileOpen(!1),et.element.classList.add("persona-hidden"),et.backdrop?.classList.add("persona-hidden"),ko=!1,sl=!1):po.artifacts.length>0&&ry()?(et.element.classList.remove("persona-hidden"),et.setMobileOpen(!0)):(et.setMobileOpen(!1),et.element.classList.add("persona-hidden"),et.backdrop?.classList.add("persona-hidden"),ko=!1,sl=!1);let b=o.features?.artifacts?.layout?.showExpandToggle===!0;if(et.setExpandToggleVisible(b),et.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),et.setRefreshButtonVisible(typeof o.features?.artifacts?.layout?.onDocumentToolbarRefresh=="function"),et.setCustomActions(o.features?.artifacts?.toolbarActions??[]),et.setTabFade(o.features?.artifacts?.layout?.tabFade),et.setRenderTabBar(o.features?.artifacts?.renderTabBar),!b&&!sl&&(ko=!1),ko!==ly){let k=et.element;ko?(Rc=k.style.width,Wc=k.style.maxWidth,k.style.removeProperty("width"),k.style.removeProperty("max-width")):(Rc&&(k.style.width=Rc),Wc&&(k.style.maxWidth=Wc),Rc="",Wc=""),ly=ko}e.classList.toggle("persona-artifact-expanded",ko),et.setExpanded(ko);let w=Bc();w!==rl&&(rl=w,Us()),Ic()};if($n(o)){Ae.style.position="relative";let a=x("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),u=x("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");a.appendChild(we),br=u,u.appendChild(a),Ae.appendChild(u);let m=w=>{oy||et||(et=w.createArtifactPane(o,{onSelect:k=>uo.current?.selectArtifact(k),onDismiss:()=>{yr=!0,Lo()},onToggleExpand:()=>{let k=!ko,q=po.selectedId??po.artifacts[po.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:q,expanded:k})!==!0&&(ko=k,k||(sl=!1),Lo())}}),et.element.classList.add("persona-hidden"),u.appendChild(et.element),et.backdrop&&Ae.appendChild(et.backdrop),Ic(),Lo())},b=qr();b?m(b):(ch(()=>{let w=qr();w&&m(w)}),iu().catch(()=>{})),Ic=()=>{if(!br||!et)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){al?.(),al=null,Xu(),Ut&&(Ut.remove(),Ut=null),et.element.style.removeProperty("width"),et.element.style.removeProperty("maxWidth");return}if(!Ut){let k=x("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=e.ownerDocument,re=q.defaultView??window,Y=ie=>{if(!et||ie.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||re.innerWidth<=640)return;ie.preventDefault(),Xu();let le=ie.clientX,de=et.element.getBoundingClientRect().width,ke=o.features?.artifacts?.layout,it=dt=>{let zn=br.getBoundingClientRect().width,Dt=e.classList.contains("persona-artifact-welded-split"),jt=mh(br,re),On=Dt?0:k.getBoundingClientRect().width||6,Kt=de-(dt.clientX-le),wt=qA(Kt,zn,jt,On,ke?.resizableMinWidth,ke?.resizableMaxWidth,fM());et.element.style.width=`${wt}px`,et.element.style.maxWidth="none",cy()},gt=()=>{q.removeEventListener("pointermove",it),q.removeEventListener("pointerup",gt),q.removeEventListener("pointercancel",gt),Hc=null;try{k.releasePointerCapture(ie.pointerId)}catch{}};Hc=gt,q.addEventListener("pointermove",it),q.addEventListener("pointerup",gt),q.addEventListener("pointercancel",gt);try{k.setPointerCapture(ie.pointerId)}catch{}};k.addEventListener("pointerdown",Y),Ut=k,br.insertBefore(k,et.element),al=()=>{k.removeEventListener("pointerdown",Y)}}if(Ut){let k=kc();Ut.classList.toggle("persona-hidden",!k),cy()}},Oc=()=>{if(!ye||!et||(o.launcher?.sidebarMode??!1)||Lt(o)&&Jn(o).reveal==="emerge")return;let k=e.ownerDocument.defaultView??window,q=o.launcher?.mobileFullscreen??!0,re=o.launcher?.mobileBreakpoint??640;if(q&&k.innerWidth<=re||!NA(o,ye))return;let Y=Hi(o).width,ie=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";kc()?(Ae.style.width=ie,Ae.style.maxWidth=ie):(Ae.style.width=Y,Ae.style.maxWidth=Y)},typeof ResizeObserver<"u"&&(ol=new ResizeObserver(()=>{Lo()}),ol.observe(Ae))}else Ae.appendChild(we);Le()&&Xt&&(Ze.peekBanner&&Xt.appendChild(Ze.peekBanner),Xt.appendChild(Ke)),e.appendChild(Qe),Xt&&e.appendChild(Xt);let Qu=()=>{let a=dy()||Le()&&o.launcher?.composerBar?.expandedSize==="fullscreen"||o.launcher?.fullHeight===!0&&!o.launcher?.sidebarMode&&!Lt(o);if(Te.style.gap=a?"var(--persona-components-message-fullscreenGap, var(--persona-components-message-gap, 12px))":"var(--persona-components-message-gap, 12px)",Te.style.setProperty("--persona-transcript-gap",Te.style.gap),Le()){Ae.style.width="100%",Ae.style.maxWidth="100%";let _e=o.launcher?.composerBar??{},Ge=Qe.dataset.state==="expanded",Ue=_e.expandedSize??"anchored";if(!(Ge&&Ue!=="fullscreen")){we.style.background="",we.style.border="",we.style.borderRadius="",we.style.overflow="",we.style.boxShadow="";return}let nn=o.theme?.components?.panel,Kn=No(o),Pr=(kr,ci)=>kr==null||kr===""?ci:wn(Kn,kr)??kr,Yg="1px solid var(--persona-border)",li="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Xg="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";we.style.background="var(--persona-surface, #ffffff)",we.style.border=Pr(nn?.border,Yg),we.style.borderRadius=Pr(nn?.borderRadius,Xg),we.style.boxShadow=Pr(nn?.shadow,li),we.style.overflow="hidden";return}let u=Lt(o),m=o.launcher?.sidebarMode??!1,b=u||m||(o.launcher?.fullHeight??!1),w=o.launcher?.enabled===!1,k=o.launcher?.detachedPanel===!0,q=o.theme?.components?.panel,re=o.darkTheme?.components?.panel,Y=xi(o)==="dark"?_o(q??{},re??{}):q,ie=No(o),le=(_e,Ge)=>_e==null||_e===""?Ge:wn(ie,_e)??_e,de=e.ownerDocument.defaultView??window,ke=o.launcher?.mobileFullscreen??!0,it=o.launcher?.mobileBreakpoint??640,gt=de.innerWidth<=it,dt=ke&>&&ye,zn=u&&ke&>,Dt=o.launcher?.position??"bottom-left",jt=Dt==="bottom-left"||Dt==="top-left",On=o.launcher?.zIndex??kn,Kt=(_e,Ge,Ue)=>`var(--persona-components-panel-modes-${_e}-${Ge}, ${Ue})`,wt=Y?.modes?.floating,Jo=le(wt?.border??Y?.border,Kt("floating","border","var(--persona-panel-border, 1px solid var(--persona-border))")),Zo=le(wt?.shadow??Y?.shadow,Kt("floating","shadow","var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))")),yo=le(wt?.borderRadius??Y?.borderRadius,Kt("floating","borderRadius","var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))")),bo=k&&!dt&&!zn,fs=dt||zn?"mobile":bo?"floating":u?"docked":m?"sidebar":w?"inline":"floating",er=Y?.modes?.[fs];bo?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let Io=bo?Jo:m||dt?"none":Jo,ms=bo?Zo:dt?"none":m?jt?"2px 0 12px rgba(0, 0, 0, 0.08)":"-2px 0 12px rgba(0, 0, 0, 0.08)":w?"none":Zo;u&&!dt&&!bo&&(ms="none",Io="none");let xl=bo?yo:m||dt?"0":yo,ai=le(er?.border??Y?.border,Kt(fs,"border",Io)),O=le(er?.shadow??Y?.shadow,Kt(fs,"shadow",ms)),Ne=le(er?.borderRadius??Y?.borderRadius,Kt(fs,"borderRadius",xl)),Fe=Bc(),se=Fe==="detached",St=Fe==="welded";e.classList.toggle("persona-artifact-detached-split",se),e.classList.toggle("persona-artifact-welded-split",St);let Jt="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)))))",Tt=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&$n(o)&&ph(o)&&w&&!u;e.classList.toggle("persona-artifact-chat-flush",Tt);let Gt=se||Tt?"none":O,ln=se?Jo:St?"none":ai,We=se?yo:Ne;Tt&&(ln="none",We="0");let Pt=er?.borderRadius!=null&&er.borderRadius!==""||Y?.borderRadius!=null&&Y.borderRadius!=="",$e=Tt&&!Pt?"0":Ne,cn=ae.scrollTop;e.style.cssText="",Qe.style.cssText="",Ae.style.cssText="",we.style.cssText="",ae.style.cssText="",Ki||(Ke.style.cssText=""),Sn&&(ae.style.display="none"),(b||w)&&(e.style.minWidth="0");let vo=()=>{if(cn<=0)return;(ae.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(ae.scrollTop===cn)return;let Ge=ae.scrollHeight-ae.clientHeight;Ge<=0||(ae.scrollTop=Math.min(cn,Ge))})};if(dt){Qe.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"),Qe.style.cssText=`
|
|
46
|
+
`,oe.addEventListener("click",()=>{g=V,A.forEach((W,j)=>{let X=j<V;W.classList.toggle("selected",X),W.setAttribute("aria-checked",j===V-1?"true":"false")})}),A.push(oe),C.appendChild(oe)}f.appendChild(C);let L=null;if(c){let V=document.createElement("div");V.className="persona-feedback-comment-container",L=document.createElement("textarea"),L.className="persona-feedback-comment",L.placeholder=s,L.rows=3,L.setAttribute("aria-label","Additional comments"),V.appendChild(L),f.appendChild(V)}let I=document.createElement("div");I.className="persona-feedback-actions";let H=document.createElement("button");H.type="button",H.className="persona-feedback-btn persona-feedback-btn-skip",H.textContent=l,H.addEventListener("click",()=>{n?.(),d.remove()});let B=document.createElement("button");return B.type="button",B.className="persona-feedback-btn persona-feedback-btn-submit",B.textContent=i,B.addEventListener("click",async()=>{if(g===null){C.classList.add("persona-feedback-shake"),setTimeout(()=>C.classList.remove("persona-feedback-shake"),500);return}B.disabled=!0,B.textContent="Submitting...";try{let V=L?.value.trim()||void 0;await t(g,V),d.remove()}catch(V){B.disabled=!1,B.textContent=i,console.error("[CSAT Feedback] Failed to submit:",V)}}),I.appendChild(H),I.appendChild(B),f.appendChild(I),d.appendChild(f),d}function yu(e){let{onSubmit:t,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:i="Submit",skipText:l="Skip",showComment:c=!0,lowLabel:p="Not likely",highLabel:d="Very likely"}=e,g=document.createElement("div");g.className="persona-feedback-container persona-feedback-nps",g.setAttribute("role","dialog"),g.setAttribute("aria-label","Net Promoter Score feedback");let f=null,h=document.createElement("div");h.className="persona-feedback-content";let y=document.createElement("div");y.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=o,y.appendChild(v);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=r,y.appendChild(C),h.appendChild(y);let A=document.createElement("div");A.className="persona-feedback-rating persona-feedback-rating-nps",A.setAttribute("role","radiogroup"),A.setAttribute("aria-label","Likelihood rating from 0 to 10");let L=document.createElement("div");L.className="persona-feedback-labels";let I=document.createElement("span");I.className="persona-feedback-label-low",I.textContent=p;let H=document.createElement("span");H.className="persona-feedback-label-high",H.textContent=d,L.appendChild(I),L.appendChild(H);let B=document.createElement("div");B.className="persona-feedback-numbers";let V=[];for(let M=0;M<=10;M++){let T=document.createElement("button");T.type="button",T.className="persona-feedback-rating-btn persona-feedback-number-btn",T.setAttribute("role","radio"),T.setAttribute("aria-checked","false"),T.setAttribute("aria-label",`Rating ${M} out of 10`),T.textContent=String(M),T.dataset.rating=String(M),M<=6?T.classList.add("persona-feedback-detractor"):M<=8?T.classList.add("persona-feedback-passive"):T.classList.add("persona-feedback-promoter"),T.addEventListener("click",()=>{f=M,V.forEach((_,P)=>{_.classList.toggle("selected",P===M),_.setAttribute("aria-checked",P===M?"true":"false")})}),V.push(T),B.appendChild(T)}A.appendChild(L),A.appendChild(B),h.appendChild(A);let oe=null;if(c){let M=document.createElement("div");M.className="persona-feedback-comment-container",oe=document.createElement("textarea"),oe.className="persona-feedback-comment",oe.placeholder=s,oe.rows=3,oe.setAttribute("aria-label","Additional comments"),M.appendChild(oe),h.appendChild(M)}let W=document.createElement("div");W.className="persona-feedback-actions";let j=document.createElement("button");j.type="button",j.className="persona-feedback-btn persona-feedback-btn-skip",j.textContent=l,j.addEventListener("click",()=>{n?.(),g.remove()});let X=document.createElement("button");return X.type="button",X.className="persona-feedback-btn persona-feedback-btn-submit",X.textContent=i,X.addEventListener("click",async()=>{if(f===null){B.classList.add("persona-feedback-shake"),setTimeout(()=>B.classList.remove("persona-feedback-shake"),500);return}X.disabled=!0,X.textContent="Submitting...";try{let M=oe?.value.trim()||void 0;await t(f,M),g.remove()}catch(M){X.disabled=!1,X.textContent=i,console.error("[NPS Feedback] Failed to submit:",M)}}),W.appendChild(j),W.appendChild(X),h.appendChild(W),g.appendChild(h),g}var Ga="persona-chat-history",nH=30*1e3,oH="Tap the mic to resume your voice call",rH=641,Ya="data-persona-composer-reason",yc="data-persona-composer-notice",sH={"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 iH(e){if(!e)return[];let t=[],n=Array.from(e.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){t.push(r);continue}let s=sH[r.type]??"png";t.push(new File([r],`clipboard-image-${Date.now()}.${s}`,{type:r.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let o of Array.from(e.files??[]))o.type.startsWith("image/")&&t.push(o);return t}function bu(e){if(!e)return!1;let t=e.types;return t?typeof t.contains=="function"?t.contains("Files"):Array.from(t).includes("Files"):!1}function aH(e){return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:e.storage??"session",keyPrefix:e.keyPrefix??"persona-",persist:{openState:e.persist?.openState??!0,voiceState:e.persist?.voiceState??!0,focusInput:e.persist?.focusInput??!0},clearOnChatClear:e.clearOnChatClear??!0}:null}function lH(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var wh=e=>!e||typeof e!="object"?{}:{...e},cx=e=>e.map(t=>({...t,streaming:!1})),dx=(e,t,n)=>{let o=e?.markdown?jl(e.markdown):null,r=Lp(e?.sanitize);e?.postprocessMessage&&r&&e?.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,i=l=>{let c=l.text??"",p=l.message.rawContent??null;if(t){let f=t.process({text:c,raw:p??c,message:l.message,streaming:l.streaming});f!==null&&(c=f.text,f.persist||(l.message.__skipPersist=!0),f.resubmit&&!l.streaming&&n&&n())}let d=nr()!==null,g;if(e?.postprocessMessage){let f=e.postprocessMessage({...l,text:c,raw:p??l.text??""});g=r?r(f):f}else if(o){let f=l.streaming?bw(c):c,h=o(f);g=r&&d?r(h):h}else g=Ur(c);return g};return l=>{try{return i(l)}catch(c){return s||(s=!0,console.error("[Persona] markdown rendering failed; falling back to plain text:",c)),Ur(l.text??"")}}};function px(e){let t=x("div","persona-attachment-drop-overlay");e?.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),e?.backdropBlur!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e?.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e?.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e?.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e?.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e?.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=e?.iconName??"upload",o=e?.iconSize??"48px",r=e?.iconColor??"rgba(59, 130, 246, 0.6)",s=e?.iconStrokeWidth??.5,i=ge(n,o,r,s);if(i&&t.appendChild(i),e?.label){let l=x("span","persona-drop-overlay-label");l.textContent=e.label,t.appendChild(l)}return t}var cH=(e,t)=>{let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];n[o]=s?{...s,...r}:r}return n},dH=e=>e.reduce((t,n)=>({blocks:[...t.blocks,...n.blocks],contentParts:[...t.contentParts,...n.contentParts],context:cH(t.context,n.context)}),{blocks:[],contentParts:[],context:{}}),vu=(e,t,n)=>{if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let o=Ma(t),r=new Set,s=new Set,i=iw((a,u)=>{Mn.delete(a);let m=Array.from(Te.querySelectorAll("[data-message-id]")).find(b=>b.dataset.messageId===a);m&&(u==="tool"?ah(a,m,r,o):oh(a,m,s))}),l=new Map,c=()=>{uC({delayMs:o.tooltip?.delayMs??200,skipDelayMs:o.tooltip?.skipDelayMs??300})};c();let p=o.features;o=uc(o);let d=gc.getForInstance(o.plugins),g=ZC(e),f=[],h=!1,y=RA(()=>o),v=null,C=null,A=null,L=!1,I=null,H=a=>{v=a,a.initApprovalUi({webMcpToolTitle:ma});let u=a.createBuiltInApprovalPlugin(l);C=u.plugin,A=u.teardown},B=()=>{if(v)return v;let a=NA();return a?(H(a),a):(DA().then(u=>{L||v||(H(u),I?.())}).catch(()=>{}),null)},V=!1,oe=!1,W=null,j=(a,u,m,b)=>{if(!a.querySelector("[data-tv-form]"))return;let w=QA();if(w){w.enhanceWithForms(a,u,m,b);return}XA().then(()=>{V||oe||!W||(oe=!0,W())}).catch(()=>{})};o.components&&Fo.registerAll(o.components);let X=ex(),T=o.persistState===!1?null:o.storageAdapter??uu(),_=!!o.clientToken&&typeof o.reconnectStream!="function",P={},J=null,U,ue=new Promise(a=>{U=a}),fe=()=>{},me=new Promise(a=>{fe=a}),He,Ee=!1,Ie=a=>{if(o.onStateLoaded)try{let u=o.onStateLoaded(a);if(u&&typeof u=="object"&&"state"in u){let{state:m,open:b}=u;return b&&(Ee=!0),m}return u}catch(u){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",u)}return a};if(T?.load)try{let a=T.load();if(a&&typeof a.then=="function")J=a.then(u=>Ie(u??{messages:[],metadata:{}}));else{let m=Ie(a??{messages:[],metadata:{}});m.metadata&&(P=wh(m.metadata)),m.messages?.length&&(o={...o,initialMessages:m.messages}),m.artifacts?.length&&(o={...o,initialArtifacts:m.artifacts,initialSelectedArtifactId:m.selectedArtifactId??null}),He=m.draft}}catch(a){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",a)}else if(o.onStateLoaded)try{let a=Ie({messages:[],metadata:{}});a.messages?.length&&(o={...o,initialMessages:a.messages})}catch(a){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",a)}J||U();let yt=()=>P,qe=a=>{P=a({...P})??{},Ji()},Oe=o.actionParsers&&o.actionParsers.length?o.actionParsers:[fc],$=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Wi.message,Wi.messageAndClick],_e=mc({parsers:Oe,handlers:$,getSessionMetadata:yt,updateSessionMetadata:qe,emit:X.emit,documentRef:typeof document<"u"?document:null});_e.syncFromMetadata();let ye=o.launcher?.enabled??!0,ut=o.launcher?.autoExpand??!1,Zt=o.autoFocusInput??!1,xt=ut,xe=ye,Wt=o.layout?.header?.layout,vt=!1,Le=()=>Rs(o),Xe=()=>ye||Le(),D=Le()?!1:ye?ut:!0,S=!1,F=null,q=()=>{S=!0,F&&clearTimeout(F),F=setTimeout(()=>{S&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),S=!1)},1e4)},K=dx(o,_e,q),te=o.features?.showReasoning??!0,ve=o.features?.showToolCalls??!0,Me=o.features?.showEventStreamToggle??!1,Ce=o.features?.scrollToBottom??{},st=o.features?.scrollBehavior??{},Ct=()=>(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-",Qe=`${Ct()}event-stream`,pn=null,Eo=o.features?.eventStream?.maxEvents??2e3,ft=null,bt=null,Ft=null,_i=!1,rn=null,Sn=!1,lo=null,Bi=0,Di=(a,u)=>{ft?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:a,timestamp:Date.now(),payload:JSON.stringify(u)})},Qa=(a,u)=>{bt?.processEvent(a,u),ft?Di(a,u):Ft&&(Ft.length>=Eo&&Ft.shift(),Ft.push({type:a,payload:u}))},cr=()=>{ft||!Me||(Ft??=[],ch().then(a=>{if(_i||ft||!Me)return;pn=new a.EventStreamStore(Qe),ft=new a.EventStreamBuffer(Eo,pn),bt=bt??new a.ThroughputTracker,pn.open().then(()=>ft?.restore()).catch(m=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",m)});let u=Ft??[];Ft=null;for(let m of u)bt?.processEvent(m.type,m.payload),Di(m.type,m.payload)}).catch(()=>{}))};Me&&cr();let un=!1,Un=null,dr=()=>{},Vn=()=>{},pr=()=>{},Uo=()=>{},Yr=()=>{},wc=()=>Sn||un&&Un==="panel",to={onCopy:a=>{X.emit("message:copy",a),R?.isClientTokenMode()&&R.submitMessageFeedback(a.id,"copy").catch(u=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",u)}),o.messageActions?.onCopy?.(a)},onFeedback:a=>{X.emit("message:feedback",a),R?.isClientTokenMode()&&R.submitMessageFeedback(a.messageId,a.type).catch(u=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",u)}),o.messageActions?.onFeedback?.(a)}},$h=o.statusIndicator??{},ur=(a,u=o.statusIndicator??{})=>a==="idle"?u.idleText??Yt.idle:a==="connecting"?u.connectingText??Yt.connecting:a==="connected"?u.connectedText??Yt.connected:a==="error"?u.errorText??Yt.error:a==="paused"?u.pausedText??Yt.paused:a==="resuming"?u.resumingText??Yt.resuming:Yt[a];function _s(a,u,m,b){if(!Le()&&(m.mode==="transient"||a.classList.contains("persona-mb-2"))&&(Tf(a,An,m),hi(a,m,b)),!(a.hasAttribute(Ya)||a.hasAttribute(yc)))if(b==="idle"&&m.idleLink){a.textContent="";let w=document.createElement("a");w.href=m.idleLink,w.target="_blank",w.rel="noopener noreferrer",w.textContent=u,w.style.color="inherit",w.style.textDecoration="none",a.appendChild(w)}else a.textContent=u}let Ln=IA({config:o,showClose:Xe()}),{wrapper:Je,panel:Ae,pillRoot:Xt}=Ln.shell,et=Ln.panelElements,{container:we,body:ae,messagesWrapper:Te,starterSuggestions:gr,transcriptSuggestions:Xr,suggestions:co,textarea:ce,sendButton:Pe,composerForm:An,statusText:tt,welcomeHost:en,welcomeIconHolder:Sc,greetingHost:Rn,introKicker:Ac,introTitle:Bu,introSubtitle:Ni,closeButton:ze,iconHolder:Ht,headerTitle:Vo,headerSubtitle:jo,header:mt,footer:Ke,actionsRow:Fi}=et,xn=et.leftActions,Bs=et.rightActions,Wn=et.sendButtonWrapper,xc=et.setSendButtonMode,he=et.micButton,gn=et.micButtonWrapper,It=et.attachmentButton,sn=et.attachmentButtonWrapper,Et=et.attachmentInput,fn=et.attachmentPreviewsContainer;we.classList.add("persona-relative"),ae.classList.add("persona-relative");let Ec=12,Qr=()=>Ce.label??"",Du=()=>Ce.iconName??"arrow-down",Nu=()=>Ce.enabled!==!1,En=()=>st.mode??"anchor-top",Mo=()=>En()==="follow"||En()==="anchor-top"&&ll,Ds=()=>st.anchorTopOffset??16,Mc=()=>st.restorePosition??"bottom",Ja=()=>st.pauseOnInteraction===!0,Za=()=>st.showActivityWhilePinned!==!1,$i=()=>st.announce===!0,Ns=()=>st.scrollbar??"on-scroll",Vt=x("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");Vt.type="button",Vt.style.display="none",Vt.setAttribute("data-persona-scroll-to-bottom","true");let Fs=x("span","persona-flex persona-items-center"),el=x("span",""),tn=x("span","");tn.setAttribute("data-persona-scroll-to-bottom-count",""),tn.style.display="none",Vt.append(Fs,el,tn),we.appendChild(Vt);let Qt=x("div","persona-stream-anchor-spacer");Qt.setAttribute("aria-hidden","true"),Qt.setAttribute("data-persona-anchor-spacer",""),Qt.style.flexShrink="0",Qt.style.pointerEvents="none",Qt.style.height="0px",Qt.style.display="none",ae.appendChild(Qt);let To=x("div","persona-sr-only");To.setAttribute("aria-live","polite"),To.setAttribute("aria-atomic","true"),To.setAttribute("role","status"),To.setAttribute("data-persona-live-region",""),Object.assign(To.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"}),we.appendChild(To);let Jr=null,fr=null,$s=a=>{!$i()||!a||(fr=a,Jr===null&&(Jr=setTimeout(()=>{Jr=null,fr&&$i()&&(To.textContent=fr),fr=null},400)))},jn=()=>{let a=e.ownerDocument.defaultView??window;return(o.launcher?.mobileFullscreen??!0)&&a.innerWidth<=(o.launcher?.mobileBreakpoint??640)&&(ye||Lt(o))||o.launcher?.fullHeight===!0&&!o.launcher.sidebarMode&&!Lt(o)},E=()=>Ua(o,jn()),N="empty",ne=0,pe=()=>ne||parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,Re=()=>{let u=Ke.style.display==="none"?0:Ke.offsetHeight;Vt.style.bottom=`${u+pe()+Ec}px`};Re();let $t=()=>{Ki||(Ke.style.marginBottom=ne>0?`${ne}px`:"")},Ot=()=>{let a=Pm(o,Le()),u=E();e.setAttribute("data-persona-welcome-fullscreen",String(jn())),e.setAttribute("data-persona-welcome-layout",u.layout??"top"),e.setAttribute("data-persona-welcome-layout-explicit",o.welcome?.layout??""),e.setAttribute("data-persona-welcome-anchor",u.anchor??"bottom");let b=Ke.style.display==="none"?0:Ke.offsetHeight,w=u.anchor==="center"&&N==="empty"?Ql(u.anchorComposerTop)??Ql("44%"):null,k=w!==null&&u.layout==="centered"&&o.welcome?.anchor===void 0&&o.welcome?.anchorComposerTop===void 0,z=k?getComputedStyle(ae):null,re=parseFloat(e.style.getPropertyValue("--persona-composer-overlay-height"))||0,Y=parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,ie=Math.max(0,(parseFloat(z?.paddingBottom??"")||0)-(a==="overlay"?re+Y:0)),le=k?ae.getBoundingClientRect().top-we.getBoundingClientRect().top:0,de=!k||en.hidden?0:(en.querySelector("[data-persona-welcome-plugin]")??en).offsetHeight,ke=w===null||Le()?0:k?Math.max(0,Math.round((we.clientHeight-le-de-ie-b)/2)):_S({columnHeight:we.clientHeight,footerHeight:b,fraction:w});e.style.setProperty("--persona-composer-overlay-height",`${b}px`),e.style.setProperty("--persona-composer-lift",`${a==="overlay"?ke:0}px`),ne=a==="block"?ke:0,$t(),Re()},_t=()=>{let a=!!Qr();Vt.setAttribute("aria-label",Qr()||"Jump to latest"),Vt.title=Qr(),Vt.setAttribute("data-persona-scroll-to-bottom-has-label",a?"true":"false"),Fs.innerHTML="";let u=ge(Du(),"14px","currentColor",2);u?(Fs.appendChild(u),Fs.style.display=""):Fs.style.display="none",el.textContent=Qr(),el.style.display=a?"":"none"};_t();let je=null,at=null,be=zw(),Ui=a=>{try{we.dispatchEvent(new CustomEvent("persona:composer:state",{detail:a,bubbles:!0,composed:!0}))}catch{}};be.subscribe(Ui);let po=()=>{be.setText(ce?.value??"")},mr=()=>{be.setMentionRefs(at?.getMentionRefs()??[])},aE=a=>({id:a.id,name:a.file.name,mimeType:a.file.type,size:a.file.size,status:a.status,progress:a.progress,error:a.error}),Uh=a=>{let u=Object.freeze(a.map(aE));be.setAttachments(u);try{o.attachments?.onChange?.(u)}catch(m){console.error("[AgentWidget] attachments.onChange failed:",m)}bg()};be.setSelectedModelId(o.composer?.selectedModelId);let tl=()=>o.composer?.modes??[],Vi=()=>lS(tl(),o.composer?.modeGroups);{let a=Dp(o.composer?.defaultActiveModeIds??[],tl());a.length&&be.setActiveModeIds(a)}function Vh(a){if(be.getState().selectedModelId!==a){be.setSelectedModelId(a),Zr?.repaint();try{o.composer?.onModelChange?.(a)}catch(u){console.error("[AgentWidget] composer.onModelChange failed:",u)}}}function Tc(a){be.setActiveModeIds(a),hr?.render(a,Vi()),ji.forEach(u=>u.repaint()),Po?.resolve(),ed(),ko()}function Fu(a){Tc(cS(be.getState().activeModeIds,a,tl(),o.composer?.modeGroups))}let Zr=null,$u=null,hr=null,ji=new Map,es=null;function qo(a){be.setQuote(a),es?.render(be.getState().quote),ko(),_y()}let jh=!1;function Uu(){let a=o.composer?.streamingSubmitBehavior??"block";return a!=="interrupt"?a:o.clientToken?"interrupt":(!jh&&o.debug===!0&&(jh=!0,typeof console<"u"&&console.warn('[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".')),"block")}let ts=null;function qi(a){be.setPendingSubmission(a),ts?.render(be.getState().pendingSubmission),ko()}let lE=a=>{let u=ji.get(a);if(u)return u;let m=uS({groupId:a,getGroup:()=>o.composer?.modeGroups?.find(b=>b.id===a),getModes:()=>tl().filter(b=>b.groupId===a),getActiveIds:()=>be.getState().activeModeIds,onSelect:b=>Fu(b)});return ji.set(a,m),m},cE=()=>{let a=[],u=be.getState().activeModeIds,m=new Set;if(tl().forEach((b,w)=>{if(Bp(b.groupId,o.composer?.modeGroups)){let k=b.groupId;if(m.has(k))return;m.add(k);let z=lE(k);z.action.order=Sm(w),z.action.label=o.composer?.modeGroups?.find(re=>re.id===k)?.label??k,a.push(z.action);return}a.push({id:iS(b.id),kind:"button",placement:"start",order:Sm(w),presentation:b.presentation??"auto",label:b.label,shortLabel:b.shortLabel,iconName:b.iconName,pressed:u.includes(b.id),onSelect:()=>Fu(b.id)})}),o.composer?.models?.length&&!d.some(b=>b.renderComposer)){let b=o.composer?.modelPicker?.presentation??"native";(!Zr||$u!==b)&&($u=b,Zr=rS({getModels:()=>o.composer?.models??[],getSelectedModelId:()=>be.getState().selectedModelId,onSelect:w=>Vh(w),presentation:b,getSuffix:()=>o.composer?.modelPicker?.suffix})),a.push(Zr.action)}return a},Vu=null,qh=d.find(a=>a.renderHeader);if(qh?.renderHeader){let a=qh.renderHeader({config:o,defaultRenderer:()=>{let u=jr({config:o,showClose:Xe()});return Ti(we,u,o),u.header},onClose:()=>Mt(!1,"user")});if(a){let u=mt;u&&(u.replaceWith(a),mt=a,Ln.header.element=a)}}let zh=()=>{rn&&(ae.style.display="none",Ke.parentNode?.insertBefore(rn.element,Ke),rn.update())},ju=()=>{if(!ft){cr();return}if(Sn=!0,rn?zh():ch().then(u=>{rn||!Sn||!ft||(rn=u.createEventStreamView({buffer:ft,getFullHistory:()=>ft.getAllFromStore(),onClose:()=>zi(),config:o,plugins:d,getThroughput:()=>bt?.getMetric()??{status:"idle"},renderIconByName:ge}),zh())}).catch(()=>{zi()}),ht){ht.style.boxShadow=`inset 0 0 0 1.5px ${Nn.actionIconColor}`;let u=o.features?.eventStream?.classNames?.toggleButtonActive;u&&u.split(/\s+/).forEach(m=>m&&ht.classList.add(m))}let a=()=>{if(!Sn)return;let u=Date.now();u-Bi>=200&&(rn?.update(),Bi=u),lo=requestAnimationFrame(a)};Bi=0,lo=requestAnimationFrame(a),Tn(),X.emit("eventStream:opened",{timestamp:Date.now()})},zi=()=>{if(Sn){if(Sn=!1,rn&&rn.element.remove(),ae.style.display="",ht){ht.style.boxShadow="";let a=o.features?.eventStream?.classNames?.toggleButtonActive;a&&a.split(/\s+/).forEach(u=>u&&ht.classList.remove(u))}lo!==null&&(cancelAnimationFrame(lo),lo=null),Tn(),X.emit("eventStream:closed",{timestamp:Date.now()})}},ht=null;if(Me){let a=o.features?.eventStream?.classNames,u="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"+(a?.toggleButton?" "+a.toggleButton:"");ht=x("button",u),ht.style.width="28px",ht.style.height="28px",ht.style.color=Nn.actionIconColor,ht.type="button",ht.setAttribute("aria-label","Event Stream"),ht.title="Event Stream";let m=Nt(Kr.Activity,"18px","currentColor",1.5);m&&ht.appendChild(m);let b=et.clearChatButtonWrapper,w=et.closeButtonWrapper,k=b||w;k&&k.parentNode===mt?mt.insertBefore(ht,k):mt.appendChild(ht),ht.addEventListener("click",()=>{Sn?zi():ju()})}let Kh=a=>{let u=o.attachments;if(!u?.enabled)return;let m=a.querySelector("[data-persona-composer-attachment-previews]")??a.querySelector(".persona-attachment-previews");if(!m){m=x("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),m.setAttribute("data-persona-composer-attachment-previews",""),m.style.display="none";let w=a.querySelector("[data-persona-composer-form]");w?.parentNode?w.parentNode.insertBefore(m,w):a.insertBefore(m,a.firstChild)}if(!(a.querySelector("[data-persona-composer-attachment-input]")??a.querySelector('input[type="file"]'))){let w=x("input");w.type="file",w.setAttribute("data-persona-composer-attachment-input",""),w.accept=(u.allowedTypes??Dr).join(","),w.multiple=(u.maxFiles??4)>1,w.style.display="none",w.setAttribute("aria-label",u.buttonTooltipText??"Attach files"),a.appendChild(w)}},Ki=!1,Gh=a=>{let u=d.find(w=>w.renderComposer);if(!u?.renderComposer)return null;let m=o.composer,b=h?R.isStreaming():!1;return u.renderComposer({config:o,defaultRenderer:a,requestRender:()=>qb(),storage:y(u.id),onSubmit:w=>{!R||R.isStreaming()||cd(w.trim(),{consumeDraft:!1})},streaming:b,disabled:b,openAttachmentPicker:()=>{Yo()||Et?.click()},models:m?.models,selectedModelId:be.getState().selectedModelId??m?.selectedModelId,onModelChange:w=>Vh(w),onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{Vu?.()}:void 0})},Yh=Gh(()=>ki({config:o}).footer);Yh&&(Ln.replaceComposer(Yh),Ke=Ln.composer.footer,Ki=!0);let ct=null,dE=a=>{An=a.form,ce=a.input,Wn=a.sendButton?a.sendButton.parentElement:null,a.sendButton&&(Pe=a.sendButton),a.micButton&&(he=a.micButton,gn=a.micButton.parentElement),a.found.status&&(tt=a.found.status),a.found.suggestions&&(co=a.found.suggestions),a.attachmentButton&&(It=a.attachmentButton,sn=a.attachmentButton.parentElement),Et=a.attachmentInput??null,fn=a.attachmentPreviews??null,a.found.actionsRow&&(Fi=a.found.actionsRow),xn=a.found.actionsStart,Bs=a.found.actionsEnd};function qu(){let a=ce;if(!a)return;let u=o.composer?.inputAttributes,m=!u?.ariaLabel&&!(a instanceof HTMLTextAreaElement)?a.getAttribute("aria-label"):null;Zd(a,u),m&&a.setAttribute("aria-label",m),Jd(a,{submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:Bl(a)}),OC(a,Qd(o.composer?.maxLines,Le()?5:3))}let Xh=a=>{ct=Gw(a,{debug:o.debug===!0}),ct&&dE(ct),qu()};Kh(Ke),Xh(Ke),po();let nl=Hs(o,Le());nl&&(Te.style.maxWidth=nl,Te.style.marginLeft="auto",Te.style.marginRight="auto",Te.style.width="100%",Rn.style.maxWidth=nl,Rn.style.marginLeft="auto",Rn.style.marginRight="auto",Rn.style.width="100%",gr.style.maxWidth=nl,Xr.style.maxWidth=nl,Xr.style.marginLeft="auto",Xr.style.marginRight="auto",Xr.style.width="100%");let Qh=()=>{let a=Hs(o,Le());if(!(!a||Le()))for(let u of[An,co,fn,tt])u&&(u.style.maxWidth=a,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%")};Qh();let Jh=()=>{!o.attachments?.enabled||!Et||!fn||(je?je.remountPreviews(fn):(je=Ai.fromConfig(o.attachments,Uh),je.setPreviewsContainer(fn)),ct?.addListener(Et,"change",a=>{let u=a.target;je?.handleFileSelect(u.files),u.value=""}),we.querySelector(".persona-attachment-drop-overlay")||we.appendChild(px(o.attachments.dropOverlay)))};Jh();let pE=()=>at?.prefetch(),zu=()=>{if(!o.contextMentions?.enabled||!ce)return;let a=Gf();if(!a){let b=ce;pp().then(()=>{at||ce!==b||!b.isConnected||(zu(),Po?.resolve())},()=>{});return}let u=ct?.header??null,m=u?wm(u):void 0;if(at=a.createContextMentionOrchestrator({deps:{loadContextMentions:lp,loadContextMentionsInline:cp,renderLucideIcon:ge,createMentionButton:ap},config:o,textarea:ce,anchor:An??ce,getMessages:()=>R.getMessages(),liveRegionHost:we,chipRow:m}),at&&!m){let b=ce;b.parentElement?.insertBefore(at.contextRow,b)}};zu();let Po=null,uE={getState:()=>be.getState(),getValue:()=>ce?.value??"",setValue:a=>{ce&&(ce.value=a,ce.dispatchEvent(new Event("input",{bubbles:!0})),po())},submit:()=>{SS(ct?.form??null)},openAttachmentPicker:()=>{Yo()||Et?.click()},toggleVoice:()=>{Vu?.()},requestRender:()=>Po?.resolve()},gE=()=>{let a=[];return(at?.affordanceButtons??[]).forEach((m,b)=>{a.push({id:`core:mention-${b}`,placement:"start",order:sr.mention+b,element:m,managed:!0})}),sn&&a.push({id:"core:attachment",placement:"start",order:sr.attachment,element:sn}),gn&&a.push({id:"core:mic",placement:"end",order:sr.mic,element:gn}),Wn&&a.push({id:"core:send",placement:"end",order:sr.send,element:Wn}),a},Zh=()=>{Po?.destroy(),Po=tS({getBindings:()=>ct,collect:()=>({builtIns:gE(),configActions:[...cE(),...o.composer?.actions??[]],plugins:d,contributionContext:{config:o,getState:()=>be.getState(),requestRender:()=>Po?.resolve()},debug:o.debug===!0}),actionContext:uE,getState:()=>be.getState(),getOverflow:()=>o.composer?.actionOverflow,reportError:(a,u)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${u.actionId}" failed:`,a)}}),Po.resolve()};Zh();let Ku=()=>{if(hr?.destroy(),hr=null,!Vi().length)return;let a=ct?.header;a&&(hr=sS({row:wm(a),onRemove:u=>Fu(u),initialIds:be.getState().activeModeIds}),hr.render(be.getState().activeModeIds,Vi()))};Ku();let ey=()=>{es?.destroy(),es=null,ts?.destroy(),ts=null;let a=ct?.header;a&&(es=gS({onDismiss:()=>qo(void 0)}),a.appendChild(es.element),es.render(be.getState().quote),Uu()==="defer-one"&&(ts=fS({onEdit:()=>cM(),onRemove:()=>qi(void 0)}),a.appendChild(ts.element),ts.render(be.getState().pendingSubmission)))};ey();let Gu=CS(),fE=()=>{let a=ct?.header?.querySelector(Cm);if(a)return a.childElementCount>0;let u=be.getState();return u.mentionRefs.length>0||Dp(u.activeModeIds,Vi()).length>0};function ko(){let a=be.getState(),u=Gu.observe(wS(ce),a.text);Ke.toggleAttribute("data-persona-composer-compact",vS({text:a.text,wrapped:u,hasAttachments:a.attachments.length>0,hasChips:fE(),hasQuote:a.quote!==void 0,hasPendingSubmission:a.pendingSubmission!==void 0}))}function ty(){o.composer?.layout==="single-row"&&!Le()?Ke.setAttribute("data-persona-composer-layout","single-row"):Ke.removeAttribute("data-persona-composer-layout")}ty(),be.subscribe(()=>{Po?.sync(),bg(),Qc(),ko(),_y()}),Qc();let ny=!1,mE=a=>{if(ny||o.debug!==!0)return;let u=["messages","composer"].filter(m=>a[m]);u.length&&(ny=!0,console.warn(`[persona] layout.slots.${u.join(" and layout.slots.")} ${u.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 a=o.layout?.slots??{};mE(a);let u=b=>{switch(b){case"body-top":return ae.querySelector("[data-persona-intro-card]");case"messages":return Te;case"footer-top":return co;case"composer":return An;case"footer-bottom":return tt;default:return null}},m=(b,w)=>{switch(b){case"header-left":case"header-center":case"header-right":if(b==="header-left")mt.insertBefore(w,mt.firstChild);else if(b==="header-right")mt.appendChild(w);else{let k=mt.querySelector(".persona-flex-col");k?k.parentNode?.insertBefore(w,k.nextSibling):mt.appendChild(w)}break;case"body-top":{let k=ae.querySelector("[data-persona-intro-card]");k?k.replaceWith(w):ae.insertBefore(w,ae.firstChild);break}case"body-bottom":ae.appendChild(w);break;case"footer-top":co.replaceWith(w);break;case"footer-bottom":tt.replaceWith(w);break;default:break}};for(let[b,w]of Object.entries(a))if(w)try{let k=w({config:o,defaultContent:()=>u(b)});k&&m(b,k)}catch(k){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${b}":`,k)}})(),Te.addEventListener("click",a=>{let u=a.target;if(!(u instanceof Element))return;let m=u.closest("button[data-persona-copy-tool-detail]");m&&(a.preventDefault(),a.stopPropagation(),_A(m))});let Yu=a=>{let m=a.target.closest('button[data-expand-header="true"]');if(!m)return;let b=m.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!b)return;let w=b.getAttribute("data-message-id");if(!w)return;is(),ta();let k=m.getAttribute("data-bubble-type");if(b.classList.contains("persona-activity-row")){i.manual(w);let z=b.parentElement?.closest("[data-persona-tool-group]");z?.dataset.messageId&&i.manual(z.dataset.messageId)}if(k==="reasoning")s.has(w)?s.delete(w):s.add(w),oh(w,b,s);else if(k==="tool")r.has(w)?r.delete(w):r.add(w),ah(w,b,r,o);else if(k==="approval"&&v){let re=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",Y=l.get(w)??re;l.set(w,!Y),v.updateApprovalDetailsUI(w,b,o,l)}Mn.delete(w)};Te.addEventListener("pointerdown",a=>{a.target.closest('button[data-expand-header="true"]')&&(a.preventDefault(),Yu(a))}),Te.addEventListener("click",a=>{a.detail===0&&a.target.closest(".persona-activity-row")&&Yu(a)}),Te.addEventListener("keydown",a=>{let u=a.target;(a.key==="Enter"||a.key===" ")&&u.closest('button[data-expand-header="true"]')&&(a.preventDefault(),Yu(a))}),Te.addEventListener("copy",a=>{let{clipboardData:u}=a;if(!u)return;let m=Te.getRootNode(),b=typeof m.getSelection=="function"?m.getSelection():window.getSelection();if(!b||b.isCollapsed)return;let w=b.toString(),k=DS(w);!k||k===w||(u.setData("text/plain",k),a.preventDefault())});let Xu=new Map,oy=null,ry="idle",hE={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},yE=(a,u)=>{let{icon:m,label:b}=hE[u];a.setAttribute("aria-label",b),a.title=b,a.setAttribute("aria-pressed",u==="idle"?"false":"true"),a.classList.toggle("persona-message-action-active",u!=="idle"),a.classList.toggle("persona-message-action-loading",u==="loading");let w=ge(m,14,"currentColor",2);w&&(a.innerHTML="",a.appendChild(w))},sy=()=>{Te.querySelectorAll('[data-action="read-aloud"]').forEach(u=>{let b=u.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;yE(u,b&&b===oy?ry:"idle")})};Te.addEventListener("click",a=>{let m=a.target.closest(".persona-message-action-btn[data-action]");if(!m)return;a.preventDefault(),a.stopPropagation();let b=m.closest("[data-actions-for]");if(!b)return;let w=b.getAttribute("data-actions-for");if(!w)return;let k=m.getAttribute("data-action");if(k==="copy"){let re=R.getMessages().find(Y=>Y.id===w);if(re&&to.onCopy){let Y=re.content||"";navigator.clipboard.writeText(Y).then(()=>{m.classList.add("persona-message-action-success");let ie=Nt(Kr.Check,14,"currentColor",2);ie&&(m.innerHTML="",m.appendChild(ie)),setTimeout(()=>{m.classList.remove("persona-message-action-success");let le=Nt(Kr.Copy,14,"currentColor",2);le&&(m.innerHTML="",m.appendChild(le))},2e3)}).catch(ie=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",ie)}),to.onCopy(re)}}else if(k==="read-aloud")R.toggleReadAloud(w);else if(k==="upvote"||k==="downvote"){let re=(Xu.get(w)??null)===k,Y=k==="upvote"?"thumbs-up":"thumbs-down";if(re){Xu.delete(w),m.classList.remove("persona-message-action-active");let ie=ge(Y,14,"currentColor",2);ie&&(m.innerHTML="",m.appendChild(ie))}else{let ie=k==="upvote"?"downvote":"upvote",le=b.querySelector(`[data-action="${ie}"]`);if(le){le.classList.remove("persona-message-action-active");let dt=ge(ie==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);dt&&(le.innerHTML="",le.appendChild(dt))}Xu.set(w,k),m.classList.add("persona-message-action-active");let de=ge(Y,14,"currentColor",2);de&&(de.setAttribute("fill","currentColor"),m.innerHTML="",m.appendChild(de)),m.classList.remove("persona-message-action-pop"),m.offsetWidth,m.classList.add("persona-message-action-pop");let it=R.getMessages().find(gt=>gt.id===w);it&&to.onFeedback&&to.onFeedback({type:k,messageId:it.id,message:it})}}else if(k==="regenerate")Pc?.regenerate(w);else if(k==="edit")Pc?.edit(w);else if(k==="quote")Pc?.quote(w);else if(k?.startsWith(ou)){let z=k.slice(ou.length),re=o.messageActions?.custom?.find(ie=>ie.id===z),Y=R.getMessages().find(ie=>ie.id===w);if(!re||!Y)return;try{re.onSelect(Y)}catch(ie){console.error(`[AgentWidget] messageActions.custom "${z}" onSelect failed:`,ie)}}});let Pc=null;Te.addEventListener("click",a=>{let m=a.target.closest("button[data-approval-action]");if(!m)return;a.preventDefault(),a.stopPropagation();let b=m.closest(".persona-approval-bubble");if(!b)return;let w=b.getAttribute("data-message-id");if(!w)return;let k=m.getAttribute("data-approval-action");if(!k)return;let z=k==="approve"?"approved":"denied",Y=R.getMessages().find(le=>le.id===w);if(!Y?.approval)return;let ie=b.querySelector("[data-approval-buttons]");ie&&ie.querySelectorAll("button").forEach(de=>{de.disabled=!0,de.style.opacity="0.5",de.style.cursor="not-allowed"}),Y.approval.toolType==="webmcp"?R.resolveWebMcpApproval(w,z):R.resolveApproval(Y.approval,z)});let nt=null,iy=!1,ol=null,Us=()=>{},rl="none",kc=null,uo={artifacts:[],selectedId:null},yr=!1,Lo=!1,sl=!1,Gi=!1,ay=()=>Gi||uo.artifacts.some(a=>or(o.features?.artifacts,a)==="panel"),Lc=()=>uo.artifacts.length>0&&!yr&&ay(),go={current:null},Qu=(a,u)=>{let m=R.getArtifactById(u),b=m?.markdown,w=m?.title||"artifact",k=m?.file,z=m?.artifactType??"markdown";if(!b){let ie=a.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(ie){let de=R.getMessages().find(ke=>ke.id===ie);if(de?.rawContent)try{let ke=JSON.parse(de.rawContent);b=ke?.props?.markdown,w=ke?.props?.title||w,ke?.props?.file&&typeof ke.props.file=="object"&&(k=ke.props.file),!m&&typeof ke?.props?.artifactType=="string"&&(z=ke.props.artifactType)}catch{}}}return{markdown:b,title:w,file:k,artifactType:z}};Te.addEventListener("click",a=>{let m=a.target.closest("[data-download-artifact]");if(!m)return;a.preventDefault(),a.stopPropagation();let b=m.getAttribute("data-download-artifact");if(!b||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:b})===!0)return;let{markdown:k,title:z,file:re}=Qu(m,b);if(!k)return;let Y=qr();Y&&Y.triggerArtifactDownload(Y.downloadInfoFor({title:z,markdown:k,file:re}))}),Te.addEventListener("click",a=>{let m=a.target.closest("[data-artifact-custom-action]");if(!m)return;a.preventDefault(),a.stopPropagation();let b=m.getAttribute("data-artifact-custom-action");if(!b)return;let w=m.closest("[data-artifact-inline]"),k=w?null:m.closest("[data-open-artifact]"),z=w?w.getAttribute("data-artifact-inline"):k?.getAttribute("data-open-artifact")??null,Y=(w?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(gt=>gt.id===b);if(!Y)return;let{markdown:ie,title:le,file:de,artifactType:ke}=Qu(m,z??""),it={artifactId:z,title:le,artifactType:ke,markdown:ie,file:de};try{Promise.resolve(Y.onClick(it)).catch(()=>{})}catch{}}),Te.addEventListener("click",a=>{let m=a.target.closest("[data-copy-artifact]");if(!m)return;a.preventDefault(),a.stopPropagation();let b=m.getAttribute("data-copy-artifact");if(!b)return;let w=R.getArtifactById(b),k=qr();if(!k)return;let z="";if(w)z=k.artifactCopyText(w);else{let{markdown:re,file:Y,artifactType:ie}=Qu(m,b);ie==="markdown"&&(z=k.artifactCopyText({id:b,artifactType:"markdown",status:"complete",markdown:re??"",...Y?{file:Y}:{}}))}z&&navigator.clipboard.writeText(z).then(()=>{let re=Nt(Kr.Check,16,"currentColor",2);re&&(m.replaceChildren(re),setTimeout(()=>{let Y=Nt(Kr.Copy,16,"currentColor",2);Y&&m.replaceChildren(Y)},1500))}).catch(()=>{})}),Te.addEventListener("click",a=>{let m=a.target.closest("[data-expand-artifact-inline]");if(!m)return;a.preventDefault(),a.stopPropagation();let b=m.getAttribute("data-expand-artifact-inline");!b||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:b})===!0||(yr=!1,Gi=!0,Lo=!0,sl=!0,R.selectArtifact(b),Ho())}),Te.addEventListener("click",a=>{let u=a.target;if(u.closest("[data-download-artifact]")||u.closest("[data-artifact-custom-action]"))return;let m=u.closest("[data-open-artifact]");if(!m)return;let b=m.getAttribute("data-open-artifact");!b||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:b})===!0||(a.preventDefault(),a.stopPropagation(),yr=!1,Gi=!0,R.selectArtifact(b),Ho())}),Te.addEventListener("keydown",a=>{if(a.key!=="Enter"&&a.key!==" ")return;let u=a.target;!u.hasAttribute("data-open-artifact")&&!u.hasAttribute("data-expand-artifact-inline")||(a.preventDefault(),u.click())});let il=et.composerOverlay,Ju=a=>{pp().catch(()=>{}),Wd(a,o,il)},ly=null,bE={mount:e,overlay:il,sessionRef:go,config:()=>o},Hc=!1,cy=a=>u=>{let m=u.target,b=m?.closest?.("[data-persona-ask-sheet-for]");if(!b||!(a==="click"?!!m?.closest("[data-ask-user-action]"):u.key==="Enter"&&!!m?.matches?.('[data-ask-free-text-input="true"]')))return;let k=re=>{ly??=re.createAskUserSheetHandlers(bE),ly[a](u)},z=Gf();if(z){k(z);return}Hc||(Hc=!0,pp().then(re=>{Hc=!1,b.isConnected&&k(re)},()=>{Hc=!1}))};il.addEventListener("click",cy("click")),il.addEventListener("keydown",cy("keydown"));let dy=a=>{if(!/^[1-9]$/.test(a.key)||a.metaKey||a.ctrlKey||a.altKey)return;let u=a.target;if(u?.tagName==="INPUT"||u?.tagName==="TEXTAREA"||u?.isContentEditable)return;let m=il.querySelector("[data-persona-ask-sheet-for]");if(!m||m.getAttribute("data-ask-layout")!=="rows"||m.getAttribute("data-multi-select")==="true")return;let b=Number(a.key),k=m.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[b-1];k&&(a.preventDefault(),k.click())};document.addEventListener("keydown",dy);let br=null,Ut=null,al=null,Ic=null,Rc=()=>{},py=!1,Wc="",Oc="";function Zu(){Ic?.(),Ic=null}let vE=()=>{let a=Bt?.railShell?Bt.railHost:null,u=a?.isConnected?a:null,m=u?u.getBoundingClientRect().width:0;return m<=0?200:m+360},uy=()=>{if(!br||!Ut)return;let a=e.classList.contains("persona-artifact-welded-split"),u=e.ownerDocument.defaultView??window,m=u.innerWidth<=640;if(!a||e.classList.contains("persona-artifact-narrow-host")||m){Ut.style.removeProperty("position"),Ut.style.removeProperty("left"),Ut.style.removeProperty("top"),Ut.style.removeProperty("bottom"),Ut.style.removeProperty("width"),Ut.style.removeProperty("z-index");return}let b=br.firstElementChild;if(!b||b===Ut)return;let w=10;Ut.style.position="absolute",Ut.style.top="0",Ut.style.bottom="0",Ut.style.width=`${w}px`,Ut.style.zIndex="5";let k=bh(br,u),z=b.offsetWidth+k/2-w/2;Ut.style.left=`${Math.max(0,z)}px`},_c=()=>{},gy=()=>{let a=e.ownerDocument.defaultView??window,u=o.launcher?.mobileFullscreen??!0,m=o.launcher?.mobileBreakpoint??640;return!u||a.innerWidth>m?!1:ye||Lt(o)},Bc=()=>!$n(o)||!Lc()||e.classList.contains("persona-artifact-narrow-host")||gy()||(e.ownerDocument.defaultView??window).innerWidth<rH?"none":fh(o)?"detached":"welded",Ho=()=>{if(!nt||!$n(o))return;dc(e,o),pc(e,o),_c();let a=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,u=Ae.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",u>0&&u<=a);let m=Lc();nt.setVisible(m),nt.update(uo),yr?(nt.setMobileOpen(!1),nt.element.classList.add("persona-hidden"),nt.backdrop?.classList.add("persona-hidden"),Lo=!1,sl=!1):uo.artifacts.length>0&&ay()?(nt.element.classList.remove("persona-hidden"),nt.setMobileOpen(!0)):(nt.setMobileOpen(!1),nt.element.classList.add("persona-hidden"),nt.backdrop?.classList.add("persona-hidden"),Lo=!1,sl=!1);let b=o.features?.artifacts?.layout?.showExpandToggle===!0;if(nt.setExpandToggleVisible(b),nt.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),nt.setRefreshButtonVisible(typeof o.features?.artifacts?.layout?.onDocumentToolbarRefresh=="function"),nt.setCustomActions(o.features?.artifacts?.toolbarActions??[]),nt.setTabFade(o.features?.artifacts?.layout?.tabFade),nt.setRenderTabBar(o.features?.artifacts?.renderTabBar),!b&&!sl&&(Lo=!1),Lo!==py){let k=nt.element;Lo?(Wc=k.style.width,Oc=k.style.maxWidth,k.style.removeProperty("width"),k.style.removeProperty("max-width")):(Wc&&(k.style.width=Wc),Oc&&(k.style.maxWidth=Oc),Wc="",Oc=""),py=Lo}e.classList.toggle("persona-artifact-expanded",Lo),nt.setExpanded(Lo);let w=Bc();w!==rl&&(rl=w,Us()),Rc()};if($n(o)){Ae.style.position="relative";let a=x("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),u=x("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");a.appendChild(we),br=u,u.appendChild(a),Ae.appendChild(u);let m=w=>{iy||nt||(nt=w.createArtifactPane(o,{onSelect:k=>go.current?.selectArtifact(k),onDismiss:()=>{yr=!0,Ho()},onToggleExpand:()=>{let k=!Lo,z=uo.selectedId??uo.artifacts[uo.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:z,expanded:k})!==!0&&(Lo=k,k||(sl=!1),Ho())}}),nt.element.classList.add("persona-hidden"),u.appendChild(nt.element),nt.backdrop&&Ae.appendChild(nt.backdrop),Rc(),Ho())},b=qr();b?m(b):(uh(()=>{let w=qr();w&&m(w)}),lu().catch(()=>{})),Rc=()=>{if(!br||!nt)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){al?.(),al=null,Zu(),Ut&&(Ut.remove(),Ut=null),nt.element.style.removeProperty("width"),nt.element.style.removeProperty("maxWidth");return}if(!Ut){let k=x("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 z=e.ownerDocument,re=z.defaultView??window,Y=ie=>{if(!nt||ie.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||re.innerWidth<=640)return;ie.preventDefault(),Zu();let le=ie.clientX,de=nt.element.getBoundingClientRect().width,ke=o.features?.artifacts?.layout,it=dt=>{let Kn=br.getBoundingClientRect().width,Dt=e.classList.contains("persona-artifact-welded-split"),jt=bh(br,re),_n=Dt?0:k.getBoundingClientRect().width||6,Kt=de-(dt.clientX-le),wt=YA(Kt,Kn,jt,_n,ke?.resizableMinWidth,ke?.resizableMaxWidth,vE());nt.element.style.width=`${wt}px`,nt.element.style.maxWidth="none",uy()},gt=()=>{z.removeEventListener("pointermove",it),z.removeEventListener("pointerup",gt),z.removeEventListener("pointercancel",gt),Ic=null;try{k.releasePointerCapture(ie.pointerId)}catch{}};Ic=gt,z.addEventListener("pointermove",it),z.addEventListener("pointerup",gt),z.addEventListener("pointercancel",gt);try{k.setPointerCapture(ie.pointerId)}catch{}};k.addEventListener("pointerdown",Y),Ut=k,br.insertBefore(k,nt.element),al=()=>{k.removeEventListener("pointerdown",Y)}}if(Ut){let k=Lc();Ut.classList.toggle("persona-hidden",!k),uy()}},_c=()=>{if(!ye||!nt||(o.launcher?.sidebarMode??!1)||Lt(o)&&Zn(o).reveal==="emerge")return;let k=e.ownerDocument.defaultView??window,z=o.launcher?.mobileFullscreen??!0,re=o.launcher?.mobileBreakpoint??640;if(z&&k.innerWidth<=re||!VA(o,ye))return;let Y=Hi(o).width,ie=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";Lc()?(Ae.style.width=ie,Ae.style.maxWidth=ie):(Ae.style.width=Y,Ae.style.maxWidth=Y)},typeof ResizeObserver<"u"&&(ol=new ResizeObserver(()=>{Ho()}),ol.observe(Ae))}else Ae.appendChild(we);Le()&&Xt&&(et.peekBanner&&Xt.appendChild(et.peekBanner),Xt.appendChild(Ke)),e.appendChild(Je),Xt&&e.appendChild(Xt);let eg=()=>{let a=gy()||Le()&&o.launcher?.composerBar?.expandedSize==="fullscreen"||o.launcher?.fullHeight===!0&&!o.launcher?.sidebarMode&&!Lt(o);if(Te.style.gap=a?"var(--persona-components-message-fullscreenGap, var(--persona-components-message-gap, 12px))":"var(--persona-components-message-gap, 12px)",Te.style.setProperty("--persona-transcript-gap",Te.style.gap),Le()){Ae.style.width="100%",Ae.style.maxWidth="100%";let Be=o.launcher?.composerBar??{},Ye=Je.dataset.state==="expanded",Ue=Be.expandedSize??"anchored";if(!(Ye&&Ue!=="fullscreen")){we.style.background="",we.style.border="",we.style.borderRadius="",we.style.overflow="",we.style.boxShadow="";return}let nn=o.theme?.components?.panel,Gn=No(o),Pr=(kr,ci)=>kr==null||kr===""?ci:wn(Gn,kr)??kr,Jg="1px solid var(--persona-border)",li="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Zg="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";we.style.background="var(--persona-surface, #ffffff)",we.style.border=Pr(nn?.border,Jg),we.style.borderRadius=Pr(nn?.borderRadius,Zg),we.style.boxShadow=Pr(nn?.shadow,li),we.style.overflow="hidden";return}let u=Lt(o),m=o.launcher?.sidebarMode??!1,b=u||m||(o.launcher?.fullHeight??!1),w=o.launcher?.enabled===!1,k=o.launcher?.detachedPanel===!0,z=o.theme?.components?.panel,re=o.darkTheme?.components?.panel,Y=xi(o)==="dark"?Bo(z??{},re??{}):z,ie=No(o),le=(Be,Ye)=>Be==null||Be===""?Ye:wn(ie,Be)??Be,de=e.ownerDocument.defaultView??window,ke=o.launcher?.mobileFullscreen??!0,it=o.launcher?.mobileBreakpoint??640,gt=de.innerWidth<=it,dt=ke&>&&ye,Kn=u&&ke&>,Dt=o.launcher?.position??"bottom-left",jt=Dt==="bottom-left"||Dt==="top-left",_n=o.launcher?.zIndex??kn,Kt=(Be,Ye,Ue)=>`var(--persona-components-panel-modes-${Be}-${Ye}, ${Ue})`,wt=Y?.modes?.floating,Jo=le(wt?.border??Y?.border,Kt("floating","border","var(--persona-panel-border, 1px solid var(--persona-border))")),Zo=le(wt?.shadow??Y?.shadow,Kt("floating","shadow","var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))")),bo=le(wt?.borderRadius??Y?.borderRadius,Kt("floating","borderRadius","var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))")),vo=k&&!dt&&!Kn,fs=dt||Kn?"mobile":vo?"floating":u?"docked":m?"sidebar":w?"inline":"floating",er=Y?.modes?.[fs];vo?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let Io=vo?Jo:m||dt?"none":Jo,ms=vo?Zo:dt?"none":m?jt?"2px 0 12px rgba(0, 0, 0, 0.08)":"-2px 0 12px rgba(0, 0, 0, 0.08)":w?"none":Zo;u&&!dt&&!vo&&(ms="none",Io="none");let xl=vo?bo:m||dt?"0":bo,ai=le(er?.border??Y?.border,Kt(fs,"border",Io)),O=le(er?.shadow??Y?.shadow,Kt(fs,"shadow",ms)),Ne=le(er?.borderRadius??Y?.borderRadius,Kt(fs,"borderRadius",xl)),Fe=Bc(),se=Fe==="detached",St=Fe==="welded";e.classList.toggle("persona-artifact-detached-split",se),e.classList.toggle("persona-artifact-welded-split",St);let Jt="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)))))",Tt=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&$n(o)&&fh(o)&&w&&!u;e.classList.toggle("persona-artifact-chat-flush",Tt);let Gt=se||Tt?"none":O,ln=se?Jo:St?"none":ai,We=se?bo:Ne;Tt&&(ln="none",We="0");let Pt=er?.borderRadius!=null&&er.borderRadius!==""||Y?.borderRadius!=null&&Y.borderRadius!=="",$e=Tt&&!Pt?"0":Ne,cn=ae.scrollTop;e.style.cssText="",Je.style.cssText="",Ae.style.cssText="",we.style.cssText="",ae.style.cssText="",Ki||(Ke.style.cssText=""),Sn&&(ae.style.display="none"),(b||w)&&(e.style.minWidth="0");let Co=()=>{if(cn<=0)return;(ae.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(ae.scrollTop===cn)return;let Ye=ae.scrollHeight-ae.clientHeight;Ye<=0||(ae.scrollTop=Math.min(cn,Ye))})};if(dt){Je.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"),Je.style.cssText=`
|
|
47
47
|
position: fixed !important;
|
|
48
48
|
inset: 0 !important;
|
|
49
49
|
width: 100% !important;
|
|
@@ -53,7 +53,7 @@ _Details: ${n.message}_`:o}var Fw=e=>bs(e)||e===Oo,Wa=class e{constructor(t={},n
|
|
|
53
53
|
padding: 0 !important;
|
|
54
54
|
display: flex !important;
|
|
55
55
|
flex-direction: column !important;
|
|
56
|
-
z-index: ${
|
|
56
|
+
z-index: ${_n} !important;
|
|
57
57
|
background-color: var(--persona-surface, #ffffff) !important;
|
|
58
58
|
`,Ae.style.cssText=`
|
|
59
59
|
position: relative !important;
|
|
@@ -79,31 +79,31 @@ _Details: ${n.message}_`:o}var Fw=e=>bs(e)||e===Oo,Wa=class e{constructor(t={},n
|
|
|
79
79
|
overflow: hidden !important;
|
|
80
80
|
border-radius: 0 !important;
|
|
81
81
|
border: none !important;
|
|
82
|
-
`,ae.style.flex="1 1 0%",ae.style.minHeight="0",ae.style.overflowY="auto",Ke.style.flexShrink="0",$t(),vt=!0,
|
|
82
|
+
`,ae.style.flex="1 1 0%",ae.style.minHeight="0",ae.style.overflowY="auto",Ke.style.flexShrink="0",$t(),vt=!0,Co();return}let hn=Hi(o);if(!m&&!u)w&&b?(Ae.style.width="100%",Ae.style.maxWidth="100%"):(Ae.style.width=hn.width,Ae.style.maxWidth=hn.maxWidth);else if(u)if(Zn(o).reveal==="emerge"&&!k){let Ye=Zn(o).width;Ae.style.width=Ye,Ae.style.maxWidth=Ye}else Ae.style.width="100%",Ae.style.maxWidth="100%";if(_c(),Ae.style.boxShadow=Gt,Ae.style.borderRadius=$e,se?Ae.style.border="none":St&&(Ae.style.border=ai),we.style.border=ln,we.style.borderRadius=We,we.style.boxShadow=se&&!Tt?Jt:"",Tt&&(we.style.background="transparent",ae.style.background="transparent",Ke.style.background="transparent",Ke.style.borderTop="none"),St){let Be=o.features?.artifacts?.layout;kc=Be?.unifiedSplitOuterRadius?.trim()||Be?.paneBorderRadius?.trim()||Ne}else kc=null;let At=er?.border!=null||Y?.border!=null;if(u&&!dt&&!vo&&!se&&!St&&!At&&(we.style.border="none",Zn(o).side==="right"?we.style.borderLeft="1px solid var(--persona-border)":we.style.borderRight="1px solid var(--persona-border)"),u&&!dt&&St&&!At&&(Zn(o).side==="right"?Ae.style.borderLeft="1px solid var(--persona-border)":Ae.style.borderRight="1px solid var(--persona-border)"),b&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",w&&(e.style.width="100%"),Je.style.display="flex",Je.style.flexDirection="column",Je.style.flex="1 1 0%",Je.style.minHeight="0",Je.style.maxHeight="100%",Je.style.height="100%",w&&(Je.style.overflow="hidden"),Ae.style.display="flex",Ae.style.flexDirection="column",Ae.style.flex="1 1 0%",Ae.style.minHeight="0",Ae.style.maxHeight="100%",Ae.style.height="100%",se||(Ae.style.overflow="hidden"),we.style.display="flex",we.style.flexDirection="column",we.style.flex="1 1 0%",we.style.minHeight="0",we.style.maxHeight="100%",we.style.overflow="hidden",ae.style.flex="1 1 0%",ae.style.minHeight="0",ae.style.overflowY="auto",Ke.style.flexShrink="0"),w&&(vo||se||Tt)&&!u&&(Tt||(Je.style.padding="var(--persona-panel-inset)"),Je.style.background="var(--persona-panel-canvas-bg)"),Je.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"),!m&&!w&&!u&&(ao[Dt]??ao["bottom-right"]).split(" ").forEach(Ye=>Je.classList.add(Ye)),m){let Be=_r(o).sidebarWidth?o.launcher?.sidebarWidth??"420px":wn(No(o),"components.panel.width")??"420px";k?Je.style.cssText=`
|
|
83
83
|
position: fixed !important;
|
|
84
84
|
top: var(--persona-panel-inset) !important;
|
|
85
85
|
bottom: var(--persona-panel-inset) !important;
|
|
86
|
-
width: ${
|
|
86
|
+
width: ${Be} !important;
|
|
87
87
|
height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
|
|
88
88
|
max-height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
|
|
89
89
|
margin: 0 !important;
|
|
90
90
|
padding: 0 !important;
|
|
91
91
|
display: flex !important;
|
|
92
92
|
flex-direction: column !important;
|
|
93
|
-
z-index: ${
|
|
93
|
+
z-index: ${_n} !important;
|
|
94
94
|
${jt?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}
|
|
95
|
-
`:
|
|
95
|
+
`:Je.style.cssText=`
|
|
96
96
|
position: fixed !important;
|
|
97
97
|
top: 0 !important;
|
|
98
98
|
bottom: 0 !important;
|
|
99
|
-
width: ${
|
|
99
|
+
width: ${Be} !important;
|
|
100
100
|
height: 100vh !important;
|
|
101
101
|
max-height: 100vh !important;
|
|
102
102
|
margin: 0 !important;
|
|
103
103
|
padding: 0 !important;
|
|
104
104
|
display: flex !important;
|
|
105
105
|
flex-direction: column !important;
|
|
106
|
-
z-index: ${
|
|
106
|
+
z-index: ${_n} !important;
|
|
107
107
|
${jt?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
|
|
108
108
|
`,Ae.style.cssText=`
|
|
109
109
|
position: relative !important;
|
|
@@ -137,23 +137,23 @@ _Details: ${n.message}_`:o}var Fw=e=>bs(e)||e===Oo,Wa=class e{constructor(t={},n
|
|
|
137
137
|
border-top: none !important;
|
|
138
138
|
padding: 8px 16px 12px 16px !important;
|
|
139
139
|
${Tt?"background: transparent !important;":""}
|
|
140
|
-
`)}if(!w&&!u){let _e="max-height: -moz-available !important; max-height: stretch !important;",Ge=m?"":"padding-top: 1.25em !important;",Ue=m?"":`z-index: ${o.launcher?.zIndex??kn} !important;`;Qe.style.cssText+=_e+Ge+Ue}$t(),vo()},Ju=()=>{e.style.setProperty("--persona-content-max-width",Hs(o,Le()))},py=!1;function uy(){o.layout?.topFade&&ae.scrollTop>1?ae.setAttribute("data-persona-top-fade","true"):ae.removeAttribute("data-persona-top-fade")}let Zu=()=>{uy();let a=Mm(o,Le());Le()&&o.composer?.placement&&o.debug===!0&&!py&&(py=!0,console.warn("[persona] composer.placement is ignored in composer-bar mount mode."));let u=M();e.setAttribute("data-persona-composer-placement",a),e.setAttribute("data-persona-conversation-state",N),e.setAttribute("data-persona-welcome-anchor",u.anchor??"bottom"),e.style.setProperty("--persona-composer-anchor-gap",u.composerGap??qp),Ot()},gy=()=>{if(Le())return;let a=Lt(o),u=o.launcher?.sidebarMode??!1;if(a||u||(o.launcher?.fullHeight??!1)||!ye)return;let b=e.ownerDocument.defaultView??window,w=o.launcher?.mobileFullscreen??!0,k=o.launcher?.mobileBreakpoint??640;if(w&&b.innerWidth<=k)return;let q=Hi(o);Ae.style.height=q.height,Ae.style.maxHeight=q.maxHeight};Qu(),Mi(e,o),dc(e,o),pc(e,o),Ju(),Zu(),Us=()=>{Qu(),gy(),Mi(e,o),dc(e,o),pc(e,o),Ju(),Zu(),Pc?e.style.setProperty("--persona-artifact-welded-outer-radius",Pc):e.style.removeProperty("--persona-artifact-welded-outer-radius"),Vn(),dr()};let Se=[];Se.push(()=>{oy=!0}),Se.push(()=>{f.forEach(a=>a()),g.destroy()}),Se.push(()=>{document.removeEventListener("keydown",ay)}),Se.push(()=>{Jr!==null&&clearTimeout(Jr)});let zo=null,Ko=null;Se.push(()=>{zo?.(),zo=null,Ko?.(),Ko=null}),ol&&Se.push(()=>{ol?.disconnect(),ol=null}),Se.push(()=>{al?.(),al=null,Xu(),Ut&&(Ut.remove(),Ut=null),et?.element.style.removeProperty("width"),et?.element.style.removeProperty("maxWidth"),et?.destroy()}),Ce&&Se.push(()=>{Bi=!0,Ft=null,ao!==null&&(cancelAnimationFrame(ao),ao=null),rn?.destroy(),rn=null,ft?.destroy(),ft=null,pn=null});let Vs=null,fy=()=>{Vs&&(Vs(),Vs=null),o.colorScheme==="auto"&&(Vs=Oa(()=>{Mi(e,o)}))};fy(),Se.push(()=>{Vs&&(Vs(),Vs=null)}),Se.push(()=>{L=!0,A?.()}),Se.push(()=>{V=!0});let my=!1;Se.push(()=>{my=!0});let eg=(a,u)=>{let m=tc(a,u);return m||!YS.includes(a)?m:(ZS().then(b=>{if(my)return;ec(b.wipe),ec(b.glyphCycle);let w=tc(a,u);w&&rc(w,e)}).catch(()=>{}),null)},_c=o.features?.streamAnimation;if(_c?.type&&_c.type!=="none"){let a=eg(_c.type,_c.plugins);a&&rc(a,e),Se.push(()=>JS(e))}let vr=ac(lo),hy=ac(gr),yy=ac(Xr),js=[vr,hy,yy];Se.push(()=>{js.forEach(a=>a.destroy())});let qs=null,R,zs=null,by=!1,vy=0,Cy=null,wy=a=>a.reduce((u,m)=>m.role==="user"?u+1:u,0),Sy=a=>{for(let u=a.length-1;u>=0;u--)if(gi(a[u]))return a[u].id??null;return null},Ay=!1,mM=()=>{Ay||o.debug!==!0||(Ay=!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".'))},xy=!1,My=!1,Ey=(a,u)=>{xy||o.debug!==!0||!u.enabled||u.expose||by||My&&(R.isStreaming()||a.some(gi)||(xy=!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.")))},Ks=a=>{if(!R)return;let u=a??R.getMessages(),m=de=>{de.render([],R,ce,u)},b=de=>{js.forEach(ke=>{ke!==de&&m(ke)})};zs&&(wy(u)>vy||Sy(u)!==Cy)&&(zs=null);let w=xs(o);Ey(u,w);let k=w.enabled?Od(u):null,q=zs??k,re=zs?"host":"agent";if(q){let de=o.suggestions?.followUps,ke=de?.placement??(de?"auto":"composer"),gt=(ke==="auto"?Le()?"composer":"after-message":ke)==="after-message"?yy:vr;b(gt),gt.render(q,R,ce,u,o.suggestionChipsConfig,{source:re,surface:"followUp",variant:de?.variant??"chip",behavior:de?.behavior??"send",overflow:de?.overflow??"wrap",maxItems:de?.maxItems??4,config:o,plugins:d,submitPrompt:id});return}if(u.some(de=>de.role==="user")){js.forEach(m);return}let Y=o.future?.v5Defaults===!0,ie=jn(),le=o.suggestions?.starters??(Y?{}:void 0);if(le){let de=Ws(M(),u),ke=le.placement??"auto",it=ke==="auto"?de?"welcome":"composer":ke;if(it==="welcome"&&!de){mM(),js.forEach(m);return}let gt=it==="welcome"?hy:vr;b(gt),gt.render(le.items??o.suggestionChips,R,ce,u,o.suggestionChipsConfig,{surface:"starter",variant:le.variant??(Y&&!ie?"chip":"card"),behavior:le.behavior??"send",overflow:le.overflow??"wrap",maxItems:le.maxItems??(Y&&!ie?3:4),config:o,plugins:d,submitPrompt:id});return}b(vr),vr.render(o.suggestionChips,R,ce,u,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",maxItems:4,config:o,plugins:d,submitPrompt:id})},Ty=()=>{zs&&(zs=null,Ks())},hM=a=>{let u=Array.isArray(a)?[...a]:[];if(!u.length){Ty();return}let m=R?R.getMessages():[];zs=u,by=!0,vy=wy(m),Cy=Sy(m),Ks(m)},to=!1,En=_S(),Yi=new Map,Gs=new Map,ns=new Map,Ys=null,os=null;function Xs(){if(!Ys)return;let a=Ys;Ys=null,os?.destroy(),os=null,En.delete(a),we.querySelector(`#wrapper-${a}`)?.removeAttribute("data-preserve-runtime"),R&&go(Te,R.getMessages(),K)}let Qs=0,yM=nr()!==null,no=US(),oo=0,rs=null,qn=!1,Dc=!1,ss=0,an=null,Js=null,tg=!1,Xi=!1,Zs=null,ll=!0,Nc=!1,Qi=null,Fc=!1,is=()=>{Fc=!0,wM()},ng=null,bM=4,Cr=24,vM=80,CM=1e3,wr=null,Py=()=>{e.setAttribute("data-persona-scrollbar",Ns()),Ns()!=="on-scroll"&&(wr!==null&&clearTimeout(wr),wr=null,ae.removeAttribute("data-persona-scrollbar-visible"))},wM=()=>{Ns()==="on-scroll"&&(ae.setAttribute("data-persona-scrollbar-visible",""),wr!==null&&clearTimeout(wr),wr=setTimeout(()=>{wr=null,Ei(ae,Cr)&&ae.removeAttribute("data-persona-scrollbar-visible")},CM))};Py(),Se.push(()=>{wr!==null&&clearTimeout(wr)});let og=new Map,rg=!1,$c=null,st={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};Po();let ky=o.voiceRecognition?.autoResume??!1,Sr=a=>{X.emit("voice:state",{active:st.active,source:a,timestamp:Date.now()})},Ho=()=>{qe(a=>({...a,voiceState:{active:st.active,timestamp:Date.now(),manuallyDeactivated:st.manuallyDeactivated}}))},SM=()=>{if(o.voiceRecognition?.enabled===!1)return;let a=bh(P.voiceState),u=!!a.active,m=Number(a.timestamp??0);st.manuallyDeactivated=!!a.manuallyDeactivated,u&&Date.now()-m<QL&&setTimeout(()=>{st.active||(st.manuallyDeactivated=!1,Dn(o.voiceRecognition?.provider)?R.toggleVoice().then(()=>{st.active=R.isVoiceActive(),Sr("restore"),R.isVoiceActive()&&da()}):dd("restore"))},1e3)},AM=()=>R?sx(R.getMessages()).filter(a=>!a.__skipPersist):[],Uc=null,Ly=(a,u)=>{typeof console<"u"&&console.error(a,u)},Vc=(a,u)=>{let m=()=>{try{let q=a();return!q||typeof q.then!="function"?null:Promise.resolve(q).catch(re=>{Ly(u,re)})}catch(q){return Ly(u,q),null}},b=Uc,w=b?b.then(()=>m()??void 0):m();if(!w)return;let k=w.finally(()=>{Uc===k&&(Uc=null)});Uc=k};function Ji(a){if(!T?.save)return;let u=a?sx(a):R?AM():[],m=B&&R?.getResumableHandle();m&&(P={...P,durableResume:{executionId:m.executionId,after:m.lastEventId}});let b={messages:u,metadata:P,artifacts:po.artifacts,selectedArtifactId:po.selectedId,...ei?{draft:ei}:{}};Vc(()=>T.save(b),"[AgentWidget] Failed to persist state:")}let ei,jc=()=>!T?.save||o.persistState===!1?!1:typeof o.persistState=="object"?o.persistState.persist?.draft!==!1:!0,cl=fS({write:()=>{if(!jc())return;let a=be.getState(),u=uS({text:a.text,mentionRefs:a.mentionRefs,contentSegments:Og(),selectedModelId:a.selectedModelId,activeModeIds:a.activeModeIds,quote:a.quote});JSON.stringify(u)!==JSON.stringify(ei)&&(ei=u,Ji())}});function Hy(){jc()&&cl.schedule()}function sg(){cl.flush()}function Iy(a){if(!jc())return;let u=gS(a,{mentionSourceIds:(o.contextMentions?.sources??[]).map(m=>m.id),modelIds:(o.composer?.models??[]).map(m=>m.id),modes:o.composer?.modes??[]});u&&(ei=a,ce&&!ce.value&&(ce.value=u.text,ce.dispatchEvent(new Event("input",{bubbles:!0})),co()),u.selectedModelId&&(be.setSelectedModelId(u.selectedModelId),Zr?.repaint()),Ec(u.activeModeIds??[]),u.quote&&qo(u.quote),cl.cancel())}function qc(){cl.cancel(),ei&&(ei=void 0,jc()&&Ji())}let Zi=null,Ry=()=>Qe.querySelector("#persona-scroll-container")||ae,ea=()=>{Zi!==null&&(cancelAnimationFrame(Zi),Zi=null),qn=!1},Wy=()=>{rs!==null&&(cancelAnimationFrame(rs),rs=null),Dc=!1,ea()},xM=()=>to&&ag()&&(Mn()!=="anchor-top"||Za()),ig=()=>{let a=Qr()||"Jump to latest",u=xM();Vt.toggleAttribute("data-persona-scroll-to-bottom-streaming",u),ss>0?(tn.textContent=String(ss),tn.style.display="",Vt.setAttribute("aria-label",`${a} (${ss} new)`)):(tn.textContent="",tn.style.display="none",Vt.setAttribute("aria-label",u?`${a} (response streaming below)`:a))},Oy=()=>{ss!==0&&(ss=0,ig())},MM=()=>{let a=an?.spacerHeight??0;return a<=0?Ei(ae,Cr):Gc(a)-ae.scrollTop-ae.clientHeight<=Cr},ag=()=>Mo()?!no.isFollowing():!MM(),lg=()=>!!R&&R.getMessages().length>0,Tn=()=>{if(!Bu()||Cc()){Vt.parentNode&&Vt.remove(),Vt.style.display="none";return}Vt.parentNode!==we&&we.appendChild(Vt),Re();let u=ir(ae)>0&&ag()&&lg();u?ig():Oy(),Vt.style.display=u?"":"none"},ta=()=>{no.pause()&&(Wy(),Tn())},Go=()=>{no.resume(),Oy(),Tn()},as=(a=!1)=>{Mo()&&lg()&&no.isFollowing()&&(!a&&!to||(rs!==null&&(cancelAnimationFrame(rs),rs=null),Dc=!0,rs=requestAnimationFrame(()=>{rs=null,Dc=!1,no.isFollowing()&&EM(Ry(),a?220:140)})))},By=(a,u,m,b=()=>!0)=>{let w=a.scrollTop,k=u(),q=k-w;if(ea(),Math.abs(q)<1){qn=!0,a.scrollTop=k,oo=a.scrollTop,qn=!1;return}let re=performance.now();qn=!0;let Y=le=>1-Math.pow(1-le,3),ie=le=>{if(!b()){ea();return}let de=u();de!==k&&(k=de,q=k-w);let ke=le-re,it=Math.min(ke/m,1),gt=Y(it),dt=w+q*gt;a.scrollTop=dt,oo=a.scrollTop,it<1?Zi=requestAnimationFrame(ie):(a.scrollTop=k,oo=a.scrollTop,Zi=null,qn=!1)};Zi=requestAnimationFrame(ie)},EM=(a,u=500)=>{let m=ir(a)-a.scrollTop;if(Math.abs(m)<1){oo=a.scrollTop;return}if(Math.abs(m)>=vM){ea(),qn=!0,a.scrollTop=ir(a),oo=a.scrollTop,qn=!1;return}By(a,()=>ir(a),u,()=>no.isFollowing())},cg=()=>{if(!lg()){Tn();return}let a=Ry();qn=!0,a.scrollTop=ir(a),oo=a.scrollTop,qn=!1,Tn()},ti=a=>{let u=0,m=a;for(;m&&m!==ae;)u+=m.offsetTop,m=m.offsetParent;return u},TM=()=>{let a=ae.getRootNode();return(typeof a.getSelection=="function"?a.getSelection():null)??ae.ownerDocument.getSelection()},zc=()=>qS(TM(),ae),dg=()=>{if(Mc()!=="last-user-turn")return!1;let a=R?.getMessages()??[];if(a.length<2)return!1;let u=[...a].reverse().find(k=>k.role==="user");if(!u)return!1;let m=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(u.id):u.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),b=ae.querySelector(`[data-message-id="${m}"]`);if(!b)return!1;let w=Math.min(Math.max(0,ti(b)-Ds()),ir(ae));return qn=!0,ae.scrollTop=w,oo=ae.scrollTop,qn=!1,Mn()==="follow"&&!Ei(ae,Cr)&&no.pause(),Tn(),!0},Kc=a=>{let u=Math.max(0,Math.round(a));Qt.style.height=`${u}px`,Qt.style.display=u>0?"":"none",an&&(an.spacerHeight=Math.max(0,a))},Gc=a=>{let u=parseFloat(getComputedStyle(ae).paddingBottom)||0,m=0;for(let w of Array.from(ae.children)){if(w===Qt||w.offsetHeight===0)continue;let k=ti(w)+w.offsetHeight;k>m&&(m=k)}let b=ae.scrollHeight-a;return m>0?Math.min(m+u,b):b},PM=()=>{if(!an||an.spacerHeight<=0)return;let a=Gc(an.spacerHeight),u=Math.max(0,Math.round(ae.scrollTop)+ae.clientHeight-a+Cr);u<an.spacerHeight&&(Kc(u),Tn())},ni=()=>{Js!==null&&(cancelAnimationFrame(Js),Js=null),ea(),an=null,Qt.style.height="0px",Qt.style.display="none"},_y=a=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(a):a.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),pg=a=>ae.querySelector(`[data-message-id="${_y(a)}"]`),Dy=a=>{Js!==null&&cancelAnimationFrame(Js),Js=requestAnimationFrame(()=>{Js=null;let u=_y(a),m=ae.querySelector(`[data-message-id="${u}"]`);if(!m)return;let b=ti(m),w=an?.spacerHeight??0,k=Gc(w),{targetScrollTop:q,spacerHeight:re}=Tm({anchorOffsetTop:b,topOffset:Ds(),viewportHeight:ae.clientHeight,contentHeight:k,slack:Cr});an={initialSpacerHeight:re,contentHeightAtAnchor:k,spacerHeight:re},Kc(re),By(ae,()=>m.isConnected?Math.max(0,ti(m)-Ds()):q,220)})},na=()=>{if(Mn()!=="anchor-top"||!an||!Qi)return;let a=pg(Qi);if(!a)return;ea();let u=an.spacerHeight,m=Gc(u),{targetScrollTop:b,spacerHeight:w}=Tm({anchorOffsetTop:ti(a),topOffset:Ds(),viewportHeight:ae.clientHeight,contentHeight:m,slack:Cr});an={initialSpacerHeight:w,contentHeightAtAnchor:m,spacerHeight:w},Kc(w),qn=!0,ae.scrollTop=b,oo=ae.scrollTop,qn=!1,Tn()},kM=()=>{if(Mo()){if(!no.isFollowing()||Ei(ae,1))return;as(!to);return}if(an&&an.initialSpacerHeight>0){let a=ae.scrollHeight-an.spacerHeight,u=zS({initialSpacerHeight:an.initialSpacerHeight,contentHeightAtAnchor:an.contentHeightAtAnchor,currentContentHeight:a});u!==an.spacerHeight&&Kc(u)}Tn()},LM=a=>{let u=Mn();u==="follow"?(Go(),as(!0)):u==="anchor-top"&&(ll=!1,Nc=!0,Fc=!1,Qi=a,Dy(a))},HM=()=>{if(Mn()==="anchor-top"){if(Nc){ll=!1;return}ll=!0,ni(),Go(),as(!0)}},IM=96,RM=a=>{if(Zs===null)return!0;let u=pg(Zs),m=pg(a);if(!u||!m)return!0;let b=ti(m)-ti(u);return Ds()+b>ae.clientHeight-IM},WM=a=>{if(Mn()!=="anchor-top"||!Nc||Fc||zc())return;let u=Zs===null;for(let m of a){if(!u){m.id===Zs&&(u=!0);continue}if($S(m)){if(m.id===Qi||!RM(m.id))return;Qi=m.id,Dy(m.id);return}}},OM=a=>{let u=new Map;a.forEach(m=>{let b=og.get(m.id);u.set(m.id,{streaming:m.streaming,role:m.role}),!b&&m.role==="assistant"&&(X.emit("assistant:message",m),!Xi&&(Mn()!=="anchor-top"||Za())&&ag()&&(ss+=1,ig(),Tn(),$s(ss===1?"1 new message below.":`${ss} new messages below.`))),m.role==="assistant"&&b?.streaming&&m.streaming===!1&&X.emit("assistant:complete",m),m.variant==="approval"&&m.approval&&(b?m.approval.status!=="pending"&&X.emit("approval:resolved",{approval:m.approval,decision:m.approval.status}):X.emit("approval:requested",{approval:m.approval,message:m}))}),og.clear(),u.forEach((m,b)=>{og.set(b,m)})},dl=(a,u)=>{let m=u==="user"?"user":"assistant",b=o.layout?.messages?.[m],w=b?.width??"content",k=b?.maxWidth??(w==="full"?`var(--persona-message-${m}-max-width, 100%)`:void 0);a.classList.add("persona-message-row"),a.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),a.classList.add(`persona-message-row-${u}`,`persona-message-width-${w}`),a.classList.toggle("persona-justify-end",u==="user"),a.setAttribute("data-message-role",u),a.setAttribute("data-message-width",w),k?a.style.setProperty("--persona-message-row-max-width",k):a.style.removeProperty("--persona-message-row-max-width")},Ar=(a,u)=>{let m=document.createElement("div");return m.className="persona-flex",m.id=`wrapper-${a}`,m.setAttribute("data-wrapper-id",a),dl(m,u),m},BM=(a,u,m)=>{let b=new Set;for(let O of u){let Ne=O.variant==="tool"?"tool":O.variant==="reasoning"?"reasoning":null;if(!Ne||Ts(o,Ne)!=="row")continue;let Fe=Ne==="tool"?o.features?.toolCallDisplay:o.features?.reasoningDisplay;Fe?.expandable!==!1&&(b.add(O.id),i.observe(O,Ne,Ne==="tool"?r:s,Fe))}let w=document.createElement("div"),q=(()=>{let O=d.find(Ne=>Ne.renderLoadingIndicator);if(O?.renderLoadingIndicator)return O.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),re=(O,Ne)=>Ne==null?!1:typeof Ne=="string"?(O.textContent=Ne,!0):(O.appendChild(Ne),!0),Y=new Set,ie=new Map,le=new Set,de=d.some(O=>O.renderAskUserQuestion),ke=[],it=[],gt=o.enableComponentStreaming!==!1,dt=o.approval!==!1,zn=[],Dt=o.messageActions,jt=Dt?.showRegenerate===!0&&Dt.enabled!==!1&&uo.current?.isStreaming()!==!0?Hw(u):null,On=Dt?.showEdit===!0&&Dt.enabled!==!1,Kt=Dt?.showQuote===!0&&Dt.enabled!==!1,wt=null,Jo=o.features?.reasoningDisplay?.completedVisibility,Zo=O=>Jo==="removed"?!0:Jo==="removed-when-short"?mv(O,o.features?.reasoningDisplay?.shortThinkThreshold):!1,yo=o.features?.toolCallDisplay?.completedVisibility==="removed",bo=O=>O.variant==="reasoning"&&O.reasoning?.status==="complete"?Zo(O.reasoning):yo&&O.variant==="tool"&&O.toolCall?.status==="complete";if(u.forEach(O=>{if(bo(O))return;if(Y.add(O.id),ie.set(O.id,O.role),Ys===O.id&&os){let $e=Ar(O.id,O.role);$e.setAttribute("data-persona-message-edit-stub","true"),$e.setAttribute("data-preserve-runtime","true"),w.appendChild($e),wt={messageId:O.id,element:os.element};return}let Ne=de&&Ir(O),Fe=dt&&O.variant==="approval"&&!!O.approval,se=!Ne&&O.role==="assistant"&&!O.variant&>&&hc(O);!Fe&&ns.has(O.id)&&(a.querySelector(`#wrapper-${O.id}`)?.removeAttribute("data-preserve-runtime"),ns.delete(O.id)),!se&&Gs.has(O.id)&&(a.querySelector(`#wrapper-${O.id}`)?.removeAttribute("data-preserve-runtime"),Gs.delete(O.id));let St=Ir(O)?`:${O.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${O.agentMetadata?.askUserQuestionAnswers?Object.keys(O.agentMetadata.askUserQuestionAnswers).length:0}`:"",Jt={canRegenerate:jt===O.id,canEdit:On&&lm(O),canQuote:Kt&&!O.variant&&(O.content?.trim().length??0)>0},Hn=`${Jt.canRegenerate?"r":""}${Jt.canEdit?"e":""}${Jt.canQuote?"q":""}`,mn=BS(O,Qs)+St+`:${Hn}`,Tt=Ne||Fe||se?null:DS(En,O.id,mn);if(Tt){w.appendChild(Tt.cloneNode(!0)),Ir(O)&&O.toolCall?.id&&O.agentMetadata?.awaitingLocalTool===!0&&!O.agentMetadata?.askUserQuestionAnswered&&(le.add(O.toolCall.id),Yu(O));return}let Gt=null,ln=d.find($e=>!!(O.variant==="reasoning"&&$e.renderReasoning||O.variant==="tool"&&$e.renderToolCall||!O.variant&&$e.renderMessage)),We=o.layout?.messages;if(Ir(O)&&O.agentMetadata?.askUserQuestionAnswered===!0){Yi.delete(O.id),a.querySelector(`#wrapper-${O.id}`)?.removeAttribute("data-preserve-runtime");return}if(gi(O)&&xs(o).enabled)return;if(Ir(O)&&o.features?.askUserQuestion?.enabled!==!1){let $e=d.find(cn=>typeof cn.renderAskUserQuestion=="function");if($e&&uo.current){let cn=Yi.get(O.id),vo=cn!==mn,hn=null;if(vo){let{payload:Ge,complete:Ue}=Rr(O),hs=O.id,nn=()=>uo.current?.getMessages().find(Kn=>Kn.id===hs);hn=$e.renderAskUserQuestion({message:O,payload:Ge,complete:Ue,resolve:Kn=>{let Pr=nn();Pr&&uo.current?.resolveAskUserQuestion(Pr,Kn)},dismiss:()=>{let Kn=nn();Kn?.agentMetadata?.awaitingLocalTool&&(uo.current?.markAskUserQuestionResolved(Kn),uo.current?.resolveAskUserQuestion(Kn,"(dismissed)"))},config:o})}let At=cn!=null;if(vo&&hn===null&&!At){O.agentMetadata?.awaitingLocalTool===!0&&!O.agentMetadata?.askUserQuestionAnswered&&(le.add(O.toolCall.id),Yu(O));return}let _e=Ar(O.id,O.role);_e.setAttribute("data-ask-plugin-stub","true"),_e.setAttribute("data-preserve-runtime","true"),w.appendChild(_e),ke.push({messageId:O.id,fingerprint:mn,bubble:hn});return}else{O.agentMetadata?.awaitingLocalTool===!0&&!O.agentMetadata?.askUserQuestionAnswered&&(le.add(O.toolCall.id),Yu(O));return}}else if(Fe){let $e=_();if(!$e){w.appendChild(Ar(O.id,O.role));return}let cn=d.find(_e=>typeof _e.renderApproval=="function")??C,hn=ns.get(O.id)!==mn,At=null;if(hn&&cn?.renderApproval){let _e=O.id,Ge=(Ue,hs)=>{let nn=uo.current?.getMessages().find(Kn=>Kn.id===_e);nn?.approval&&(nn.approval.toolType==="webmcp"?uo.current?.resolveWebMcpApproval(nn.id,Ue):uo.current?.resolveApproval(nn.approval,Ue,hs))};At=cn.renderApproval({message:O,defaultRenderer:()=>$e.createApprovalBubble(O,o,l),config:o,approve:Ue=>Ge("approved",Ue),deny:Ue=>Ge("denied",Ue)})}if(hn&&At===null)a.querySelector(`#wrapper-${O.id}`)?.removeAttribute("data-preserve-runtime"),ns.delete(O.id),Gt=$e.createApprovalBubble(O,o,l);else{let _e=Ar(O.id,O.role);_e.setAttribute("data-approval-plugin-stub","true"),_e.setAttribute("data-preserve-runtime","true"),w.appendChild(_e),zn.push({messageId:O.id,fingerprint:mn,bubble:At});return}}else if(ln)if(O.variant==="reasoning"&&O.reasoning&&ln.renderReasoning){if(!te)return;Gt=ln.renderReasoning({message:O,defaultRenderer:()=>th(O,o,s),config:o})}else if(O.variant==="tool"&&O.toolCall&&ln.renderToolCall){if(!ve)return;Gt=ln.renderToolCall({message:O,defaultRenderer:()=>sh(O,o,r),config:o})}else ln.renderMessage&&(Gt=ln.renderMessage({message:O,defaultRenderer:()=>{let $e=Fa(O,m,We,o.messageActions,eo,{loadingIndicatorRenderer:q,widgetConfig:o,actionEligibility:Jt});return O.role!=="user"&&j($e,O,o,R),$e},config:o}));if(!Gt&&se){let $e=gu(O);if($e){let cn=Gs.get(O.id),vo=cn!==mn,hn=o.wrapComponentDirectiveInBubble!==!1&&Fo.getOptions($e.component)?.bubbleChrome!==!1,At=null;if(vo){let _e=uu($e,{config:o,message:O,transform:m});if(_e&&$e.component==="PersonaArtifactInline"){let Ge=_e.hasAttribute("data-artifact-inline")?_e:_e.querySelector("[data-artifact-inline]"),Ue=Ge?.getAttribute("data-artifact-inline")??"",hs=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(Ue):Ue,nn=Ue?a.querySelector(`#wrapper-${O.id}`)?.querySelector(`[data-artifact-inline="${hs}"]`)??null:null;Ge&&nn&&nn!==Ge&&qr()?.hasLiveInlineArtifactBlock(nn)&&(Ge===_e?_e=nn:Ge.replaceWith(nn))}if(_e)if(hn){let Ge=document.createElement("div");if(Ge.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Ge.id=`bubble-${O.id}`,Ge.setAttribute("data-message-id",O.id),O.content&&O.content.trim()){let Ue=document.createElement("div");Ue.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Ue.innerHTML=m({text:O.content,message:O,streaming:!!O.streaming,raw:O.rawContent}),Ge.appendChild(Ue)}Ge.appendChild(_e),At=Ge}else{let Ge=document.createElement("div");if(Ge.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ge.id=`bubble-${O.id}`,Ge.setAttribute("data-message-id",O.id),Ge.setAttribute("data-persona-component-directive","true"),O.content&&O.content.trim()){let Ue=document.createElement("div");Ue.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Ue.innerHTML=m({text:O.content,message:O,streaming:!!O.streaming,raw:O.rawContent}),Ge.appendChild(Ue)}Ge.appendChild(_e),At=Ge}}if(At||cn!=null){let _e=Ar(O.id,O.role);_e.setAttribute("data-component-directive-stub","true"),_e.setAttribute("data-preserve-runtime","true"),w.appendChild(_e),it.push({messageId:O.id,fingerprint:mn,bubble:At});return}}}if(!Gt)if(O.variant==="reasoning"&&O.reasoning){if(!te)return;Gt=th(O,o,s)}else if(O.variant==="tool"&&O.toolCall){if(!ve)return;Gt=sh(O,o,r)}else if(O.variant==="approval"&&O.approval){if(o.approval===!1)return;let $e=_();if(!$e)return;Gt=$e.createApprovalBubble(O,o,l)}else{let $e=o.layout?.messages;$e?.renderUserMessage&&O.role==="user"?Gt=$e.renderUserMessage({message:O,config:o,streaming:!!O.streaming}):$e?.renderAssistantMessage&&O.role==="assistant"?Gt=$e.renderAssistantMessage({message:O,config:o,streaming:!!O.streaming}):Gt=Fa(O,m,$e,o.messageActions,eo,{loadingIndicatorRenderer:q,widgetConfig:o,actionEligibility:Jt}),O.role!=="user"&&Gt&&j(Gt,O,o,R)}let Pt=Ar(O.id,O.role);Pt.appendChild(Gt),NS(En,O.id,mn,Pt),w.appendChild(Pt)}),Ze.composerOverlay&&Ze.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Ne=>{let Fe=Ne.getAttribute("data-persona-ask-sheet-for");Fe&&!le.has(Fe)&&Wr(Ze.composerOverlay,Fe)}),o.features?.toolCallDisplay?.grouped){let O=[],Ne=[],Fe=o.features.toolCallDisplay.groupedMode==="summary";u.forEach(se=>{if(se.variant==="tool"&&se.toolCall&&ve){if(yo&&se.toolCall.status==="complete")return;Ne.push(se);return}se.variant==="reasoning"&&(!te||se.reasoning?.status==="complete"&&Zo(se.reasoning))||((Ne.length>1||Fe&&Ne.length>0)&&O.push(Ne),Ne=[])}),(Ne.length>1||Fe&&Ne.length>0)&&O.push(Ne),O.forEach(se=>{let St=se.map(We=>Array.from(w.children).find(Pt=>Pt instanceof HTMLElement&&Pt.getAttribute("data-wrapper-id")===We.id)).filter(We=>!!We);if(St.length<(Fe?1:2))return;let Jt=Ar(`tool-group-${se[0].id}`,"assistant");if(Jt.setAttribute("data-persona-tool-group-row","true"),o.features?.toolCallDisplay?.groupedMode==="collapsible"){let We=`tool-group-${se[0].id}`,Pt=se.some(At=>At.toolCall?.status!=="complete"),$e={...se[0],id:We,toolCall:{id:We,name:`${se.length} tools`,status:Pt?"running":"complete",chunks:se.flatMap(At=>At.toolCall?.chunks??[]),success:!se.some(At=>At.toolCall?.success===!1)}};b.add(We),i.observe($e,"tool",r,o.features.toolCallDisplay);let cn=`${Pt?"Using":"Used"} ${se.length} tools`,vo=o.toolCall?.renderGroupedSummary?.({messages:se,toolCalls:se.map(At=>At.toolCall),defaultSummary:cn,config:o}),hn=ow($e,o,r.has(We),vo??cn);hn.bubble.classList.add("persona-tool-group"),hn.body.dataset.personaToolGroupStack="true",St[0].before(Jt),Jt.appendChild(hn.bubble),St.forEach((At,_e)=>{At.style.setProperty("--persona-message-row-max-width","100%"),At.style.setProperty("--persona-activity-stagger",`${_e*40}ms`),At.classList.add("persona-activity-group-child"),hn.body.appendChild(At)});return}let Hn=document.createElement("div");Hn.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Hn.setAttribute("data-persona-tool-group","true");let mn=document.createElement("div");mn.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",mn.id=`tool-group-summary-${se[0].id}`;let Tt=`Called ${se.length} ${se.length===1?"tool":"tools"}`,Gt=o.toolCall?.renderGroupedSummary?.({messages:se,toolCalls:se.map(We=>We.toolCall).filter(We=>!!We),defaultSummary:Tt,config:o});re(mn,Gt)||(mn.textContent=Tt);let ln=document.createElement("div");ln.className="persona-tool-group-stack persona-flex persona-flex-col",ln.id=`tool-group-stack-${se[0].id}`,ln.setAttribute("data-persona-tool-group-stack","true"),Hn.appendChild(mn),Fe||Hn.appendChild(ln),Jt.appendChild(Hn),St[0].before(Jt),St.forEach((We,Pt)=>{if(Fe){We.remove();return}We.style.setProperty("--persona-message-row-max-width","100%");let $e=document.createElement("div");$e.className="persona-tool-group-item persona-relative",$e.setAttribute("data-persona-tool-group-item","true"),Pt<St.length-1&&$e.setAttribute("data-persona-tool-group-connector","true"),$e.appendChild(We),ln.appendChild($e)})})}i.prune(b),FS(En,Y);let fs=O=>O.variant==="tool"&&!ve||O.variant==="reasoning"&&!te||bo(O),er=u.some(O=>O.role==="assistant"&&O.streaming&&!fs(O)),Io=u.length-1;for(;Io>=0&&fs(u[Io]);)Io--;let ms=Io>=0?u[Io]:void 0,xl=Io<u.length-1,ai=ms?.role==="assistant"&&!ms.streaming&&ms.variant!=="approval"&&!xl;if(to&&u.some(O=>O.role==="user")&&!er&&!ai){let O={config:o,streaming:!0,location:"standalone",defaultRenderer:Li},Ne=d.find(se=>se.renderLoadingIndicator),Fe=null;if(Ne?.renderLoadingIndicator&&(Fe=Ne.renderLoadingIndicator(O)),Fe===null&&o.loadingIndicator?.render&&(Fe=o.loadingIndicator.render(O)),Fe===null&&(Fe=Li()),Fe){let se=document.createElement("div"),St=o.loadingIndicator?.showBubble!==!1,Jt=o.layout?.messages?.layout??"bubble";se.className=St?cc("assistant",Jt).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),se.setAttribute("data-typing-indicator","true"),St&&(se.style.color="var(--persona-message-assistant-text, var(--persona-text))",Jt!=="flat"&&(se.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",se.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),se.appendChild(Fe);let Hn=Ar("typing-indicator","assistant");Hn.appendChild(se),w.appendChild(Hn)}}if(!to&&u.length>0){let O=u[u.length-1],Ne={config:o,lastMessage:O,messageCount:u.length},Fe=d.find(St=>St.renderIdleIndicator),se=null;if(Fe?.renderIdleIndicator&&(se=Fe.renderIdleIndicator(Ne)),se===null&&o.loadingIndicator?.renderIdle&&(se=o.loadingIndicator.renderIdle(Ne)),se){let St=document.createElement("div"),Jt=o.loadingIndicator?.showBubble!==!1;St.className=Jt?["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(" "),St.setAttribute("data-idle-indicator","true"),St.appendChild(se);let Hn=Ar("idle-indicator","assistant");Hn.appendChild(St),w.appendChild(Hn)}}if(bw(w),zp(a,w),om(a),wt){let{messageId:O,element:Ne}=wt,Fe=a.querySelector(`#wrapper-${O}`);Fe&&Ne.parentElement!==Fe&&(dl(Fe,ie.get(O)??"user"),Fe.replaceChildren(Ne))}if(ke.length>0)for(let{messageId:O,fingerprint:Ne,bubble:Fe}of ke){let se=a.querySelector(`#wrapper-${O}`);se&&(dl(se,ie.get(O)??"assistant"),Fe!==null&&(se.replaceChildren(Fe),se.setAttribute("data-bubble-fp",Ne),Yi.set(O,Ne)))}if(Yi.size>0)for(let O of Yi.keys())Y.has(O)||Yi.delete(O);if(it.length>0)for(let{messageId:O,fingerprint:Ne,bubble:Fe}of it){let se=a.querySelector(`#wrapper-${O}`);se&&(dl(se,ie.get(O)??"assistant"),Fe!==null&&(se.replaceChildren(Fe),se.setAttribute("data-bubble-fp",Ne),Gs.set(O,Ne)))}if(Gs.size>0)for(let O of Gs.keys())Y.has(O)||Gs.delete(O);if(zn.length>0)for(let{messageId:O,fingerprint:Ne,bubble:Fe}of zn){let se=a.querySelector(`#wrapper-${O}`);se&&(dl(se,ie.get(O)??"assistant"),Fe!==null&&(se.replaceChildren(Fe),se.setAttribute("data-bubble-fp",Ne),ns.set(O,Ne)))}if(ns.size>0)for(let O of ns.keys())Y.has(O)||ns.delete(O)},ug=!1,Yc=()=>{ug||(ug=!0,mi().catch(()=>{}),yd().catch(()=>{ug=!1}))},go=(a,u,m)=>{u.length>0&&Yc(),BM(a,u,m),ny()},pl=null,_M=()=>{if(pl)return;let a=m=>{let b=m.composedPath();b.includes(Qe)||Xt&&b.includes(Xt)||Et(!1,"user")};pl=a,(e.ownerDocument??document).addEventListener("pointerdown",a,!0)},Ny=()=>{if(!pl)return;(e.ownerDocument??document).removeEventListener("pointerdown",pl,!0),pl=null};Se.push(()=>Ny());let ul=null,DM=()=>{if(ul)return;let a=m=>{m.key==="Escape"&&(m.isComposing||Et(!1,"user"))};ul=a,(e.ownerDocument??document).addEventListener("keydown",a,!0)},Fy=()=>{if(!ul)return;(e.ownerDocument??document).removeEventListener("keydown",ul,!0),ul=null};Se.push(()=>Fy());let gl=!1,$y=new Set,NM=()=>{let a=o.launcher?.composerBar?.peek?.streamAnimation;return a||o.features?.streamAnimation},oa=()=>{if(!Le())return;let a=Ze.peekBanner,u=Ze.peekTextNode;if(!a||!u)return;if(D){a.classList.remove("persona-pill-peek--visible");return}let m=R?.getMessages()??[],b;for(let Dt=m.length-1;Dt>=0;Dt--){let jt=m[Dt];if(jt.role==="assistant"&&jt.content){b=jt;break}}if(!b){a.classList.remove("persona-pill-peek--visible");return}let w=b.content,k=!!b.streaming,q=NM(),re=Kp(q),Y=re.type!=="none"?eg(re.type,q?.plugins):null,ie=Y?.isAnimating?.(b)===!0,le=Y!==null&&(k||ie);le&&Y&&!$y.has(Y.name)&&(rc(Y,e),$y.add(Y.name));let de=le&&Y?.containerClass?Y.containerClass:null,ke=u.dataset.personaPeekStreamClass??null;ke&&ke!==de&&(u.classList.remove(ke),delete u.dataset.personaPeekStreamClass),de&&ke!==de&&(u.classList.add(de),u.dataset.personaPeekStreamClass=de),le?(u.style.setProperty("--persona-stream-step",`${re.speed}ms`),u.style.setProperty("--persona-stream-duration",`${re.duration}ms`)):(u.style.removeProperty("--persona-stream-step"),u.style.removeProperty("--persona-stream-duration"));let it=le?Gp(w,re.buffer,Y,b,k):w;if(le&&re.placeholder==="skeleton"&&k&&(!it||!it.trim())){let Dt=document.createElement("div"),jt=oc();jt.classList.add("persona-pill-peek__skeleton"),Dt.appendChild(jt),zp(u,Dt)}else{let Dt=Math.max(0,it.length-100),jt=it.length>100?it.slice(-100):it,On=Ur(jt);if(!le||!Y){let Kt=it.length>100?`\u2026${jt}`:jt;u.textContent!==Kt&&(u.textContent=Kt)}else{let Kt=On;(Y.wrap==="char"||Y.wrap==="word")&&(Kt=nc(On,Y.wrap,`peek-${b.id}`,{skipTags:Y.skipTags,startIndex:Dt}));let wt=document.createElement("div");if(wt.innerHTML=Kt,Y.useCaret&&jt.length>0){let Jo=Yp(),Zo=wt.querySelectorAll(".persona-stream-char, .persona-stream-word"),yo=Zo[Zo.length-1];yo?.parentNode?yo.parentNode.insertBefore(Jo,yo.nextSibling):wt.appendChild(Jo)}zp(u,wt),Y.onAfterRender?.({container:u,bubble:a,messageId:b.id,message:b,speed:re.speed,duration:re.duration})}}let zn=to||gl;a.classList.toggle("persona-pill-peek--visible",zn)};if(Le()){let a=Ze.peekBanner;if(a){let b=w=>{w.preventDefault(),w.stopPropagation(),Et(!0,"user")};a.addEventListener("pointerdown",b),Se.push(()=>{a.removeEventListener("pointerdown",b)})}let u=()=>{gl||(gl=!0,oa())},m=()=>{gl&&(gl=!1,oa())};Ae.addEventListener("pointerenter",u),Ae.addEventListener("pointerleave",m),Se.push(()=>{Ae.removeEventListener("pointerenter",u),Ae.removeEventListener("pointerleave",m)}),Xt&&(Xt.addEventListener("pointerenter",u),Xt.addEventListener("pointerleave",m),Se.push(()=>{Xt.removeEventListener("pointerenter",u),Xt.removeEventListener("pointerleave",m)}))}let FM=a=>{let u=o.launcher?.composerBar??{},m=u.expandedSize??"anchored",b=u.bottomOffset??"16px",w=u.collapsedMaxWidth,k=u.expandedMaxWidth??"880px",q=u.expandedTopOffset??"5vh",re=u.modalMaxWidth??"880px",Y=u.modalMaxHeight??"min(90vh, 800px)",ie="calc(100vw - 32px)",le="var(--persona-pill-area-height, 80px)",de=Qe.style;if(de.left="",de.right="",de.top="",de.bottom="",de.transform="",de.width="",de.maxWidth="",de.height="",de.maxHeight="",Xt){let ke=Xt.style;ke.bottom=b,ke.width=w??""}if(a&&m!=="fullscreen"){if(m==="modal"){de.top="50%",de.left="50%",de.transform="translate(-50%, -50%)",de.bottom="auto",de.right="auto",de.width=re,de.maxWidth=ie,de.maxHeight=Y,de.height=Y;return}de.left="50%",de.transform="translateX(-50%)",de.bottom=`calc(${b} + ${le})`,de.top=q,de.width=k,de.maxWidth=ie}},fl=()=>{if(D&&Yc(),!Ye())return;if(Le()){let ie=(o.launcher?.composerBar??{}).expandedSize??"anchored",le=D?"expanded":"collapsed";Qe.dataset.state=le,Qe.dataset.expandedSize=ie,Xt&&(Xt.dataset.state=le,Xt.dataset.expandedSize=ie),Qe.style.removeProperty("display"),Qe.classList.remove("persona-pointer-events-none","persona-opacity-0"),Ae.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),FM(D),we.style.display=D?"flex":"none",Us(),D?(_M(),DM()):(Ny(),Fy()),oa();return}let a=Lt(o),u=e.ownerDocument.defaultView??window,m=o.launcher?.mobileBreakpoint??640,b=o.launcher?.mobileFullscreen??!0,w=u.innerWidth<=m,k=b&&w&&ye,q=Jn(o).reveal;D?(Qe.style.removeProperty("display"),Qe.style.display=a?"flex":"",Qe.classList.remove("persona-pointer-events-none","persona-opacity-0"),Ae.classList.remove("persona-scale-95","persona-opacity-0"),Ae.classList.add("persona-scale-100","persona-opacity-100"),qt?(qt.setPanelOpen(!0),qt.element.style.display="none"):Wn&&(Wn.style.display="none")):(a?a&&(q==="overlay"||q==="push")&&!k?(Qe.style.removeProperty("display"),Qe.style.display="flex",Qe.classList.remove("persona-pointer-events-none","persona-opacity-0"),Ae.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Qe.style.setProperty("display","none","important"),Qe.classList.remove("persona-pointer-events-none","persona-opacity-0"),Ae.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Qe.style.display="",Qe.classList.add("persona-pointer-events-none","persona-opacity-0"),Ae.classList.remove("persona-scale-100","persona-opacity-100"),Ae.classList.add("persona-scale-95","persona-opacity-0")),qt?(qt.setPanelOpen(!1),qt.element.style.display=a?"none":""):Wn&&(Wn.style.display=a?"none":""))},Et=(a,u="user")=>{if(!Ye()||D===a)return;let m=D;D=a,fl();let b=(()=>{let k=o.launcher?.sidebarMode??!1,q=e.ownerDocument.defaultView??window,re=o.launcher?.mobileFullscreen??!0,Y=o.launcher?.mobileBreakpoint??640,ie=q.innerWidth<=Y,le=Lt(o)&&re&&ie,de=Le()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return k||re&&ie&&ye||le||de})();if(D&&b){if(!zo){let k=e.getRootNode(),q=k instanceof ShadowRoot?k.host:e.closest(".persona-host");q&&(zo=Lm(q,o.launcher?.zIndex??kn))}Ko||(Ko=Hm(e.ownerDocument))}else D||(zo?.(),zo=null,Ko?.(),Ko=null);D&&(wl(),dg()||(Mn()==="follow"?as(!0):cg()));let w={open:D,source:u,timestamp:Date.now()};D&&!m?X.emit("widget:opened",w):!D&&m&&X.emit("widget:closed",w),X.emit("widget:state",{open:D,launcherEnabled:ye,voiceActive:st.active,streaming:R.isStreaming()})},ls={inputDisabled:!1,sendDisabled:!1},Yo=()=>ls.inputDisabled,gg=()=>Dn(o.voiceRecognition?.provider)&&!!R&&(R.isBargeInActive()||["listening","processing","speaking"].includes(R.getVoiceStatus())),oi=()=>ls.inputDisabled||ls.sendDisabled,$M=()=>(ls.inputDisabled?ls.inputReason:void 0)??(ls.sendDisabled?ls.sendReason:void 0);function fg(){if(!Pe)return;if(be.getState().phase==="streaming"){Pe.disabled=!1;return}let a=je?!je.isReady():!1;Pe.disabled=oi()||a}function Xc(){if(!Rn)return;let a=be.getState(),u=o.sendButton?.visibility==="when-text"&&a.phase!=="streaming"&&a.text.trim().length===0&&a.attachments.length===0;Rn.toggleAttribute("data-persona-send-hidden",u)}function UM(){let a=$M();if(Le()){let u=An??Ke;a?u.setAttribute("title",a):u.removeAttribute("title"),Ke.toggleAttribute(Ya,!!a);return}if(a){rt.setAttribute("role","status"),rt.setAttribute("aria-live","polite"),rt.setAttribute(Ya,""),rt.textContent=a,hi(rt,o.statusIndicator??{},"idle");return}if(rt.hasAttribute(Ya)&&(rt.removeAttribute("role"),rt.removeAttribute("aria-live"),rt.removeAttribute(Ya),h)){let u=R.getStatus();Bs(rt,ur(u),o.statusIndicator??{},u)}}function mg(){let a=Bf(o.composer?.inputDisabled),u=Bf(o.composer?.sendDisabled);ls={inputDisabled:a.disabled,inputReason:a.reason,sendDisabled:u.disabled,sendReason:u.reason},be.setInputDisabled(a.disabled),be.setSendDisabled(u.disabled);let m=be.getState().phase==="streaming",b=a.disabled,w=m||b;ce&&(ce instanceof HTMLTextAreaElement?ce.disabled=b:ce.setAttribute("contenteditable",b?"false":"true"),ce.setAttribute("aria-disabled",b?"true":"false")),It&&(It.disabled=b),Mt&&(Mt.disabled=b);for(let k of at?.affordanceButtons??[])k.querySelectorAll("button").forEach(q=>{q.disabled=b});he&&(he.disabled=b||m&&!gg()),js.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})}),wg.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})}),Ke.dataset.personaComposerStreaming=m?"true":"false",Ke.dataset.personaComposerInputDisabled=b?"true":"false",Ke.dataset.personaComposerSendDisabled=oi()?"true":"false",Ke.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(k=>{(k instanceof HTMLButtonElement||k instanceof HTMLInputElement||k instanceof HTMLTextAreaElement||k instanceof HTMLSelectElement)&&(k.disabled=m)}),fg(),UM()}let ml=a=>{be.setStreaming(a),Ac(a?"stop":"send"),mg()},Qc=()=>{st.active||ce&&ce.focus()};X.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>Qc(),200)});let Uy=null,hg=!1,yg=!en.hidden,cs=null,bg=!J,Jc=null;Se.push(()=>{Jc?.cancel(),Jc=null});let VM=a=>{let u=vA(a);if(u===N)return;N=u,e.setAttribute("data-persona-conversation-state",u);let m=pe();Ot(),bg&&(Jc?.cancel(),Jc=yA(Ke,u==="active"?m:pe(),u==="active"?"drop":"rise",M().layout==="centered"?320:260)),na()},Vy=null,jy,qy=null,ra=null,vg=!1,hl=a=>{let u=M(),m=`${u.variant}|${u.layout}|${u.dismiss}|${u.anchor??"bottom"}|${u.align??""}|${u.iconPlacement}|${u.kicker??""}|${u.title}|${u.subtitle}`;(m!==Vy||u.icon!==jy)&&(Vy=m,jy=u.icon,ou({host:en,iconHolder:wc,kicker:Sc,title:Wu,subtitle:Ni,starterSuggestions:gr},u));let b=u.message===void 0?null:`${o.layout?.messages?.layout??"bubble"}|${u.message}`;b!==qy&&(qy=b,ru(In,u.message,o));let w=a??(R?R.getMessages():o.initialMessages);VM(w);let k=hg,q=!k&&Ws(u,w),re=q!==yg;if(yg=q,ra){cs?.cancel(),cs=null,k!==vg&&(vg=k,k?Km(ae,en,null):zm(ae,en,ra)),$a(ae,en,!k);return}if(re&&!q&&!k&&u.dismiss==="on-first-message"&&bg){cs=hA(en,ie=>{cs===ie&&(cs=null),!yg&&!ra&&($a(ae,en,!1),na()),ie?.cancel()});return}if(cs){if(!q&&!k)return;cs.cancel(),cs=null}let Y=!en.hidden;$a(ae,en,q),!q&&Y&&na()},Cg=[],wg=[],Sg=!1,zy=null,Ky,Gy=()=>{wg.length=0;let a=Cg.splice(0,Cg.length);for(let u of a)try{u()}catch(m){console.warn("[persona] renderWelcome cleanup threw",m)}};Se.push(Gy);let jM=(a,u)=>{let m=Rm(a,u);if(!m)return o.debug===!0&&console.warn("[persona] renderStarter received a suggestion with no label"),x("span");let b=o.suggestions?.starters,w=Wm({item:{...m,behavior:m.behavior??b?.behavior??"send"},index:u,surface:"starter",source:"config",variant:b?.variant??"card",streaming:h?R.isStreaming():!1,config:o,plugins:d,chipsConfig:o.suggestionChipsConfig,session:R,getTextarea:()=>ce,eventTarget:en,submitPrompt:id});return wg.push(w),w},Ag=()=>{if(Sg)return;Sg=!0;let a=M();zy=`${a.variant}|${a.layout}|${a.dismiss}|${a.title}|${a.subtitle}|${a.message??""}`,Ky=a.icon;try{Gy(),Km(ae,en,ra),ra=null,vg=!1;let u=R?R.getMessages():o.initialMessages,m=Ws(a,u),b=0,w=null;for(let k of d)if(k.renderWelcome&&(w=k.renderWelcome({config:a,variant:a.variant,visible:m,defaultRenderer:()=>en,sendMessage:q=>{if(!R||R.isStreaming())return;let re=q.trim();re&&R.sendMessage(re)},requestRender:()=>Ag(),renderStarter:q=>jM(q,b++),storage:y(k.id),onCleanup:q=>{Cg.push(q)}}),w))break;w&&w!==en&&(ra=w,zm(ae,en,w))}finally{Sg=!1}hl()},qM=()=>{let a=M();`${a.variant}|${a.layout}|${a.dismiss}|${a.title}|${a.subtitle}|${a.message??""}`===zy&&a.icon===Ky||Ag()},Zc=()=>{hl(),Ki||(ce.placeholder=aS(be.getState().activeModeIds,o.composer?.modes)??o.copy?.inputPlaceholder??"How can I help...",!(o.sendButton?.useIcon??!1)&&!R?.isStreaming()&&(Pe.textContent=o.copy?.sendButtonLabel??"Send")),ce.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ce.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},zM=!!o.setStoredConversationId,sa=a=>qe(u=>{let m={...u};return delete m[a],m}),ed=a=>{let u=P[a];return typeof u=="string"?u:null},Yy=()=>{let a=P.durableResume;if(!a||typeof a!="object")return null;let u=a;return typeof u.executionId=="string"&&u.executionId.length>0&&typeof u.after=="string"&&u.after.length>0?{executionId:u.executionId,after:u.after}:null};o.clientToken&&(o={...o,getStoredSessionId:()=>ed("sessionId"),setStoredSessionId:a=>{qe(u=>({...u,sessionId:a}))},clearStoredSessionId:o.clearStoredSessionId??(()=>sa("sessionId")),getStoredConversationId:o.getStoredConversationId??(()=>ed("conversationId")),setStoredConversationId:o.setStoredConversationId??(a=>{qe(u=>({...u,conversationId:a}))}),clearStoredConversationId:o.clearStoredConversationId??(()=>sa("conversationId"))});let Xy=()=>o.clientToken??null,Qy=a=>ZA(a,Ct(),o.persistState===!1),Jy=Xy(),fo=Jy?Qy(Jy):null,KM=()=>{let a=P.pendingDisplayProjections;if(!a||typeof a!="object")return null;let u=a;return typeof u.conversationId!="string"||!Array.isArray(u.messageIds)?null:{conversationId:u.conversationId,messageIds:u.messageIds.filter(m=>typeof m=="string")}},ds={...fo?{visitorStore:fo}:{},historyBootstrapReady:o.features?.history?.enabled===!0&&!vp()?Promise.all([ue,me]).then(()=>{}):ue,getStoredMessageCursor:()=>ed("historyMessageCursor"),setStoredMessageCursor:a=>{if(a===null){sa("historyMessageCursor");return}qe(u=>({...u,historyMessageCursor:a}))},getPendingDisplayProjections:KM,setPendingDisplayProjections:a=>{if(!a){sa("pendingDisplayProjections");return}qe(u=>({...u,pendingDisplayProjections:a}))},getStoredResumableHandle:Yy,setStoredResumableHandle:a=>{if(!a){sa("durableResume");return}qe(u=>({...u,durableResume:a}))},shouldResumeDurableConversation:()=>B&&Yy()!==null,...zM?{}:{getStoredConversationRevision:()=>ed("conversationRevision"),setStoredConversationRevision:a=>{if(a===null){sa("conversationRevision");return}qe(u=>({...u,conversationRevision:a}))}}};if(B){let a=o.onExecutionState,u=e.ownerDocument.defaultView,m=!1,b=()=>m=!0,w=()=>m=!1;u?.addEventListener("pagehide",b),u?.addEventListener("pageshow",w),Se.push(()=>{u?.removeEventListener("pagehide",b),u?.removeEventListener("pageshow",w)}),o={...o,reconnectStream:o.reconnectStream??(k=>R.getClient().reconnectClientTokenStream(k)),onExecutionState:k=>{(k||!m)&&ds.setStoredResumableHandle?.(k?{executionId:k.executionId,after:k.lastEventId}:null),a?.(k)}}}let GM=()=>{let a=Xy();if(a&&fo?.matches(a,Ct(),o.persistState===!1)||!a&&!fo)return;fo?.destroy(),fo=a?Qy(a):null;let u={...ds};fo?u.visitorStore=fo:delete u.visitorStore,ds=u,R.setHistoryInternals(ds)},ri=null,YM=()=>{ri==null&&(ri=setInterval(()=>{let a=Te.querySelectorAll("[data-tool-elapsed]");if(a.length===0){clearInterval(ri),ri=null;return}let u=Date.now();a.forEach(m=>{let b=Number(m.getAttribute("data-tool-elapsed"));b&&(m.textContent=m.closest(".persona-activity-row")?Ul(u-b):Ad(u-b))})},100))},xg=(a,u)=>{if(Object.is(a,u))return!0;if(a===null||u===null||typeof a!="object"||typeof u!="object")return!1;if(Array.isArray(a)||Array.isArray(u))return!Array.isArray(a)||!Array.isArray(u)||a.length!==u.length?!1:a.every((q,re)=>xg(q,u[re]));let m=a,b=u,w=Object.keys(m),k=Object.keys(b);return w.length===k.length&&w.every(q=>Object.prototype.hasOwnProperty.call(b,q)&&xg(m[q],b[q]))},Zy=a=>{let{content:u,rawContent:m,llmContent:b,...w}=a;return w},Mg=a=>a.role==="assistant"&&a.streaming===!0&&!a.variant&&!a.toolCall&&!a.tools&&!a.approval&&!a.reasoning&&!a.contentParts&&!a.stopReason&&!hc(a),XM=(a,u,m)=>{if(a.length!==u.length)return!1;let b=a[m.index],w=u[m.index];return!b||!w||b.id!==m.id||w.id!==m.id?!1:(!Object.is(b.content,w.content)||!Object.is(b.rawContent,w.rawContent)||!Object.is(b.llmContent,w.llmContent))&&Mg(b)&&Mg(w)&&xg(Zy(b),Zy(w))},td=null,ia=null,si=null,xr=null,Eg=null,QM=a=>{if(!B)return Ji(a);Eg=a,queueMicrotask(()=>{Eg===a&&(Eg=null,Ji(a))})},nd=a=>{td=a;let u,m;ia=null;for(let w=a.length-1;w>=0;w-=1){let k=a[w];if(!u&&k.role==="user"&&(u=k),!m&&k.role==="assistant"&&(m=k),!ia&&Mg(k)&&(ia={index:w,id:k.id}),u&&m&&ia)break}go(Te,a,K),qr()?.updateInlineArtifactBlocks(Te,po.artifacts,{suppressTransition:to}),YM(),hl(a),Ks(a),as(!to),OM(a),a.length===0&&(ni(),ll=!0,Nc=!1,Qi=null,Fc=!1),!tg||Xi?(tg=!0,Zs=u?.id??null,ng=m?.id??null):u&&u.id!==Zs?(Zs=u.id,LM(u.id)):m&&m.id!==ng&&HM(),m&&(ng=m.id),WM(a);let b=st.lastUserMessageId;u&&u.id!==b&&(st.lastUserMessageId=u.id,X.emit("user:message",u)),st.lastUserMessageWasVoice=!!u?.viaVoice,QM(a),oa()},Tg=()=>{xr!==null&&(cancelAnimationFrame(xr),xr=null);let a=si;si=null,a&&nd(a)},eb=()=>{xr!==null&&cancelAnimationFrame(xr),xr=null,si=null},JM=a=>{let u=si??td;if(to&&u&&ia&&XM(u,a,ia)){si=a,xr===null&&(xr=requestAnimationFrame(()=>{xr=null;let m=si;si=null,m&&nd(m)}));return}if(a.length===0){eb(),nd(a);return}Tg(),nd(a)};R=new Wa(o,{onMessagesChanged(a){JM(a)},onStatusChanged(a){let u=o.statusIndicator??{};Bs(rt,(b=>b==="idle"?u.idleText??Yt.idle:b==="connecting"?u.connectingText??Yt.connecting:b==="connected"?u.connectedText??Yt.connected:b==="error"?u.errorText??Yt.error:b==="paused"?u.pausedText??Yt.paused:b==="resuming"?u.resumingText??Yt.resuming:Yt[b])(a),u,a),Yr()},onStreamingChanged(a){a||(R?.getMessages().length===0?eb():Tg()),to=a,ml(a),Yr(),R&&go(Te,R.getMessages(),K),a||(as(!0),PM(),My=!0,R&&Ey(R.getMessages(),xs(o))),Tn(),$s(a?"Responding\u2026":"Response complete."),oa()},onVoiceStatusChanged(a){if(X.emit("voice:status",{status:a,timestamp:Date.now()}),!(a!=="disconnected"&&!Dn(o.voiceRecognition?.provider)))switch(a){case"listening":if(!rg){let u=R.getVoiceDisclosure();u&&(rg=!0,Le()?($c=ce.placeholder,ce.placeholder=u,$s(u)):pb(u,1e4))}Tr(),da();break;case"processing":Tr(),wE();break;case"speaking":Tr(),SE();break;default:a==="idle"&&R.isBargeInActive()?(Tr(),da(),he?.setAttribute("aria-label","End voice session")):(st.active=!1,rg=!1,$c!==null&&(ce.placeholder=$c,$c=null),Tr(),Sr("system"),Ho());break}},onArtifactsState(a){po=a,a.artifacts.length===0&&(Gi=!1),qr()?.updateInlineArtifactBlocks(Te,a.artifacts,{suppressTransition:to}),Lo(),Ji()},onHistoryStateChanged(a){pr(a)},onHistoryNotice(a){Uo(a)},onReconnect(a){let{executionId:u,lastEventId:m}=a.handle;a.phase==="paused"?X.emit("stream:paused",{executionId:u,after:m}):a.phase==="resuming"?X.emit("stream:resuming",{executionId:u,after:m,attempt:a.attempt??1}):X.emit("stream:resumed",{executionId:u,after:m})}},ds),uo.current=R,Se.push(()=>R.cancel()),Se.push(()=>{R.destroy(),fo?.destroy(),fo=null});let Pg=null;if(R.onReadAloudChange((a,u)=>{ey=a,ty=u,ny();let m=a??Pg;a&&(Pg=a);let b=m?R.getMessages().find(w=>w.id===m)??null:null;X.emit("message:read-aloud",{messageId:m,message:b,state:u,timestamp:Date.now()}),u==="idle"&&(Pg=null)}),h=!0,tg=!0,o.voiceRecognition?.enabled===!0&&Dn(o.voiceRecognition.provider))try{R.setupVoice()}catch(a){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",a)}let _t=null,kg=null,tb=!1,nb=R.getHistoryState(),yl=()=>o.features?.history?.enabled===!0,ob=a=>{a&&(Eo.textContent="",Eo.textContent=a)},Lg=()=>{f.forEach(m=>m()),f=[];let a=_t,u=a?.railCollapseShortcut();a&&u&&f.push(g.register({id:"history-rail-collapse",combo:u.combo,scope:o.features?.history?.rail?.collapseShortcutScope==="page"?"page":"widget",when:()=>un&&Un==="rail"&&a.railCollapsible()||a.railTriggerApplies(),run:()=>a.railOverlayMode()?a.toggleRailPinned():a.toggleRailCollapsed()}));for(let m of o.layout?.header?.trailingActions??[])m.shortcut&&f.push(g.register({id:`header-action-${m.id}`,combo:m.shortcut,run:()=>{let b=e.querySelector(`[data-persona-header-action="${m.id}"]`);b?b.click():o.layout?.header?.onAction?.(m.id)}}));for(let m of d)for(let b of m.shortcuts??[])f.push(g.register({...b,id:`${m.id}:${b.id}`}))};Lg();let od=null,rb=!1,bl=()=>{if(!Vo)return;let a=o.layout?.header?.titleSource==="conversation",u=a&&od?.trim()||null;Vo.textContent=u??o.launcher?.title??"Chat Assistant";let m=Vo.closest(".persona-combo-btn");if(!m)return;let b=!a||R.getActiveConversationId()!==null;m.setAttribute("data-persona-menu-locked",b?"false":"true"),m.setAttribute("aria-haspopup",b?"true":"false"),b||m.setAttribute("aria-expanded","false"),m.style.cursor=b?"pointer":"default";let w=m.querySelector("svg");w&&(w.style.display=b?"":"none")},ZM=a=>{a!==od&&(od=a,bl())},eE=a=>{rb=a?.starred===!0,ZM(a&&a.title.trim()||null),bl()};bl(),we.addEventListener("persona:title-menu-builtin",a=>{let u=a.detail?.actionId,m=R.getActiveConversationId();m&&(u==="delete"?Xo(b=>b.requestDeleteConversation(m)):u==="star"&&R.canUpdateConversations()&&Xo(b=>b.updateHistoryConversation(m,{starred:!rb})).catch(()=>{}))}),pr=a=>{nb=a,_t?.historySurface?.view.setNewConversationRequired(a.recovery==="new_conversation_required"),ml(a.sendBlocked||to),_t?.syncEarlierMessagesPill()},Uo=a=>{(a.code==="history_continuity_reset"||a.code==="conversation_deleted_recovered")&&(En.clear(),ni(),Go()),ob(a.message),_t?.historySurface?.view.refresh()};let tE={get actionManager(){return Be},get activeConversationTitle(){return od},announceHistory:ob,get applyRailChrome(){return Vn},set applyRailChrome(a){Vn=a},get artifactSplitRoot(){return br},get body(){return ae},get config(){return o},get container(){return we},get conversationOpenPendingEl(){return Uy},set conversationOpenPendingEl(a){Uy=a},get conversationOpenTakeover(){return hg},set conversationOpenTakeover(a){hg=a},currentKeyPrefix:Ct,destroyCallbacks:Se,eventBus:X,get footer(){return Ke},get header(){return mt},get historyChromeSync(){return Yr},set historyChromeSync(a){Yr=a},historyFeatureEnabled:yl,get historyInternals(){return ds},set historyInternals(a){ds=a},get historyPresentation(){return Un},set historyPresentation(a){Un=a},get historySessionState(){return nb},get historyVisible(){return un},set historyVisible(a){un=a},get isStreaming(){return to},jumpToBottomInstant:cg,get lastAppliedMessages(){return td},set lastAppliedMessages(a){td=a},get launcherEnabled(){return ye},get launcherSurfaceInstance(){return qt},maybeFocusInput:Qc,messageCache:En,get messagesWrapper(){return Te},mount:e,get open(){return D},panel:Ae,panelElements:Ze,get persistentMetadata(){return P},set persistentMetadata(a){P=a},plugins:d,get reapplyHistoryHostChrome(){return dr},set reapplyHistoryHostChrome(a){dr=a},repinAnchoredMessage:na,resetAnchorState:ni,restoreScrollPosition:dg,resumeAutoScroll:Go,runStorageMutation:Vc,get session(){return R},setActiveConversationSummary:eE,storageAdapter:T,get suppressScrollSend(){return Xi},set suppressScrollSend(a){Xi=a},syncScrollToBottomButton:Tn,updateWelcome:hl,getHistoryProviderFactory:tx,historyErrors:{HistoryClientError:on,HistoryProviderError:Vr},isDockedMountMode:Lt,renderLucideIcon:ge,loadHistoryView:ex,createHeaderIconButton:Ba,attachTooltip:vn},Hg=a=>(!_t&&!tb&&(_t=a.createHistoryShell(tE),_t.railCollapseShortcut()&&Lg()),_t),Ig=()=>{if(_t)return Promise.resolve(_t);let a=vp();return a?Promise.resolve(Hg(a)):(kg??=ew().then(Hg,u=>{throw kg=null,u}),kg)},Xo=a=>{let u=vp(),m=_t??(u?Hg(u):null);return m?a(m):Ig().then(b=>{if(!b)throw new Error("[AgentWidget] The widget was destroyed");return a(b)})},rd=()=>{_t?.syncHistoryPresentation()};Se.push(()=>{tb=!0}),yl()&&Ig().catch(()=>{}).finally(fe),o.clientToken&&(o.features?.history?.enabled===!0||o.sessionInit==="mount")&&R.initClientSession().then(()=>{let a=_t;if(a?.historyAvailable())return R.reconcileBootConversation({scope:a.historyScope()})}).then(()=>{_t?.syncEarlierMessagesPill()}).catch(a=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",a)});let Rg=()=>R.warmClientSession(),sb=a=>{let u=o.sessionInit??"input",m=ct?.input??ce,b=a.target;m&&(a.type==="input"?(u==="input"||u==="focus")&&b===m&&a.inputType&&m.value.trim():u==="focus"&&(a.type==="keyup"?b===m&&a.key==="Tab":(ct?.form??An)?.contains(b)))&&Rg()},ib=["input","pointerdown","keyup"];ib.forEach(a=>e.addEventListener(a,sb));let ab,Wg,lb=()=>{let a=Wg;Wg=void 0;try{typeof a=="function"&&a()}catch{}},cb=()=>{let a=o.clientToken&&typeof o.sessionInit=="function"?o.sessionInit:void 0;if(a!==ab){lb(),ab=a;try{Wg=a?.({warm:Rg,mount:e})}catch{}}};cb(),Se.push(()=>{ib.forEach(a=>e.removeEventListener(a,sb)),lb()}),(Ce||o.onSSEEvent)&&R.setSSEEventCallback((a,u)=>{o.onSSEEvent?.(a,u),Qa(a,u)});let db=()=>{let a=o.resume??(B?ds.getStoredResumableHandle?.():null);a&&typeof o.reconnectStream=="function"&&R.resumeFromHandle(a)};J?J.then(a=>{if(a){if(a.metadata&&(P=bh(a.metadata),Be.syncFromMetadata()),a.messages?.length){Xi=!0;try{R.hydrateMessages(a.messages)}finally{Xi=!1}Yc()}a.artifacts?.length&&R.hydrateArtifacts(a.artifacts,a.selectedArtifactId??null),Iy(a.draft)}}).catch(a=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",a)}).finally(()=>{bg=!0,U(),db()}):(Iy(He),db());let nE=()=>{!Le()||D||!(o.launcher?.composerBar?.expandOnSubmit??!0)||Et(!0,"auto")},oE=(a,u)=>a?u?{refs:[...a.refs,...u.refs],finalize:async()=>{let[m,b]=await Promise.allSettled([a.finalize(),u.finalize()]),w=[];return m.status==="fulfilled"?w.push(m.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",m.reason),b.status==="fulfilled"?w.push(b.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",b.reason),rH(w)}}:a:u,Og=()=>{let u=ce.getInlineMessageFields?.();return u&&u.contentSegments.some(b=>b.kind==="mention")?u.contentSegments:void 0},Mr=!1,ii=null,sd=()=>{ce.value="",ce.style.height="auto",co(),Cl()},Bg="data-persona-composer-notice",aa=null;function pb(a,u=4e3){$s(a),!(Le()||!rt)&&(rt.hasAttribute(Ya)||(rt.setAttribute(Bg,""),rt.setAttribute("role","status"),rt.setAttribute("aria-live","polite"),rt.textContent=a,hi(rt,o.statusIndicator??{},"idle"),aa&&clearTimeout(aa),aa=setTimeout(()=>{if(aa=null,!!rt?.hasAttribute(Bg)&&(rt.removeAttribute(Bg),rt.removeAttribute("role"),rt.removeAttribute("aria-live"),h)){let m=R.getStatus();Bs(rt,ur(m),o.statusIndicator??{},m)}},u)))}function rE(){let a=be.getState().pendingSubmission;a&&(qi(void 0),ce&&(ce.value=a.text,ce.dispatchEvent(new Event("input",{bubbles:!0})),co()),a.options.selectedModelId&&(be.setSelectedModelId(a.options.selectedModelId),Zr?.repaint()),a.options.activeModeIds?.length&&Ec(a.options.activeModeIds),a.options.quote&&qo(a.options.quote),ce?.focus())}let sE=a=>{typeof console<"u"&&console.error("[AgentWidget] composer.onBeforeSend failed; the draft was preserved:",a)},ub=(a={})=>{let u=(a.overrideText??ce?.value??"").trim();return a.resolveInlineCommand&&u?(at?.takeInlineCommand(u)??Promise.resolve(null)).then(m=>gb(a,u,m)):gb(a,u,null)},gb=(a,u,m)=>{if(m?.kind==="action"){sd(),at?.clear(),mr();return}let b=m?.kind==="server"?m.mentions:null,w=m?.kind==="prompt"?m.sendText:u,k=a.pending?.contentParts,q=(je?.hasAttachments()??!1)||(k?.length??0)>0;if(!CS({text:w,hasAttachments:q,attachmentsReady:je?.isReady()??!0,hasMentions:at?.hasMentions()??!1,hasServerMentions:!!b,inputDisabled:Yo(),sendDisabled:oi()}))return;let re=R.isStreaming()?Nu():"block";if(re==="defer-one"&&!a.pending){if(be.getState().pendingSubmission){pb("One message is already queued. Edit or remove it first.");return}iE({intent:a,sendText:w,serverMentions:b});return}let Y={text:w,mentionRefs:[...at?.getMentionRefs()??[],...b?.refs??[]],contentSegments:m?.kind==="prompt"?void 0:Og(),options:{...be.getState().selectedModelId&&{selectedModelId:be.getState().selectedModelId},...be.getState().activeModeIds.length>0&&{activeModeIds:[...be.getState().activeModeIds]},...be.getState().quote&&{quote:{...be.getState().quote}}},viaVoice:a.viaVoice};a.pending&&(Y.options={...a.pending.options},Y.contentSegments=a.pending.contentSegments,Y.mentionRefs=[...a.pending.mentionRefs],Y.viaVoice=a.pending.viaVoice);let ie=()=>{if(k?.length)return[...k];if(!je?.hasAttachments())return;let dt=[...je.getContentParts()];return Y.text&&dt.push(So(Y.text)),dt};Y.contentParts=ie();let le=()=>{Xs(),nE();let dt=at?.collectForSubmit()??null,zn=oE(dt,b),Dt=ie();a.consumeDraft!==!1&&sd();let jt={selectedModelId:Y.options.selectedModelId,activeModeIds:Y.options.activeModeIds},On=re==="interrupt";On&&R.cancel(),R.sendMessage(Y.text,{contentParts:Dt,mentions:zn??void 0,contentSegments:Y.contentSegments,viaVoice:Y.viaVoice,composerOptions:jt,...Y.options.quote&&{quote:Y.options.quote},...On&&{interrupt:!0}}),je?.hasAttachments()&&je.clearAttachments(),dt&&at?.clear(),mr();let Kt=be.getState().activeModeIds,wt=iS(Kt,o.composer?.modes);wt.length!==Kt.length&&Ec(wt),be.getState().quote&&qo(void 0),qc(),qu.release(),Po()},de=o.composer?.onBeforeSend;if(!de){le();return}let ke=new AbortController;ii=ke;let it=dt=>{if(ii=null,dt.status==="error"){sE(dt.error);return}dt.status==="proceed"&&le()},gt=wS(de,Y,ke.signal);if(!(gt instanceof Promise)){it(gt);return}return be.setPreparing(!0),gt.then(it).finally(()=>be.setPreparing(!1))};function iE(a){let u=be.getState(),m=je?.hasAttachments()??!1,b=m?[...je.getContentParts()]:[];m&&a.sendText&&b.push(So(a.sendText));let w=Cm({text:a.sendText,contentParts:b.length?b:void 0,mentionRefs:[...at?.getMentionRefs()??[],...a.serverMentions?.refs??[]],contentSegments:Og(),options:{...u.selectedModelId&&{selectedModelId:u.selectedModelId},...u.activeModeIds.length>0&&{activeModeIds:[...u.activeModeIds]},...u.quote&&{quote:{...u.quote}}},viaVoice:a.intent.viaVoice});qi(w),a.intent.consumeDraft!==!1&&sd(),m&&je.clearAttachments(),at?.clear(),mr(),u.quote&&qo(void 0),qc(),qu.release(),Po(),$s("Message queued. It sends when the response finishes.")}function aE(){let a=be.getState().pendingSubmission;a&&(qi(void 0),ad(a.text,{consumeDraft:!1,pending:a}))}function lE(a){if(o.messageActions?.showEdit!==!0)return;let u=R.getMessages().find(m=>m.id===a);!u||!lm(u)||Ys!==a&&(Xs(),Ys=a,os=pS({messageId:a,initialText:u.content,onSave:m=>cE(a,m),onCancel:()=>Xs()}),En.delete(a),go(Te,R.getMessages(),K),os.focus())}function cE(a,u){let m=os;if(Ys=null,os=null,m?.destroy(),En.delete(a),!R.resubmitFrom(a,{reason:"edit",replacement:{text:u,mentionRefs:[],options:{}}})){go(Te,R.getMessages(),K);return}na()}function dE(a){if(R.isStreaming())return;let u=am(R.getMessages(),a);u&&(Xs(),R.resubmitFrom(u,{reason:"retry"})&&na())}Tc={regenerate:dE,edit:lE,quote:a=>{let m=R.getMessages().find(b=>b.id===a)?.content?.trim();m&&(qo({text:m,messageId:a}),ce?.focus())}};let vl=async a=>{if(!Mr){Mr=!0;try{await ub({resolveInlineCommand:!0,...a})}finally{Mr=!1}}};function id(a){oi()||(sd(),ad(a,{consumeDraft:!1}))}let ad=(a,u)=>{if(Mr)return;Mr=!0;let m=()=>{Mr=!1};try{let b=ub({...u,overrideText:a});b instanceof Promise?b.finally(m):m()}catch(b){throw m(),b}},pE=a=>{if(a.preventDefault(),R.isStreaming()){R.cancel(),bt?.reset(),rn?.update();return}Mr||vl()},uE=()=>o.features?.composerHistory!==!1,_g={...Em},Dg=!1,Cl=()=>{_g={...Em}},gE=()=>R.getMessages().filter(a=>a.role==="user").map(a=>a.content??"").filter(a=>a.length>0),fE=a=>{if(!ce)return;Dg=!0,ce.value=a,ce.dispatchEvent(new Event("input",{bubbles:!0})),Dg=!1;let u=ce.value.length;ce.setSelectionRange(u,u)},mE=a=>{Dg||(a.isComposing||at?.handleInput(a.inputType??void 0),Cl())},hE=()=>({submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:_l(ce)}),yE=a=>{if(ce&&!Yo()&&!(!a.isComposing&&at?.handleKeydown(a))){if(uE()&&(a.key==="ArrowUp"||a.key==="ArrowDown")&&!a.shiftKey&&!a.metaKey&&!a.ctrlKey&&!a.altKey&&!a.isComposing){let u=ce.selectionStart===0&&ce.selectionEnd===0,m=OS({direction:a.key==="ArrowUp"?"up":"down",history:gE(),currentValue:ce.value,atStart:u,state:_g});if(_g=m.state,m.handled){a.preventDefault(),m.value!==void 0&&fE(m.value);return}}if(RC(a,hE())){if(R.isStreaming()){if(a.preventDefault(),Nu()==="block"||Mr||oi())return;Cl(),vl();return}if(Mr){a.preventDefault();return}if(oi()){a.preventDefault();return}Cl(),a.preventDefault(),Pe.click()}}},fb=a=>{if(!(a.key!=="Escape"||a.isComposing)&&a.composedPath().includes(we)){if(ii){ii.abort(),ii=null,a.preventDefault(),a.stopImmediatePropagation();return}R.isStreaming()&&(R.cancel(),bt?.reset(),rn?.update(),Cl(),a.preventDefault(),a.stopImmediatePropagation())}},bE=async a=>{if(o.attachments?.enabled!==!0||!je||Yo())return;let u=eH(a.clipboardData);u.length!==0&&(a.preventDefault(),await je.handleFiles(u))},mo=null,Qo=!1,la=null,Er=null,Ng=()=>o.voiceRecognition?.completionBehavior==="review";function ld(a){he?.setAttribute("data-state",a),a==="recording"?CE():Vg()}let mb="--persona-voice-level",Fg=.5,ca=null,$g=-1,cd=0,hb=()=>{let a=[],u=gn??he?.parentElement??null;return u&&a.push(u),Ke&&a.push(Ke),a},Ug=a=>{let u=Math.round(Math.max(0,Math.min(1,a))*100)/100;if(u!==$g){$g=u;for(let m of hb())m.style.setProperty(mb,String(u))}},vE=()=>{$g=-1,cd=0;for(let a of hb())a.style.removeProperty(mb)};function CE(){if(ca!==null)return;if(typeof requestAnimationFrame!="function"){Ug(h?R.getVoiceLevel()??Fg:Fg);return}let a=()=>{ca=requestAnimationFrame(a);let u=h?R.getVoiceLevel():null;if(u===null){Ug(Fg);return}cd+=(u-cd)*.3,Ug(cd)};ca=requestAnimationFrame(a)}function Vg(){ca!==null&&(cancelAnimationFrame(ca),ca=null),vE()}let yb=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,dd=(a="user")=>{if(Qo||R.isStreaming())return;let u=yb();if(!u)return;mo=new u;let m=o.voiceRecognition??{},b=m.pauseDuration??2e3;mo.continuous=m.provider?.browser?.continuous??!0,mo.interimResults=!0,mo.lang=m.provider?.browser?.language??"en-US";let w=ce.value;mo.onresult=k=>{let q="",re="";for(let ie=0;ie<k.results.length;ie++){let le=k.results[ie],de=le[0].transcript;le.isFinal?q+=de+" ":re=de}let Y=w+q+re;ce.value=Y,co(),la&&clearTimeout(la),(q||re)&&(la=window.setTimeout(()=>{if(ce.value.trim()&&mo&&Qo){if(ps(),Ng())return;vl({viaVoice:!0})}},b))},mo.onerror=k=>{k.error!=="no-speech"&&ps()},mo.onend=()=>{if(Qo){let k=ce.value.trim();!Ng()&&k&&k!==w.trim()&&vl({viaVoice:!0}),ps()}};try{if(mo.start(),Qo=!0,st.active=!0,a!=="system"&&(st.manuallyDeactivated=!1),Sr(a),Ho(),Po(),he){let k=o.voiceRecognition??{};Er={backgroundColor:he.style.backgroundColor,color:he.style.color,borderColor:he.style.borderColor,iconName:k.iconName??"mic",iconSize:parseFloat(k.iconSize??"")||Xn};let q=k.recordingBackgroundColor,re=k.recordingIconColor,Y=k.recordingBorderColor;if(he.classList.add("persona-voice-recording"),ld("recording"),he.style.backgroundColor=q??"var(--persona-voice-recording-bg, #ef4444)",he.style.color=re??"var(--persona-voice-recording-indicator, #ffffff)",re){let ie=he.querySelector("svg");ie&&ie.setAttribute("stroke",re)}Y&&(he.style.borderColor=Y),he.setAttribute("aria-label","Stop voice recognition")}}catch{ps("system")}},ps=(a="user")=>{if(Qo){if(Qo=!1,la&&(clearTimeout(la),la=null),mo){try{mo.stop()}catch{}mo=null}if(st.active=!1,Sr(a),Ho(),Po(),he){if(he.classList.remove("persona-voice-recording"),ld("idle"),Er){he.style.backgroundColor=Er.backgroundColor,he.style.color=Er.color,he.style.borderColor=Er.borderColor;let u=he.querySelector("svg");u&&u.setAttribute("stroke",Er.color||"currentColor"),Er=null}he.setAttribute("aria-label","Start voice recognition")}}},bb=null,pd=a=>{let u=b=>{bb??=b.createMicStateStyles({mic:()=>he,config:()=>o,session:()=>R,get original(){return Er},set original(w){Er=w},setMicState:ld,renderIcon:ge,iconFallbackPx:Xn}),a(bb)},m=Iw();m?u(m):zl().then(u,()=>{})},da=()=>pd(a=>a.recording()),wE=()=>pd(a=>a.processing()),SE=()=>pd(a=>a.speaking()),Tr=()=>pd(a=>a.reset()),jg=()=>{if(!Yo()){if(Dn(o.voiceRecognition?.provider)){let a=R.getVoiceStatus(),u=R.getVoiceInterruptionMode();if(u==="none"&&(a==="processing"||a==="speaking"))return;if(u==="cancel"&&(a==="processing"||a==="speaking")){R.stopVoicePlayback();return}if(R.isBargeInActive()){R.stopVoicePlayback(),R.deactivateBargeIn().then(()=>{st.active=!1,st.manuallyDeactivated=!0,Ho(),Sr("user"),Tr()});return}R.toggleVoice().then(()=>{st.active=R.isVoiceActive(),st.manuallyDeactivated=!R.isVoiceActive(),Ho(),Sr("user"),R.isVoiceActive()?da():Tr()});return}if(Qo){let a=ce.value.trim();st.manuallyDeactivated=!0,Ho(),ps("user"),a&&!Ng()&&vl()}else st.manuallyDeactivated=!1,Ho(),dd("user")}};Fu=jg;let vb=()=>R.prewarmVoice(),Cb=()=>{let a=o.voiceRecognition;return a?.enabled!==!0?!1:a.prewarm??(o.clientToken?"hover":!1)},wb=a=>{Cb()==="hover"&&he?.contains(a.target)&&vb()},Sb=["pointerover","pointerdown","focusin"];Sb.forEach(a=>e.addEventListener(a,wb));let Ab,xb=null,qg,Mb=()=>{let a=qg;qg=void 0;try{typeof a=="function"&&a()}catch{}},zg=()=>{let a=Cb(),u=typeof a=="function"&&he?a:void 0,m=u?he:null;if(!(u===Ab&&m===xb)&&(Mb(),Ab=u,xb=m,!(!u||!m)))try{qg=u({warm:vb,micButton:m,mount:e})}catch{}};zg(),Se.push(()=>{Sb.forEach(a=>e.removeEventListener(a,wb)),Mb()}),he&&Se.push(()=>{Dn(o.voiceRecognition?.provider)?(R.isVoiceActive()&&R.toggleVoice(),Tr()):ps("system")});let AE=X.on("assistant:complete",()=>{be.getState().pendingSubmission&&setTimeout(()=>{R.isStreaming()||aE()},0)});Se.push(AE);let xE=X.on("assistant:complete",()=>{ky&&(st.active||st.manuallyDeactivated||ky==="assistant"&&!st.lastUserMessageWasVoice||setTimeout(()=>{!st.active&&!st.manuallyDeactivated&&(Dn(o.voiceRecognition?.provider)?R.toggleVoice().then(()=>{st.active=R.isVoiceActive(),Sr("auto"),R.isVoiceActive()&&da()}):dd("auto"))},600))});Se.push(xE);let ME=X.on("action:resubmit",()=>{setTimeout(()=>{R&&!R.isStreaming()&&R.continueConversation()},100)});Se.push(ME);let Eb=()=>{Et(!D,"user")},qt=null,Wn=null;if(ye&&!Le()){let{instance:a,element:u}=Zm({config:o,plugins:d,onToggle:Eb});qt=a,a||(Wn=u)}qt?e.appendChild(qt.element):Wn&&e.appendChild(Wn),fl(),Ks(),Zc(),Ag(),ml(R.isStreaming()),dg()||(Mn()==="follow"?as(!0):cg()),SM(),Zt&&(!ye||Le()?setTimeout(()=>Qc(),0):D&&setTimeout(()=>Qc(),200));let us=null,Tb=()=>{us&&(us.disconnect(),us.observe(Ke),us.observe(we),us.observe(en))},Pb=jn(),wl=()=>{if(Le()){Re(),fl();return}let a=Lt(o),u=o.launcher?.sidebarMode??!1,m=e.ownerDocument.defaultView??window,b=o.launcher?.mobileFullscreen??!0,w=o.launcher?.mobileBreakpoint??640,k=m.innerWidth<=w,q=b&&k&&ye;try{if(q){Us(),rl=Bc();return}let re=!1;vt&&(vt=!1,Us(),re=!0);let Y=Bc();if(!re&&Y!==rl&&(Us(),re=!0),rl=Y,re&&Ic(),!ye&&!a){Ae.style.height="",Ae.style.width="";return}if(!u&&!a){let ie=Hi(o);Ae.style.width=ie.width,Ae.style.maxWidth=ie.maxWidth}Oc(),gy()}finally{Re(),Ot();let re=jn();if(re!==Pb&&(Pb=re,hl(),Ks()),fl(),D&&ye){let ie=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),le=o.launcher?.sidebarMode??!1,de=o.launcher?.mobileFullscreen??!0,ke=Lt(o)&&de&&ie,it=le||de&&ie&&ye||ke;if(it&&!Ko){let gt=e.getRootNode(),dt=gt instanceof ShadowRoot?gt.host:e.closest(".persona-host");dt&&!zo&&(zo=Lm(dt,o.launcher?.zIndex??kn)),Ko=Hm(e.ownerDocument)}else it||(zo?.(),zo=null,Ko?.(),Ko=null)}}};wl();let ud=e.ownerDocument.defaultView??window;if(ud.addEventListener("resize",wl),Se.push(()=>ud.removeEventListener("resize",wl)),typeof ResizeObserver<"u"){us=new ResizeObserver(()=>{Ot()}),Tb(),Se.push(()=>{us?.disconnect(),us=null});let a=new ResizeObserver(()=>{rd()});a.observe(we),Se.push(()=>a.disconnect())}ud.addEventListener("resize",rd),Se.push(()=>ud.removeEventListener("resize",rd)),oo=ae.scrollTop;let kb=ir(ae),Lb=()=>{uy();let a=ae.scrollTop,u=ir(ae),m=u<kb;if(kb=u,!Mo()){oo=a,Tn();return}let{action:b,nextLastScrollTop:w}=VS({following:no.isFollowing(),currentScrollTop:a,lastScrollTop:oo,nearBottom:Ei(ae,Cr),userScrollThreshold:bM,isAutoScrolling:qn||Dc||m,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(oo=w,b==="resume"){zc()||Go();return}b==="pause"&&ta()};if(ae.addEventListener("scroll",Lb,{passive:!0}),Se.push(()=>ae.removeEventListener("scroll",Lb)),typeof ResizeObserver<"u"){let a=new ResizeObserver(()=>{kM(),om(Te)});a.observe(Te),a.observe(ae),Se.push(()=>a.disconnect())}let Hb=()=>{Mo()&&no.isFollowing()&&zc()&&ta()},Ib=ae.ownerDocument;Ib.addEventListener("selectionchange",Hb),Se.push(()=>{Ib.removeEventListener("selectionchange",Hb)});let EE=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),Rb=a=>{EE.has(a.key)&&(is(),Ja()&&Mo()&&no.isFollowing()&&ta())},Wb=a=>{a.target?.closest("a, button, [tabindex], input, textarea, select")&&(is(),Ja()&&Mo()&&no.isFollowing()&&ta())};ae.addEventListener("keydown",Rb),ae.addEventListener("focusin",Wb),Se.push(()=>{ae.removeEventListener("keydown",Rb),ae.removeEventListener("focusin",Wb)});let Ob=a=>{if(a.deltaY!==0&&is(),!Mo())return;let u=jS({following:no.isFollowing(),deltaY:a.deltaY,nearBottom:Ei(ae,Cr),resumeWhenNearBottom:!0});u==="pause"?ta():u==="resume"&&!zc()&&Go()};ae.addEventListener("wheel",Ob,{passive:!0}),ae.addEventListener("touchmove",is,{passive:!0}),ae.addEventListener("pointerdown",is,{passive:!0}),Se.push(()=>{ae.removeEventListener("touchmove",is),ae.removeEventListener("pointerdown",is)}),Se.push(()=>ae.removeEventListener("wheel",Ob)),Vt.addEventListener("click",()=>{ni(),ae.scrollTop=ae.scrollHeight,oo=ae.scrollTop,Go(),as(!0),Tn()}),Se.push(()=>Vt.remove()),Se.push(()=>{Wy(),ni()});let Bb=()=>{ze&&(qs&&(ze.removeEventListener("click",qs),qs=null),Ye()?(ze.style.display="",qs=()=>{Et(!1,"user")},ze.addEventListener("click",qs)):ze.style.display="none")};Bb(),(()=>{let{clearChatButton:a}=Ze;a&&a.addEventListener("click",()=>{let u=_t;if(u?.historyAvailable()){u.startNewConversation({focusComposer:!0}).catch(b=>{o.debug&&console.warn("[AgentWidget] New conversation failed:",b)});return}R.clearMessages(),o.layout?.topFade&&(ae.scrollTop=0),ae.removeAttribute("data-persona-top-fade"),En.clear(),Go(),Wr(Ze.composerOverlay);try{localStorage.removeItem(Ga),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ga}`)}catch(b){console.error("[AgentWidget] Failed to clear default localStorage:",b)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Ga)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(b){console.error("[AgentWidget] Failed to clear custom localStorage:",b)}let m=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(m),T?.clear&&Vc(()=>T.clear(),"[AgentWidget] Failed to clear storage adapter:"),P={},Be.syncFromMetadata(),je?.clearAttachments(),qc(),qi(void 0),qo(void 0),Xs(),ft?.clear(),bt?.reset(),rn?.update()})})();let _b=[["keydown",yE],["input",mE],["input",co],["input",mr],["keyup",mr],["paste",bE],["focus",iM]],Db=a=>{if(a)for(let[u,m]of _b)ct?.addListener(a,u,m)},TE=a=>{if(a)for(let[u,m]of _b)ct?.removeListener(a,u,m)},Nb=()=>{ct&&(ct.addListener(ct.form,"submit",pE),ct.addListener(ct.footer,"click",mr),Db(ce),he&&ct.addListener(he,"click",jg),zg())};Nb();let Fb=()=>{at?.onComposerSwap((a,u)=>{TE(u),ce=a,ct&&(ct.input=a),Db(a),Uu(),mg(),co()})};Fb();let Kg=!1;function $b(){if(!Kg){Kg=!0;try{let a=ce?.value??"",u=Ke.ownerDocument??document,m=ce?u.activeElement===ce:!1;Vg(),ct?.destroy(),ct=null,at?.destroy(),at=null;let b=null,w=()=>(b=Le()?eu({config:o}):ki({config:o}),b.footer),k=qh(w)??w();Ln.replaceComposer(k),Ke=Ln.composer.footer;let q=b!==null&&k===b.footer;Ki=!q,Ac=q?b.setSendButtonMode:()=>{},jh(Ke),Kh(Ke),Gh(),Yh(),Vu(),Fb(),Xh(),ju(),Qh(),Nb();let re=js.indexOf(vr);if(vr.destroy(),vr=ac(lo),re>=0&&(js[re]=vr),ce&&(ce.value=a),co(),mr(),Zc(),Ks(),ml(R.isStreaming()),o.statusIndicator?.mode==="transient"&&!Le()){let Y=R.getStatus();Bs(rt,ur(Y),o.statusIndicator,Y)}st.active&&ld("recording"),Us(),Tb(),Re(),Po(),Xc(),m&&ce?.focus()}finally{Kg=!1}}}let Sl=e.ownerDocument??document;Sl.addEventListener("keydown",fb,!0);let Ub=()=>{sg()},Vb=()=>{Sl.visibilityState==="hidden"&&sg()};typeof window<"u"&&(window.addEventListener("pagehide",Ub),Sl.addEventListener("visibilitychange",Vb),Se.push(()=>{window.removeEventListener("pagehide",Ub),Sl.removeEventListener("visibilitychange",Vb)}));let jb="persona-attachment-drop-active",Al=0,Gg=()=>{Al=0,we.classList.remove(jb)},pa=()=>o.attachments?.enabled===!0&&je!==null&&!Yo(),qb=a=>{!hu(a.dataTransfer)||!pa()||(Al++,Al===1&&we.classList.add(jb))},zb=a=>{!hu(a.dataTransfer)||!pa()||(Al--,Al<=0&&Gg())},Kb=a=>{!hu(a.dataTransfer)||!pa()||(a.preventDefault(),a.dataTransfer.dropEffect="copy")},Gb=a=>{if(!hu(a.dataTransfer)||!pa())return;a.preventDefault(),a.stopPropagation(),Gg();let u=Array.from(a.dataTransfer.files??[]);u.length!==0&&je.handleFiles(u)},gs=!0;we.addEventListener("dragenter",qb,gs),we.addEventListener("dragleave",zb,gs),e.addEventListener("dragover",Kb,gs),e.addEventListener("drop",Gb,gs);let gd=e.ownerDocument,Yb=a=>{pa()&&a.preventDefault()},Xb=a=>{pa()&&a.preventDefault()};gd.addEventListener("dragover",Yb),gd.addEventListener("drop",Xb),Se.push(()=>{ct?.destroy(),ct=null,Vg(),To?.destroy(),To=null,hr?.destroy(),hr=null,es?.destroy(),es=null,ts?.destroy(),ts=null,Zr=null,Du=null,sg(),cl.destroy(),aa&&clearTimeout(aa),Xs(),ii?.abort(),ii=null,je?.destroy(),je=null,be.destroy(),Sl.removeEventListener("keydown",fb,!0),at?.destroy()}),Se.push(()=>{we.removeEventListener("dragenter",qb,gs),we.removeEventListener("dragleave",zb,gs),e.removeEventListener("dragover",Kb,gs),e.removeEventListener("drop",Gb,gs),gd.removeEventListener("dragover",Yb),gd.removeEventListener("drop",Xb),Gg()}),Se.push(()=>{R.cancel()}),qt?Se.push(()=>{qt?.destroy()}):Wn&&Se.push(()=>{Wn?.remove()});let zt={update(a){let u=o.future?.v5Defaults===!0,m=o.toolCall,b=o.messageActions,w=o.layout?.messages,k=o.colorScheme,q=o.loadingIndicator,re=o.iterationDisplay,Y=o.features?.showReasoning,ie=o.features?.showToolCalls,le=o.features?.toolCallDisplay,de=o.features?.reasoningDisplay,ke=o.features?.streamAnimation?.type,it=o.features?.history?.enabled===!0,gt=o.features?.history?.provider,dt=o.getIdentityProof,zn=o.clientToken,Dt=o.contextMentions;o=cu({...o,features:p},a),p=o.features,o=uc(o),c(),Qu(),Mi(e,o),dc(e,o),pc(e,o),Vn(),Lo(),o.colorScheme!==k&&fy();let jt=gc.getForInstance(o.plugins);d.length=0,d.push(...jt),Lg(),ye=o.launcher?.enabled??!0,ut=o.launcher?.autoExpand??!1,te=o.features?.showReasoning??!0,ve=o.features?.showToolCalls??!0,Me=o.features?.scrollToBottom??{};let On=Mn();ot=o.features?.scrollBehavior??{},On!==Mn()&&(ni(),Go()),Py(),Bt(),Tn();let Kt=Ce;if(Ce=o.features?.showEventStreamToggle??!1,Ce&&!Kt){if(ft||(cr(),R.setSSEEventCallback((Z,tt)=>{o.onSSEEvent?.(Z,tt),Qa(Z,tt)})),!ht&&mt){let Z=o.features?.eventStream?.classNames,tt="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"+(Z?.toggleButton?" "+Z.toggleButton:"");ht=x("button",tt),ht.style.width="28px",ht.style.height="28px",ht.style.color=Nn.actionIconColor,ht.type="button",ht.setAttribute("aria-label","Event Stream"),ht.title="Event Stream";let nt=Nt(Kr.Activity,"18px","currentColor",1.5);nt&&ht.appendChild(nt);let pt=Ze.clearChatButtonWrapper,Rt=Ze.closeButtonWrapper,Pn=pt||Rt;Pn&&Pn.parentNode===mt?mt.insertBefore(ht,Pn):mt.appendChild(ht),ht.addEventListener("click",()=>{Sn?zi():$u()})}}else!Ce&&Kt&&(zi(),ht&&(ht.remove(),ht=null),ft?.clear(),pn?.destroy(),ft=null,pn=null,bt?.reset(),bt=null,Ft=null);if(o.launcher?.enabled===!1&&qt&&(qt.destroy(),qt=null),o.launcher?.enabled===!1&&Wn&&(Wn.remove(),Wn=null),o.launcher?.enabled!==!1&&!qt&&!Wn){let{instance:Z,element:tt}=Zm({config:o,plugins:d,onToggle:Eb});qt=Z,Z||(Wn=tt),e.appendChild(tt)}qt&&qt.update(o),bl(),jo&&o.launcher?.subtitle!==void 0&&(jo.textContent=o.launcher.subtitle);let wt=o.layout?.header;if(wt?.layout!==Wt&&mt){let Z=wt?Na(o,wt,{showClose:Ye(),onClose:()=>Et(!1,"user")}):jr({config:o,showClose:Ye(),onClose:()=>Et(!1,"user")});Ln.replaceHeader(Z),mt=Ln.header.element,Ht=Ln.header.iconHolder,Vo=Ln.header.headerTitle,jo=Ln.header.headerSubtitle,ze=Ln.header.closeButton,Wt=wt?.layout,bl()}else if(wt){if(Ht&&(Ht.style.display=wt.showIcon===!1?"none":""),Vo&&(Vo.style.display=wt.showTitle===!1?"none":""),jo&&(jo.style.display=wt.showSubtitle===!1?"none":""),ze){let Z=Ye()&&wt.showCloseButton!==!1;ze.style.display=Z?"":"none"}if(Ze.clearChatButtonWrapper){let Z=wt.showClearChat;if(Z!==void 0){Ze.clearChatButtonWrapper.style.display=Z?"":"none";let{closeButtonWrapper:tt}=Ze;tt&&!tt.classList.contains("persona-absolute")&&(Z?tt.classList.remove("persona-ml-auto"):tt.classList.add("persona-ml-auto"))}}}let Zo=o.layout?.showHeader!==!1;mt&&(mt.style.display=Zo?"":"none");let yo=o.layout?.showFooter!==!1;Ke&&(Ke.style.display=yo?"":"none"),Re(),Tn(),ye!==xe?ye?Et(ut,"auto"):(D=!0,fl()):ut!==xt&&Et(ut,"auto"),xt=ut,xe=ye,wl(),Bb();let er=JSON.stringify(o.toolCall)!==JSON.stringify(m),Io=JSON.stringify(o.messageActions)!==JSON.stringify(b),ms=JSON.stringify(o.layout?.messages)!==JSON.stringify(w),xl=o.loadingIndicator?.render!==q?.render||o.loadingIndicator?.renderIdle!==q?.renderIdle||o.loadingIndicator?.showBubble!==q?.showBubble,ai=o.iterationDisplay!==re,O=(o.features?.showReasoning??!0)!==(Y??!0)||(o.features?.showToolCalls??!0)!==(ie??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(le)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(de);(o.future?.v5Defaults===!0!==u||er||Io||ms||xl||ai||O)&&R&&(Qs++,go(Te,R.getMessages(),K));let Fe=o.features?.streamAnimation?.type;if(Fe!==ke&&Fe&&Fe!=="none"){let Z=eg(Fe,o.features?.streamAnimation?.plugins);Z&&rc(Z,e)}let se=o.launcher??{},St=se.headerIconHidden??!1,Jt=o.layout?.header?.showIcon,Hn=St||Jt===!1,mn=se.headerIconName,Tt=se.headerIconSize??Bl;if(Ht){let Z=mt,tt=Z?.querySelector(".persona-flex-col");if(Hn)Ht.style.display="none",Z&&tt&&!Z.contains(tt)&&Z.insertBefore(tt,Z.firstChild);else{if(Ht.style.display="",Ht.style.height=Tt,Ht.style.width=Tt,Z&&tt&&(Z.contains(Ht)?Ht.nextSibling!==tt&&(Ht.remove(),Z.insertBefore(Ht,tt)):Z.insertBefore(Ht,tt)),mn){let pt=parseFloat(Tt)||24,Rt=ge(mn,pt*.6,"currentColor",1);Rt?(Rt.style.width=`calc(${pt}px * var(--persona-components-header-iconScale, 0.6))`,Rt.style.height=`calc(${pt}px * var(--persona-components-header-iconScale, 0.6))`,Ht.replaceChildren(Rt)):Ht.textContent=se.agentIconText??"\u{1F4AC}"}else if(se.iconUrl){let pt=Ht.querySelector("img");if(pt)pt.src=se.iconUrl,pt.style.height=Tt,pt.style.width=Tt;else{let Rt=document.createElement("img");Rt.src=se.iconUrl,Rt.alt="",Rt.className="persona-rounded-xl persona-object-cover",Rt.style.height=Tt,Rt.style.width=Tt,Ht.replaceChildren(Rt)}}else{let pt=Ht.querySelector("svg"),Rt=Ht.querySelector("img");(pt||Rt)&&Ht.replaceChildren(),Ht.textContent=se.agentIconText??"\u{1F4AC}"}let nt=Ht.querySelector("img");nt&&(nt.style.height=Tt,nt.style.width=Tt)}}let Gt=o.layout?.header?.showTitle,ln=o.layout?.header?.showSubtitle;if(Vo&&(Vo.style.display=Gt===!1?"none":""),jo&&(jo.style.display=ln===!1?"none":""),ze){let Z=Ye()&&o.layout?.header?.showCloseButton!==!1;if(ze.style.display=Z?"":"none",!Le()){let yn=se.closeButtonSize??"";ze.style.height=yn,ze.style.width=yn,ze.style.minWidth=yn,ze.style.minHeight=yn}let tt=se.closeButtonPlacement??"inline",{closeButtonWrapper:nt}=Ze,pt=tt==="top-right",Rt=nt?.classList.contains("persona-absolute");if(nt&&pt!==Rt)if(nt.remove(),pt){nt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let yn=_t?.railColumn??we;yn.style.position="relative",yn.appendChild(nt)}else{let yn=se.clearChat?.placement??"inline",bn=se.clearChat?.enabled??!0;nt.className=bn&&yn==="inline"?"":"persona-ml-auto",mt&&mt.appendChild(nt)}if(ze.style.color=se.closeButtonColor||Nn.actionIconColor,se.closeButtonBackgroundColor?(ze.style.backgroundColor=se.closeButtonBackgroundColor,ze.classList.remove("hover:persona-bg-gray-100")):(ze.style.backgroundColor="",ze.classList.add("hover:persona-bg-gray-100")),se.closeButtonBorderWidth||se.closeButtonBorderColor){let yn=se.closeButtonBorderWidth||"0px",bn=se.closeButtonBorderColor||"transparent";ze.style.border=`${yn} solid ${bn}`,ze.classList.remove("persona-border-none")}else ze.style.border="",ze.classList.add("persona-border-none");se.closeButtonBorderRadius?(ze.style.borderRadius=se.closeButtonBorderRadius,ze.classList.remove("persona-rounded-full")):(ze.style.borderRadius="",ze.classList.add("persona-rounded-full")),se.closeButtonPaddingX?(ze.style.paddingLeft=se.closeButtonPaddingX,ze.style.paddingRight=se.closeButtonPaddingX):(ze.style.paddingLeft="",ze.style.paddingRight=""),se.closeButtonPaddingY?(ze.style.paddingTop=se.closeButtonPaddingY,ze.style.paddingBottom=se.closeButtonPaddingY):(ze.style.paddingTop="",ze.style.paddingBottom=""),Xp(ze,se.closeButtonIconName??"x",{iconSize:Le()?Ym:void 0,iconText:se.closeButtonIconText??"\xD7"});let Pn=se.closeButtonTooltipText??"Close chat",Wo=se.closeButtonShowTooltip??!0;ze.setAttribute("aria-label",Pn),nt&&vn({anchor:ze,trigger:nt,text:()=>ze?.getAttribute("aria-label")??Pn,enabled:Wo})}let{clearChatButton:We,clearChatButtonWrapper:Pt}=Ze;if(We){let Z=se.clearChat??{},tt=Z.enabled??!0,nt=o.layout?.header?.showClearChat,pt=nt!==void 0?nt:tt,Rt=Z.placement??"inline";if(Pt){Pt.style.display=pt?"":"none";let{closeButtonWrapper:Pn}=Ze;!Le()&&Pn&&!Pn.classList.contains("persona-absolute")&&(pt?Pn.classList.remove("persona-ml-auto"):Pn.classList.add("persona-ml-auto"));let Wo=Rt==="top-right",yn=Pt.classList.contains("persona-absolute");if(!Le()&&Wo!==yn&&pt){if(Pt.remove(),Wo){Pt.className="persona-absolute persona-top-4 persona-z-50",Pt.style.right="48px";let tr=_t?.railColumn??we;tr.style.position="relative",tr.appendChild(Pt)}else{Pt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Pt.style.right="";let tr=Ze.closeButtonWrapper;mt&&tr&&tr.parentElement===mt?mt.insertBefore(Pt,tr):mt&&mt.appendChild(Pt)}let bn=Ze.closeButtonWrapper;bn&&!bn.classList.contains("persona-absolute")&&(Wo?bn.classList.add("persona-ml-auto"):bn.classList.remove("persona-ml-auto"))}}if(pt){if(!Le()){let bn=Z.size??"";We.style.height=bn,We.style.width=bn,We.style.minWidth=bn,We.style.minHeight=bn}let Pn=Z.iconColor??"";if(We.style.color=Pn||Nn.actionIconColor,Xp(We,Z.iconName??"refresh-cw",{iconSize:Le()?Xm:void 0}),Z.backgroundColor?(We.style.backgroundColor=Z.backgroundColor,We.classList.remove("hover:persona-bg-gray-100")):(We.style.backgroundColor="",We.classList.add("hover:persona-bg-gray-100")),Z.borderWidth||Z.borderColor){let bn=Z.borderWidth||"0px",tr=Z.borderColor||"transparent";We.style.border=`${bn} solid ${tr}`,We.classList.remove("persona-border-none")}else We.style.border="",We.classList.add("persona-border-none");Z.borderRadius?(We.style.borderRadius=Z.borderRadius,We.classList.remove("persona-rounded-full")):(We.style.borderRadius="",We.classList.add("persona-rounded-full")),Z.paddingX?(We.style.paddingLeft=Z.paddingX,We.style.paddingRight=Z.paddingX):(We.style.paddingLeft="",We.style.paddingRight=""),Z.paddingY?(We.style.paddingTop=Z.paddingY,We.style.paddingBottom=Z.paddingY):(We.style.paddingTop="",We.style.paddingBottom="");let Wo=Z.tooltipText??"Clear chat",yn=Z.showTooltip??!0;We.setAttribute("aria-label",Wo),Pt&&vn({anchor:We,trigger:Pt,text:()=>We?.getAttribute("aria-label")??Wo,enabled:yn})}}let $e=o.actionParsers&&o.actionParsers.length?o.actionParsers:[fc],cn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Wi.message,Wi.messageAndClick];Be=mc({parsers:$e,handlers:cn,getSessionMetadata:yt,updateSessionMetadata:qe,emit:X.emit,documentRef:typeof document<"u"?document:null}),K=ix(o,Be,z),GM(),R.updateConfig(o),cb(),(o.features?.history?.enabled===!0!==it||o.features?.history?.provider!==gt||o.getIdentityProof!==dt||o.clientToken!==zn)&&(_t?.closeHistory({restoreFocus:!1}),_t?.installHistoryProvider()),_t?.syncHistoryChromeImpl(),rd(),yl()&&!_t&&Ig().catch(()=>{}),go(Te,R.getMessages(),K),Ks(),Zc(),qM(),ml(R.isStreaming()),Dt!==o.contextMentions&&$b();let vo=o.voiceRecognition?.enabled===!0,hn=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),At=Dn(o.voiceRecognition?.provider);if(vo&&(hn||At))if(!he||!gn){let Z=ka(o);if(Z){he=Z.button,gn=Z.wrapper;let tt=Rn&&Rn.parentElement===_s?Rn:null;_s?_s.insertBefore(gn,tt):An?.appendChild(gn),ct&&(ct.micButton=he),ct?.addListener(he,"click",jg),he.disabled=Yo()||R.isStreaming()&&!gg()}}else{let Z=o.voiceRecognition??{},tt=o.sendButton??{},nt=Z.iconName??"mic",pt=Z.iconSize,Rt=parseFloat(pt??"")||Xn;he.classList.add(ro),he.classList.toggle(Do,!pt),he.style.width=pt??"",he.style.height=pt??"",he.style.minWidth=pt??"",he.style.minHeight=pt??"";let Pn=Z.iconColor??tt.textColor;he.innerHTML="";let Wo=ge(nt,Rt,Pn||"currentColor",1.5);Wo?he.appendChild(Wo):he.textContent="\u{1F3A4}";let yn=Z.backgroundColor??tt.backgroundColor;yn?he.style.backgroundColor=yn:he.style.backgroundColor="",Pn?he.style.color=Pn:he.style.color="var(--persona-text, #111827)",Z.borderWidth?(he.style.borderWidth=Z.borderWidth,he.style.borderStyle="solid"):(he.style.borderWidth="",he.style.borderStyle=""),Z.borderColor?he.style.borderColor=Z.borderColor:he.style.borderColor="",Z.paddingX?(he.style.paddingLeft=Z.paddingX,he.style.paddingRight=Z.paddingX):(he.style.paddingLeft="",he.style.paddingRight=""),Z.paddingY?(he.style.paddingTop=Z.paddingY,he.style.paddingBottom=Z.paddingY):(he.style.paddingTop="",he.style.paddingBottom="");let bn=Z.tooltipText??"Start voice recognition",tr=Z.showTooltip??!1;he.setAttribute("aria-label",bn),gn&&vn({anchor:he,trigger:gn,text:()=>he?.getAttribute("aria-label")??bn,enabled:tr}),gn.style.display="",he.disabled=Yo()||R.isStreaming()&&!gg()}else he&&gn&&(gn.style.display="none",Dn(o.voiceRecognition?.provider)?R.isVoiceActive()&&R.toggleVoice():Qo&&ps());if(zg(),o.attachments?.enabled===!0){if(!sn||!It){let Z=o.attachments??{};fn||(fn=x("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),fn.style.display="none",(ce.parentElement??An).insertBefore(fn,ce)),Mt||(Mt=document.createElement("input"),Mt.type="file",Mt.accept=(Z.allowedTypes??Dr).join(","),Mt.multiple=(Z.maxFiles??4)>1,Mt.style.display="none",Mt.setAttribute("aria-label","Attach files"),(ce.parentElement??An).insertBefore(Mt,ce)),sn=x("div","persona-send-button-wrapper"),It=x("button",`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${ro} ${Do}`),It.type="button",It.setAttribute("aria-label",Z.buttonTooltipText??"Attach file");let tt=Z.buttonIconName??"paperclip";It.style.fontSize="18px",It.style.lineHeight="1";let nt=ge(tt,Xn,"currentColor",1.5);nt?It.appendChild(nt):It.textContent="\u{1F4CE}",It.addEventListener("click",Rt=>{Rt.preventDefault(),Mt?.click()}),sn.appendChild(It);let pt=Z.buttonTooltipText??"Attach file";vn({anchor:It,trigger:sn,text:()=>It?.getAttribute("aria-label")??pt}),xn?xn.append(sn):An.appendChild(sn),ct&&(ct.attachmentButton=It,ct.attachmentInput=Mt??void 0,ct.attachmentPreviews=fn??void 0),!je&&Mt&&fn&&(je=Ai.fromConfig(Z,Nh),je.setPreviewsContainer(fn),ct?.addListener(Mt,"change",async()=>{je&&Mt?.files&&(await je.handleFileSelect(Mt.files),Mt.value="")}))}else{sn.style.display="";let Z=o.attachments??{};Mt&&(Mt.accept=(Z.allowedTypes??Dr).join(","),Mt.multiple=(Z.maxFiles??4)>1),je&&je.updateConfig({allowedTypes:Z.allowedTypes,maxFileSize:Z.maxFileSize,maxFiles:Z.maxFiles,adapter:Z.adapter})}if(we.querySelector(".persona-attachment-drop-overlay")?.remove(),we.appendChild(ax(o.attachments?.dropOverlay)),It){let Z=o.attachments??{},tt=Z.buttonTooltipText??"Attach file";It.setAttribute("aria-label",tt),It.textContent="";let nt=ge(Z.buttonIconName??"paperclip",Xn,"currentColor",1.5);nt?It.appendChild(nt):It.textContent="\u{1F4CE}",sn&&vn({anchor:It,trigger:sn,text:()=>It?.getAttribute("aria-label")??tt})}}else sn&&(sn.style.display="none"),je&&je.clearAttachments(),we.querySelector(".persona-attachment-drop-overlay")?.remove();let Ue=o.sendButton??{},hs=Ue.useIcon??!1,nn=Ue.iconText??"\u2191",Kn=Ue.iconName,Pr=Ue.tooltipText??"Send message",Yg=Ue.showTooltip??!1,li=Ue.size,Xg=parseFloat(li??"")||Df,kr=Ue.backgroundColor,ci=Ue.textColor;if(hs){if(Pe.style.width=li??"",Pe.style.height=li??"",Pe.style.minWidth=li??"",Pe.style.minHeight=li??"",Pe.style.fontSize="18px",Pe.style.lineHeight="1",ci?Pe.style.color=ci:Pe.style.color="var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))",!R.isStreaming())if(Pe.innerHTML="",Kn){let Z=parseFloat(Ue.iconSize??"")||Math.round(Xg*.5),tt=ci?.trim()||"currentColor",nt=Ue.iconStrokeWidth??2,pt=ge(Kn,Z,tt,nt),Rt=ge(Ue.stopIconName??"square",Z,tt,nt);pt&&Rt?Pe.appendChild(Nf(pt,Rt)):pt?Pe.appendChild(pt):Pe.textContent=nn}else Pe.textContent=nn;Pe.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${ro}`,kr?(Pe.style.backgroundColor=kr,Pe.classList.remove("persona-bg-persona-primary")):(Pe.style.backgroundColor="",Pe.classList.add("persona-bg-persona-primary"))}else Pe.textContent=o.copy?.sendButtonLabel??"Send",Pe.style.width="",Pe.style.height="",Pe.style.minWidth="",Pe.style.minHeight="",Pe.style.fontSize="",Pe.style.lineHeight="",Pe.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",kr?(Pe.style.backgroundColor=kr,Pe.classList.remove("persona-bg-persona-accent")):Pe.classList.add("persona-bg-persona-accent"),ci?Pe.style.color=ci:Pe.classList.add("persona-text-white");Ue.borderWidth?(Pe.style.borderWidth=Ue.borderWidth,Pe.style.borderStyle="solid"):(Pe.style.borderWidth="",Pe.style.borderStyle=""),Ue.borderColor?Pe.style.borderColor=Ue.borderColor:Pe.style.borderColor="",Ue.paddingX?(Pe.style.paddingLeft=Ue.paddingX,Pe.style.paddingRight=Ue.paddingX):(Pe.style.paddingLeft="",Pe.style.paddingRight=""),Ue.paddingY?(Pe.style.paddingTop=Ue.paddingY,Pe.style.paddingBottom=Ue.paddingY):(Pe.style.paddingTop="",Pe.style.paddingBottom=""),R.isStreaming()||Pe.setAttribute("aria-label",Pr),Xc(),Rn&&vn({anchor:Pe,trigger:Rn,text:()=>Pe.getAttribute("aria-label")??Pr,enabled:Yg}),Jh(),Zu();let Qb=Bp(be.getState().activeModeIds,o.composer?.modes);be.setActiveModeIds(Qb),Vi().length>0!==!!hr&&ju(),hr?.render(Qb,Vi());for(let Z of[...ji.keys()])Op(Z,o.composer?.modeGroups)||ji.delete(Z);ji.forEach(Z=>Z.repaint()),Zr?.repaint(),To?.resolve();let fd=Hs(o,Le());if(Ju(),fd){Te.style.maxWidth=fd,Te.style.marginLeft="auto",Te.style.marginRight="auto",Te.style.width="100%",In.style.maxWidth=fd,In.style.marginLeft="auto",In.style.marginRight="auto",In.style.width="100%";for(let Z of[An,lo,fn,rt])Z&&(Z.style.maxWidth=fd,Z.style.marginLeft="auto",Z.style.marginRight="auto",Z.style.width="100%")}else{Te.style.maxWidth="",Te.style.marginLeft="",Te.style.marginRight="",Te.style.width="",In.style.maxWidth="",In.style.marginLeft="",In.style.marginRight="",In.style.width="";for(let Z of[An,lo,fn,rt])Z&&(Z.style.maxWidth="",Z.style.marginLeft="",Z.style.marginRight="",Z.style.width="")}let Ro=o.statusIndicator??{};if(xf(rt,An,Ro),hi(rt,Ro,R?.getStatus()??"idle"),R){let Z=R.getStatus();Bs(rt,(nt=>nt==="idle"?Ro.idleText??Yt.idle:nt==="connecting"?Ro.connectingText??Yt.connecting:nt==="connected"?Ro.connectedText??Yt.connected:nt==="error"?Ro.errorText??Yt.error:nt==="paused"?Ro.pausedText??Yt.paused:nt==="resuming"?Ro.resumingText??Yt.resuming:Yt[nt])(Z),Ro,Z)}rt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let LE=Ro.align==="left"?"persona-text-left":Ro.align==="center"?"persona-text-center":"persona-text-right";rt.classList.add(LE),Uu(),mg(),Po(),dr()},open(){Ye()&&Et(!0,"api")},close(){Ye()&&Et(!1,"api")},toggle(){Ye()&&Et(!D,"api")},reconnect(){R.reconnectNow()},clearChat(){yr=!1,i.clear(),r.clear(),s.clear(),l.clear(),R.clearMessages(),o.layout?.topFade&&(ae.scrollTop=0),ae.removeAttribute("data-persona-top-fade"),En.clear(),Go();try{localStorage.removeItem(Ga),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ga}`)}catch(u){console.error("[AgentWidget] Failed to clear default localStorage:",u)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Ga)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(u){console.error("[AgentWidget] Failed to clear custom localStorage:",u)}let a=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(a),T?.clear&&Vc(()=>T.clear(),"[AgentWidget] Failed to clear storage adapter:"),P={},Be.syncFromMetadata(),je?.clearAttachments(),qc(),qi(void 0),qo(void 0),Xs(),ft?.clear(),bt?.reset(),rn?.update()},setMessage(a){return!ce||R.isStreaming()||Yo()?!1:(!D&&Ye()&&Et(!0,"system"),ce.value=a,ce.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(a){if(R.isStreaming()||oi())return!1;let u=a?.trim()||ce.value.trim();return u?(!D&&Ye()&&Et(!0,"system"),ce.value="",ce.style.height="auto",co(),ad(u,{consumeDraft:!1}),!0):!1},getComposerState(){return be.getState()},setQuote(a){let u=a?.text?.trim();u&&qo({...a,text:u})},clearQuote(){qo(void 0)},startVoiceRecognition(){return R.isStreaming()?!1:Dn(o.voiceRecognition?.provider)?(R.isVoiceActive()||R.isBargeInActive()||(!D&&Ye()&&Et(!0,"system"),st.manuallyDeactivated=!1,Ho(),R.toggleVoice().then(()=>{st.active=R.isVoiceActive(),Sr("user"),R.isVoiceActive()&&da()})),!0):Qo?!0:yb()?(!D&&Ye()&&Et(!0,"system"),st.manuallyDeactivated=!1,Ho(),dd("user"),!0):!1},stopVoiceRecognition(){return Dn(o.voiceRecognition?.provider)?!R.isVoiceActive()&&!R.isBargeInActive()?!1:((R.isBargeInActive()?R.deactivateBargeIn():R.toggleVoice()).then(()=>{st.active=!1,st.manuallyDeactivated=!0,Ho(),Sr("user"),Tr()}),!0):Qo?(st.manuallyDeactivated=!0,Ho(),ps("user"),!0):!1},injectMessage(a){return!D&&Ye()&&Et(!0,"system"),R.injectMessage(a)},injectAssistantMessage(a){!D&&Ye()&&Et(!0,"system");let u=R.injectAssistantMessage(a);return S&&(S=!1,F&&(clearTimeout(F),F=null),setTimeout(()=>{R&&!R.isStreaming()&&R.continueConversation()},100)),u},injectUserMessage(a){return!D&&Ye()&&Et(!0,"system"),R.injectUserMessage(a)},injectSystemMessage(a){return!D&&Ye()&&Et(!0,"system"),R.injectSystemMessage(a)},injectMessageBatch(a){return!D&&Ye()&&Et(!0,"system"),R.injectMessageBatch(a)},injectComponentDirective(a){return!D&&Ye()&&Et(!0,"system"),R.injectComponentDirective(a)},injectTestMessage(a){!D&&Ye()&&Et(!0,"system"),R.injectTestEvent(a)},async connectStream(a,u){return R.connectStream(a,u)},__pushEventStreamEvent(a){Ce&&(cr(),Qa(a.type,a.payload))},showEventStream(){Ce&&$u()},hideEventStream(){Sn&&zi()},isEventStreamVisible(){return Sn},listConversations(a){return R.listConversations(a)},getActiveConversationId(){return R.getActiveConversationId()},openConversation(a,u){return Xo(m=>m.openHistoryConversation(a,{focusComposer:u?.focus===!0}))},startNewConversation(a){return Xo(u=>u.startNewConversation({focusComposer:a?.focus===!0}))},warmSession(){Rg()},deleteConversation(a){return Xo(u=>u.deleteHistoryConversation(a))},renameConversation(a,u){return Xo(m=>m.updateHistoryConversation(a,{title:u}))},setConversationStarred(a,u){return Xo(m=>m.updateHistoryConversation(a,{starred:u}))},clearConversationHistory(a){return Xo(u=>u.clearConversationHistory(a))},resetHistoryIdentity(){return Xo(a=>a.resetHistoryIdentity())},async getVisitorToken(){let a=fo;if(!a)return null;let u=await a.get();return a===fo?u:null},getHistoryIdentityStatus(){let a=_t?.historyProvider;return a?a.getIdentityStatus():yl()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory(a){return yl()?Xo(u=>u.openHistory({...a?.returnSurface?{returnSurface:a.returnSurface}:{},...a?.focus!==void 0?{focus:a.focus}:{}})):Promise.resolve()},hideHistory(a){_t?.closeHistory(a?.restoreFocus!==void 0?{restoreFocus:a.restoreFocus}:void 0)},isHistoryVisible(){return un},showArtifacts(){$n(o)&&(yr=!1,Gi=!0,Lo(),et?.setMobileOpen(!0))},hideArtifacts(){$n(o)&&(yr=!0,Lo())},upsertArtifact(a){return $n(o)?(or(o.features?.artifacts,{artifactType:a.artifactType,...a.artifactType==="markdown"&&a.file?{file:a.file}:{},...a.presentation?{presentation:a.presentation}:{}})==="panel"&&(yr=!1,Gi=!0),R.upsertArtifact(a)):null},selectArtifact(a){$n(o)&&R.selectArtifact(a)},clearArtifacts(){$n(o)&&R.clearArtifacts()},getArtifacts(){return R?.getArtifacts()??[]},getSelectedArtifactId(){return R?.getSelectedArtifactId()??null},focusInput(){return ye&&!D&&!Le()||!ce?!1:(ce.focus(),!0)},async resolveApproval(a,u,m){let w=R.getMessages().find(k=>k.variant==="approval"&&k.approval?.id===a);if(!w?.approval)throw new Error(`Approval not found: ${a}`);if(w.approval.toolType==="webmcp"){R.resolveWebMcpApproval(w.id,u);return}return R.resolveApproval(w.approval,u,m)},setFollowUpSuggestions(a){hM(a)},clearFollowUpSuggestions(){Ty()},getMessages(){return R.getMessages()},getStatus(){return R.getStatus()},getPersistentMetadata(){return{...P}},updatePersistentMetadata(a){qe(a)},on(a,u){return X.on(a,u)},off(a,u){X.off(a,u)},isOpen(){return Ye()&&D},isVoiceActive(){return st.active},toggleReadAloud(a){R.toggleReadAloud(a)},stopReadAloud(){R.stopSpeaking()},getReadAloudState(a){return R.getReadAloudState(a)},onReadAloudChange(a){return R.onReadAloudChange(a)},getState(){return{open:Ye()&&D,launcherEnabled:ye,voiceActive:st.active,streaming:R.isStreaming()}},showCSATFeedback(a){!D&&Ye()&&Et(!0,"system");let u=Te.querySelector(".persona-feedback-container");u&&u.remove();let m=fu({onSubmit:async(b,w)=>{R.isClientTokenMode()&&await R.submitCSATFeedback(b,w),a?.onSubmit?.(b,w)},onDismiss:a?.onDismiss,...a});Te.appendChild(m),m.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(a){!D&&Ye()&&Et(!0,"system");let u=Te.querySelector(".persona-feedback-container");u&&u.remove();let m=mu({onSubmit:async(b,w)=>{R.isClientTokenMode()&&await R.submitNPSFeedback(b,w),a?.onSubmit?.(b,w)},onDismiss:a?.onDismiss,...a});Te.appendChild(m),m.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(a,u){return R.submitCSATFeedback(a,u)},async submitNPSFeedback(a,u){return R.submitNPSFeedback(a,u)},destroy(){Tg(),ri!=null&&(clearInterval(ri),ri=null),i.clear(),r.clear(),s.clear(),l.clear(),Se.forEach(a=>a()),Qe.remove(),Xt?.remove(),qt?.destroy(),Wn?.remove(),qs&&ze.removeEventListener("click",qs)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let a=window.AgentWidgetBrowser,u={controller:zt,getMessages:zt.getMessages,getStatus:zt.getStatus,getMetadata:zt.getPersistentMetadata,updateMetadata:zt.updatePersistentMetadata,clearHistory:()=>zt.clearChat(),setVoiceActive:m=>m?zt.startVoiceRecognition():zt.stopVoiceRecognition()};window.AgentWidgetBrowser=u,Se.push(()=>{window.AgentWidgetBrowser===u&&(window.AgentWidgetBrowser=a)})}if(typeof window<"u"){let a=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),u=ie=>{let le=ie.detail;(!le?.instanceId||le.instanceId===a)&&zt.focusInput()};if(window.addEventListener("persona:focusInput",u),Se.push(()=>{window.removeEventListener("persona:focusInput",u)}),Ce){let ie=de=>{let ke=de.detail;(!ke?.instanceId||ke.instanceId===a)&&zt.showEventStream()},le=de=>{let ke=de.detail;(!ke?.instanceId||ke.instanceId===a)&&zt.hideEventStream()};window.addEventListener("persona:showEventStream",ie),window.addEventListener("persona:hideEventStream",le),Se.push(()=>{window.removeEventListener("persona:showEventStream",ie),window.removeEventListener("persona:hideEventStream",le)})}let m=ie=>{let le=ie.detail;(!le?.instanceId||le.instanceId===a)&&zt.showHistory()},b=ie=>{let le=ie.detail;(!le?.instanceId||le.instanceId===a)&&zt.hideHistory()};window.addEventListener("persona:showHistory",m),window.addEventListener("persona:hideHistory",b),Se.push(()=>{window.removeEventListener("persona:showHistory",m),window.removeEventListener("persona:hideHistory",b)});let w=ie=>{let le=ie.detail;(!le?.instanceId||le.instanceId===a)&&zt.showArtifacts()},k=ie=>{let le=ie.detail;(!le?.instanceId||le.instanceId===a)&&zt.hideArtifacts()},q=ie=>{let le=ie.detail;le?.instanceId&&le.instanceId!==a||le?.artifact&&zt.upsertArtifact(le.artifact)},re=ie=>{let le=ie.detail;le?.instanceId&&le.instanceId!==a||typeof le?.id=="string"&&zt.selectArtifact(le.id)},Y=ie=>{let le=ie.detail;(!le?.instanceId||le.instanceId===a)&&zt.clearArtifacts()};window.addEventListener("persona:showArtifacts",w),window.addEventListener("persona:hideArtifacts",k),window.addEventListener("persona:upsertArtifact",q),window.addEventListener("persona:selectArtifact",re),window.addEventListener("persona:clearArtifacts",Y),Se.push(()=>{window.removeEventListener("persona:showArtifacts",w),window.removeEventListener("persona:hideArtifacts",k),window.removeEventListener("persona:upsertArtifact",q),window.removeEventListener("persona:selectArtifact",re),window.removeEventListener("persona:clearArtifacts",Y)})}let ho=tH(o.persistState);if(ho&&Ye()){let a=nH(ho.storage),u=`${ho.keyPrefix}widget-open`,m=`${ho.keyPrefix}widget-voice`,b=`${ho.keyPrefix}widget-voice-mode`;if(a){let w=ho.persist?.openState&&a.getItem(u)==="true",k=ho.persist?.voiceState&&a.getItem(m)==="true",q=ho.persist?.voiceState&&a.getItem(b)==="true";if(w&&(qt?.setPanelOpen(!0,"auto"),setTimeout(()=>{zt.open(),setTimeout(()=>{if(k||q)zt.startVoiceRecognition();else if(ho.persist?.focusInput){let re=e.querySelector("textarea");re&&re.focus()}},100)},0)),ho.persist?.openState&&(X.on("widget:opened",()=>{a.setItem(u,"true")}),X.on("widget:closed",()=>{a.setItem(u,"false")})),ho.persist?.voiceState&&(X.on("voice:state",re=>{a.setItem(m,re.active?"true":"false")}),X.on("user:message",re=>{a.setItem(b,re.viaVoice?"true":"false")})),ho.clearOnChatClear){let re=()=>{a.removeItem(u),a.removeItem(m),a.removeItem(b)},Y=()=>re();window.addEventListener("persona:clear-chat",Y),Se.push(()=>{window.removeEventListener("persona:clear-chat",Y)})}}}if(Ee&&Ye()&&(qt?.setPanelOpen(!0,"auto"),setTimeout(()=>{zt.open()},0)),oa(),!yM){let a=ua(()=>{R&&(Qs++,En.clear(),go(Te,R.getMessages(),K))});Se.push(a)}I=()=>{R&&(Qs++,En.clear(),go(Te,R.getMessages(),K))},R.getMessages().length>0&&Yc(),W=()=>{R&&(Qs++,En.clear(),go(Te,R.getMessages(),K))};let PE=lv(()=>{R&&(Qs++,En.clear(),go(Te,R.getMessages(),K))});Se.push(PE);let kE=ch(()=>{R&&(Qs++,En.clear(),go(Te,R.getMessages(),K),qr()?.updateInlineArtifactBlocks(Te,po.artifacts,{suppressTransition:!0}),Lo())});return Se.push(kE),zt};Bo();var lx=(e,t)=>{let n=e.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,t*parseFloat(r[1])/100):420},sH=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},iH=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},aH=(e,t)=>{let n=e.parentElement;if(!n)return;let o=e.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."+(t.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 ${t.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.")},cx=(e,t)=>{let n=t?.launcher?.enabled??!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0",e.style.minWidth=n?"":"0"},Sh=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},dx=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",Sh(e)},vh=e=>{e.style.transition=""},Ch=e=>{e.style.display="",e.style.flexDirection="",e.style.flex="",e.style.minHeight="",e.style.minWidth="",e.style.width="",e.style.height="",e.style.alignItems="",e.style.transition="",e.style.transform="",e.style.marginLeft=""},wh=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},bu=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},lH=(e,t,n,o,r)=>{r?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,o),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(o))},cH=(e,t,n,o,r,s)=>{let i=s?t:e;r==="left"?i.firstElementChild!==o&&i.replaceChildren(o,n):i.lastElementChild!==o&&i.replaceChildren(n,o)},dH=e=>{let t=No(e),n=t.components?.panel,o=(r,s)=>r==null||r===""?s:wn(t,r)??r;return{inset:o(n?.inset,Fp),canvasBackground:o(n?.canvasBackground,$p)}},px=(e,t,n,o)=>{if(!t){e.style.padding="",e.style.background="",e.style.boxSizing="";return}e.style.boxSizing="border-box",e.style.padding=n,e.style.background=o},pH=(e,t,n,o,r,s,i,l)=>{let c=Jn(s),p=c.reveal==="push",d=l!=null,g=l?.inset??"",f=l?.canvasBackground??"";lH(e,t,n,o,p),cH(e,t,n,o,c.side,p),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=c.side,e.dataset.personaDockOpen=i?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.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=e.ownerDocument.defaultView,y=s?.launcher?.mobileFullscreen??!0,v=s?.launcher?.mobileBreakpoint??640,C=h!=null?h.innerWidth<=v:!1;if(y&&C&&i){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Ch(t),vh(o),dx(o),wh(n),bu(r,o),px(o,!1,"",""),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.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??kn),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",p&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.marginLeft="0",t.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),dx(o),sH(o,c.maxHeight),px(o,d&&i,g,f),c.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Ch(t),vh(o),wh(n),bu(r,o);let L=c.animate?"transform 180ms ease":"none",I=c.side==="right"?"translateX(100%)":"translateX(-100%)",H=i?"translateX(0)":I;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=L,o.style.transform=H,o.style.pointerEvents=i?"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"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",vh(o),Sh(o),bu(r,o);let L=lx(c.width,e.clientWidth),I=Math.max(0,e.clientWidth),H=c.animate?"margin-left 180ms ease":"none",_=c.side==="right"?i?-L:0:i?0:-L;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${I+L}px`,t.style.transition=H,t.style.marginLeft=`${_}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${I}px`,n.style.maxWidth=`${I}px`,n.style.minWidth=`${I}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=i?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Ch(t),Sh(o),wh(n),bu(r,o);let L=c.reveal==="emerge";L?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let I=i?c.width:"0px",H=c.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${d?", padding 180ms ease":""}`:"none",_=!i;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${I}`,o.style.width=I,o.style.maxWidth=I,o.style.minWidth=I,o.style.minHeight="0",iH(o,c.maxHeight),o.style.overflow=L||_?"hidden":"visible",o.style.transition=H,L){o.style.alignItems=c.side==="right"?"flex-start":"flex-end";let V=d?`calc(${lx(c.width,e.clientWidth)}px - (2 * ${g}))`:c.width;r.style.width=V,r.style.minWidth=V,r.style.maxWidth=V,r.style.boxSizing="border-box"}}},uH=(e,t)=>{let n=e.ownerDocument.createElement("div");return cx(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){cx(n,o)},destroy(){n.remove()}}},gH=(e,t)=>{let{ownerDocument:n}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=e.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=e.nextSibling,i=n.createElement("div"),l=n.createElement("div"),c=n.createElement("div"),p=n.createElement("aside"),d=n.createElement("div"),g=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;l.dataset.personaDockRole="push-track",c.dataset.personaDockRole="content",p.dataset.personaDockRole="panel",d.dataset.personaDockRole="host",p.appendChild(d),o.insertBefore(i,e),c.appendChild(e);let f=null,h=()=>{f?.disconnect(),f=null},y=null,v=()=>{y=t?.launcher?.detachedPanel===!0?dH(t):null};v();let C=()=>{pH(i,l,c,p,d,t,g,y)},A=null,L=()=>{A?.(),A=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(A=Oa(()=>{v(),C()}))},I=()=>{h(),Jn(t).reveal==="push"&&(typeof ResizeObserver>"u"||(f=new ResizeObserver(()=>{C()}),f.observe(i)))},H=!1,_=()=>{C(),I(),g&&!H&&i.dataset.personaDockMobileFullscreen!=="true"&&(H=!0,aH(i,Jn(t)))},V=i.ownerDocument.defaultView,oe=()=>{_()};return V?.addEventListener("resize",oe),Jn(t).reveal==="push"?(l.appendChild(c),l.appendChild(p),i.appendChild(l)):(i.appendChild(c),i.appendChild(p)),_(),L(),{mode:"docked",host:d,shell:i,syncWidgetState(W){let j=W.launcherEnabled?W.open:!0;g!==j&&(g=j,_())},updateConfig(W){t=W,(t?.launcher?.enabled??!0)===!1&&(g=!0),v(),_(),L()},destroy(){V?.removeEventListener("resize",oe),A?.(),A=null,h(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),i.remove()}}},yc=(e,t)=>Lt(t)?gH(e,t):uH(e,t);var fH=e=>{if(typeof window>"u"||typeof document>"u")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let t=document.querySelector(e);if(!t)throw new Error(`Chat widget target "${e}" was not found`);return t}return e},ux=(e,t)=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let n=t.head.querySelector("link[data-persona]");if(!n)return;let o=n.cloneNode(!0);e.insertBefore(o,e.firstChild)},vu=[],gx=()=>[...vu],Ah=e=>{let t=fH(e.target),n=e.useShadowDom===!0,o=t.ownerDocument,r=e.config,s=yc(t,r),i,l=[],c=(C,A)=>{let I=!(A?.launcher?.enabled??!0)||Lt(A),H=o.createElement("div");if(H.setAttribute("data-persona-root","true"),I&&(H.style.height="100%",H.style.display="flex",H.style.flexDirection="column",H.style.flex="1",H.style.minHeight="0",H.style.minWidth="0"),n){let _=C.attachShadow({mode:"open"});_.appendChild(H),ux(_,o)}else C.appendChild(H),ux(C,o);return t.id&&H.setAttribute("data-persona-instance",t.id),H},p=()=>{s.syncWidgetState(i.getState())},d=()=>{l.forEach(C=>C()),l=[i.on("widget:opened",p),i.on("widget:closed",p)],p()},g=()=>{let C=c(s.host,r);i=yu(C,r,{debugTools:e.debugTools}),d()},f=()=>{l.forEach(C=>C()),l=[],i.destroy()};g(),e.onChatReady?.();let h=C=>{f(),s.destroy(),s=yc(t,C),r=C,g()},y={update(C){let A=cu(r??{},C),L=Lt(r),I=Lt(A),H=Rs(r),_=Rs(A);if(L!==I||H!==_){h(A);return}r=A,s.updateConfig(r),i.update(C),p()},destroy(){f(),s.destroy();let C=vu.indexOf(v);C!==-1&&vu.splice(C,1),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},v=new Proxy(y,{get(C,A,L){if(A==="host")return s.host;if(A in C)return Reflect.get(C,A,L);let I=i[A];return typeof I=="function"?I.bind(i):I}});return vu.push(v),e.windowKey&&typeof window<"u"&&(window[e.windowKey]=v),v};ha();Rl();Bd();Ca();pi();Cs();Nr();var bx=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),mH=new Set(["button","a","input","select","textarea","details","summary"]),hH=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),xh=/\b(product|card|item|listing|result)\b/i,Eh=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,yH=3e3,bH=100;function vx(e){let t=typeof e.className=="string"?e.className:"";if(xh.test(t)||e.id&&xh.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let o=e.attributes[n];if(o.name.startsWith("data-")&&xh.test(o.value))return!0}return!1}function Cx(e){return Eh.test((e.textContent??"").trim())}function wx(e){let t=e.querySelectorAll("a[href]");for(let n=0;n<t.length;n++){let o=t[n].getAttribute("href")??"";if(o&&o!=="#"&&!o.toLowerCase().startsWith("javascript:"))return!0}return!1}function vH(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function fx(e){let t=e.match(Eh);return t?t[0]:null}function mx(e){let t=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]")??e.querySelector("a[href]");if(t&&t.textContent?.trim()){let o=t.getAttribute("href");return{title:t.textContent.trim(),href:o&&o!=="#"?o:null}}let n=e.querySelector("h1, h2, h3, h4, h5, h6");return n?.textContent?.trim()?{title:n.textContent.trim(),href:null}:{title:"",href:null}}function CH(e){let t=[],n=o=>{let r=o.trim();r&&!t.includes(r)&&t.push(r)};return e.querySelectorAll("button").forEach(o=>n(o.textContent??"")),e.querySelectorAll('[role="button"]').forEach(o=>n(o.textContent??"")),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(o=>{n(o.value??"")}),t.slice(0,6)}var wH="commerce-card",SH="result-card";function hx(e){return!vx(e)||!Cx(e)||!wx(e)&&!vH(e)?0:5200}function yx(e){return!vx(e)||Cx(e)||!wx(e)||(e.textContent??"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var Th=[{id:wH,scoreElement(e){return hx(e)},shouldSuppressDescendant(e,t,n){if(t===e||!e.contains(t))return!1;if(n.interactivity==="static"){let o=n.text.trim();return!!(o.length===0||Eh.test(o)&&o.length<32)}return!0},formatSummary(e,t){if(hx(e)===0)return null;let{title:n,href:o}=mx(e),r=fx((e.textContent??"").trim())??fx(t.text)??"",s=CH(e);return[o&&n?`[${n}](${o})${r?`: ${r}`:""}`:n?`${n}${r?`: ${r}`:""}`:r||t.text.trim().slice(0,120),`selector: ${t.selector}`,s.length?`actions: ${s.join(", ")}`:""].filter(Boolean).join(`
|
|
141
|
-
`)}},{id:
|
|
142
|
-
`)}}];function
|
|
140
|
+
`)}if(!w&&!u){let Be="max-height: -moz-available !important; max-height: stretch !important;",Ye=m?"":"padding-top: 1.25em !important;",Ue=m?"":`z-index: ${o.launcher?.zIndex??kn} !important;`;Je.style.cssText+=Be+Ye+Ue}$t(),Co()},tg=()=>{e.style.setProperty("--persona-content-max-width",Hs(o,Le()))},fy=!1;function my(){o.layout?.topFade&&ae.scrollTop>1?ae.setAttribute("data-persona-top-fade","true"):ae.removeAttribute("data-persona-top-fade")}let ng=()=>{my();let a=Pm(o,Le());Le()&&o.composer?.placement&&o.debug===!0&&!fy&&(fy=!0,console.warn("[persona] composer.placement is ignored in composer-bar mount mode."));let u=E();e.setAttribute("data-persona-composer-placement",a),e.setAttribute("data-persona-conversation-state",N),e.setAttribute("data-persona-welcome-anchor",u.anchor??"bottom"),e.style.setProperty("--persona-composer-anchor-gap",u.composerGap??Kp),Ot()},hy=()=>{if(Le())return;let a=Lt(o),u=o.launcher?.sidebarMode??!1;if(a||u||(o.launcher?.fullHeight??!1)||!ye)return;let b=e.ownerDocument.defaultView??window,w=o.launcher?.mobileFullscreen??!0,k=o.launcher?.mobileBreakpoint??640;if(w&&b.innerWidth<=k)return;let z=Hi(o);Ae.style.height=z.height,Ae.style.maxHeight=z.maxHeight};eg(),Ei(e,o),dc(e,o),pc(e,o),tg(),ng(),Us=()=>{eg(),hy(),Ei(e,o),dc(e,o),pc(e,o),tg(),ng(),kc?e.style.setProperty("--persona-artifact-welded-outer-radius",kc):e.style.removeProperty("--persona-artifact-welded-outer-radius"),Vn(),dr()};let Se=[];Se.push(()=>{iy=!0}),Se.push(()=>{f.forEach(a=>a()),g.destroy()}),Se.push(()=>{document.removeEventListener("keydown",dy)}),Se.push(()=>{Jr!==null&&clearTimeout(Jr)});let zo=null,Ko=null;Se.push(()=>{zo?.(),zo=null,Ko?.(),Ko=null}),ol&&Se.push(()=>{ol?.disconnect(),ol=null}),Se.push(()=>{al?.(),al=null,Zu(),Ut&&(Ut.remove(),Ut=null),nt?.element.style.removeProperty("width"),nt?.element.style.removeProperty("maxWidth"),nt?.destroy()}),Me&&Se.push(()=>{_i=!0,Ft=null,lo!==null&&(cancelAnimationFrame(lo),lo=null),rn?.destroy(),rn=null,ft?.destroy(),ft=null,pn=null});let Vs=null,yy=()=>{Vs&&(Vs(),Vs=null),o.colorScheme==="auto"&&(Vs=Oa(()=>{Ei(e,o)}))};yy(),Se.push(()=>{Vs&&(Vs(),Vs=null)}),Se.push(()=>{L=!0,A?.()}),Se.push(()=>{V=!0});let by=!1;Se.push(()=>{by=!0});let og=(a,u)=>{let m=tc(a,u);return m||!ZS.includes(a)?m:(oA().then(b=>{if(by)return;ec(b.wipe),ec(b.glyphCycle);let w=tc(a,u);w&&rc(w,e)}).catch(()=>{}),null)},Dc=o.features?.streamAnimation;if(Dc?.type&&Dc.type!=="none"){let a=og(Dc.type,Dc.plugins);a&&rc(a,e),Se.push(()=>nA(e))}let vr=ac(co),vy=ac(gr),Cy=ac(Xr),js=[vr,vy,Cy];Se.push(()=>{js.forEach(a=>a.destroy())});let qs=null,R,zs=null,wy=!1,Sy=0,Ay=null,xy=a=>a.reduce((u,m)=>m.role==="user"?u+1:u,0),Ey=a=>{for(let u=a.length-1;u>=0;u--)if(gi(a[u]))return a[u].id??null;return null},My=!1,CE=()=>{My||o.debug!==!0||(My=!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".'))},Ty=!1,Py=!1,ky=(a,u)=>{Ty||o.debug!==!0||!u.enabled||u.expose||wy||Py&&(R.isStreaming()||a.some(gi)||(Ty=!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.")))},Ks=a=>{if(!R)return;let u=a??R.getMessages(),m=de=>{de.render([],R,ce,u)},b=de=>{js.forEach(ke=>{ke!==de&&m(ke)})};zs&&(xy(u)>Sy||Ey(u)!==Ay)&&(zs=null);let w=xs(o);ky(u,w);let k=w.enabled?Bd(u):null,z=zs??k,re=zs?"host":"agent";if(z){let de=o.suggestions?.followUps,ke=de?.placement??(de?"auto":"composer"),gt=(ke==="auto"?Le()?"composer":"after-message":ke)==="after-message"?Cy:vr;b(gt),gt.render(z,R,ce,u,o.suggestionChipsConfig,{source:re,surface:"followUp",variant:de?.variant??"chip",behavior:de?.behavior??"send",overflow:de?.overflow??"wrap",maxItems:de?.maxItems??4,config:o,plugins:d,submitPrompt:ld});return}if(u.some(de=>de.role==="user")){js.forEach(m);return}let Y=o.future?.v5Defaults===!0,ie=jn(),le=o.suggestions?.starters??(Y?{}:void 0);if(le){let de=Ws(E(),u),ke=le.placement??"auto",it=ke==="auto"?de?"welcome":"composer":ke;if(it==="welcome"&&!de){CE(),js.forEach(m);return}let gt=it==="welcome"?vy:vr;b(gt),gt.render(le.items??o.suggestionChips,R,ce,u,o.suggestionChipsConfig,{surface:"starter",variant:le.variant??(Y&&!ie?"chip":"card"),behavior:le.behavior??"send",overflow:le.overflow??"wrap",maxItems:le.maxItems??(Y&&!ie?3:4),config:o,plugins:d,submitPrompt:ld});return}b(vr),vr.render(o.suggestionChips,R,ce,u,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",maxItems:4,config:o,plugins:d,submitPrompt:ld})},Ly=()=>{zs&&(zs=null,Ks())},wE=a=>{let u=Array.isArray(a)?[...a]:[];if(!u.length){Ly();return}let m=R?R.getMessages():[];zs=u,wy=!0,Sy=xy(m),Ay=Ey(m),Ks(m)},no=!1,Mn=$S(),Yi=new Map,Gs=new Map,ns=new Map,Ys=null,os=null;function Xs(){if(!Ys)return;let a=Ys;Ys=null,os?.destroy(),os=null,Mn.delete(a),we.querySelector(`#wrapper-${a}`)?.removeAttribute("data-preserve-runtime"),R&&fo(Te,R.getMessages(),K)}let Qs=0,SE=nr()!==null,oo=zS(),ro=0,rs=null,qn=!1,Nc=!1,ss=0,an=null,Js=null,rg=!1,Xi=!1,Zs=null,ll=!0,Fc=!1,Qi=null,$c=!1,is=()=>{$c=!0,ME()},sg=null,AE=4,Cr=24,xE=80,EE=1e3,wr=null,Hy=()=>{e.setAttribute("data-persona-scrollbar",Ns()),Ns()!=="on-scroll"&&(wr!==null&&clearTimeout(wr),wr=null,ae.removeAttribute("data-persona-scrollbar-visible"))},ME=()=>{Ns()==="on-scroll"&&(ae.setAttribute("data-persona-scrollbar-visible",""),wr!==null&&clearTimeout(wr),wr=setTimeout(()=>{wr=null,Mi(ae,Cr)&&ae.removeAttribute("data-persona-scrollbar-visible")},EE))};Hy(),Se.push(()=>{wr!==null&&clearTimeout(wr)});let ig=new Map,ag=!1,Uc=null,Ge={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};ko();let Iy=o.voiceRecognition?.autoResume??!1,lg=()=>R.isVoiceActive()||R.isBargeInActive(),Ry=!1,Sr=a=>{X.emit("voice:state",{active:Ge.active,source:a,timestamp:Date.now()})},zn=()=>{qe(a=>({...a,voiceState:{active:Ge.active,timestamp:Date.now(),manuallyDeactivated:Ge.manuallyDeactivated}}))},TE=()=>{if(o.voiceRecognition?.enabled===!1)return;let a=wh(P.voiceState),u=!!a.active,m=Number(a.timestamp??0);Ge.manuallyDeactivated=!!a.manuallyDeactivated,u&&Date.now()-m<nH&&setTimeout(()=>{Ge.active||(Ge.manuallyDeactivated=!1,In(o.voiceRecognition?.provider)?R.toggleVoice().then(()=>{Ge.active=lg(),Sr("restore"),Ge.active?da():(zn(),ad(oH,1e4))}):ud("restore"))},In(o.voiceRecognition?.provider)?0:1e3)},Wy=a=>{Ry=!a.persisted,Ge.active&&zn()};typeof window<"u"&&(window.addEventListener("pagehide",Wy),Se.push(()=>window.removeEventListener("pagehide",Wy)));let PE=()=>R?cx(R.getMessages()).filter(a=>!a.__skipPersist):[],Vc=null,Oy=(a,u)=>{typeof console<"u"&&console.error(a,u)},jc=(a,u)=>{let m=()=>{try{let z=a();return!z||typeof z.then!="function"?null:Promise.resolve(z).catch(re=>{Oy(u,re)})}catch(z){return Oy(u,z),null}},b=Vc,w=b?b.then(()=>m()??void 0):m();if(!w)return;let k=w.finally(()=>{Vc===k&&(Vc=null)});Vc=k};function Ji(a){if(!T?.save)return;let u=a?cx(a):R?PE():[],m=_&&R?.getResumableHandle();m&&(P={...P,durableResume:{executionId:m.executionId,after:m.lastEventId}});let b={messages:u,metadata:P,artifacts:uo.artifacts,selectedArtifactId:uo.selectedId,...ei?{draft:ei}:{}};jc(()=>T.save(b),"[AgentWidget] Failed to persist state:")}let ei,qc=()=>!T?.save||o.persistState===!1?!1:typeof o.persistState=="object"?o.persistState.persist?.draft!==!1:!0,cl=bS({write:()=>{if(!qc())return;let a=be.getState(),u=hS({text:a.text,mentionRefs:a.mentionRefs,contentSegments:Ng(),selectedModelId:a.selectedModelId,activeModeIds:a.activeModeIds,quote:a.quote});JSON.stringify(u)!==JSON.stringify(ei)&&(ei=u,Ji())}});function _y(){qc()&&cl.schedule()}function cg(){cl.flush()}function By(a){if(!qc())return;let u=yS(a,{mentionSourceIds:(o.contextMentions?.sources??[]).map(m=>m.id),modelIds:(o.composer?.models??[]).map(m=>m.id),modes:o.composer?.modes??[]});u&&(ei=a,ce&&!ce.value&&(ce.value=u.text,ce.dispatchEvent(new Event("input",{bubbles:!0})),po()),u.selectedModelId&&(be.setSelectedModelId(u.selectedModelId),Zr?.repaint()),Tc(u.activeModeIds??[]),u.quote&&qo(u.quote),cl.cancel())}function zc(){cl.cancel(),ei&&(ei=void 0,qc()&&Ji())}let Zi=null,Dy=()=>Je.querySelector("#persona-scroll-container")||ae,ea=()=>{Zi!==null&&(cancelAnimationFrame(Zi),Zi=null),qn=!1},Ny=()=>{rs!==null&&(cancelAnimationFrame(rs),rs=null),Nc=!1,ea()},kE=()=>no&&pg()&&(En()!=="anchor-top"||Za()),dg=()=>{let a=Qr()||"Jump to latest",u=kE();Vt.toggleAttribute("data-persona-scroll-to-bottom-streaming",u),ss>0?(tn.textContent=String(ss),tn.style.display="",Vt.setAttribute("aria-label",`${a} (${ss} new)`)):(tn.textContent="",tn.style.display="none",Vt.setAttribute("aria-label",u?`${a} (response streaming below)`:a))},Fy=()=>{ss!==0&&(ss=0,dg())},LE=()=>{let a=an?.spacerHeight??0;return a<=0?Mi(ae,Cr):Yc(a)-ae.scrollTop-ae.clientHeight<=Cr},pg=()=>Mo()?!oo.isFollowing():!LE(),ug=()=>!!R&&R.getMessages().length>0,Tn=()=>{if(!Nu()||wc()){Vt.parentNode&&Vt.remove(),Vt.style.display="none";return}Vt.parentNode!==we&&we.appendChild(Vt),Re();let u=ir(ae)>0&&pg()&&ug();u?dg():Fy(),Vt.style.display=u?"":"none"},ta=()=>{oo.pause()&&(Ny(),Tn())},Go=()=>{oo.resume(),Fy(),Tn()},as=(a=!1)=>{Mo()&&ug()&&oo.isFollowing()&&(!a&&!no||(rs!==null&&(cancelAnimationFrame(rs),rs=null),Nc=!0,rs=requestAnimationFrame(()=>{rs=null,Nc=!1,oo.isFollowing()&&HE(Dy(),a?220:140)})))},$y=(a,u,m,b=()=>!0)=>{let w=a.scrollTop,k=u(),z=k-w;if(ea(),Math.abs(z)<1){qn=!0,a.scrollTop=k,ro=a.scrollTop,qn=!1;return}let re=performance.now();qn=!0;let Y=le=>1-Math.pow(1-le,3),ie=le=>{if(!b()){ea();return}let de=u();de!==k&&(k=de,z=k-w);let ke=le-re,it=Math.min(ke/m,1),gt=Y(it),dt=w+z*gt;a.scrollTop=dt,ro=a.scrollTop,it<1?Zi=requestAnimationFrame(ie):(a.scrollTop=k,ro=a.scrollTop,Zi=null,qn=!1)};Zi=requestAnimationFrame(ie)},HE=(a,u=500)=>{let m=ir(a)-a.scrollTop;if(Math.abs(m)<1){ro=a.scrollTop;return}if(Math.abs(m)>=xE){ea(),qn=!0,a.scrollTop=ir(a),ro=a.scrollTop,qn=!1;return}$y(a,()=>ir(a),u,()=>oo.isFollowing())},gg=()=>{if(!ug()){Tn();return}let a=Dy();qn=!0,a.scrollTop=ir(a),ro=a.scrollTop,qn=!1,Tn()},ti=a=>{let u=0,m=a;for(;m&&m!==ae;)u+=m.offsetTop,m=m.offsetParent;return u},IE=()=>{let a=ae.getRootNode();return(typeof a.getSelection=="function"?a.getSelection():null)??ae.ownerDocument.getSelection()},Kc=()=>YS(IE(),ae),fg=()=>{if(Mc()!=="last-user-turn")return!1;let a=R?.getMessages()??[];if(a.length<2)return!1;let u=[...a].reverse().find(k=>k.role==="user");if(!u)return!1;let m=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(u.id):u.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),b=ae.querySelector(`[data-message-id="${m}"]`);if(!b)return!1;let w=Math.min(Math.max(0,ti(b)-Ds()),ir(ae));return qn=!0,ae.scrollTop=w,ro=ae.scrollTop,qn=!1,En()==="follow"&&!Mi(ae,Cr)&&oo.pause(),Tn(),!0},Gc=a=>{let u=Math.max(0,Math.round(a));Qt.style.height=`${u}px`,Qt.style.display=u>0?"":"none",an&&(an.spacerHeight=Math.max(0,a))},Yc=a=>{let u=parseFloat(getComputedStyle(ae).paddingBottom)||0,m=0;for(let w of Array.from(ae.children)){if(w===Qt||w.offsetHeight===0)continue;let k=ti(w)+w.offsetHeight;k>m&&(m=k)}let b=ae.scrollHeight-a;return m>0?Math.min(m+u,b):b},RE=()=>{if(!an||an.spacerHeight<=0)return;let a=Yc(an.spacerHeight),u=Math.max(0,Math.round(ae.scrollTop)+ae.clientHeight-a+Cr);u<an.spacerHeight&&(Gc(u),Tn())},ni=()=>{Js!==null&&(cancelAnimationFrame(Js),Js=null),ea(),an=null,Qt.style.height="0px",Qt.style.display="none"},Uy=a=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(a):a.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),mg=a=>ae.querySelector(`[data-message-id="${Uy(a)}"]`),Vy=a=>{Js!==null&&cancelAnimationFrame(Js),Js=requestAnimationFrame(()=>{Js=null;let u=Uy(a),m=ae.querySelector(`[data-message-id="${u}"]`);if(!m)return;let b=ti(m),w=an?.spacerHeight??0,k=Yc(w),{targetScrollTop:z,spacerHeight:re}=Lm({anchorOffsetTop:b,topOffset:Ds(),viewportHeight:ae.clientHeight,contentHeight:k,slack:Cr});an={initialSpacerHeight:re,contentHeightAtAnchor:k,spacerHeight:re},Gc(re),$y(ae,()=>m.isConnected?Math.max(0,ti(m)-Ds()):z,220)})},na=()=>{if(En()!=="anchor-top"||!an||!Qi)return;let a=mg(Qi);if(!a)return;ea();let u=an.spacerHeight,m=Yc(u),{targetScrollTop:b,spacerHeight:w}=Lm({anchorOffsetTop:ti(a),topOffset:Ds(),viewportHeight:ae.clientHeight,contentHeight:m,slack:Cr});an={initialSpacerHeight:w,contentHeightAtAnchor:m,spacerHeight:w},Gc(w),qn=!0,ae.scrollTop=b,ro=ae.scrollTop,qn=!1,Tn()},WE=()=>{if(Mo()){if(!oo.isFollowing()||Mi(ae,1))return;as(!no);return}if(an&&an.initialSpacerHeight>0){let a=ae.scrollHeight-an.spacerHeight,u=XS({initialSpacerHeight:an.initialSpacerHeight,contentHeightAtAnchor:an.contentHeightAtAnchor,currentContentHeight:a});u!==an.spacerHeight&&Gc(u)}Tn()},OE=a=>{let u=En();u==="follow"?(Go(),as(!0)):u==="anchor-top"&&(ll=!1,Fc=!0,$c=!1,Qi=a,Vy(a))},_E=()=>{if(En()==="anchor-top"){if(Fc){ll=!1;return}ll=!0,ni(),Go(),as(!0)}},BE=96,DE=a=>{if(Zs===null)return!0;let u=mg(Zs),m=mg(a);if(!u||!m)return!0;let b=ti(m)-ti(u);return Ds()+b>ae.clientHeight-BE},NE=a=>{if(En()!=="anchor-top"||!Fc||$c||Kc())return;let u=Zs===null;for(let m of a){if(!u){m.id===Zs&&(u=!0);continue}if(qS(m)){if(m.id===Qi||!DE(m.id))return;Qi=m.id,Vy(m.id);return}}},FE=a=>{let u=new Map;a.forEach(m=>{let b=ig.get(m.id);u.set(m.id,{streaming:m.streaming,role:m.role}),!b&&m.role==="assistant"&&(X.emit("assistant:message",m),!Xi&&(En()!=="anchor-top"||Za())&&pg()&&(ss+=1,dg(),Tn(),$s(ss===1?"1 new message below.":`${ss} new messages below.`))),m.role==="assistant"&&b?.streaming&&m.streaming===!1&&X.emit("assistant:complete",m),m.variant==="approval"&&m.approval&&(b?m.approval.status!=="pending"&&X.emit("approval:resolved",{approval:m.approval,decision:m.approval.status}):X.emit("approval:requested",{approval:m.approval,message:m}))}),ig.clear(),u.forEach((m,b)=>{ig.set(b,m)})},dl=(a,u)=>{let m=u==="user"?"user":"assistant",b=o.layout?.messages?.[m],w=b?.width??"content",k=b?.maxWidth??(w==="full"?`var(--persona-message-${m}-max-width, 100%)`:void 0);a.classList.add("persona-message-row"),a.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),a.classList.add(`persona-message-row-${u}`,`persona-message-width-${w}`),a.classList.toggle("persona-justify-end",u==="user"),a.setAttribute("data-message-role",u),a.setAttribute("data-message-width",w),k?a.style.setProperty("--persona-message-row-max-width",k):a.style.removeProperty("--persona-message-row-max-width")},Ar=(a,u)=>{let m=document.createElement("div");return m.className="persona-flex",m.id=`wrapper-${a}`,m.setAttribute("data-wrapper-id",a),dl(m,u),m},$E=(a,u,m)=>{let b=new Set;for(let O of u){let Ne=O.variant==="tool"?"tool":O.variant==="reasoning"?"reasoning":null;if(!Ne||Ts(o,Ne)!=="row")continue;let Fe=Ne==="tool"?o.features?.toolCallDisplay:o.features?.reasoningDisplay;Fe?.expandable!==!1&&(b.add(O.id),i.observe(O,Ne,Ne==="tool"?r:s,Fe))}let w=document.createElement("div"),z=(()=>{let O=d.find(Ne=>Ne.renderLoadingIndicator);if(O?.renderLoadingIndicator)return O.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),re=(O,Ne)=>Ne==null?!1:typeof Ne=="string"?(O.textContent=Ne,!0):(O.appendChild(Ne),!0),Y=new Set,ie=new Map,le=new Set,de=d.some(O=>O.renderAskUserQuestion),ke=[],it=[],gt=o.enableComponentStreaming!==!1,dt=o.approval!==!1,Kn=[],Dt=o.messageActions,jt=Dt?.showRegenerate===!0&&Dt.enabled!==!1&&go.current?.isStreaming()!==!0?Ow(u):null,_n=Dt?.showEdit===!0&&Dt.enabled!==!1,Kt=Dt?.showQuote===!0&&Dt.enabled!==!1,wt=null,Jo=o.features?.reasoningDisplay?.completedVisibility,Zo=O=>Jo==="removed"?!0:Jo==="removed-when-short"?vv(O,o.features?.reasoningDisplay?.shortThinkThreshold):!1,bo=o.features?.toolCallDisplay?.completedVisibility==="removed",vo=O=>O.variant==="reasoning"&&O.reasoning?.status==="complete"?Zo(O.reasoning):bo&&O.variant==="tool"&&O.toolCall?.status==="complete";if(u.forEach(O=>{if(vo(O))return;if(Y.add(O.id),ie.set(O.id,O.role),Ys===O.id&&os){let $e=Ar(O.id,O.role);$e.setAttribute("data-persona-message-edit-stub","true"),$e.setAttribute("data-preserve-runtime","true"),w.appendChild($e),wt={messageId:O.id,element:os.element};return}let Ne=de&&Ir(O),Fe=dt&&O.variant==="approval"&&!!O.approval,se=!Ne&&O.role==="assistant"&&!O.variant&>&&hc(O);!Fe&&ns.has(O.id)&&(a.querySelector(`#wrapper-${O.id}`)?.removeAttribute("data-preserve-runtime"),ns.delete(O.id)),!se&&Gs.has(O.id)&&(a.querySelector(`#wrapper-${O.id}`)?.removeAttribute("data-preserve-runtime"),Gs.delete(O.id));let St=Ir(O)?`:${O.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${O.agentMetadata?.askUserQuestionAnswers?Object.keys(O.agentMetadata.askUserQuestionAnswers).length:0}`:"",Jt={canRegenerate:jt===O.id,canEdit:_n&&pm(O),canQuote:Kt&&!O.variant&&(O.content?.trim().length??0)>0},Hn=`${Jt.canRegenerate?"r":""}${Jt.canEdit?"e":""}${Jt.canQuote?"q":""}`,mn=FS(O,Qs)+St+`:${Hn}`,Tt=Ne||Fe||se?null:US(Mn,O.id,mn);if(Tt){w.appendChild(Tt.cloneNode(!0)),Ir(O)&&O.toolCall?.id&&O.agentMetadata?.awaitingLocalTool===!0&&!O.agentMetadata?.askUserQuestionAnswered&&(le.add(O.toolCall.id),Ju(O));return}let Gt=null,ln=d.find($e=>!!(O.variant==="reasoning"&&$e.renderReasoning||O.variant==="tool"&&$e.renderToolCall||!O.variant&&$e.renderMessage)),We=o.layout?.messages;if(Ir(O)&&O.agentMetadata?.askUserQuestionAnswered===!0){Yi.delete(O.id),a.querySelector(`#wrapper-${O.id}`)?.removeAttribute("data-preserve-runtime");return}if(gi(O)&&xs(o).enabled)return;if(Ir(O)&&o.features?.askUserQuestion?.enabled!==!1){let $e=d.find(cn=>typeof cn.renderAskUserQuestion=="function");if($e&&go.current){let cn=Yi.get(O.id),Co=cn!==mn,hn=null;if(Co){let{payload:Ye,complete:Ue}=Rr(O),hs=O.id,nn=()=>go.current?.getMessages().find(Gn=>Gn.id===hs);hn=$e.renderAskUserQuestion({message:O,payload:Ye,complete:Ue,resolve:Gn=>{let Pr=nn();Pr&&go.current?.resolveAskUserQuestion(Pr,Gn)},dismiss:()=>{let Gn=nn();Gn?.agentMetadata?.awaitingLocalTool&&(go.current?.markAskUserQuestionResolved(Gn),go.current?.resolveAskUserQuestion(Gn,"(dismissed)"))},config:o})}let At=cn!=null;if(Co&&hn===null&&!At){O.agentMetadata?.awaitingLocalTool===!0&&!O.agentMetadata?.askUserQuestionAnswered&&(le.add(O.toolCall.id),Ju(O));return}let Be=Ar(O.id,O.role);Be.setAttribute("data-ask-plugin-stub","true"),Be.setAttribute("data-preserve-runtime","true"),w.appendChild(Be),ke.push({messageId:O.id,fingerprint:mn,bubble:hn});return}else{O.agentMetadata?.awaitingLocalTool===!0&&!O.agentMetadata?.askUserQuestionAnswered&&(le.add(O.toolCall.id),Ju(O));return}}else if(Fe){let $e=B();if(!$e){w.appendChild(Ar(O.id,O.role));return}let cn=d.find(Be=>typeof Be.renderApproval=="function")??C,hn=ns.get(O.id)!==mn,At=null;if(hn&&cn?.renderApproval){let Be=O.id,Ye=(Ue,hs)=>{let nn=go.current?.getMessages().find(Gn=>Gn.id===Be);nn?.approval&&(nn.approval.toolType==="webmcp"?go.current?.resolveWebMcpApproval(nn.id,Ue):go.current?.resolveApproval(nn.approval,Ue,hs))};At=cn.renderApproval({message:O,defaultRenderer:()=>$e.createApprovalBubble(O,o,l),config:o,approve:Ue=>Ye("approved",Ue),deny:Ue=>Ye("denied",Ue)})}if(hn&&At===null)a.querySelector(`#wrapper-${O.id}`)?.removeAttribute("data-preserve-runtime"),ns.delete(O.id),Gt=$e.createApprovalBubble(O,o,l);else{let Be=Ar(O.id,O.role);Be.setAttribute("data-approval-plugin-stub","true"),Be.setAttribute("data-preserve-runtime","true"),w.appendChild(Be),Kn.push({messageId:O.id,fingerprint:mn,bubble:At});return}}else if(ln)if(O.variant==="reasoning"&&O.reasoning&&ln.renderReasoning){if(!te)return;Gt=ln.renderReasoning({message:O,defaultRenderer:()=>rh(O,o,s),config:o})}else if(O.variant==="tool"&&O.toolCall&&ln.renderToolCall){if(!ve)return;Gt=ln.renderToolCall({message:O,defaultRenderer:()=>lh(O,o,r),config:o})}else ln.renderMessage&&(Gt=ln.renderMessage({message:O,defaultRenderer:()=>{let $e=Fa(O,m,We,o.messageActions,to,{loadingIndicatorRenderer:z,widgetConfig:o,actionEligibility:Jt});return O.role!=="user"&&j($e,O,o,R),$e},config:o}));if(!Gt&&se){let $e=mu(O);if($e){let cn=Gs.get(O.id),Co=cn!==mn,hn=o.wrapComponentDirectiveInBubble!==!1&&Fo.getOptions($e.component)?.bubbleChrome!==!1,At=null;if(Co){let Be=fu($e,{config:o,message:O,transform:m});if(Be&&$e.component==="PersonaArtifactInline"){let Ye=Be.hasAttribute("data-artifact-inline")?Be:Be.querySelector("[data-artifact-inline]"),Ue=Ye?.getAttribute("data-artifact-inline")??"",hs=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(Ue):Ue,nn=Ue?a.querySelector(`#wrapper-${O.id}`)?.querySelector(`[data-artifact-inline="${hs}"]`)??null:null;Ye&&nn&&nn!==Ye&&qr()?.hasLiveInlineArtifactBlock(nn)&&(Ye===Be?Be=nn:Ye.replaceWith(nn))}if(Be)if(hn){let Ye=document.createElement("div");if(Ye.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Ye.id=`bubble-${O.id}`,Ye.setAttribute("data-message-id",O.id),O.content&&O.content.trim()){let Ue=document.createElement("div");Ue.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Ue.innerHTML=m({text:O.content,message:O,streaming:!!O.streaming,raw:O.rawContent}),Ye.appendChild(Ue)}Ye.appendChild(Be),At=Ye}else{let Ye=document.createElement("div");if(Ye.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ye.id=`bubble-${O.id}`,Ye.setAttribute("data-message-id",O.id),Ye.setAttribute("data-persona-component-directive","true"),O.content&&O.content.trim()){let Ue=document.createElement("div");Ue.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Ue.innerHTML=m({text:O.content,message:O,streaming:!!O.streaming,raw:O.rawContent}),Ye.appendChild(Ue)}Ye.appendChild(Be),At=Ye}}if(At||cn!=null){let Be=Ar(O.id,O.role);Be.setAttribute("data-component-directive-stub","true"),Be.setAttribute("data-preserve-runtime","true"),w.appendChild(Be),it.push({messageId:O.id,fingerprint:mn,bubble:At});return}}}if(!Gt)if(O.variant==="reasoning"&&O.reasoning){if(!te)return;Gt=rh(O,o,s)}else if(O.variant==="tool"&&O.toolCall){if(!ve)return;Gt=lh(O,o,r)}else if(O.variant==="approval"&&O.approval){if(o.approval===!1)return;let $e=B();if(!$e)return;Gt=$e.createApprovalBubble(O,o,l)}else{let $e=o.layout?.messages;$e?.renderUserMessage&&O.role==="user"?Gt=$e.renderUserMessage({message:O,config:o,streaming:!!O.streaming}):$e?.renderAssistantMessage&&O.role==="assistant"?Gt=$e.renderAssistantMessage({message:O,config:o,streaming:!!O.streaming}):Gt=Fa(O,m,$e,o.messageActions,to,{loadingIndicatorRenderer:z,widgetConfig:o,actionEligibility:Jt}),O.role!=="user"&&Gt&&j(Gt,O,o,R)}let Pt=Ar(O.id,O.role);Pt.appendChild(Gt),VS(Mn,O.id,mn,Pt),w.appendChild(Pt)}),et.composerOverlay&&et.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Ne=>{let Fe=Ne.getAttribute("data-persona-ask-sheet-for");Fe&&!le.has(Fe)&&Wr(et.composerOverlay,Fe)}),o.features?.toolCallDisplay?.grouped){let O=[],Ne=[],Fe=o.features.toolCallDisplay.groupedMode==="summary";u.forEach(se=>{if(se.variant==="tool"&&se.toolCall&&ve){if(bo&&se.toolCall.status==="complete")return;Ne.push(se);return}se.variant==="reasoning"&&(!te||se.reasoning?.status==="complete"&&Zo(se.reasoning))||((Ne.length>1||Fe&&Ne.length>0)&&O.push(Ne),Ne=[])}),(Ne.length>1||Fe&&Ne.length>0)&&O.push(Ne),O.forEach(se=>{let St=se.map(We=>Array.from(w.children).find(Pt=>Pt instanceof HTMLElement&&Pt.getAttribute("data-wrapper-id")===We.id)).filter(We=>!!We);if(St.length<(Fe?1:2))return;let Jt=Ar(`tool-group-${se[0].id}`,"assistant");if(Jt.setAttribute("data-persona-tool-group-row","true"),o.features?.toolCallDisplay?.groupedMode==="collapsible"){let We=`tool-group-${se[0].id}`,Pt=se.some(At=>At.toolCall?.status!=="complete"),$e={...se[0],id:We,toolCall:{id:We,name:`${se.length} tools`,status:Pt?"running":"complete",chunks:se.flatMap(At=>At.toolCall?.chunks??[]),success:!se.some(At=>At.toolCall?.success===!1)}};b.add(We),i.observe($e,"tool",r,o.features.toolCallDisplay);let cn=`${Pt?"Using":"Used"} ${se.length} tools`,Co=o.toolCall?.renderGroupedSummary?.({messages:se,toolCalls:se.map(At=>At.toolCall),defaultSummary:cn,config:o}),hn=aw($e,o,r.has(We),Co??cn);hn.bubble.classList.add("persona-tool-group"),hn.body.dataset.personaToolGroupStack="true",St[0].before(Jt),Jt.appendChild(hn.bubble),St.forEach((At,Be)=>{At.style.setProperty("--persona-message-row-max-width","100%"),At.style.setProperty("--persona-activity-stagger",`${Be*40}ms`),At.classList.add("persona-activity-group-child"),hn.body.appendChild(At)});return}let Hn=document.createElement("div");Hn.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Hn.setAttribute("data-persona-tool-group","true");let mn=document.createElement("div");mn.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",mn.id=`tool-group-summary-${se[0].id}`;let Tt=`Called ${se.length} ${se.length===1?"tool":"tools"}`,Gt=o.toolCall?.renderGroupedSummary?.({messages:se,toolCalls:se.map(We=>We.toolCall).filter(We=>!!We),defaultSummary:Tt,config:o});re(mn,Gt)||(mn.textContent=Tt);let ln=document.createElement("div");ln.className="persona-tool-group-stack persona-flex persona-flex-col",ln.id=`tool-group-stack-${se[0].id}`,ln.setAttribute("data-persona-tool-group-stack","true"),Hn.appendChild(mn),Fe||Hn.appendChild(ln),Jt.appendChild(Hn),St[0].before(Jt),St.forEach((We,Pt)=>{if(Fe){We.remove();return}We.style.setProperty("--persona-message-row-max-width","100%");let $e=document.createElement("div");$e.className="persona-tool-group-item persona-relative",$e.setAttribute("data-persona-tool-group-item","true"),Pt<St.length-1&&$e.setAttribute("data-persona-tool-group-connector","true"),$e.appendChild(We),ln.appendChild($e)})})}i.prune(b),jS(Mn,Y);let fs=O=>O.variant==="tool"&&!ve||O.variant==="reasoning"&&!te||vo(O),er=u.some(O=>O.role==="assistant"&&O.streaming&&!fs(O)),Io=u.length-1;for(;Io>=0&&fs(u[Io]);)Io--;let ms=Io>=0?u[Io]:void 0,xl=Io<u.length-1,ai=ms?.role==="assistant"&&!ms.streaming&&ms.variant!=="approval"&&!xl;if(no&&u.some(O=>O.role==="user")&&!er&&!ai){let O={config:o,streaming:!0,location:"standalone",defaultRenderer:Li},Ne=d.find(se=>se.renderLoadingIndicator),Fe=null;if(Ne?.renderLoadingIndicator&&(Fe=Ne.renderLoadingIndicator(O)),Fe===null&&o.loadingIndicator?.render&&(Fe=o.loadingIndicator.render(O)),Fe===null&&(Fe=Li()),Fe){let se=document.createElement("div"),St=o.loadingIndicator?.showBubble!==!1,Jt=o.layout?.messages?.layout??"bubble";se.className=St?cc("assistant",Jt).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),se.setAttribute("data-typing-indicator","true"),St&&(se.style.color="var(--persona-message-assistant-text, var(--persona-text))",Jt!=="flat"&&(se.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",se.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),se.appendChild(Fe);let Hn=Ar("typing-indicator","assistant");Hn.appendChild(se),w.appendChild(Hn)}}if(!no&&u.length>0){let O=u[u.length-1],Ne={config:o,lastMessage:O,messageCount:u.length},Fe=d.find(St=>St.renderIdleIndicator),se=null;if(Fe?.renderIdleIndicator&&(se=Fe.renderIdleIndicator(Ne)),se===null&&o.loadingIndicator?.renderIdle&&(se=o.loadingIndicator.renderIdle(Ne)),se){let St=document.createElement("div"),Jt=o.loadingIndicator?.showBubble!==!1;St.className=Jt?["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(" "),St.setAttribute("data-idle-indicator","true"),St.appendChild(se);let Hn=Ar("idle-indicator","assistant");Hn.appendChild(St),w.appendChild(Hn)}}if(Sw(w),Gp(a,w),im(a),wt){let{messageId:O,element:Ne}=wt,Fe=a.querySelector(`#wrapper-${O}`);Fe&&Ne.parentElement!==Fe&&(dl(Fe,ie.get(O)??"user"),Fe.replaceChildren(Ne))}if(ke.length>0)for(let{messageId:O,fingerprint:Ne,bubble:Fe}of ke){let se=a.querySelector(`#wrapper-${O}`);se&&(dl(se,ie.get(O)??"assistant"),Fe!==null&&(se.replaceChildren(Fe),se.setAttribute("data-bubble-fp",Ne),Yi.set(O,Ne)))}if(Yi.size>0)for(let O of Yi.keys())Y.has(O)||Yi.delete(O);if(it.length>0)for(let{messageId:O,fingerprint:Ne,bubble:Fe}of it){let se=a.querySelector(`#wrapper-${O}`);se&&(dl(se,ie.get(O)??"assistant"),Fe!==null&&(se.replaceChildren(Fe),se.setAttribute("data-bubble-fp",Ne),Gs.set(O,Ne)))}if(Gs.size>0)for(let O of Gs.keys())Y.has(O)||Gs.delete(O);if(Kn.length>0)for(let{messageId:O,fingerprint:Ne,bubble:Fe}of Kn){let se=a.querySelector(`#wrapper-${O}`);se&&(dl(se,ie.get(O)??"assistant"),Fe!==null&&(se.replaceChildren(Fe),se.setAttribute("data-bubble-fp",Ne),ns.set(O,Ne)))}if(ns.size>0)for(let O of ns.keys())Y.has(O)||ns.delete(O)},hg=!1,Xc=()=>{hg||(hg=!0,mi().catch(()=>{}),vd().catch(()=>{hg=!1}))},fo=(a,u,m)=>{u.length>0&&Xc(),$E(a,u,m),sy()},pl=null,UE=()=>{if(pl)return;let a=m=>{let b=m.composedPath();b.includes(Je)||Xt&&b.includes(Xt)||Mt(!1,"user")};pl=a,(e.ownerDocument??document).addEventListener("pointerdown",a,!0)},jy=()=>{if(!pl)return;(e.ownerDocument??document).removeEventListener("pointerdown",pl,!0),pl=null};Se.push(()=>jy());let ul=null,VE=()=>{if(ul)return;let a=m=>{m.key==="Escape"&&(m.isComposing||Mt(!1,"user"))};ul=a,(e.ownerDocument??document).addEventListener("keydown",a,!0)},qy=()=>{if(!ul)return;(e.ownerDocument??document).removeEventListener("keydown",ul,!0),ul=null};Se.push(()=>qy());let gl=!1,zy=new Set,jE=()=>{let a=o.launcher?.composerBar?.peek?.streamAnimation;return a||o.features?.streamAnimation},oa=()=>{if(!Le())return;let a=et.peekBanner,u=et.peekTextNode;if(!a||!u)return;if(D){a.classList.remove("persona-pill-peek--visible");return}let m=R?.getMessages()??[],b;for(let Dt=m.length-1;Dt>=0;Dt--){let jt=m[Dt];if(jt.role==="assistant"&&jt.content){b=jt;break}}if(!b){a.classList.remove("persona-pill-peek--visible");return}let w=b.content,k=!!b.streaming,z=jE(),re=Yp(z),Y=re.type!=="none"?og(re.type,z?.plugins):null,ie=Y?.isAnimating?.(b)===!0,le=Y!==null&&(k||ie);le&&Y&&!zy.has(Y.name)&&(rc(Y,e),zy.add(Y.name));let de=le&&Y?.containerClass?Y.containerClass:null,ke=u.dataset.personaPeekStreamClass??null;ke&&ke!==de&&(u.classList.remove(ke),delete u.dataset.personaPeekStreamClass),de&&ke!==de&&(u.classList.add(de),u.dataset.personaPeekStreamClass=de),le?(u.style.setProperty("--persona-stream-step",`${re.speed}ms`),u.style.setProperty("--persona-stream-duration",`${re.duration}ms`)):(u.style.removeProperty("--persona-stream-step"),u.style.removeProperty("--persona-stream-duration"));let it=le?Xp(w,re.buffer,Y,b,k):w;if(le&&re.placeholder==="skeleton"&&k&&(!it||!it.trim())){let Dt=document.createElement("div"),jt=oc();jt.classList.add("persona-pill-peek__skeleton"),Dt.appendChild(jt),Gp(u,Dt)}else{let Dt=Math.max(0,it.length-100),jt=it.length>100?it.slice(-100):it,_n=Ur(jt);if(!le||!Y){let Kt=it.length>100?`\u2026${jt}`:jt;u.textContent!==Kt&&(u.textContent=Kt)}else{let Kt=_n;(Y.wrap==="char"||Y.wrap==="word")&&(Kt=nc(_n,Y.wrap,`peek-${b.id}`,{skipTags:Y.skipTags,startIndex:Dt}));let wt=document.createElement("div");if(wt.innerHTML=Kt,Y.useCaret&&jt.length>0){let Jo=Qp(),Zo=wt.querySelectorAll(".persona-stream-char, .persona-stream-word"),bo=Zo[Zo.length-1];bo?.parentNode?bo.parentNode.insertBefore(Jo,bo.nextSibling):wt.appendChild(Jo)}Gp(u,wt),Y.onAfterRender?.({container:u,bubble:a,messageId:b.id,message:b,speed:re.speed,duration:re.duration})}}let Kn=no||gl;a.classList.toggle("persona-pill-peek--visible",Kn)};if(Le()){let a=et.peekBanner;if(a){let b=w=>{w.preventDefault(),w.stopPropagation(),Mt(!0,"user")};a.addEventListener("pointerdown",b),Se.push(()=>{a.removeEventListener("pointerdown",b)})}let u=()=>{gl||(gl=!0,oa())},m=()=>{gl&&(gl=!1,oa())};Ae.addEventListener("pointerenter",u),Ae.addEventListener("pointerleave",m),Se.push(()=>{Ae.removeEventListener("pointerenter",u),Ae.removeEventListener("pointerleave",m)}),Xt&&(Xt.addEventListener("pointerenter",u),Xt.addEventListener("pointerleave",m),Se.push(()=>{Xt.removeEventListener("pointerenter",u),Xt.removeEventListener("pointerleave",m)}))}let qE=a=>{let u=o.launcher?.composerBar??{},m=u.expandedSize??"anchored",b=u.bottomOffset??"16px",w=u.collapsedMaxWidth,k=u.expandedMaxWidth??"880px",z=u.expandedTopOffset??"5vh",re=u.modalMaxWidth??"880px",Y=u.modalMaxHeight??"min(90vh, 800px)",ie="calc(100vw - 32px)",le="var(--persona-pill-area-height, 80px)",de=Je.style;if(de.left="",de.right="",de.top="",de.bottom="",de.transform="",de.width="",de.maxWidth="",de.height="",de.maxHeight="",Xt){let ke=Xt.style;ke.bottom=b,ke.width=w??""}if(a&&m!=="fullscreen"){if(m==="modal"){de.top="50%",de.left="50%",de.transform="translate(-50%, -50%)",de.bottom="auto",de.right="auto",de.width=re,de.maxWidth=ie,de.maxHeight=Y,de.height=Y;return}de.left="50%",de.transform="translateX(-50%)",de.bottom=`calc(${b} + ${le})`,de.top=z,de.width=k,de.maxWidth=ie}},fl=()=>{if(D&&Xc(),!Xe())return;if(Le()){let ie=(o.launcher?.composerBar??{}).expandedSize??"anchored",le=D?"expanded":"collapsed";Je.dataset.state=le,Je.dataset.expandedSize=ie,Xt&&(Xt.dataset.state=le,Xt.dataset.expandedSize=ie),Je.style.removeProperty("display"),Je.classList.remove("persona-pointer-events-none","persona-opacity-0"),Ae.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),qE(D),we.style.display=D?"flex":"none",Us(),D?(UE(),VE()):(jy(),qy()),oa();return}let a=Lt(o),u=e.ownerDocument.defaultView??window,m=o.launcher?.mobileBreakpoint??640,b=o.launcher?.mobileFullscreen??!0,w=u.innerWidth<=m,k=b&&w&&ye,z=Zn(o).reveal;D?(Je.style.removeProperty("display"),Je.style.display=a?"flex":"",Je.classList.remove("persona-pointer-events-none","persona-opacity-0"),Ae.classList.remove("persona-scale-95","persona-opacity-0"),Ae.classList.add("persona-scale-100","persona-opacity-100"),qt?(qt.setPanelOpen(!0),qt.element.style.display="none"):On&&(On.style.display="none")):(a?a&&(z==="overlay"||z==="push")&&!k?(Je.style.removeProperty("display"),Je.style.display="flex",Je.classList.remove("persona-pointer-events-none","persona-opacity-0"),Ae.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Je.style.setProperty("display","none","important"),Je.classList.remove("persona-pointer-events-none","persona-opacity-0"),Ae.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Je.style.display="",Je.classList.add("persona-pointer-events-none","persona-opacity-0"),Ae.classList.remove("persona-scale-100","persona-opacity-100"),Ae.classList.add("persona-scale-95","persona-opacity-0")),qt?(qt.setPanelOpen(!1),qt.element.style.display=a?"none":""):On&&(On.style.display=a?"none":""))},Mt=(a,u="user")=>{if(!Xe()||D===a)return;let m=D;D=a,fl();let b=(()=>{let k=o.launcher?.sidebarMode??!1,z=e.ownerDocument.defaultView??window,re=o.launcher?.mobileFullscreen??!0,Y=o.launcher?.mobileBreakpoint??640,ie=z.innerWidth<=Y,le=Lt(o)&&re&&ie,de=Le()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return k||re&&ie&&ye||le||de})();if(D&&b){if(!zo){let k=e.getRootNode(),z=k instanceof ShadowRoot?k.host:e.closest(".persona-host");z&&(zo=Rm(z,o.launcher?.zIndex??kn))}Ko||(Ko=Wm(e.ownerDocument))}else D||(zo?.(),zo=null,Ko?.(),Ko=null);D&&(wl(),fg()||(En()==="follow"?as(!0):gg()));let w={open:D,source:u,timestamp:Date.now()};D&&!m?X.emit("widget:opened",w):!D&&m&&X.emit("widget:closed",w),X.emit("widget:state",{open:D,launcherEnabled:ye,voiceActive:Ge.active,streaming:R.isStreaming()})},ls={inputDisabled:!1,sendDisabled:!1},Yo=()=>ls.inputDisabled,yg=()=>In(o.voiceRecognition?.provider)&&!!R&&(R.isBargeInActive()||["listening","processing","speaking"].includes(R.getVoiceStatus())),oi=()=>ls.inputDisabled||ls.sendDisabled,zE=()=>(ls.inputDisabled?ls.inputReason:void 0)??(ls.sendDisabled?ls.sendReason:void 0);function bg(){if(!Pe)return;if(be.getState().phase==="streaming"){Pe.disabled=!1;return}let a=je?!je.isReady():!1;Pe.disabled=oi()||a}function Qc(){if(!Wn)return;let a=be.getState(),u=o.sendButton?.visibility==="when-text"&&a.phase!=="streaming"&&a.text.trim().length===0&&a.attachments.length===0;Wn.toggleAttribute("data-persona-send-hidden",u)}function KE(){let a=zE();if(Le()){let u=An??Ke;a?u.setAttribute("title",a):u.removeAttribute("title"),Ke.toggleAttribute(Ya,!!a);return}if(a){tt.setAttribute("role","status"),tt.setAttribute("aria-live","polite"),tt.setAttribute(Ya,""),tt.removeAttribute(yc),tt.textContent=a,hi(tt,o.statusIndicator??{},"idle");return}if(tt.hasAttribute(Ya)&&(tt.removeAttribute("role"),tt.removeAttribute("aria-live"),tt.removeAttribute(Ya),h)){let u=R.getStatus();_s(tt,ur(u),o.statusIndicator??{},u)}}function vg(){let a=Nf(o.composer?.inputDisabled),u=Nf(o.composer?.sendDisabled);ls={inputDisabled:a.disabled,inputReason:a.reason,sendDisabled:u.disabled,sendReason:u.reason},be.setInputDisabled(a.disabled),be.setSendDisabled(u.disabled);let m=be.getState().phase==="streaming",b=a.disabled,w=m||b;ce&&(ce instanceof HTMLTextAreaElement?ce.disabled=b:ce.setAttribute("contenteditable",b?"false":"true"),ce.setAttribute("aria-disabled",b?"true":"false")),It&&(It.disabled=b),Et&&(Et.disabled=b);for(let k of at?.affordanceButtons??[])k.querySelectorAll("button").forEach(z=>{z.disabled=b});he&&(he.disabled=b||m&&!yg()),js.forEach(k=>{k.elements.forEach(z=>{z.toggleAttribute("data-disabled",w),z instanceof HTMLButtonElement||z.setAttribute("aria-disabled",w?"true":"false")}),k.buttons.forEach(z=>{z.disabled=w})}),Eg.forEach(k=>{k.toggleAttribute("data-disabled",w),k instanceof HTMLButtonElement?k.disabled=w:k.setAttribute("aria-disabled",w?"true":"false"),k.querySelectorAll("button").forEach(z=>{z.disabled=w})}),Ke.dataset.personaComposerStreaming=m?"true":"false",Ke.dataset.personaComposerInputDisabled=b?"true":"false",Ke.dataset.personaComposerSendDisabled=oi()?"true":"false",Ke.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(k=>{(k instanceof HTMLButtonElement||k instanceof HTMLInputElement||k instanceof HTMLTextAreaElement||k instanceof HTMLSelectElement)&&(k.disabled=m)}),bg(),KE()}let ml=a=>{be.setStreaming(a),xc(a?"stop":"send"),vg()},Jc=()=>{Ge.active||ce&&ce.focus()};X.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>Jc(),200)});let Ky=null,Cg=!1,wg=!en.hidden,cs=null,Sg=!J,Zc=null;Se.push(()=>{Zc?.cancel(),Zc=null});let GE=a=>{let u=AA(a);if(u===N)return;N=u,e.setAttribute("data-persona-conversation-state",u);let m=pe();Ot(),Sg&&(Zc?.cancel(),Zc=wA(Ke,u==="active"?m:pe(),u==="active"?"drop":"rise",E().layout==="centered"?320:260)),na()},Gy=null,Yy,Xy=null,ra=null,Ag=!1,hl=a=>{let u=E(),m=`${u.variant}|${u.layout}|${u.dismiss}|${u.anchor??"bottom"}|${u.align??""}|${u.iconPlacement}|${u.kicker??""}|${u.title}|${u.subtitle}`;(m!==Gy||u.icon!==Yy)&&(Gy=m,Yy=u.icon,su({host:en,iconHolder:Sc,kicker:Ac,title:Bu,subtitle:Ni,starterSuggestions:gr},u));let b=u.message===void 0?null:`${o.layout?.messages?.layout??"bubble"}|${u.message}`;b!==Xy&&(Xy=b,iu(Rn,u.message,o));let w=a??(R?R.getMessages():o.initialMessages);GE(w);let k=Cg,z=!k&&Ws(u,w),re=z!==wg;if(wg=z,ra){cs?.cancel(),cs=null,k!==Ag&&(Ag=k,k?Xm(ae,en,null):Ym(ae,en,ra)),$a(ae,en,!k);return}if(re&&!z&&!k&&u.dismiss==="on-first-message"&&Sg){cs=CA(en,ie=>{cs===ie&&(cs=null),!wg&&!ra&&($a(ae,en,!1),na()),ie?.cancel()});return}if(cs){if(!z&&!k)return;cs.cancel(),cs=null}let Y=!en.hidden;$a(ae,en,z),!z&&Y&&na()},xg=[],Eg=[],Mg=!1,Qy=null,Jy,Zy=()=>{Eg.length=0;let a=xg.splice(0,xg.length);for(let u of a)try{u()}catch(m){console.warn("[persona] renderWelcome cleanup threw",m)}};Se.push(Zy);let YE=(a,u)=>{let m=_m(a,u);if(!m)return o.debug===!0&&console.warn("[persona] renderStarter received a suggestion with no label"),x("span");let b=o.suggestions?.starters,w=Bm({item:{...m,behavior:m.behavior??b?.behavior??"send"},index:u,surface:"starter",source:"config",variant:b?.variant??"card",streaming:h?R.isStreaming():!1,config:o,plugins:d,chipsConfig:o.suggestionChipsConfig,session:R,getTextarea:()=>ce,eventTarget:en,submitPrompt:ld});return Eg.push(w),w},Tg=()=>{if(Mg)return;Mg=!0;let a=E();Qy=`${a.variant}|${a.layout}|${a.dismiss}|${a.title}|${a.subtitle}|${a.message??""}`,Jy=a.icon;try{Zy(),Xm(ae,en,ra),ra=null,Ag=!1;let u=R?R.getMessages():o.initialMessages,m=Ws(a,u),b=0,w=null;for(let k of d)if(k.renderWelcome&&(w=k.renderWelcome({config:a,variant:a.variant,visible:m,defaultRenderer:()=>en,sendMessage:z=>{if(!R||R.isStreaming())return;let re=z.trim();re&&R.sendMessage(re)},requestRender:()=>Tg(),renderStarter:z=>YE(z,b++),storage:y(k.id),onCleanup:z=>{xg.push(z)}}),w))break;w&&w!==en&&(ra=w,Ym(ae,en,w))}finally{Mg=!1}hl()},XE=()=>{let a=E();`${a.variant}|${a.layout}|${a.dismiss}|${a.title}|${a.subtitle}|${a.message??""}`===Qy&&a.icon===Jy||Tg()},ed=()=>{hl(),Ki||(ce.placeholder=pS(be.getState().activeModeIds,o.composer?.modes)??o.copy?.inputPlaceholder??"How can I help...",!(o.sendButton?.useIcon??!1)&&!R?.isStreaming()&&(Pe.textContent=o.copy?.sendButtonLabel??"Send")),ce.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ce.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},QE=!!o.setStoredConversationId,sa=a=>qe(u=>{let m={...u};return delete m[a],m}),td=a=>{let u=P[a];return typeof u=="string"?u:null},eb=()=>{let a=P.durableResume;if(!a||typeof a!="object")return null;let u=a;return typeof u.executionId=="string"&&u.executionId.length>0&&typeof u.after=="string"&&u.after.length>0?{executionId:u.executionId,after:u.after}:null};o.clientToken&&(o={...o,getStoredSessionId:()=>td("sessionId"),setStoredSessionId:a=>{qe(u=>({...u,sessionId:a}))},clearStoredSessionId:o.clearStoredSessionId??(()=>sa("sessionId")),getStoredConversationId:o.getStoredConversationId??(()=>td("conversationId")),setStoredConversationId:o.setStoredConversationId??(a=>{qe(u=>({...u,conversationId:a}))}),clearStoredConversationId:o.clearStoredConversationId??(()=>sa("conversationId"))});let tb=()=>o.clientToken??null,nb=a=>ox(a,Ct(),o.persistState===!1),ob=tb(),mo=ob?nb(ob):null,JE=()=>{let a=P.pendingDisplayProjections;if(!a||typeof a!="object")return null;let u=a;return typeof u.conversationId!="string"||!Array.isArray(u.messageIds)?null:{conversationId:u.conversationId,messageIds:u.messageIds.filter(m=>typeof m=="string")}},ds={...mo?{visitorStore:mo}:{},historyBootstrapReady:o.features?.history?.enabled===!0&&!wp()?Promise.all([ue,me]).then(()=>{}):ue,getStoredMessageCursor:()=>td("historyMessageCursor"),setStoredMessageCursor:a=>{if(a===null){sa("historyMessageCursor");return}qe(u=>({...u,historyMessageCursor:a}))},getPendingDisplayProjections:JE,setPendingDisplayProjections:a=>{if(!a){sa("pendingDisplayProjections");return}qe(u=>({...u,pendingDisplayProjections:a}))},getStoredResumableHandle:eb,setStoredResumableHandle:a=>{if(!a){sa("durableResume");return}qe(u=>({...u,durableResume:a}))},shouldResumeDurableConversation:()=>_&&eb()!==null,...QE?{}:{getStoredConversationRevision:()=>td("conversationRevision"),setStoredConversationRevision:a=>{if(a===null){sa("conversationRevision");return}qe(u=>({...u,conversationRevision:a}))}}};if(_){let a=o.onExecutionState,u=e.ownerDocument.defaultView,m=!1,b=()=>m=!0,w=()=>m=!1;u?.addEventListener("pagehide",b),u?.addEventListener("pageshow",w),Se.push(()=>{u?.removeEventListener("pagehide",b),u?.removeEventListener("pageshow",w)}),o={...o,reconnectStream:o.reconnectStream??(k=>R.getClient().reconnectClientTokenStream(k)),onExecutionState:k=>{(k||!m)&&ds.setStoredResumableHandle?.(k?{executionId:k.executionId,after:k.lastEventId}:null),a?.(k)}}}let ZE=()=>{let a=tb();if(a&&mo?.matches(a,Ct(),o.persistState===!1)||!a&&!mo)return;mo?.destroy(),mo=a?nb(a):null;let u={...ds};mo?u.visitorStore=mo:delete u.visitorStore,ds=u,R.setHistoryInternals(ds)},ri=null,eM=()=>{ri==null&&(ri=setInterval(()=>{let a=Te.querySelectorAll("[data-tool-elapsed]");if(a.length===0){clearInterval(ri),ri=null;return}let u=Date.now();a.forEach(m=>{let b=Number(m.getAttribute("data-tool-elapsed"));b&&(m.textContent=m.closest(".persona-activity-row")?Ul(u-b):Ed(u-b))})},100))},Pg=(a,u)=>{if(Object.is(a,u))return!0;if(a===null||u===null||typeof a!="object"||typeof u!="object")return!1;if(Array.isArray(a)||Array.isArray(u))return!Array.isArray(a)||!Array.isArray(u)||a.length!==u.length?!1:a.every((z,re)=>Pg(z,u[re]));let m=a,b=u,w=Object.keys(m),k=Object.keys(b);return w.length===k.length&&w.every(z=>Object.prototype.hasOwnProperty.call(b,z)&&Pg(m[z],b[z]))},rb=a=>{let{content:u,rawContent:m,llmContent:b,...w}=a;return w},kg=a=>a.role==="assistant"&&a.streaming===!0&&!a.variant&&!a.toolCall&&!a.tools&&!a.approval&&!a.reasoning&&!a.contentParts&&!a.stopReason&&!hc(a),tM=(a,u,m)=>{if(a.length!==u.length)return!1;let b=a[m.index],w=u[m.index];return!b||!w||b.id!==m.id||w.id!==m.id?!1:(!Object.is(b.content,w.content)||!Object.is(b.rawContent,w.rawContent)||!Object.is(b.llmContent,w.llmContent))&&kg(b)&&kg(w)&&Pg(rb(b),rb(w))},nd=null,ia=null,si=null,xr=null,Lg=null,nM=a=>{if(!_)return Ji(a);Lg=a,queueMicrotask(()=>{Lg===a&&(Lg=null,Ji(a))})},od=a=>{nd=a;let u,m;ia=null;for(let w=a.length-1;w>=0;w-=1){let k=a[w];if(!u&&k.role==="user"&&(u=k),!m&&k.role==="assistant"&&(m=k),!ia&&kg(k)&&(ia={index:w,id:k.id}),u&&m&&ia)break}fo(Te,a,K),qr()?.updateInlineArtifactBlocks(Te,uo.artifacts,{suppressTransition:no}),eM(),hl(a),Ks(a),as(!no),FE(a),a.length===0&&(ni(),ll=!0,Fc=!1,Qi=null,$c=!1),!rg||Xi?(rg=!0,Zs=u?.id??null,sg=m?.id??null):u&&u.id!==Zs?(Zs=u.id,OE(u.id)):m&&m.id!==sg&&_E(),m&&(sg=m.id),NE(a);let b=Ge.lastUserMessageId;u&&u.id!==b&&(Ge.lastUserMessageId=u.id,X.emit("user:message",u)),Ge.lastUserMessageWasVoice=!!u?.viaVoice,nM(a),oa()},Hg=()=>{xr!==null&&(cancelAnimationFrame(xr),xr=null);let a=si;si=null,a&&od(a)},sb=()=>{xr!==null&&cancelAnimationFrame(xr),xr=null,si=null},oM=a=>{let u=si??nd;if(no&&u&&ia&&tM(u,a,ia)){si=a,xr===null&&(xr=requestAnimationFrame(()=>{xr=null;let m=si;si=null,m&&od(m)}));return}if(a.length===0){sb(),od(a);return}Hg(),od(a)};R=new Wa(o,{onMessagesChanged(a){oM(a)},onStatusChanged(a){let u=o.statusIndicator??{};_s(tt,(b=>b==="idle"?u.idleText??Yt.idle:b==="connecting"?u.connectingText??Yt.connecting:b==="connected"?u.connectedText??Yt.connected:b==="error"?u.errorText??Yt.error:b==="paused"?u.pausedText??Yt.paused:b==="resuming"?u.resumingText??Yt.resuming:Yt[b])(a),u,a),Yr()},onStreamingChanged(a){a||(R?.getMessages().length===0?sb():Hg()),no=a,ml(a),Yr(),R&&fo(Te,R.getMessages(),K),a||(as(!0),RE(),Py=!0,R&&ky(R.getMessages(),xs(o))),Tn(),$s(a?"Responding\u2026":"Response complete."),oa()},onVoiceStatusChanged(a){if(X.emit("voice:status",{status:a,timestamp:Date.now()}),a!=="disconnected"&&!In(o.voiceRecognition?.provider))return;let u=R.getVoiceNotice();switch(u&&ad(u,1e4),a){case"listening":if(!ag){let m=R.getVoiceDisclosure();m&&(ag=!0,Le()?(Uc=ce.placeholder,ce.placeholder=m,$s(m)):ad(m,1e4))}Tr(),da();break;case"processing":Tr(),MM();break;case"speaking":Tr(),TM();break;default:a==="idle"&&R.isBargeInActive()?(Tr(),da(),he?.setAttribute("aria-label","End voice session")):(Ge.active=!1,ag=!1,Uc!==null&&(ce.placeholder=Uc,Uc=null),Tr(),Sr("system"),Ry||zn());break}},onArtifactsState(a){uo=a,a.artifacts.length===0&&(Gi=!1),qr()?.updateInlineArtifactBlocks(Te,a.artifacts,{suppressTransition:no}),Ho(),Ji()},onHistoryStateChanged(a){pr(a)},onHistoryNotice(a){Uo(a)},onReconnect(a){let{executionId:u,lastEventId:m}=a.handle;a.phase==="paused"?X.emit("stream:paused",{executionId:u,after:m}):a.phase==="resuming"?X.emit("stream:resuming",{executionId:u,after:m,attempt:a.attempt??1}):X.emit("stream:resumed",{executionId:u,after:m})}},ds),go.current=R,Se.push(()=>R.cancel()),Se.push(()=>{R.destroy(),mo?.destroy(),mo=null});let Ig=null;if(R.onReadAloudChange((a,u)=>{oy=a,ry=u,sy();let m=a??Ig;a&&(Ig=a);let b=m?R.getMessages().find(w=>w.id===m)??null:null;X.emit("message:read-aloud",{messageId:m,message:b,state:u,timestamp:Date.now()}),u==="idle"&&(Ig=null)}),h=!0,rg=!0,o.voiceRecognition?.enabled===!0&&In(o.voiceRecognition.provider))try{R.setupVoice()}catch(a){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",a)}let Bt=null,Rg=null,ib=!1,ab=R.getHistoryState(),yl=()=>o.features?.history?.enabled===!0,lb=a=>{a&&(To.textContent="",To.textContent=a)},Wg=()=>{f.forEach(m=>m()),f=[];let a=Bt,u=a?.railCollapseShortcut();a&&u&&f.push(g.register({id:"history-rail-collapse",combo:u.combo,scope:o.features?.history?.rail?.collapseShortcutScope==="page"?"page":"widget",when:()=>un&&Un==="rail"&&a.railCollapsible()||a.railTriggerApplies(),run:()=>a.railOverlayMode()?a.toggleRailPinned():a.toggleRailCollapsed()}));for(let m of o.layout?.header?.trailingActions??[])m.shortcut&&f.push(g.register({id:`header-action-${m.id}`,combo:m.shortcut,run:()=>{let b=e.querySelector(`[data-persona-header-action="${m.id}"]`);b?b.click():o.layout?.header?.onAction?.(m.id)}}));for(let m of d)for(let b of m.shortcuts??[])f.push(g.register({...b,id:`${m.id}:${b.id}`}))};Wg();let rd=null,cb=!1,bl=()=>{if(!Vo)return;let a=o.layout?.header?.titleSource==="conversation",u=a&&rd?.trim()||null;Vo.textContent=u??o.launcher?.title??"Chat Assistant";let m=Vo.closest(".persona-combo-btn");if(!m)return;let b=!a||R.getActiveConversationId()!==null;m.setAttribute("data-persona-menu-locked",b?"false":"true"),m.setAttribute("aria-haspopup",b?"true":"false"),b||m.setAttribute("aria-expanded","false"),m.style.cursor=b?"pointer":"default";let w=m.querySelector("svg");w&&(w.style.display=b?"":"none")},rM=a=>{a!==rd&&(rd=a,bl())},sM=a=>{cb=a?.starred===!0,rM(a&&a.title.trim()||null),bl()};bl(),we.addEventListener("persona:title-menu-builtin",a=>{let u=a.detail?.actionId,m=R.getActiveConversationId();m&&(u==="delete"?Xo(b=>b.requestDeleteConversation(m)):u==="star"&&R.canUpdateConversations()&&Xo(b=>b.updateHistoryConversation(m,{starred:!cb})).catch(()=>{}))}),pr=a=>{ab=a,Bt?.historySurface?.view.setNewConversationRequired(a.recovery==="new_conversation_required"),ml(a.sendBlocked||no),Bt?.syncEarlierMessagesPill()},Uo=a=>{(a.code==="history_continuity_reset"||a.code==="conversation_deleted_recovered")&&(Mn.clear(),ni(),Go()),lb(a.message),Bt?.historySurface?.view.refresh()};let iM={get actionManager(){return _e},get activeConversationTitle(){return rd},announceHistory:lb,get applyRailChrome(){return Vn},set applyRailChrome(a){Vn=a},get artifactSplitRoot(){return br},get body(){return ae},get config(){return o},get container(){return we},get conversationOpenPendingEl(){return Ky},set conversationOpenPendingEl(a){Ky=a},get conversationOpenTakeover(){return Cg},set conversationOpenTakeover(a){Cg=a},currentKeyPrefix:Ct,destroyCallbacks:Se,eventBus:X,get footer(){return Ke},get header(){return mt},get historyChromeSync(){return Yr},set historyChromeSync(a){Yr=a},historyFeatureEnabled:yl,get historyInternals(){return ds},set historyInternals(a){ds=a},get historyPresentation(){return Un},set historyPresentation(a){Un=a},get historySessionState(){return ab},get historyVisible(){return un},set historyVisible(a){un=a},get isStreaming(){return no},jumpToBottomInstant:gg,get lastAppliedMessages(){return nd},set lastAppliedMessages(a){nd=a},get launcherEnabled(){return ye},get launcherSurfaceInstance(){return qt},maybeFocusInput:Jc,messageCache:Mn,get messagesWrapper(){return Te},mount:e,get open(){return D},panel:Ae,panelElements:et,get persistentMetadata(){return P},set persistentMetadata(a){P=a},plugins:d,get reapplyHistoryHostChrome(){return dr},set reapplyHistoryHostChrome(a){dr=a},repinAnchoredMessage:na,resetAnchorState:ni,restoreScrollPosition:fg,resumeAutoScroll:Go,runStorageMutation:jc,get session(){return R},setActiveConversationSummary:sM,storageAdapter:T,get suppressScrollSend(){return Xi},set suppressScrollSend(a){Xi=a},syncScrollToBottomButton:Tn,updateWelcome:hl,getHistoryProviderFactory:sx,historyErrors:{HistoryClientError:on,HistoryProviderError:Vr},isDockedMountMode:Lt,renderLucideIcon:ge,loadHistoryView:rx,createHeaderIconButton:_a,attachTooltip:vn},Og=a=>(!Bt&&!ib&&(Bt=a.createHistoryShell(iM),Bt.railCollapseShortcut()&&Wg()),Bt),_g=()=>{if(Bt)return Promise.resolve(Bt);let a=wp();return a?Promise.resolve(Og(a)):(Rg??=rw().then(Og,u=>{throw Rg=null,u}),Rg)},Xo=a=>{let u=wp(),m=Bt??(u?Og(u):null);return m?a(m):_g().then(b=>{if(!b)throw new Error("[AgentWidget] The widget was destroyed");return a(b)})},sd=()=>{Bt?.syncHistoryPresentation()};Se.push(()=>{ib=!0}),yl()&&_g().catch(()=>{}).finally(fe),o.clientToken&&(o.features?.history?.enabled===!0||o.sessionInit==="mount")&&R.initClientSession().then(()=>{let a=Bt;if(a?.historyAvailable())return R.reconcileBootConversation({scope:a.historyScope()})}).then(()=>{Bt?.syncEarlierMessagesPill()}).catch(a=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",a)});let Bg=()=>R.warmClientSession(),db=a=>{let u=o.sessionInit??"input",m=ct?.input??ce,b=a.target;m&&(a.type==="input"?(u==="input"||u==="focus")&&b===m&&a.inputType&&m.value.trim():u==="focus"&&(a.type==="keyup"?b===m&&a.key==="Tab":(ct?.form??An)?.contains(b)))&&Bg()},pb=["input","pointerdown","keyup"];pb.forEach(a=>e.addEventListener(a,db));let ub,Dg,gb=()=>{let a=Dg;Dg=void 0;try{typeof a=="function"&&a()}catch{}},fb=()=>{let a=o.clientToken&&typeof o.sessionInit=="function"?o.sessionInit:void 0;if(a!==ub){gb(),ub=a;try{Dg=a?.({warm:Bg,mount:e})}catch{}}};fb(),Se.push(()=>{pb.forEach(a=>e.removeEventListener(a,db)),gb()}),(Me||o.onSSEEvent)&&R.setSSEEventCallback((a,u)=>{o.onSSEEvent?.(a,u),Qa(a,u)});let mb=()=>{let a=o.resume??(_?ds.getStoredResumableHandle?.():null);a&&typeof o.reconnectStream=="function"&&R.resumeFromHandle(a)};J?J.then(a=>{if(a){if(a.metadata&&(P=wh(a.metadata),_e.syncFromMetadata()),a.messages?.length){Xi=!0;try{R.hydrateMessages(a.messages)}finally{Xi=!1}Xc()}a.artifacts?.length&&R.hydrateArtifacts(a.artifacts,a.selectedArtifactId??null),By(a.draft)}}).catch(a=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",a)}).finally(()=>{Sg=!0,U(),mb()}):(By(He),mb());let aM=()=>{!Le()||D||!(o.launcher?.composerBar?.expandOnSubmit??!0)||Mt(!0,"auto")},lM=(a,u)=>a?u?{refs:[...a.refs,...u.refs],finalize:async()=>{let[m,b]=await Promise.allSettled([a.finalize(),u.finalize()]),w=[];return m.status==="fulfilled"?w.push(m.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",m.reason),b.status==="fulfilled"?w.push(b.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",b.reason),dH(w)}}:a:u,Ng=()=>{let u=ce.getInlineMessageFields?.();return u&&u.contentSegments.some(b=>b.kind==="mention")?u.contentSegments:void 0},Er=!1,ii=null,id=()=>{ce.value="",ce.style.height="auto",po(),Cl()},aa=null;function ad(a,u=4e3){$s(a),!(Le()||!tt)&&(tt.hasAttribute(Ya)||(tt.setAttribute(yc,""),tt.setAttribute("role","status"),tt.setAttribute("aria-live","polite"),tt.textContent=a,hi(tt,o.statusIndicator??{},"idle"),aa&&clearTimeout(aa),aa=setTimeout(()=>{if(aa=null,!!tt?.hasAttribute(yc)&&(tt.removeAttribute(yc),tt.removeAttribute("role"),tt.removeAttribute("aria-live"),h)){let m=R.getStatus();_s(tt,ur(m),o.statusIndicator??{},m)}},u)))}function cM(){let a=be.getState().pendingSubmission;a&&(qi(void 0),ce&&(ce.value=a.text,ce.dispatchEvent(new Event("input",{bubbles:!0})),po()),a.options.selectedModelId&&(be.setSelectedModelId(a.options.selectedModelId),Zr?.repaint()),a.options.activeModeIds?.length&&Tc(a.options.activeModeIds),a.options.quote&&qo(a.options.quote),ce?.focus())}let dM=a=>{typeof console<"u"&&console.error("[AgentWidget] composer.onBeforeSend failed; the draft was preserved:",a)},hb=(a={})=>{let u=(a.overrideText??ce?.value??"").trim();return a.resolveInlineCommand&&u?(at?.takeInlineCommand(u)??Promise.resolve(null)).then(m=>yb(a,u,m)):yb(a,u,null)},yb=(a,u,m)=>{if(m?.kind==="action"){id(),at?.clear(),mr();return}let b=m?.kind==="server"?m.mentions:null,w=m?.kind==="prompt"?m.sendText:u,k=a.pending?.contentParts,z=(je?.hasAttachments()??!1)||(k?.length??0)>0;if(!xS({text:w,hasAttachments:z,attachmentsReady:je?.isReady()??!0,hasMentions:at?.hasMentions()??!1,hasServerMentions:!!b,inputDisabled:Yo(),sendDisabled:oi()}))return;let re=R.isStreaming()?Uu():"block";if(re==="defer-one"&&!a.pending){if(be.getState().pendingSubmission){ad("One message is already queued. Edit or remove it first.");return}pM({intent:a,sendText:w,serverMentions:b});return}let Y={text:w,mentionRefs:[...at?.getMentionRefs()??[],...b?.refs??[]],contentSegments:m?.kind==="prompt"?void 0:Ng(),options:{...be.getState().selectedModelId&&{selectedModelId:be.getState().selectedModelId},...be.getState().activeModeIds.length>0&&{activeModeIds:[...be.getState().activeModeIds]},...be.getState().quote&&{quote:{...be.getState().quote}}},viaVoice:a.viaVoice};a.pending&&(Y.options={...a.pending.options},Y.contentSegments=a.pending.contentSegments,Y.mentionRefs=[...a.pending.mentionRefs],Y.viaVoice=a.pending.viaVoice);let ie=()=>{if(k?.length)return[...k];if(!je?.hasAttachments())return;let dt=[...je.getContentParts()];return Y.text&&dt.push(Ao(Y.text)),dt};Y.contentParts=ie();let le=()=>{Xs(),aM();let dt=at?.collectForSubmit()??null,Kn=lM(dt,b),Dt=ie();a.consumeDraft!==!1&&id();let jt={selectedModelId:Y.options.selectedModelId,activeModeIds:Y.options.activeModeIds},_n=re==="interrupt";_n&&R.cancel(),R.sendMessage(Y.text,{contentParts:Dt,mentions:Kn??void 0,contentSegments:Y.contentSegments,viaVoice:Y.viaVoice,composerOptions:jt,...Y.options.quote&&{quote:Y.options.quote},..._n&&{interrupt:!0}}),je?.hasAttachments()&&je.clearAttachments(),dt&&at?.clear(),mr();let Kt=be.getState().activeModeIds,wt=dS(Kt,o.composer?.modes);wt.length!==Kt.length&&Tc(wt),be.getState().quote&&qo(void 0),zc(),Gu.release(),ko()},de=o.composer?.onBeforeSend;if(!de){le();return}let ke=new AbortController;ii=ke;let it=dt=>{if(ii=null,dt.status==="error"){dM(dt.error);return}dt.status==="proceed"&&le()},gt=ES(de,Y,ke.signal);if(!(gt instanceof Promise)){it(gt);return}return be.setPreparing(!0),gt.then(it).finally(()=>be.setPreparing(!1))};function pM(a){let u=be.getState(),m=je?.hasAttachments()??!1,b=m?[...je.getContentParts()]:[];m&&a.sendText&&b.push(Ao(a.sendText));let w=Am({text:a.sendText,contentParts:b.length?b:void 0,mentionRefs:[...at?.getMentionRefs()??[],...a.serverMentions?.refs??[]],contentSegments:Ng(),options:{...u.selectedModelId&&{selectedModelId:u.selectedModelId},...u.activeModeIds.length>0&&{activeModeIds:[...u.activeModeIds]},...u.quote&&{quote:{...u.quote}}},viaVoice:a.intent.viaVoice});qi(w),a.intent.consumeDraft!==!1&&id(),m&&je.clearAttachments(),at?.clear(),mr(),u.quote&&qo(void 0),zc(),Gu.release(),ko(),$s("Message queued. It sends when the response finishes.")}function uM(){let a=be.getState().pendingSubmission;a&&(qi(void 0),cd(a.text,{consumeDraft:!1,pending:a}))}function gM(a){if(o.messageActions?.showEdit!==!0)return;let u=R.getMessages().find(m=>m.id===a);!u||!pm(u)||Ys!==a&&(Xs(),Ys=a,os=mS({messageId:a,initialText:u.content,onSave:m=>fM(a,m),onCancel:()=>Xs()}),Mn.delete(a),fo(Te,R.getMessages(),K),os.focus())}function fM(a,u){let m=os;if(Ys=null,os=null,m?.destroy(),Mn.delete(a),!R.resubmitFrom(a,{reason:"edit",replacement:{text:u,mentionRefs:[],options:{}}})){fo(Te,R.getMessages(),K);return}na()}function mM(a){if(R.isStreaming())return;let u=dm(R.getMessages(),a);u&&(Xs(),R.resubmitFrom(u,{reason:"retry"})&&na())}Pc={regenerate:mM,edit:gM,quote:a=>{let m=R.getMessages().find(b=>b.id===a)?.content?.trim();m&&(qo({text:m,messageId:a}),ce?.focus())}};let vl=async a=>{if(!Er){Er=!0;try{await hb({resolveInlineCommand:!0,...a})}finally{Er=!1}}};function ld(a){oi()||(id(),cd(a,{consumeDraft:!1}))}let cd=(a,u)=>{if(Er)return;Er=!0;let m=()=>{Er=!1};try{let b=hb({...u,overrideText:a});b instanceof Promise?b.finally(m):m()}catch(b){throw m(),b}},hM=a=>{if(a.preventDefault(),R.isStreaming()){R.cancel(),bt?.reset(),rn?.update();return}Er||vl()},yM=()=>o.features?.composerHistory!==!1,Fg={...km},$g=!1,Cl=()=>{Fg={...km}},bM=()=>R.getMessages().filter(a=>a.role==="user").map(a=>a.content??"").filter(a=>a.length>0),vM=a=>{if(!ce)return;$g=!0,ce.value=a,ce.dispatchEvent(new Event("input",{bubbles:!0})),$g=!1;let u=ce.value.length;ce.setSelectionRange(u,u)},CM=a=>{$g||(a.isComposing||at?.handleInput(a.inputType??void 0),Cl())},wM=()=>({submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:Bl(ce)}),SM=a=>{if(ce&&!Yo()&&!(!a.isComposing&&at?.handleKeydown(a))){if(yM()&&(a.key==="ArrowUp"||a.key==="ArrowDown")&&!a.shiftKey&&!a.metaKey&&!a.ctrlKey&&!a.altKey&&!a.isComposing){let u=ce.selectionStart===0&&ce.selectionEnd===0,m=NS({direction:a.key==="ArrowUp"?"up":"down",history:bM(),currentValue:ce.value,atStart:u,state:Fg});if(Fg=m.state,m.handled){a.preventDefault(),m.value!==void 0&&vM(m.value);return}}if(BC(a,wM())){if(R.isStreaming()){if(a.preventDefault(),Uu()==="block"||Er||oi())return;Cl(),vl();return}if(Er){a.preventDefault();return}if(oi()){a.preventDefault();return}Cl(),a.preventDefault(),Pe.click()}}},bb=a=>{if(!(a.key!=="Escape"||a.isComposing)&&a.composedPath().includes(we)){if(ii){ii.abort(),ii=null,a.preventDefault(),a.stopImmediatePropagation();return}R.isStreaming()&&(R.cancel(),bt?.reset(),rn?.update(),Cl(),a.preventDefault(),a.stopImmediatePropagation())}},AM=async a=>{if(o.attachments?.enabled!==!0||!je||Yo())return;let u=iH(a.clipboardData);u.length!==0&&(a.preventDefault(),await je.handleFiles(u))},ho=null,Qo=!1,la=null,Mr=null,Ug=()=>o.voiceRecognition?.completionBehavior==="review";function dd(a){he?.setAttribute("data-state",a),a==="recording"?EM():zg()}let vb="--persona-voice-level",Vg=.5,ca=null,jg=-1,pd=0,Cb=()=>{let a=[],u=gn??he?.parentElement??null;return u&&a.push(u),Ke&&a.push(Ke),a},qg=a=>{let u=Math.round(Math.max(0,Math.min(1,a))*100)/100;if(u!==jg){jg=u;for(let m of Cb())m.style.setProperty(vb,String(u))}},xM=()=>{jg=-1,pd=0;for(let a of Cb())a.style.removeProperty(vb)};function EM(){if(ca!==null)return;if(typeof requestAnimationFrame!="function"){qg(h?R.getVoiceLevel()??Vg:Vg);return}let a=()=>{ca=requestAnimationFrame(a);let u=h?R.getVoiceLevel():null;if(u===null){qg(Vg);return}pd+=(u-pd)*.3,qg(pd)};ca=requestAnimationFrame(a)}function zg(){ca!==null&&(cancelAnimationFrame(ca),ca=null),xM()}let wb=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,ud=(a="user")=>{if(Qo||R.isStreaming())return;let u=wb();if(!u)return;ho=new u;let m=o.voiceRecognition??{},b=m.pauseDuration??2e3;ho.continuous=m.provider?.browser?.continuous??!0,ho.interimResults=!0,ho.lang=m.provider?.browser?.language??"en-US";let w=ce.value;ho.onresult=k=>{let z="",re="";for(let ie=0;ie<k.results.length;ie++){let le=k.results[ie],de=le[0].transcript;le.isFinal?z+=de+" ":re=de}let Y=w+z+re;ce.value=Y,po(),la&&clearTimeout(la),(z||re)&&(la=window.setTimeout(()=>{if(ce.value.trim()&&ho&&Qo){if(ps(),Ug())return;vl({viaVoice:!0})}},b))},ho.onerror=k=>{k.error!=="no-speech"&&ps()},ho.onend=()=>{if(Qo){let k=ce.value.trim();!Ug()&&k&&k!==w.trim()&&vl({viaVoice:!0}),ps()}};try{if(ho.start(),Qo=!0,Ge.active=!0,a!=="system"&&(Ge.manuallyDeactivated=!1),Sr(a),zn(),ko(),he){let k=o.voiceRecognition??{};Mr={backgroundColor:he.style.backgroundColor,color:he.style.color,borderColor:he.style.borderColor,iconName:k.iconName??"mic",iconSize:parseFloat(k.iconSize??"")||Qn};let z=k.recordingBackgroundColor,re=k.recordingIconColor,Y=k.recordingBorderColor;if(he.classList.add("persona-voice-recording"),dd("recording"),he.style.backgroundColor=z??"var(--persona-voice-recording-bg, #ef4444)",he.style.color=re??"var(--persona-voice-recording-indicator, #ffffff)",re){let ie=he.querySelector("svg");ie&&ie.setAttribute("stroke",re)}Y&&(he.style.borderColor=Y),he.setAttribute("aria-label","Stop voice recognition")}}catch{ps("system")}},ps=(a="user")=>{if(Qo){if(Qo=!1,la&&(clearTimeout(la),la=null),ho){try{ho.stop()}catch{}ho=null}if(Ge.active=!1,Sr(a),zn(),ko(),he){if(he.classList.remove("persona-voice-recording"),dd("idle"),Mr){he.style.backgroundColor=Mr.backgroundColor,he.style.color=Mr.color,he.style.borderColor=Mr.borderColor;let u=he.querySelector("svg");u&&u.setAttribute("stroke",Mr.color||"currentColor"),Mr=null}he.setAttribute("aria-label","Start voice recognition")}}},Sb=null,gd=a=>{let u=b=>{Sb??=b.createMicStateStyles({mic:()=>he,config:()=>o,session:()=>R,get original(){return Mr},set original(w){Mr=w},setMicState:dd,renderIcon:ge,iconFallbackPx:Qn}),a(Sb)},m=_w();m?u(m):zl().then(u,()=>{})},da=()=>gd(a=>a.recording()),MM=()=>gd(a=>a.processing()),TM=()=>gd(a=>a.speaking()),Tr=()=>gd(a=>a.reset()),Kg=()=>{if(!Yo()){if(In(o.voiceRecognition?.provider)){let a=R.getVoiceStatus(),u=R.getVoiceInterruptionMode();if(u==="none"&&(a==="processing"||a==="speaking"))return;if(u==="cancel"&&(a==="processing"||a==="speaking")){R.stopVoicePlayback();return}if(R.isBargeInActive()){R.stopVoicePlayback(),R.deactivateBargeIn().then(()=>{Ge.active=!1,Ge.manuallyDeactivated=!0,zn(),Sr("user"),Tr()});return}R.toggleVoice().then(()=>{Ge.active=lg(),Ge.manuallyDeactivated=!Ge.active,zn(),Sr("user"),Ge.active?da():Tr()});return}if(Qo){let a=ce.value.trim();Ge.manuallyDeactivated=!0,zn(),ps("user"),a&&!Ug()&&vl()}else Ge.manuallyDeactivated=!1,zn(),ud("user")}};Vu=Kg;let Ab=()=>R.prewarmVoice(),xb=()=>{let a=o.voiceRecognition;return a?.enabled!==!0?!1:a.prewarm??(o.clientToken?"hover":!1)},Eb=a=>{xb()==="hover"&&he?.contains(a.target)&&Ab()},Mb=["pointerover","pointerdown","focusin"];Mb.forEach(a=>e.addEventListener(a,Eb));let Tb,Pb=null,Gg,kb=()=>{let a=Gg;Gg=void 0;try{typeof a=="function"&&a()}catch{}},Yg=()=>{let a=xb(),u=typeof a=="function"&&he?a:void 0,m=u?he:null;if(!(u===Tb&&m===Pb)&&(kb(),Tb=u,Pb=m,!(!u||!m)))try{Gg=u({warm:Ab,micButton:m,mount:e})}catch{}};Yg(),Se.push(()=>{Mb.forEach(a=>e.removeEventListener(a,Eb)),kb()}),he&&Se.push(()=>{In(o.voiceRecognition?.provider)?(R.isVoiceActive()&&R.toggleVoice(),Tr()):ps("system")});let PM=X.on("assistant:complete",()=>{be.getState().pendingSubmission&&setTimeout(()=>{R.isStreaming()||uM()},0)});Se.push(PM);let kM=X.on("assistant:complete",()=>{Iy&&(Ge.active||Ge.manuallyDeactivated||Iy==="assistant"&&!Ge.lastUserMessageWasVoice||setTimeout(()=>{!Ge.active&&!Ge.manuallyDeactivated&&(In(o.voiceRecognition?.provider)?R.toggleVoice().then(()=>{Ge.active=R.isVoiceActive(),Sr("auto"),R.isVoiceActive()&&da()}):ud("auto"))},600))});Se.push(kM);let LM=X.on("action:resubmit",()=>{setTimeout(()=>{R&&!R.isStreaming()&&R.continueConversation()},100)});Se.push(LM);let Lb=()=>{Mt(!D,"user")},qt=null,On=null;if(ye&&!Le()){let{instance:a,element:u}=nh({config:o,plugins:d,onToggle:Lb});qt=a,a||(On=u)}qt?e.appendChild(qt.element):On&&e.appendChild(On),fl(),Ks(),ed(),Tg(),ml(R.isStreaming()),fg()||(En()==="follow"?as(!0):gg()),TE(),Zt&&(!ye||Le()?setTimeout(()=>Jc(),0):D&&setTimeout(()=>Jc(),200));let us=null,Hb=()=>{us&&(us.disconnect(),us.observe(Ke),us.observe(we),us.observe(en))},Ib=jn(),wl=()=>{if(Le()){Re(),fl();return}let a=Lt(o),u=o.launcher?.sidebarMode??!1,m=e.ownerDocument.defaultView??window,b=o.launcher?.mobileFullscreen??!0,w=o.launcher?.mobileBreakpoint??640,k=m.innerWidth<=w,z=b&&k&&ye;try{if(z){Us(),rl=Bc();return}let re=!1;vt&&(vt=!1,Us(),re=!0);let Y=Bc();if(!re&&Y!==rl&&(Us(),re=!0),rl=Y,re&&Rc(),!ye&&!a){Ae.style.height="",Ae.style.width="";return}if(!u&&!a){let ie=Hi(o);Ae.style.width=ie.width,Ae.style.maxWidth=ie.maxWidth}_c(),hy()}finally{Re(),Ot();let re=jn();if(re!==Ib&&(Ib=re,hl(),Ks()),fl(),D&&ye){let ie=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),le=o.launcher?.sidebarMode??!1,de=o.launcher?.mobileFullscreen??!0,ke=Lt(o)&&de&&ie,it=le||de&&ie&&ye||ke;if(it&&!Ko){let gt=e.getRootNode(),dt=gt instanceof ShadowRoot?gt.host:e.closest(".persona-host");dt&&!zo&&(zo=Rm(dt,o.launcher?.zIndex??kn)),Ko=Wm(e.ownerDocument)}else it||(zo?.(),zo=null,Ko?.(),Ko=null)}}};wl();let fd=e.ownerDocument.defaultView??window;if(fd.addEventListener("resize",wl),Se.push(()=>fd.removeEventListener("resize",wl)),typeof ResizeObserver<"u"){us=new ResizeObserver(()=>{Ot()}),Hb(),Se.push(()=>{us?.disconnect(),us=null});let a=new ResizeObserver(()=>{sd()});a.observe(we),Se.push(()=>a.disconnect())}fd.addEventListener("resize",sd),Se.push(()=>fd.removeEventListener("resize",sd)),ro=ae.scrollTop;let Rb=ir(ae),Wb=()=>{my();let a=ae.scrollTop,u=ir(ae),m=u<Rb;if(Rb=u,!Mo()){ro=a,Tn();return}let{action:b,nextLastScrollTop:w}=KS({following:oo.isFollowing(),currentScrollTop:a,lastScrollTop:ro,nearBottom:Mi(ae,Cr),userScrollThreshold:AE,isAutoScrolling:qn||Nc||m,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(ro=w,b==="resume"){Kc()||Go();return}b==="pause"&&ta()};if(ae.addEventListener("scroll",Wb,{passive:!0}),Se.push(()=>ae.removeEventListener("scroll",Wb)),typeof ResizeObserver<"u"){let a=new ResizeObserver(()=>{WE(),im(Te)});a.observe(Te),a.observe(ae),Se.push(()=>a.disconnect())}let Ob=()=>{Mo()&&oo.isFollowing()&&Kc()&&ta()},_b=ae.ownerDocument;_b.addEventListener("selectionchange",Ob),Se.push(()=>{_b.removeEventListener("selectionchange",Ob)});let HM=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),Bb=a=>{HM.has(a.key)&&(is(),Ja()&&Mo()&&oo.isFollowing()&&ta())},Db=a=>{a.target?.closest("a, button, [tabindex], input, textarea, select")&&(is(),Ja()&&Mo()&&oo.isFollowing()&&ta())};ae.addEventListener("keydown",Bb),ae.addEventListener("focusin",Db),Se.push(()=>{ae.removeEventListener("keydown",Bb),ae.removeEventListener("focusin",Db)});let Nb=a=>{if(a.deltaY!==0&&is(),!Mo())return;let u=GS({following:oo.isFollowing(),deltaY:a.deltaY,nearBottom:Mi(ae,Cr),resumeWhenNearBottom:!0});u==="pause"?ta():u==="resume"&&!Kc()&&Go()};ae.addEventListener("wheel",Nb,{passive:!0}),ae.addEventListener("touchmove",is,{passive:!0}),ae.addEventListener("pointerdown",is,{passive:!0}),Se.push(()=>{ae.removeEventListener("touchmove",is),ae.removeEventListener("pointerdown",is)}),Se.push(()=>ae.removeEventListener("wheel",Nb)),Vt.addEventListener("click",()=>{ni(),ae.scrollTop=ae.scrollHeight,ro=ae.scrollTop,Go(),as(!0),Tn()}),Se.push(()=>Vt.remove()),Se.push(()=>{Ny(),ni()});let Fb=()=>{ze&&(qs&&(ze.removeEventListener("click",qs),qs=null),Xe()?(ze.style.display="",qs=()=>{Mt(!1,"user")},ze.addEventListener("click",qs)):ze.style.display="none")};Fb(),(()=>{let{clearChatButton:a}=et;a&&a.addEventListener("click",()=>{let u=Bt;if(u?.historyAvailable()){u.startNewConversation({focusComposer:!0}).catch(b=>{o.debug&&console.warn("[AgentWidget] New conversation failed:",b)});return}R.clearMessages(),o.layout?.topFade&&(ae.scrollTop=0),ae.removeAttribute("data-persona-top-fade"),Mn.clear(),Go(),Wr(et.composerOverlay);try{localStorage.removeItem(Ga),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ga}`)}catch(b){console.error("[AgentWidget] Failed to clear default localStorage:",b)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Ga)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(b){console.error("[AgentWidget] Failed to clear custom localStorage:",b)}let m=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(m),T?.clear&&jc(()=>T.clear(),"[AgentWidget] Failed to clear storage adapter:"),P={},_e.syncFromMetadata(),je?.clearAttachments(),zc(),qi(void 0),qo(void 0),Xs(),ft?.clear(),bt?.reset(),rn?.update()})})();let $b=[["keydown",SM],["input",CM],["input",po],["input",mr],["keyup",mr],["paste",AM],["focus",pE]],Ub=a=>{if(a)for(let[u,m]of $b)ct?.addListener(a,u,m)},IM=a=>{if(a)for(let[u,m]of $b)ct?.removeListener(a,u,m)},Vb=()=>{ct&&(ct.addListener(ct.form,"submit",hM),ct.addListener(ct.footer,"click",mr),Ub(ce),he&&ct.addListener(he,"click",Kg),Yg())};Vb();let jb=()=>{at?.onComposerSwap((a,u)=>{IM(u),ce=a,ct&&(ct.input=a),Ub(a),qu(),vg(),po()})};jb();let Xg=!1;function qb(){if(!Xg){Xg=!0;try{let a=ce?.value??"",u=Ke.ownerDocument??document,m=ce?u.activeElement===ce:!1;zg(),ct?.destroy(),ct=null,at?.destroy(),at=null;let b=null,w=()=>(b=Le()?nu({config:o}):ki({config:o}),b.footer),k=Gh(w)??w();Ln.replaceComposer(k),Ke=Ln.composer.footer;let z=b!==null&&k===b.footer;Ki=!z,xc=z?b.setSendButtonMode:()=>{},Kh(Ke),Xh(Ke),Qh(),Jh(),zu(),jb(),Zh(),Ku(),ey(),Vb();let re=js.indexOf(vr);if(vr.destroy(),vr=ac(co),re>=0&&(js[re]=vr),ce&&(ce.value=a),po(),mr(),ed(),Ks(),ml(R.isStreaming()),o.statusIndicator?.mode==="transient"&&!Le()){let Y=R.getStatus();_s(tt,ur(Y),o.statusIndicator,Y)}Ge.active&&dd("recording"),Us(),Hb(),Re(),ko(),Qc(),m&&ce?.focus()}finally{Xg=!1}}}let Sl=e.ownerDocument??document;Sl.addEventListener("keydown",bb,!0);let zb=()=>{cg()},Kb=()=>{Sl.visibilityState==="hidden"&&cg()};typeof window<"u"&&(window.addEventListener("pagehide",zb),Sl.addEventListener("visibilitychange",Kb),Se.push(()=>{window.removeEventListener("pagehide",zb),Sl.removeEventListener("visibilitychange",Kb)}));let Gb="persona-attachment-drop-active",Al=0,Qg=()=>{Al=0,we.classList.remove(Gb)},pa=()=>o.attachments?.enabled===!0&&je!==null&&!Yo(),Yb=a=>{!bu(a.dataTransfer)||!pa()||(Al++,Al===1&&we.classList.add(Gb))},Xb=a=>{!bu(a.dataTransfer)||!pa()||(Al--,Al<=0&&Qg())},Qb=a=>{!bu(a.dataTransfer)||!pa()||(a.preventDefault(),a.dataTransfer.dropEffect="copy")},Jb=a=>{if(!bu(a.dataTransfer)||!pa())return;a.preventDefault(),a.stopPropagation(),Qg();let u=Array.from(a.dataTransfer.files??[]);u.length!==0&&je.handleFiles(u)},gs=!0;we.addEventListener("dragenter",Yb,gs),we.addEventListener("dragleave",Xb,gs),e.addEventListener("dragover",Qb,gs),e.addEventListener("drop",Jb,gs);let md=e.ownerDocument,Zb=a=>{pa()&&a.preventDefault()},ev=a=>{pa()&&a.preventDefault()};md.addEventListener("dragover",Zb),md.addEventListener("drop",ev),Se.push(()=>{ct?.destroy(),ct=null,zg(),Po?.destroy(),Po=null,hr?.destroy(),hr=null,es?.destroy(),es=null,ts?.destroy(),ts=null,Zr=null,$u=null,cg(),cl.destroy(),aa&&clearTimeout(aa),Xs(),ii?.abort(),ii=null,je?.destroy(),je=null,be.destroy(),Sl.removeEventListener("keydown",bb,!0),at?.destroy()}),Se.push(()=>{we.removeEventListener("dragenter",Yb,gs),we.removeEventListener("dragleave",Xb,gs),e.removeEventListener("dragover",Qb,gs),e.removeEventListener("drop",Jb,gs),md.removeEventListener("dragover",Zb),md.removeEventListener("drop",ev),Qg()}),Se.push(()=>{R.cancel()}),qt?Se.push(()=>{qt?.destroy()}):On&&Se.push(()=>{On?.remove()});let zt={update(a){let u=o.future?.v5Defaults===!0,m=o.toolCall,b=o.messageActions,w=o.layout?.messages,k=o.colorScheme,z=o.loadingIndicator,re=o.iterationDisplay,Y=o.features?.showReasoning,ie=o.features?.showToolCalls,le=o.features?.toolCallDisplay,de=o.features?.reasoningDisplay,ke=o.features?.streamAnimation?.type,it=o.features?.history?.enabled===!0,gt=o.features?.history?.provider,dt=o.getIdentityProof,Kn=o.clientToken,Dt=o.contextMentions;o=pu({...o,features:p},a),p=o.features,o=uc(o),c(),eg(),Ei(e,o),dc(e,o),pc(e,o),Vn(),Ho(),o.colorScheme!==k&&yy();let jt=gc.getForInstance(o.plugins);d.length=0,d.push(...jt),Wg(),ye=o.launcher?.enabled??!0,ut=o.launcher?.autoExpand??!1,te=o.features?.showReasoning??!0,ve=o.features?.showToolCalls??!0,Ce=o.features?.scrollToBottom??{};let _n=En();st=o.features?.scrollBehavior??{},_n!==En()&&(ni(),Go()),Hy(),_t(),Tn();let Kt=Me;if(Me=o.features?.showEventStreamToggle??!1,Me&&!Kt){if(ft||(cr(),R.setSSEEventCallback((Z,ot)=>{o.onSSEEvent?.(Z,ot),Qa(Z,ot)})),!ht&&mt){let Z=o.features?.eventStream?.classNames,ot="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"+(Z?.toggleButton?" "+Z.toggleButton:"");ht=x("button",ot),ht.style.width="28px",ht.style.height="28px",ht.style.color=Nn.actionIconColor,ht.type="button",ht.setAttribute("aria-label","Event Stream"),ht.title="Event Stream";let rt=Nt(Kr.Activity,"18px","currentColor",1.5);rt&&ht.appendChild(rt);let pt=et.clearChatButtonWrapper,Rt=et.closeButtonWrapper,Pn=pt||Rt;Pn&&Pn.parentNode===mt?mt.insertBefore(ht,Pn):mt.appendChild(ht),ht.addEventListener("click",()=>{Sn?zi():ju()})}}else!Me&&Kt&&(zi(),ht&&(ht.remove(),ht=null),ft?.clear(),pn?.destroy(),ft=null,pn=null,bt?.reset(),bt=null,Ft=null);if(o.launcher?.enabled===!1&&qt&&(qt.destroy(),qt=null),o.launcher?.enabled===!1&&On&&(On.remove(),On=null),o.launcher?.enabled!==!1&&!qt&&!On){let{instance:Z,element:ot}=nh({config:o,plugins:d,onToggle:Lb});qt=Z,Z||(On=ot),e.appendChild(ot)}qt&&qt.update(o),bl(),jo&&o.launcher?.subtitle!==void 0&&(jo.textContent=o.launcher.subtitle);let wt=o.layout?.header;if(wt?.layout!==Wt&&mt){let Z=wt?Na(o,wt,{showClose:Xe(),onClose:()=>Mt(!1,"user")}):jr({config:o,showClose:Xe(),onClose:()=>Mt(!1,"user")});Ln.replaceHeader(Z),mt=Ln.header.element,Ht=Ln.header.iconHolder,Vo=Ln.header.headerTitle,jo=Ln.header.headerSubtitle,ze=Ln.header.closeButton,Wt=wt?.layout,bl()}else if(wt){if(Ht&&(Ht.style.display=wt.showIcon===!1?"none":""),Vo&&(Vo.style.display=wt.showTitle===!1?"none":""),jo&&(jo.style.display=wt.showSubtitle===!1?"none":""),ze){let Z=Xe()&&wt.showCloseButton!==!1;ze.style.display=Z?"":"none"}if(et.clearChatButtonWrapper){let Z=wt.showClearChat;if(Z!==void 0){et.clearChatButtonWrapper.style.display=Z?"":"none";let{closeButtonWrapper:ot}=et;ot&&!ot.classList.contains("persona-absolute")&&(Z?ot.classList.remove("persona-ml-auto"):ot.classList.add("persona-ml-auto"))}}}let Zo=o.layout?.showHeader!==!1;mt&&(mt.style.display=Zo?"":"none");let bo=o.layout?.showFooter!==!1;Ke&&(Ke.style.display=bo?"":"none"),Re(),Tn(),ye!==xe?ye?Mt(ut,"auto"):(D=!0,fl()):ut!==xt&&Mt(ut,"auto"),xt=ut,xe=ye,wl(),Fb();let er=JSON.stringify(o.toolCall)!==JSON.stringify(m),Io=JSON.stringify(o.messageActions)!==JSON.stringify(b),ms=JSON.stringify(o.layout?.messages)!==JSON.stringify(w),xl=o.loadingIndicator?.render!==z?.render||o.loadingIndicator?.renderIdle!==z?.renderIdle||o.loadingIndicator?.showBubble!==z?.showBubble,ai=o.iterationDisplay!==re,O=(o.features?.showReasoning??!0)!==(Y??!0)||(o.features?.showToolCalls??!0)!==(ie??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(le)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(de);(o.future?.v5Defaults===!0!==u||er||Io||ms||xl||ai||O)&&R&&(Qs++,fo(Te,R.getMessages(),K));let Fe=o.features?.streamAnimation?.type;if(Fe!==ke&&Fe&&Fe!=="none"){let Z=og(Fe,o.features?.streamAnimation?.plugins);Z&&rc(Z,e)}let se=o.launcher??{},St=se.headerIconHidden??!1,Jt=o.layout?.header?.showIcon,Hn=St||Jt===!1,mn=se.headerIconName,Tt=se.headerIconSize??_l;if(Ht){let Z=mt,ot=Z?.querySelector(".persona-flex-col");if(Hn)Ht.style.display="none",Z&&ot&&!Z.contains(ot)&&Z.insertBefore(ot,Z.firstChild);else{if(Ht.style.display="",Ht.style.height=Tt,Ht.style.width=Tt,Z&&ot&&(Z.contains(Ht)?Ht.nextSibling!==ot&&(Ht.remove(),Z.insertBefore(Ht,ot)):Z.insertBefore(Ht,ot)),mn){let pt=parseFloat(Tt)||24,Rt=ge(mn,pt*.6,"currentColor",1);Rt?(Rt.style.width=`calc(${pt}px * var(--persona-components-header-iconScale, 0.6))`,Rt.style.height=`calc(${pt}px * var(--persona-components-header-iconScale, 0.6))`,Ht.replaceChildren(Rt)):Ht.textContent=se.agentIconText??"\u{1F4AC}"}else if(se.iconUrl){let pt=Ht.querySelector("img");if(pt)pt.src=se.iconUrl,pt.style.height=Tt,pt.style.width=Tt;else{let Rt=document.createElement("img");Rt.src=se.iconUrl,Rt.alt="",Rt.className="persona-rounded-xl persona-object-cover",Rt.style.height=Tt,Rt.style.width=Tt,Ht.replaceChildren(Rt)}}else{let pt=Ht.querySelector("svg"),Rt=Ht.querySelector("img");(pt||Rt)&&Ht.replaceChildren(),Ht.textContent=se.agentIconText??"\u{1F4AC}"}let rt=Ht.querySelector("img");rt&&(rt.style.height=Tt,rt.style.width=Tt)}}let Gt=o.layout?.header?.showTitle,ln=o.layout?.header?.showSubtitle;if(Vo&&(Vo.style.display=Gt===!1?"none":""),jo&&(jo.style.display=ln===!1?"none":""),ze){let Z=Xe()&&o.layout?.header?.showCloseButton!==!1;if(ze.style.display=Z?"":"none",!Le()){let yn=se.closeButtonSize??"";ze.style.height=yn,ze.style.width=yn,ze.style.minWidth=yn,ze.style.minHeight=yn}let ot=se.closeButtonPlacement??"inline",{closeButtonWrapper:rt}=et,pt=ot==="top-right",Rt=rt?.classList.contains("persona-absolute");if(rt&&pt!==Rt)if(rt.remove(),pt){rt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let yn=Bt?.railColumn??we;yn.style.position="relative",yn.appendChild(rt)}else{let yn=se.clearChat?.placement??"inline",bn=se.clearChat?.enabled??!0;rt.className=bn&&yn==="inline"?"":"persona-ml-auto",mt&&mt.appendChild(rt)}if(ze.style.color=se.closeButtonColor||Nn.actionIconColor,se.closeButtonBackgroundColor?(ze.style.backgroundColor=se.closeButtonBackgroundColor,ze.classList.remove("hover:persona-bg-gray-100")):(ze.style.backgroundColor="",ze.classList.add("hover:persona-bg-gray-100")),se.closeButtonBorderWidth||se.closeButtonBorderColor){let yn=se.closeButtonBorderWidth||"0px",bn=se.closeButtonBorderColor||"transparent";ze.style.border=`${yn} solid ${bn}`,ze.classList.remove("persona-border-none")}else ze.style.border="",ze.classList.add("persona-border-none");se.closeButtonBorderRadius?(ze.style.borderRadius=se.closeButtonBorderRadius,ze.classList.remove("persona-rounded-full")):(ze.style.borderRadius="",ze.classList.add("persona-rounded-full")),se.closeButtonPaddingX?(ze.style.paddingLeft=se.closeButtonPaddingX,ze.style.paddingRight=se.closeButtonPaddingX):(ze.style.paddingLeft="",ze.style.paddingRight=""),se.closeButtonPaddingY?(ze.style.paddingTop=se.closeButtonPaddingY,ze.style.paddingBottom=se.closeButtonPaddingY):(ze.style.paddingTop="",ze.style.paddingBottom=""),Jp(ze,se.closeButtonIconName??"x",{iconSize:Le()?Jm:void 0,iconText:se.closeButtonIconText??"\xD7"});let Pn=se.closeButtonTooltipText??"Close chat",Wo=se.closeButtonShowTooltip??!0;ze.setAttribute("aria-label",Pn),rt&&vn({anchor:ze,trigger:rt,text:()=>ze?.getAttribute("aria-label")??Pn,enabled:Wo})}let{clearChatButton:We,clearChatButtonWrapper:Pt}=et;if(We){let Z=se.clearChat??{},ot=Z.enabled??!0,rt=o.layout?.header?.showClearChat,pt=rt!==void 0?rt:ot,Rt=Z.placement??"inline";if(Pt){Pt.style.display=pt?"":"none";let{closeButtonWrapper:Pn}=et;!Le()&&Pn&&!Pn.classList.contains("persona-absolute")&&(pt?Pn.classList.remove("persona-ml-auto"):Pn.classList.add("persona-ml-auto"));let Wo=Rt==="top-right",yn=Pt.classList.contains("persona-absolute");if(!Le()&&Wo!==yn&&pt){if(Pt.remove(),Wo){Pt.className="persona-absolute persona-top-4 persona-z-50",Pt.style.right="48px";let tr=Bt?.railColumn??we;tr.style.position="relative",tr.appendChild(Pt)}else{Pt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Pt.style.right="";let tr=et.closeButtonWrapper;mt&&tr&&tr.parentElement===mt?mt.insertBefore(Pt,tr):mt&&mt.appendChild(Pt)}let bn=et.closeButtonWrapper;bn&&!bn.classList.contains("persona-absolute")&&(Wo?bn.classList.add("persona-ml-auto"):bn.classList.remove("persona-ml-auto"))}}if(pt){if(!Le()){let bn=Z.size??"";We.style.height=bn,We.style.width=bn,We.style.minWidth=bn,We.style.minHeight=bn}let Pn=Z.iconColor??"";if(We.style.color=Pn||Nn.actionIconColor,Jp(We,Z.iconName??"refresh-cw",{iconSize:Le()?Zm:void 0}),Z.backgroundColor?(We.style.backgroundColor=Z.backgroundColor,We.classList.remove("hover:persona-bg-gray-100")):(We.style.backgroundColor="",We.classList.add("hover:persona-bg-gray-100")),Z.borderWidth||Z.borderColor){let bn=Z.borderWidth||"0px",tr=Z.borderColor||"transparent";We.style.border=`${bn} solid ${tr}`,We.classList.remove("persona-border-none")}else We.style.border="",We.classList.add("persona-border-none");Z.borderRadius?(We.style.borderRadius=Z.borderRadius,We.classList.remove("persona-rounded-full")):(We.style.borderRadius="",We.classList.add("persona-rounded-full")),Z.paddingX?(We.style.paddingLeft=Z.paddingX,We.style.paddingRight=Z.paddingX):(We.style.paddingLeft="",We.style.paddingRight=""),Z.paddingY?(We.style.paddingTop=Z.paddingY,We.style.paddingBottom=Z.paddingY):(We.style.paddingTop="",We.style.paddingBottom="");let Wo=Z.tooltipText??"Clear chat",yn=Z.showTooltip??!0;We.setAttribute("aria-label",Wo),Pt&&vn({anchor:We,trigger:Pt,text:()=>We?.getAttribute("aria-label")??Wo,enabled:yn})}}let $e=o.actionParsers&&o.actionParsers.length?o.actionParsers:[fc],cn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Wi.message,Wi.messageAndClick];_e=mc({parsers:$e,handlers:cn,getSessionMetadata:yt,updateSessionMetadata:qe,emit:X.emit,documentRef:typeof document<"u"?document:null}),K=dx(o,_e,q),ZE(),R.updateConfig(o),fb(),(o.features?.history?.enabled===!0!==it||o.features?.history?.provider!==gt||o.getIdentityProof!==dt||o.clientToken!==Kn)&&(Bt?.closeHistory({restoreFocus:!1}),Bt?.installHistoryProvider()),Bt?.syncHistoryChromeImpl(),sd(),yl()&&!Bt&&_g().catch(()=>{}),fo(Te,R.getMessages(),K),Ks(),ed(),XE(),ml(R.isStreaming()),Dt!==o.contextMentions&&qb();let Co=o.voiceRecognition?.enabled===!0,hn=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),At=In(o.voiceRecognition?.provider);if(Co&&(hn||At))if(!he||!gn){let Z=ka(o);if(Z){he=Z.button,gn=Z.wrapper;let ot=Wn&&Wn.parentElement===Bs?Wn:null;Bs?Bs.insertBefore(gn,ot):An?.appendChild(gn),ct&&(ct.micButton=he),ct?.addListener(he,"click",Kg),he.disabled=Yo()||R.isStreaming()&&!yg()}}else{let Z=o.voiceRecognition??{},ot=o.sendButton??{},rt=Z.iconName??"mic",pt=Z.iconSize,Rt=parseFloat(pt??"")||Qn;he.classList.add(so),he.classList.toggle(Do,!pt),he.style.width=pt??"",he.style.height=pt??"",he.style.minWidth=pt??"",he.style.minHeight=pt??"";let Pn=Z.iconColor??ot.textColor;he.innerHTML="";let Wo=ge(rt,Rt,Pn||"currentColor",1.5);Wo?he.appendChild(Wo):he.textContent="\u{1F3A4}";let yn=Z.backgroundColor??ot.backgroundColor;yn?he.style.backgroundColor=yn:he.style.backgroundColor="",Pn?he.style.color=Pn:he.style.color="var(--persona-text, #111827)",Z.borderWidth?(he.style.borderWidth=Z.borderWidth,he.style.borderStyle="solid"):(he.style.borderWidth="",he.style.borderStyle=""),Z.borderColor?he.style.borderColor=Z.borderColor:he.style.borderColor="",Z.paddingX?(he.style.paddingLeft=Z.paddingX,he.style.paddingRight=Z.paddingX):(he.style.paddingLeft="",he.style.paddingRight=""),Z.paddingY?(he.style.paddingTop=Z.paddingY,he.style.paddingBottom=Z.paddingY):(he.style.paddingTop="",he.style.paddingBottom="");let bn=Z.tooltipText??"Start voice recognition",tr=Z.showTooltip??!1;he.setAttribute("aria-label",bn),gn&&vn({anchor:he,trigger:gn,text:()=>he?.getAttribute("aria-label")??bn,enabled:tr}),gn.style.display="",he.disabled=Yo()||R.isStreaming()&&!yg()}else he&&gn&&(gn.style.display="none",In(o.voiceRecognition?.provider)?R.isVoiceActive()&&R.toggleVoice():Qo&&ps());if(Yg(),o.attachments?.enabled===!0){if(!sn||!It){let Z=o.attachments??{};fn||(fn=x("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),fn.style.display="none",(ce.parentElement??An).insertBefore(fn,ce)),Et||(Et=document.createElement("input"),Et.type="file",Et.accept=(Z.allowedTypes??Dr).join(","),Et.multiple=(Z.maxFiles??4)>1,Et.style.display="none",Et.setAttribute("aria-label","Attach files"),(ce.parentElement??An).insertBefore(Et,ce)),sn=x("div","persona-send-button-wrapper"),It=x("button",`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${so} ${Do}`),It.type="button",It.setAttribute("aria-label",Z.buttonTooltipText??"Attach file");let ot=Z.buttonIconName??"paperclip";It.style.fontSize="18px",It.style.lineHeight="1";let rt=ge(ot,Qn,"currentColor",1.5);rt?It.appendChild(rt):It.textContent="\u{1F4CE}",It.addEventListener("click",Rt=>{Rt.preventDefault(),Et?.click()}),sn.appendChild(It);let pt=Z.buttonTooltipText??"Attach file";vn({anchor:It,trigger:sn,text:()=>It?.getAttribute("aria-label")??pt}),xn?xn.append(sn):An.appendChild(sn),ct&&(ct.attachmentButton=It,ct.attachmentInput=Et??void 0,ct.attachmentPreviews=fn??void 0),!je&&Et&&fn&&(je=Ai.fromConfig(Z,Uh),je.setPreviewsContainer(fn),ct?.addListener(Et,"change",async()=>{je&&Et?.files&&(await je.handleFileSelect(Et.files),Et.value="")}))}else{sn.style.display="";let Z=o.attachments??{};Et&&(Et.accept=(Z.allowedTypes??Dr).join(","),Et.multiple=(Z.maxFiles??4)>1),je&&je.updateConfig({allowedTypes:Z.allowedTypes,maxFileSize:Z.maxFileSize,maxFiles:Z.maxFiles,adapter:Z.adapter})}if(we.querySelector(".persona-attachment-drop-overlay")?.remove(),we.appendChild(px(o.attachments?.dropOverlay)),It){let Z=o.attachments??{},ot=Z.buttonTooltipText??"Attach file";It.setAttribute("aria-label",ot),It.textContent="";let rt=ge(Z.buttonIconName??"paperclip",Qn,"currentColor",1.5);rt?It.appendChild(rt):It.textContent="\u{1F4CE}",sn&&vn({anchor:It,trigger:sn,text:()=>It?.getAttribute("aria-label")??ot})}}else sn&&(sn.style.display="none"),je&&je.clearAttachments(),we.querySelector(".persona-attachment-drop-overlay")?.remove();let Ue=o.sendButton??{},hs=Ue.useIcon??!1,nn=Ue.iconText??"\u2191",Gn=Ue.iconName,Pr=Ue.tooltipText??"Send message",Jg=Ue.showTooltip??!1,li=Ue.size,Zg=parseFloat(li??"")||$f,kr=Ue.backgroundColor,ci=Ue.textColor;if(hs){if(Pe.style.width=li??"",Pe.style.height=li??"",Pe.style.minWidth=li??"",Pe.style.minHeight=li??"",Pe.style.fontSize="18px",Pe.style.lineHeight="1",ci?Pe.style.color=ci:Pe.style.color="var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))",!R.isStreaming())if(Pe.innerHTML="",Gn){let Z=parseFloat(Ue.iconSize??"")||Math.round(Zg*.5),ot=ci?.trim()||"currentColor",rt=Ue.iconStrokeWidth??2,pt=ge(Gn,Z,ot,rt),Rt=ge(Ue.stopIconName??"square",Z,ot,rt);pt&&Rt?Pe.appendChild(Uf(pt,Rt)):pt?Pe.appendChild(pt):Pe.textContent=nn}else Pe.textContent=nn;Pe.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${so}`,kr?(Pe.style.backgroundColor=kr,Pe.classList.remove("persona-bg-persona-primary")):(Pe.style.backgroundColor="",Pe.classList.add("persona-bg-persona-primary"))}else Pe.textContent=o.copy?.sendButtonLabel??"Send",Pe.style.width="",Pe.style.height="",Pe.style.minWidth="",Pe.style.minHeight="",Pe.style.fontSize="",Pe.style.lineHeight="",Pe.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",kr?(Pe.style.backgroundColor=kr,Pe.classList.remove("persona-bg-persona-accent")):Pe.classList.add("persona-bg-persona-accent"),ci?Pe.style.color=ci:Pe.classList.add("persona-text-white");Ue.borderWidth?(Pe.style.borderWidth=Ue.borderWidth,Pe.style.borderStyle="solid"):(Pe.style.borderWidth="",Pe.style.borderStyle=""),Ue.borderColor?Pe.style.borderColor=Ue.borderColor:Pe.style.borderColor="",Ue.paddingX?(Pe.style.paddingLeft=Ue.paddingX,Pe.style.paddingRight=Ue.paddingX):(Pe.style.paddingLeft="",Pe.style.paddingRight=""),Ue.paddingY?(Pe.style.paddingTop=Ue.paddingY,Pe.style.paddingBottom=Ue.paddingY):(Pe.style.paddingTop="",Pe.style.paddingBottom=""),R.isStreaming()||Pe.setAttribute("aria-label",Pr),Qc(),Wn&&vn({anchor:Pe,trigger:Wn,text:()=>Pe.getAttribute("aria-label")??Pr,enabled:Jg}),ty(),ng();let tv=Dp(be.getState().activeModeIds,o.composer?.modes);be.setActiveModeIds(tv),Vi().length>0!==!!hr&&Ku(),hr?.render(tv,Vi());for(let Z of[...ji.keys()])Bp(Z,o.composer?.modeGroups)||ji.delete(Z);ji.forEach(Z=>Z.repaint()),Zr?.repaint(),Po?.resolve();let hd=Hs(o,Le());if(tg(),hd){Te.style.maxWidth=hd,Te.style.marginLeft="auto",Te.style.marginRight="auto",Te.style.width="100%",Rn.style.maxWidth=hd,Rn.style.marginLeft="auto",Rn.style.marginRight="auto",Rn.style.width="100%";for(let Z of[An,co,fn,tt])Z&&(Z.style.maxWidth=hd,Z.style.marginLeft="auto",Z.style.marginRight="auto",Z.style.width="100%")}else{Te.style.maxWidth="",Te.style.marginLeft="",Te.style.marginRight="",Te.style.width="",Rn.style.maxWidth="",Rn.style.marginLeft="",Rn.style.marginRight="",Rn.style.width="";for(let Z of[An,co,fn,tt])Z&&(Z.style.maxWidth="",Z.style.marginLeft="",Z.style.marginRight="",Z.style.width="")}let Ro=o.statusIndicator??{};if(Tf(tt,An,Ro),hi(tt,Ro,R?.getStatus()??"idle"),R){let Z=R.getStatus();_s(tt,(rt=>rt==="idle"?Ro.idleText??Yt.idle:rt==="connecting"?Ro.connectingText??Yt.connecting:rt==="connected"?Ro.connectedText??Yt.connected:rt==="error"?Ro.errorText??Yt.error:rt==="paused"?Ro.pausedText??Yt.paused:rt==="resuming"?Ro.resumingText??Yt.resuming:Yt[rt])(Z),Ro,Z)}tt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let OM=Ro.align==="left"?"persona-text-left":Ro.align==="center"?"persona-text-center":"persona-text-right";tt.classList.add(OM),qu(),vg(),ko(),dr()},open(){Xe()&&Mt(!0,"api")},close(){Xe()&&Mt(!1,"api")},toggle(){Xe()&&Mt(!D,"api")},reconnect(){R.reconnectNow()},clearChat(){yr=!1,i.clear(),r.clear(),s.clear(),l.clear(),R.clearMessages(),o.layout?.topFade&&(ae.scrollTop=0),ae.removeAttribute("data-persona-top-fade"),Mn.clear(),Go();try{localStorage.removeItem(Ga),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ga}`)}catch(u){console.error("[AgentWidget] Failed to clear default localStorage:",u)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Ga)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(u){console.error("[AgentWidget] Failed to clear custom localStorage:",u)}let a=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(a),T?.clear&&jc(()=>T.clear(),"[AgentWidget] Failed to clear storage adapter:"),P={},_e.syncFromMetadata(),je?.clearAttachments(),zc(),qi(void 0),qo(void 0),Xs(),ft?.clear(),bt?.reset(),rn?.update()},setMessage(a){return!ce||R.isStreaming()||Yo()?!1:(!D&&Xe()&&Mt(!0,"system"),ce.value=a,ce.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(a){if(R.isStreaming()||oi())return!1;let u=a?.trim()||ce.value.trim();return u?(!D&&Xe()&&Mt(!0,"system"),ce.value="",ce.style.height="auto",po(),cd(u,{consumeDraft:!1}),!0):!1},getComposerState(){return be.getState()},setQuote(a){let u=a?.text?.trim();u&&qo({...a,text:u})},clearQuote(){qo(void 0)},startVoiceRecognition(){return R.isStreaming()?!1:In(o.voiceRecognition?.provider)?(R.isVoiceActive()||R.isBargeInActive()||(!D&&Xe()&&Mt(!0,"system"),Ge.manuallyDeactivated=!1,zn(),R.toggleVoice().then(()=>{Ge.active=lg(),zn(),Sr("user"),Ge.active&&da()})),!0):Qo?!0:wb()?(!D&&Xe()&&Mt(!0,"system"),Ge.manuallyDeactivated=!1,zn(),ud("user"),!0):!1},stopVoiceRecognition(){return In(o.voiceRecognition?.provider)?!R.isVoiceActive()&&!R.isBargeInActive()?!1:((R.isBargeInActive()?R.deactivateBargeIn():R.toggleVoice()).then(()=>{Ge.active=!1,Ge.manuallyDeactivated=!0,zn(),Sr("user"),Tr()}),!0):Qo?(Ge.manuallyDeactivated=!0,zn(),ps("user"),!0):!1},injectMessage(a){return!D&&Xe()&&Mt(!0,"system"),R.injectMessage(a)},injectAssistantMessage(a){!D&&Xe()&&Mt(!0,"system");let u=R.injectAssistantMessage(a);return S&&(S=!1,F&&(clearTimeout(F),F=null),setTimeout(()=>{R&&!R.isStreaming()&&R.continueConversation()},100)),u},injectUserMessage(a){return!D&&Xe()&&Mt(!0,"system"),R.injectUserMessage(a)},injectSystemMessage(a){return!D&&Xe()&&Mt(!0,"system"),R.injectSystemMessage(a)},injectMessageBatch(a){return!D&&Xe()&&Mt(!0,"system"),R.injectMessageBatch(a)},injectComponentDirective(a){return!D&&Xe()&&Mt(!0,"system"),R.injectComponentDirective(a)},injectTestMessage(a){!D&&Xe()&&Mt(!0,"system"),R.injectTestEvent(a)},async connectStream(a,u){return R.connectStream(a,u)},__pushEventStreamEvent(a){Me&&(cr(),Qa(a.type,a.payload))},showEventStream(){Me&&ju()},hideEventStream(){Sn&&zi()},isEventStreamVisible(){return Sn},listConversations(a){return R.listConversations(a)},getActiveConversationId(){return R.getActiveConversationId()},openConversation(a,u){return Xo(m=>m.openHistoryConversation(a,{focusComposer:u?.focus===!0}))},startNewConversation(a){return Xo(u=>u.startNewConversation({focusComposer:a?.focus===!0}))},warmSession(){Bg()},deleteConversation(a){return Xo(u=>u.deleteHistoryConversation(a))},renameConversation(a,u){return Xo(m=>m.updateHistoryConversation(a,{title:u}))},setConversationStarred(a,u){return Xo(m=>m.updateHistoryConversation(a,{starred:u}))},clearConversationHistory(a){return Xo(u=>u.clearConversationHistory(a))},resetHistoryIdentity(){return Xo(a=>a.resetHistoryIdentity())},async getVisitorToken(){let a=mo;if(!a)return null;let u=await a.get();return a===mo?u:null},getHistoryIdentityStatus(){let a=Bt?.historyProvider;return a?a.getIdentityStatus():yl()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory(a){return yl()?Xo(u=>u.openHistory({...a?.returnSurface?{returnSurface:a.returnSurface}:{},...a?.focus!==void 0?{focus:a.focus}:{}})):Promise.resolve()},hideHistory(a){Bt?.closeHistory(a?.restoreFocus!==void 0?{restoreFocus:a.restoreFocus}:void 0)},isHistoryVisible(){return un},showArtifacts(){$n(o)&&(yr=!1,Gi=!0,Ho(),nt?.setMobileOpen(!0))},hideArtifacts(){$n(o)&&(yr=!0,Ho())},upsertArtifact(a){return $n(o)?(or(o.features?.artifacts,{artifactType:a.artifactType,...a.artifactType==="markdown"&&a.file?{file:a.file}:{},...a.presentation?{presentation:a.presentation}:{}})==="panel"&&(yr=!1,Gi=!0),R.upsertArtifact(a)):null},selectArtifact(a){$n(o)&&R.selectArtifact(a)},clearArtifacts(){$n(o)&&R.clearArtifacts()},getArtifacts(){return R?.getArtifacts()??[]},getSelectedArtifactId(){return R?.getSelectedArtifactId()??null},focusInput(){return ye&&!D&&!Le()||!ce?!1:(ce.focus(),!0)},async resolveApproval(a,u,m){let w=R.getMessages().find(k=>k.variant==="approval"&&k.approval?.id===a);if(!w?.approval)throw new Error(`Approval not found: ${a}`);if(w.approval.toolType==="webmcp"){R.resolveWebMcpApproval(w.id,u);return}return R.resolveApproval(w.approval,u,m)},setFollowUpSuggestions(a){wE(a)},clearFollowUpSuggestions(){Ly()},getMessages(){return R.getMessages()},getStatus(){return R.getStatus()},getPersistentMetadata(){return{...P}},updatePersistentMetadata(a){qe(a)},on(a,u){return X.on(a,u)},off(a,u){X.off(a,u)},isOpen(){return Xe()&&D},isVoiceActive(){return Ge.active},toggleReadAloud(a){R.toggleReadAloud(a)},stopReadAloud(){R.stopSpeaking()},getReadAloudState(a){return R.getReadAloudState(a)},onReadAloudChange(a){return R.onReadAloudChange(a)},getState(){return{open:Xe()&&D,launcherEnabled:ye,voiceActive:Ge.active,streaming:R.isStreaming()}},showCSATFeedback(a){!D&&Xe()&&Mt(!0,"system");let u=Te.querySelector(".persona-feedback-container");u&&u.remove();let m=hu({onSubmit:async(b,w)=>{R.isClientTokenMode()&&await R.submitCSATFeedback(b,w),a?.onSubmit?.(b,w)},onDismiss:a?.onDismiss,...a});Te.appendChild(m),m.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(a){!D&&Xe()&&Mt(!0,"system");let u=Te.querySelector(".persona-feedback-container");u&&u.remove();let m=yu({onSubmit:async(b,w)=>{R.isClientTokenMode()&&await R.submitNPSFeedback(b,w),a?.onSubmit?.(b,w)},onDismiss:a?.onDismiss,...a});Te.appendChild(m),m.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(a,u){return R.submitCSATFeedback(a,u)},async submitNPSFeedback(a,u){return R.submitNPSFeedback(a,u)},destroy(){Hg(),ri!=null&&(clearInterval(ri),ri=null),i.clear(),r.clear(),s.clear(),l.clear(),Se.forEach(a=>a()),Je.remove(),Xt?.remove(),qt?.destroy(),On?.remove(),qs&&ze.removeEventListener("click",qs)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let a=window.AgentWidgetBrowser,u={controller:zt,getMessages:zt.getMessages,getStatus:zt.getStatus,getMetadata:zt.getPersistentMetadata,updateMetadata:zt.updatePersistentMetadata,clearHistory:()=>zt.clearChat(),setVoiceActive:m=>m?zt.startVoiceRecognition():zt.stopVoiceRecognition()};window.AgentWidgetBrowser=u,Se.push(()=>{window.AgentWidgetBrowser===u&&(window.AgentWidgetBrowser=a)})}if(typeof window<"u"){let a=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),u=ie=>{let le=ie.detail;(!le?.instanceId||le.instanceId===a)&&zt.focusInput()};if(window.addEventListener("persona:focusInput",u),Se.push(()=>{window.removeEventListener("persona:focusInput",u)}),Me){let ie=de=>{let ke=de.detail;(!ke?.instanceId||ke.instanceId===a)&&zt.showEventStream()},le=de=>{let ke=de.detail;(!ke?.instanceId||ke.instanceId===a)&&zt.hideEventStream()};window.addEventListener("persona:showEventStream",ie),window.addEventListener("persona:hideEventStream",le),Se.push(()=>{window.removeEventListener("persona:showEventStream",ie),window.removeEventListener("persona:hideEventStream",le)})}let m=ie=>{let le=ie.detail;(!le?.instanceId||le.instanceId===a)&&zt.showHistory()},b=ie=>{let le=ie.detail;(!le?.instanceId||le.instanceId===a)&&zt.hideHistory()};window.addEventListener("persona:showHistory",m),window.addEventListener("persona:hideHistory",b),Se.push(()=>{window.removeEventListener("persona:showHistory",m),window.removeEventListener("persona:hideHistory",b)});let w=ie=>{let le=ie.detail;(!le?.instanceId||le.instanceId===a)&&zt.showArtifacts()},k=ie=>{let le=ie.detail;(!le?.instanceId||le.instanceId===a)&&zt.hideArtifacts()},z=ie=>{let le=ie.detail;le?.instanceId&&le.instanceId!==a||le?.artifact&&zt.upsertArtifact(le.artifact)},re=ie=>{let le=ie.detail;le?.instanceId&&le.instanceId!==a||typeof le?.id=="string"&&zt.selectArtifact(le.id)},Y=ie=>{let le=ie.detail;(!le?.instanceId||le.instanceId===a)&&zt.clearArtifacts()};window.addEventListener("persona:showArtifacts",w),window.addEventListener("persona:hideArtifacts",k),window.addEventListener("persona:upsertArtifact",z),window.addEventListener("persona:selectArtifact",re),window.addEventListener("persona:clearArtifacts",Y),Se.push(()=>{window.removeEventListener("persona:showArtifacts",w),window.removeEventListener("persona:hideArtifacts",k),window.removeEventListener("persona:upsertArtifact",z),window.removeEventListener("persona:selectArtifact",re),window.removeEventListener("persona:clearArtifacts",Y)})}let yo=aH(o.persistState);if(yo&&Xe()){let a=lH(yo.storage),u=`${yo.keyPrefix}widget-open`,m=`${yo.keyPrefix}widget-voice`,b=`${yo.keyPrefix}widget-voice-mode`;if(a){let w=yo.persist?.openState&&a.getItem(u)==="true",k=yo.persist?.voiceState&&a.getItem(m)==="true",z=yo.persist?.voiceState&&a.getItem(b)==="true";if(w&&(qt?.setPanelOpen(!0,"auto"),setTimeout(()=>{zt.open(),setTimeout(()=>{if(k||z)zt.startVoiceRecognition();else if(yo.persist?.focusInput){let re=e.querySelector("textarea");re&&re.focus()}},100)},0)),yo.persist?.openState&&(X.on("widget:opened",()=>{a.setItem(u,"true")}),X.on("widget:closed",()=>{a.setItem(u,"false")})),yo.persist?.voiceState&&(X.on("voice:state",re=>{a.setItem(m,re.active?"true":"false")}),X.on("user:message",re=>{a.setItem(b,re.viaVoice?"true":"false")})),yo.clearOnChatClear){let re=()=>{a.removeItem(u),a.removeItem(m),a.removeItem(b)},Y=()=>re();window.addEventListener("persona:clear-chat",Y),Se.push(()=>{window.removeEventListener("persona:clear-chat",Y)})}}}if(Ee&&Xe()&&(qt?.setPanelOpen(!0,"auto"),setTimeout(()=>{zt.open()},0)),oa(),!SE){let a=ua(()=>{R&&(Qs++,Mn.clear(),fo(Te,R.getMessages(),K))});Se.push(a)}I=()=>{R&&(Qs++,Mn.clear(),fo(Te,R.getMessages(),K))},R.getMessages().length>0&&Xc(),W=()=>{R&&(Qs++,Mn.clear(),fo(Te,R.getMessages(),K))};let RM=uv(()=>{R&&(Qs++,Mn.clear(),fo(Te,R.getMessages(),K))});Se.push(RM);let WM=uh(()=>{R&&(Qs++,Mn.clear(),fo(Te,R.getMessages(),K),qr()?.updateInlineArtifactBlocks(Te,uo.artifacts,{suppressTransition:!0}),Ho())});return Se.push(WM),zt};_o();var ux=(e,t)=>{let n=e.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,t*parseFloat(r[1])/100):420},pH=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},uH=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},gH=(e,t)=>{let n=e.parentElement;if(!n)return;let o=e.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."+(t.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 ${t.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.")},gx=(e,t)=>{let n=t?.launcher?.enabled??!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0",e.style.minWidth=n?"":"0"},Eh=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},fx=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",Eh(e)},Sh=e=>{e.style.transition=""},Ah=e=>{e.style.display="",e.style.flexDirection="",e.style.flex="",e.style.minHeight="",e.style.minWidth="",e.style.width="",e.style.height="",e.style.alignItems="",e.style.transition="",e.style.transform="",e.style.marginLeft=""},xh=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Cu=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},fH=(e,t,n,o,r)=>{r?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,o),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(o))},mH=(e,t,n,o,r,s)=>{let i=s?t:e;r==="left"?i.firstElementChild!==o&&i.replaceChildren(o,n):i.lastElementChild!==o&&i.replaceChildren(n,o)},hH=e=>{let t=No(e),n=t.components?.panel,o=(r,s)=>r==null||r===""?s:wn(t,r)??r;return{inset:o(n?.inset,Up),canvasBackground:o(n?.canvasBackground,Vp)}},mx=(e,t,n,o)=>{if(!t){e.style.padding="",e.style.background="",e.style.boxSizing="";return}e.style.boxSizing="border-box",e.style.padding=n,e.style.background=o},yH=(e,t,n,o,r,s,i,l)=>{let c=Zn(s),p=c.reveal==="push",d=l!=null,g=l?.inset??"",f=l?.canvasBackground??"";fH(e,t,n,o,p),mH(e,t,n,o,c.side,p),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=c.side,e.dataset.personaDockOpen=i?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.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=e.ownerDocument.defaultView,y=s?.launcher?.mobileFullscreen??!0,v=s?.launcher?.mobileBreakpoint??640,C=h!=null?h.innerWidth<=v:!1;if(y&&C&&i){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Ah(t),Sh(o),fx(o),xh(n),Cu(r,o),mx(o,!1,"",""),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.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??kn),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",p&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.marginLeft="0",t.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),fx(o),pH(o,c.maxHeight),mx(o,d&&i,g,f),c.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Ah(t),Sh(o),xh(n),Cu(r,o);let L=c.animate?"transform 180ms ease":"none",I=c.side==="right"?"translateX(100%)":"translateX(-100%)",H=i?"translateX(0)":I;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=L,o.style.transform=H,o.style.pointerEvents=i?"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"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",Sh(o),Eh(o),Cu(r,o);let L=ux(c.width,e.clientWidth),I=Math.max(0,e.clientWidth),H=c.animate?"margin-left 180ms ease":"none",B=c.side==="right"?i?-L:0:i?0:-L;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${I+L}px`,t.style.transition=H,t.style.marginLeft=`${B}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${I}px`,n.style.maxWidth=`${I}px`,n.style.minWidth=`${I}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=i?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Ah(t),Eh(o),xh(n),Cu(r,o);let L=c.reveal==="emerge";L?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let I=i?c.width:"0px",H=c.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${d?", padding 180ms ease":""}`:"none",B=!i;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${I}`,o.style.width=I,o.style.maxWidth=I,o.style.minWidth=I,o.style.minHeight="0",uH(o,c.maxHeight),o.style.overflow=L||B?"hidden":"visible",o.style.transition=H,L){o.style.alignItems=c.side==="right"?"flex-start":"flex-end";let V=d?`calc(${ux(c.width,e.clientWidth)}px - (2 * ${g}))`:c.width;r.style.width=V,r.style.minWidth=V,r.style.maxWidth=V,r.style.boxSizing="border-box"}}},bH=(e,t)=>{let n=e.ownerDocument.createElement("div");return gx(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){gx(n,o)},destroy(){n.remove()}}},vH=(e,t)=>{let{ownerDocument:n}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=e.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=e.nextSibling,i=n.createElement("div"),l=n.createElement("div"),c=n.createElement("div"),p=n.createElement("aside"),d=n.createElement("div"),g=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;l.dataset.personaDockRole="push-track",c.dataset.personaDockRole="content",p.dataset.personaDockRole="panel",d.dataset.personaDockRole="host",p.appendChild(d),o.insertBefore(i,e),c.appendChild(e);let f=null,h=()=>{f?.disconnect(),f=null},y=null,v=()=>{y=t?.launcher?.detachedPanel===!0?hH(t):null};v();let C=()=>{yH(i,l,c,p,d,t,g,y)},A=null,L=()=>{A?.(),A=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(A=Oa(()=>{v(),C()}))},I=()=>{h(),Zn(t).reveal==="push"&&(typeof ResizeObserver>"u"||(f=new ResizeObserver(()=>{C()}),f.observe(i)))},H=!1,B=()=>{C(),I(),g&&!H&&i.dataset.personaDockMobileFullscreen!=="true"&&(H=!0,gH(i,Zn(t)))},V=i.ownerDocument.defaultView,oe=()=>{B()};return V?.addEventListener("resize",oe),Zn(t).reveal==="push"?(l.appendChild(c),l.appendChild(p),i.appendChild(l)):(i.appendChild(c),i.appendChild(p)),B(),L(),{mode:"docked",host:d,shell:i,syncWidgetState(W){let j=W.launcherEnabled?W.open:!0;g!==j&&(g=j,B())},updateConfig(W){t=W,(t?.launcher?.enabled??!0)===!1&&(g=!0),v(),B(),L()},destroy(){V?.removeEventListener("resize",oe),A?.(),A=null,h(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),i.remove()}}},bc=(e,t)=>Lt(t)?vH(e,t):bH(e,t);var CH=e=>{if(typeof window>"u"||typeof document>"u")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let t=document.querySelector(e);if(!t)throw new Error(`Chat widget target "${e}" was not found`);return t}return e},hx=(e,t)=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let n=t.head.querySelector("link[data-persona]");if(!n)return;let o=n.cloneNode(!0);e.insertBefore(o,e.firstChild)},wu=[],yx=()=>[...wu],Mh=e=>{let t=CH(e.target),n=e.useShadowDom===!0,o=t.ownerDocument,r=e.config,s=bc(t,r),i,l=[],c=(C,A)=>{let I=!(A?.launcher?.enabled??!0)||Lt(A),H=o.createElement("div");if(H.setAttribute("data-persona-root","true"),I&&(H.style.height="100%",H.style.display="flex",H.style.flexDirection="column",H.style.flex="1",H.style.minHeight="0",H.style.minWidth="0"),n){let B=C.attachShadow({mode:"open"});B.appendChild(H),hx(B,o)}else C.appendChild(H),hx(C,o);return t.id&&H.setAttribute("data-persona-instance",t.id),H},p=()=>{s.syncWidgetState(i.getState())},d=()=>{l.forEach(C=>C()),l=[i.on("widget:opened",p),i.on("widget:closed",p)],p()},g=()=>{let C=c(s.host,r);i=vu(C,r,{debugTools:e.debugTools}),d()},f=()=>{l.forEach(C=>C()),l=[],i.destroy()};g(),e.onChatReady?.();let h=C=>{f(),s.destroy(),s=bc(t,C),r=C,g()},y={update(C){let A=pu(r??{},C),L=Lt(r),I=Lt(A),H=Rs(r),B=Rs(A);if(L!==I||H!==B){h(A);return}r=A,s.updateConfig(r),i.update(C),p()},destroy(){f(),s.destroy();let C=wu.indexOf(v);C!==-1&&wu.splice(C,1),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},v=new Proxy(y,{get(C,A,L){if(A==="host")return s.host;if(A in C)return Reflect.get(C,A,L);let I=i[A];return typeof I=="function"?I.bind(i):I}});return wu.push(v),e.windowKey&&typeof window<"u"&&(window[e.windowKey]=v),v};ha();Rl();Dd();Ca();pi();Cs();Nr();var Sx=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),wH=new Set(["button","a","input","select","textarea","details","summary"]),SH=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Th=/\b(product|card|item|listing|result)\b/i,kh=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,AH=3e3,xH=100;function Ax(e){let t=typeof e.className=="string"?e.className:"";if(Th.test(t)||e.id&&Th.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let o=e.attributes[n];if(o.name.startsWith("data-")&&Th.test(o.value))return!0}return!1}function xx(e){return kh.test((e.textContent??"").trim())}function Ex(e){let t=e.querySelectorAll("a[href]");for(let n=0;n<t.length;n++){let o=t[n].getAttribute("href")??"";if(o&&o!=="#"&&!o.toLowerCase().startsWith("javascript:"))return!0}return!1}function EH(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function bx(e){let t=e.match(kh);return t?t[0]:null}function vx(e){let t=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]")??e.querySelector("a[href]");if(t&&t.textContent?.trim()){let o=t.getAttribute("href");return{title:t.textContent.trim(),href:o&&o!=="#"?o:null}}let n=e.querySelector("h1, h2, h3, h4, h5, h6");return n?.textContent?.trim()?{title:n.textContent.trim(),href:null}:{title:"",href:null}}function MH(e){let t=[],n=o=>{let r=o.trim();r&&!t.includes(r)&&t.push(r)};return e.querySelectorAll("button").forEach(o=>n(o.textContent??"")),e.querySelectorAll('[role="button"]').forEach(o=>n(o.textContent??"")),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(o=>{n(o.value??"")}),t.slice(0,6)}var TH="commerce-card",PH="result-card";function Cx(e){return!Ax(e)||!xx(e)||!Ex(e)&&!EH(e)?0:5200}function wx(e){return!Ax(e)||xx(e)||!Ex(e)||(e.textContent??"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var Lh=[{id:TH,scoreElement(e){return Cx(e)},shouldSuppressDescendant(e,t,n){if(t===e||!e.contains(t))return!1;if(n.interactivity==="static"){let o=n.text.trim();return!!(o.length===0||kh.test(o)&&o.length<32)}return!0},formatSummary(e,t){if(Cx(e)===0)return null;let{title:n,href:o}=vx(e),r=bx((e.textContent??"").trim())??bx(t.text)??"",s=MH(e);return[o&&n?`[${n}](${o})${r?`: ${r}`:""}`:n?`${n}${r?`: ${r}`:""}`:r||t.text.trim().slice(0,120),`selector: ${t.selector}`,s.length?`actions: ${s.join(", ")}`:""].filter(Boolean).join(`
|
|
141
|
+
`)}},{id:PH,scoreElement(e){return wx(e)},formatSummary(e,t){if(wx(e)===0)return null;let{title:n,href:o}=vx(e);return[o&&n?`[${n}](${o})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
|
|
142
|
+
`)}}];function kH(){typeof console<"u"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function LH(e){let t=e.options??{},n=t.maxElements??e.maxElements??80,o=t.excludeSelector??e.excludeSelector??".persona-host",r=t.maxTextLength??e.maxTextLength??200,s=t.visibleOnly??e.visibleOnly??!0,i=t.root??e.root,l=t.mode??"structured",c=t.maxCandidates??Math.max(500,n*10),p=e.rules??Lh;return l==="simple"&&e.rules&&e.rules.length>0?(kH(),p=[]):l==="simple"&&(p=[]),{mode:l,maxElements:n,maxCandidates:c,excludeSelector:o,maxTextLength:r,visibleOnly:s,root:i,rules:p}}function Ph(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var HH=["data-testid","data-product","data-action","data-id","data-name","data-type"];function IH(e){let t=e.tagName.toLowerCase(),n=e.getAttribute("role");return t==="a"&&e.hasAttribute("href")?"navigable":t==="input"||t==="select"||t==="textarea"||n==="textbox"||n==="combobox"||n==="listbox"||n==="spinbutton"?"input":t==="button"||n==="button"||wH.has(t)||n&&SH.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Mx(e){if(e.hidden)return!1;try{let t=getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden")return!1}catch{}return!(e.style.display==="none"||e.style.visibility==="hidden")}function RH(e){let t={},n=e.id;n&&(t.id=n);let o=e.getAttribute("href");o&&(t.href=o);let r=e.getAttribute("aria-label");r&&(t["aria-label"]=r);let s=e.getAttribute("type");s&&(t.type=s);let i=e.getAttribute("value");i&&(t.value=i);let l=e.getAttribute("name");l&&(t.name=l);let c=e.getAttribute("role");c&&(t.role=c);for(let p=0;p<e.attributes.length;p++){let d=e.attributes[p];d.name.startsWith("data-")&&(t[d.name]=d.value)}return t}function Hh(e){let t=e.tagName.toLowerCase();if(e.id){let r=`#${Ph(e.id)}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}}for(let r of HH){let s=e.getAttribute(r);if(s){let i=`${t}[${r}="${Ph(s)}"]`;try{if(e.ownerDocument.querySelectorAll(i).length===1)return i}catch{}}}let n=Array.from(e.classList).filter(r=>r&&!r.startsWith("persona-")).slice(0,3);if(n.length>0){let r=`${t}.${n.map(i=>Ph(i)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}let s=e.parentElement;if(s){let l=Array.from(s.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(l>=0){let c=`${r}:nth-of-type(${l+1})`;try{if(e.ownerDocument.querySelectorAll(c).length===1)return c}catch{}}}}let o=e.parentElement;if(o){let s=Array.from(o.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(s>=0)return`${t}:nth-of-type(${s+1})`}return t}function WH(e){return e==="static"?xH:AH}function Tx(e,t){let n=e.tagName.toLowerCase(),o=(e.textContent??"").trim().substring(0,t);return{selector:Hh(e),tagName:n,text:o,role:e.getAttribute("role"),interactivity:IH(e),attributes:RH(e)}}function OH(e,t,n,o){let r=WH(t.interactivity),s=null;for(let i of n){let l=i.scoreElement(e,t,o);l>0&&(r+=l,i.formatSummary&&!s&&(s=i))}return{score:r,formattingRule:s}}function _H(e,t){for(let n of e)if(t.el!==n.el&&n.formattingRule?.shouldSuppressDescendant&&n.el.contains(t.el)&&n.formattingRule.shouldSuppressDescendant(n.el,t.el,t.enriched))return!0;return!1}function BH(e,t){let n={doc:t.ownerDocument,maxTextLength:e.maxTextLength},o=new Set,r=[],s=0,i=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),l=i.currentNode;for(;l&&r.length<e.maxCandidates;){if(l.nodeType===Node.ELEMENT_NODE){let p=l,d=p.tagName.toLowerCase();if(Sx.has(d)){l=i.nextNode();continue}if(e.excludeSelector)try{if(p.closest(e.excludeSelector)){l=i.nextNode();continue}}catch{}if(e.visibleOnly&&!Mx(p)){l=i.nextNode();continue}let g=Tx(p,e.maxTextLength),f=g.text.length>0,h=Object.keys(g.attributes).length>0&&!Object.keys(g.attributes).every(C=>C==="role");if(!f&&!h){l=i.nextNode();continue}if(o.has(g.selector)){l=i.nextNode();continue}o.add(g.selector);let{score:y,formattingRule:v}=OH(p,g,e.rules,n);r.push({el:p,domIndex:s,enriched:g,score:y,formattingRule:v}),s+=1}l=i.nextNode()}r.sort((p,d)=>{let g=p.enriched.interactivity==="static"?1:0,f=d.enriched.interactivity==="static"?1:0;return g!==f?g-f:d.score!==p.score?d.score-p.score:p.domIndex-d.domIndex});let c=[];for(let p of r){if(c.length>=e.maxElements)break;_H(c,p)||c.push(p)}return c.sort((p,d)=>{let g=p.enriched.interactivity==="static"?1:0,f=d.enriched.interactivity==="static"?1:0;return g!==f?g-f:g===1&&d.score!==p.score?d.score-p.score:p.domIndex-d.domIndex}),c.map(p=>{let d;if(p.formattingRule?.formatSummary){let f=p.formattingRule.formatSummary(p.el,p.enriched,n);f&&(d=f)}let g={...p.enriched};return d&&(g.formattedSummary=d),g})}function DH(e,t){let n=[],o=new Set,r=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),s=r.currentNode;for(;s&&n.length<e.maxElements;){if(s.nodeType===Node.ELEMENT_NODE){let c=s,p=c.tagName.toLowerCase();if(Sx.has(p)){s=r.nextNode();continue}if(e.excludeSelector)try{if(c.closest(e.excludeSelector)){s=r.nextNode();continue}}catch{}if(e.visibleOnly&&!Mx(c)){s=r.nextNode();continue}let d=Tx(c,e.maxTextLength),g=d.text.length>0,f=Object.keys(d.attributes).length>0&&!Object.keys(d.attributes).every(h=>h==="role");if(!g&&!f){s=r.nextNode();continue}o.has(d.selector)||(o.add(d.selector),n.push(d))}s=r.nextNode()}let i=[],l=[];for(let c of n)c.interactivity!=="static"?i.push(c):l.push(c);return[...i,...l].slice(0,e.maxElements)}function Px(e={}){let t=LH(e),n=t.root??document.body;return n?t.mode==="simple"?DH(t,n):BH(t,n):[]}var Su=100;function kx(e,t={}){if(e.length===0)return"No page elements found.";let n=t.mode??"structured",o=[];if(n==="structured"){let s=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);s.length>0&&o.push(`Structured summaries:
|
|
143
143
|
${s.map(i=>`- ${i.split(`
|
|
144
144
|
`).join(`
|
|
145
145
|
`)}`).join(`
|
|
146
|
-
`)}`)}let r={clickable:[],navigable:[],input:[],static:[]};for(let s of e)n==="structured"&&s.formattedSummary||r[s.interactivity].push(s);if(r.clickable.length>0){let s=r.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,
|
|
146
|
+
`)}`)}let r={clickable:[],navigable:[],input:[],static:[]};for(let s of e)n==="structured"&&s.formattedSummary||r[s.interactivity].push(s);if(r.clickable.length>0){let s=r.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,Su)}" (clickable)`);o.push(`Interactive elements:
|
|
147
147
|
${s.join(`
|
|
148
|
-
`)}`)}if(r.navigable.length>0){let s=r.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,
|
|
148
|
+
`)}`)}if(r.navigable.length>0){let s=r.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,Su)}" (navigable)`);o.push(`Navigation links:
|
|
149
149
|
${s.join(`
|
|
150
|
-
`)}`)}if(r.input.length>0){let s=r.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,
|
|
150
|
+
`)}`)}if(r.input.length>0){let s=r.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,Su)}" (input)`);o.push(`Form inputs:
|
|
151
151
|
${s.join(`
|
|
152
|
-
`)}`)}if(r.static.length>0){let s=r.static.map(i=>`- ${i.selector}: "${i.text.substring(0,
|
|
152
|
+
`)}`)}if(r.static.length>0){let s=r.static.map(i=>`- ${i.selector}: "${i.text.substring(0,Su)}"`);o.push(`Content:
|
|
153
153
|
${s.join(`
|
|
154
154
|
`)}`)}return o.join(`
|
|
155
155
|
|
|
156
|
-
`)}Sa();kt();
|
|
156
|
+
`)}Sa();kt();So();So();var NH={palette:{colors:{primary:{500:"#111827"},accent:{600:"#1d4ed8"},gray:{50:"#ffffff",100:"#f8fafc",200:"#f1f5f9",500:"#6b7280",900:"#000000"}},radius:{sm:"0.75rem",md:"1rem",lg:"1.5rem",launcher:"9999px",button:"9999px"}},semantic:{colors:{primary:"palette.colors.primary.500",textInverse:"palette.colors.gray.50"}}},Lx={components:{panel:{borderRadius:"0",shadow:"none"}}},Ih={id:"shop",label:"Shopping Assistant",config:{theme:NH,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:vi},copy:{welcomeTitle:"Welcome to our shop!",welcomeSubtitle:"I can help you find products and answer questions",inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestionChips:["Show me what you can help with","Walk me through getting started","Answer a question about this page"]}},Rh={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Lx}},Wh={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Lx}},Oh={shop:Ih,minimal:Rh,fullscreen:Wh};function Hx(e){return Oh[e]}var Ix=Mh;function Rx(){return{name:"@persona/accessibility",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,interactive:{...e.semantic.colors.interactive,focus:"palette.colors.primary.700",disabled:"palette.colors.gray.300"}}}}},cssVariables:{"--persona-accessibility-focus-ring":"0 0 0 2px var(--persona-semantic-colors-surface, #fff), 0 0 0 4px var(--persona-semantic-colors-interactive-focus, #0f0f0f)"}}}function Wx(){return{name:"@persona/animations",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"150ms",normal:"200ms",slow:"300ms",bounce:"500ms cubic-bezier(0.68, -0.55, 0.265, 1.55)"},easings:{easeIn:"cubic-bezier(0.4, 0, 1, 1)",easeOut:"cubic-bezier(0, 0, 0.2, 1)",easeInOut:"cubic-bezier(0.4, 0, 0.2, 1)"}}}},cssVariables:{"--persona-transition-fast":"150ms ease","--persona-transition-normal":"200ms ease","--persona-transition-slow":"300ms ease"}}}function Ox(e){return{name:"@persona/brand",version:"1.0.0",transform(t){let n={...t.palette};return e.colors?.primary&&(n.colors={...n.colors,primary:{50:lr(e.colors.primary,.95),100:lr(e.colors.primary,.9),200:lr(e.colors.primary,.8),300:lr(e.colors.primary,.7),400:lr(e.colors.primary,.6),500:e.colors.primary,600:lr(e.colors.primary,.8),700:lr(e.colors.primary,.7),800:lr(e.colors.primary,.6),900:lr(e.colors.primary,.5),950:lr(e.colors.primary,.45)}}),{...t,palette:n}}}}function _x(){return{name:"@persona/reduced-motion",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"0ms",normal:"0ms",slow:"0ms",bounce:"0ms"}}}},afterResolve(e){return{...e,"--persona-transition-fast":"0ms","--persona-transition-normal":"0ms","--persona-transition-slow":"0ms"}}}}function Bx(){return{name:"@persona/high-contrast",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",border:"palette.colors.gray.900",divider:"palette.colors.gray.900"}}}}}}function lr(e,t){let n=parseInt(e.slice(1,3),16),o=parseInt(e.slice(3,5),16),r=parseInt(e.slice(5,7),16),s=Math.round(n+(255-n)*(1-t)),i=Math.round(o+(255-o)*(1-t)),l=Math.round(r+(255-r)*(1-t));return`#${s.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}${l.toString(16).padStart(2,"0")}`}function Dx(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}Sa();function _h(e){return e?.cdnBase?.trim().replace(/\/+$/,"").replace(/[\\'"<>`]/g,n=>`%${n.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0")}`)||`https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Xn}/dist`}function Gr(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function FH(e){if(e)return{getHeaders:Gr(e.getHeaders),onFeedback:Gr(e.onFeedback),onCopy:Gr(e.onCopy),requestMiddleware:Gr(e.requestMiddleware),actionHandlers:Gr(e.actionHandlers),actionParsers:Gr(e.actionParsers),postprocessMessage:Gr(e.postprocessMessage),contextProviders:Gr(e.contextProviders),streamParser:Gr(e.streamParser)}}var Nx=`({ text, message }: any) => {
|
|
157
157
|
const jsonSource = (message as any).rawContent || text || message.content;
|
|
158
158
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
159
159
|
let cleanJson = jsonSource
|
|
@@ -166,7 +166,7 @@ ${s.join(`
|
|
|
166
166
|
if (parsed.action) return { type: parsed.action, payload: parsed };
|
|
167
167
|
} catch (e) { return null; }
|
|
168
168
|
return null;
|
|
169
|
-
}`,
|
|
169
|
+
}`,Fx=`function(ctx) {
|
|
170
170
|
var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
|
|
171
171
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
172
172
|
var cleanJson = jsonSource
|
|
@@ -179,7 +179,7 @@ ${s.join(`
|
|
|
179
179
|
if (parsed.action) return { type: parsed.action, payload: parsed };
|
|
180
180
|
} catch (e) { return null; }
|
|
181
181
|
return null;
|
|
182
|
-
}
|
|
182
|
+
}`,$x=`(action: any, context: any) => {
|
|
183
183
|
if (action.type !== 'nav_then_click') return;
|
|
184
184
|
const payload = action.payload || action.raw || {};
|
|
185
185
|
const url = payload?.page;
|
|
@@ -196,7 +196,7 @@ ${s.join(`
|
|
|
196
196
|
const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
|
|
197
197
|
window.location.href = targetUrl;
|
|
198
198
|
return { handled: true, displayText: text };
|
|
199
|
-
}`,
|
|
199
|
+
}`,Ux=`function(action, context) {
|
|
200
200
|
if (action.type !== 'nav_then_click') return;
|
|
201
201
|
var payload = action.payload || action.raw || {};
|
|
202
202
|
var url = payload.page;
|
|
@@ -213,27 +213,27 @@ ${s.join(`
|
|
|
213
213
|
var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
|
|
214
214
|
window.location.href = targetUrl;
|
|
215
215
|
return { handled: true, displayText: text };
|
|
216
|
-
}
|
|
216
|
+
}`,$H=`(parsed: any) => {
|
|
217
217
|
if (!parsed || typeof parsed !== 'object') return null;
|
|
218
218
|
if (parsed.action === 'nav_then_click') return 'Navigating...';
|
|
219
219
|
if (parsed.action === 'message') return parsed.text || '';
|
|
220
220
|
if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
|
|
221
221
|
return parsed.text || null;
|
|
222
|
-
}`,
|
|
222
|
+
}`,UH=`function(parsed) {
|
|
223
223
|
if (!parsed || typeof parsed !== 'object') return null;
|
|
224
224
|
if (parsed.action === 'nav_then_click') return 'Navigating...';
|
|
225
225
|
if (parsed.action === 'message') return parsed.text || '';
|
|
226
226
|
if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
|
|
227
227
|
return parsed.text || null;
|
|
228
|
-
}`;function
|
|
229
|
-
`);return n.map((o,r)=>{let s=r===0?`${t}suggestions: `:t,i=r===n.length-1?",":"";return`${s}${o}${i}`})}function
|
|
230
|
-
`)}function
|
|
231
|
-
`)}function FH(e,t){let n=t?.hooks,o=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({",` target: '${bc(t)}',`," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.agentId&&o.push(` agentId: "${e.agentId}",`),e.target&&o.push(` target: "${e.target}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),Tu(o,e," "),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Os(o,"theme",e.theme," "),e.launcher&&Os(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([r,s])=>{o.push(` ${r}: "${s}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([r,s])=>{typeof s=="string"?o.push(` ${r}: "${s}",`):typeof s=="boolean"&&o.push(` ${r}: ${s},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([r,s])=>{typeof s=="string"?o.push(` ${r}: "${s}",`):typeof s=="boolean"?o.push(` ${r}: ${s},`):typeof s=="number"&&o.push(` ${r}: ${s},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([r,s])=>{typeof s=="string"?o.push(` ${r}: "${s}",`):typeof s=="boolean"&&o.push(` ${r}: ${s},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([r,s])=>{o.push(` ${r}: ${s},`)}),o.push(" },")),o.push(...Mu(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(r=>{o.push(` "${r}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...Su(e," ")),o.push(...Au(e," ",n)),o.push(...xu(e," ")),o.push(...Eu(e," ")),n?.getHeaders&&o.push(` getHeaders: ${n.getHeaders},`),n?.contextProviders&&o.push(` contextProviders: ${n.contextProviders},`),e.debug&&o.push(` debug: ${e.debug},`),o.push(" initialMessages: loadSavedMessages(),"),n?.streamParser?o.push(` streamParser: ${n.streamParser},`):(o.push(" // Flexible JSON stream parser for handling structured actions"),o.push(` streamParser: () => createFlexibleJsonStreamParser(${OH}),`)),n?.actionParsers?(o.push(" // Action parsers (custom merged with defaults)"),o.push(` actionParsers: [...(${n.actionParsers}), defaultJsonActionParser,`),o.push(" // Built-in parser for markdown-wrapped JSON"),o.push(` ${Ox}`),o.push(" ],")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" actionParsers: ["),o.push(" defaultJsonActionParser,"),o.push(" // Parser for markdown-wrapped JSON"),o.push(` ${Ox}`),o.push(" ],")),n?.actionHandlers?(o.push(" // Action handlers (custom merged with defaults)"),o.push(` actionHandlers: [...(${n.actionHandlers}),`),o.push(" defaultActionHandlers.message,"),o.push(" defaultActionHandlers.messageAndClick,"),o.push(" // Built-in handler for nav_then_click action"),o.push(` ${_x}`),o.push(" ],")):(o.push(" // Action handlers for navigation and other actions"),o.push(" actionHandlers: ["),o.push(" defaultActionHandlers.message,"),o.push(" defaultActionHandlers.messageAndClick,"),o.push(" // Handler for nav_then_click action"),o.push(` ${_x}`),o.push(" ],")),n?.postprocessMessage?o.push(` postprocessMessage: ${n.postprocessMessage},`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),n?.requestMiddleware?(o.push(" // Request middleware (custom merged with DOM context)"),o.push(" requestMiddleware: ({ payload, config }) => {"),o.push(` const customResult = (${n.requestMiddleware})({ payload, config });`),o.push(" const merged = customResult || payload;"),o.push(" return {"),o.push(" ...merged,"),o.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),o.push(" };"),o.push(" }")):(o.push(" requestMiddleware: ({ payload }) => {"),o.push(" return {"),o.push(" ...payload,"),o.push(" metadata: collectDOMContext()"),o.push(" };"),o.push(" }")),o.push(" }"),o.push(" });"),o.push(""),o.push(" // Save state on message events"),o.push(" const handleMessage = () => {"),o.push(" const session = handle?.getSession?.();"),o.push(" if (session) {"),o.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),o.push(" messages: session.messages,"),o.push(" timestamp: new Date().toISOString()"),o.push(" }));"),o.push(" }"),o.push(" };"),o.push(""),o.push(" // Clear state on clear chat"),o.push(" const handleClearChat = () => {"),o.push(" localStorage.removeItem(STORAGE_KEY);"),o.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),o.push(" };"),o.push(""),o.push(" window.addEventListener('persona:message', handleMessage);"),o.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),o.push(""),o.push(" // Cleanup on unmount"),o.push(" return () => {"),o.push(" window.removeEventListener('persona:message', handleMessage);"),o.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),o.push(" if (handle) {"),o.push(" handle.destroy();"),o.push(" }"),o.push(" };"),o.push(" }, []);"),o.push(""),o.push(" return null; // Widget injects itself into the DOM"),o.push("}"),o.push(""),o.push("// Usage: Collects DOM context for AI-powered navigation"),o.push("// Features:"),o.push("// - Extracts page elements (products, buttons, links)"),o.push("// - Persists chat history across page loads"),o.push("// - Handles navigation actions (nav_then_click)"),o.push("// - Processes structured JSON actions from AI"),o.push("//"),o.push("// Example usage in Next.js:"),o.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),o.push("//"),o.push("// export default function RootLayout({ children }) {"),o.push("// return ("),o.push('// <html lang="en">'),o.push("// <body>"),o.push("// {children}"),o.push("// <ChatWidgetAdvanced />"),o.push("// </body>"),o.push("// </html>"),o.push("// );"),o.push("// }"),o.join(`
|
|
232
|
-
`)}function
|
|
233
|
-
`)}function
|
|
228
|
+
}`;function VH(e){if(!e)return null;let t=e.toString();return t.includes("createJsonStreamParser")||t.includes("partial-json")?"json":t.includes("createRegexJsonParser")||t.includes("regex")?"regex-json":t.includes("createXmlParser")||t.includes("<text>")?"xml":null}function Au(e){return e.parserType??VH(e.streamParser)??"plain"}function xu(e,t){let n=[];return e.toolCall&&(n.push(`${t}toolCall: {`),Object.entries(e.toolCall).forEach(([o,r])=>{typeof r=="string"&&n.push(`${t} ${o}: "${r}",`)}),n.push(`${t}},`)),n}function Eu(e,t,n){let o=[],r=e.messageActions&&Object.entries(e.messageActions).some(([i,l])=>i!=="onFeedback"&&i!=="onCopy"&&l!==void 0),s=n?.onFeedback||n?.onCopy;return(r||s)&&(o.push(`${t}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([i,l])=>{i==="onFeedback"||i==="onCopy"||(typeof l=="string"?o.push(`${t} ${i}: "${l}",`):typeof l=="boolean"&&o.push(`${t} ${i}: ${l},`))}),n?.onFeedback&&o.push(`${t} onFeedback: ${n.onFeedback},`),n?.onCopy&&o.push(`${t} onCopy: ${n.onCopy},`),o.push(`${t}},`)),o}function Mu(e,t){let n=[];if(e.markdown){let o=e.markdown.options&&Object.keys(e.markdown.options).length>0,r=e.markdown.disableDefaultStyles!==void 0;(o||r)&&(n.push(`${t}markdown: {`),o&&(n.push(`${t} options: {`),Object.entries(e.markdown.options).forEach(([s,i])=>{typeof i=="string"?n.push(`${t} ${s}: "${i}",`):typeof i=="boolean"&&n.push(`${t} ${s}: ${i},`)}),n.push(`${t} },`)),r&&n.push(`${t} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),n.push(`${t}},`))}return n}function Tu(e,t){if(!e.suggestions)return[];let n=JSON.stringify(e.suggestions,null,2).split(`
|
|
229
|
+
`);return n.map((o,r)=>{let s=r===0?`${t}suggestions: `:t,i=r===n.length-1?",":"";return`${s}${o}${i}`})}function Pu(e,t){let n=[];if(e.layout){let o=e.layout.header&&Object.keys(e.layout.header).some(s=>s!=="render"),r=e.layout.messages&&Object.keys(e.layout.messages).some(s=>s!=="renderUserMessage"&&s!=="renderAssistantMessage");(o||r)&&(n.push(`${t}layout: {`),o&&(n.push(`${t} header: {`),Object.entries(e.layout.header).forEach(([s,i])=>{s!=="render"&&(typeof i=="string"?n.push(`${t} ${s}: "${i}",`):typeof i=="boolean"&&n.push(`${t} ${s}: ${i},`))}),n.push(`${t} },`)),r&&(n.push(`${t} messages: {`),Object.entries(e.layout.messages).forEach(([s,i])=>{s==="renderUserMessage"||s==="renderAssistantMessage"||(s==="avatar"&&typeof i=="object"&&i!==null?(n.push(`${t} avatar: {`),Object.entries(i).forEach(([l,c])=>{typeof c=="string"?n.push(`${t} ${l}: "${c}",`):typeof c=="boolean"&&n.push(`${t} ${l}: ${c},`)}),n.push(`${t} },`)):s==="timestamp"&&typeof i=="object"&&i!==null?Object.entries(i).some(([c])=>c!=="format")&&(n.push(`${t} timestamp: {`),Object.entries(i).forEach(([c,p])=>{c!=="format"&&(typeof p=="string"?n.push(`${t} ${c}: "${p}",`):typeof p=="boolean"&&n.push(`${t} ${c}: ${p},`))}),n.push(`${t} },`)):typeof i=="string"?n.push(`${t} ${s}: "${i}",`):typeof i=="boolean"&&n.push(`${t} ${s}: ${i},`))}),n.push(`${t} },`)),n.push(`${t}},`))}return n}function Bh(e,t){let n=[];return e&&(e.getHeaders&&n.push(`${t}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&n.push(`${t}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&n.push(`${t}actionParsers: ${e.actionParsers},`),e.actionHandlers&&n.push(`${t}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&n.push(`${t}contextProviders: ${e.contextProviders},`),e.streamParser&&n.push(`${t}streamParser: ${e.streamParser},`)),n}function Vx(e,t,n){Object.entries(t).forEach(([o,r])=>{if(!(r===void 0||typeof r=="function")){if(Array.isArray(r)){e.push(`${n}${o}: ${JSON.stringify(r)},`);return}if(r&&typeof r=="object"){e.push(`${n}${o}: {`),Vx(e,r,`${n} `),e.push(`${n}},`);return}e.push(`${n}${o}: ${JSON.stringify(r)},`)}})}function Os(e,t,n,o){n&&(e.push(`${o}${t}: {`),Vx(e,n,`${o} `),e.push(`${o}},`))}function ku(e,t,n){t.future?.v5Defaults!==void 0&&e.push(`${n}future: { v5Defaults: ${t.future.v5Defaults===!0} },`)}function vc(e){return(e?.target??"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function jx(e,t="esm",n){let o={...e};delete o.postprocessMessage,delete o.initialMessages;let r=n?{...n,hooks:FH(n.hooks)}:void 0;return t==="esm"?jH(o,r):t==="script-installer"?KH(o,r):t==="script-advanced"?YH(o,r):t==="react-component"?qH(o,r):t==="react-advanced"?zH(o,r):GH(o,r)}function jH(e,t){let n=t?.hooks,o=Au(e),r=o!=="plain",s=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${vc(t)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),r&&s.push(` parserType: "${o}",`),ku(s,e," "),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Os(s,"theme",e.theme," "),e.launcher&&Os(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([i,l])=>{s.push(` ${i}: "${l}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,l])=>{typeof l=="string"?s.push(` ${i}: "${l}",`):typeof l=="boolean"&&s.push(` ${i}: ${l},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,l])=>{typeof l=="string"?s.push(` ${i}: "${l}",`):typeof l=="boolean"?s.push(` ${i}: ${l},`):typeof l=="number"&&s.push(` ${i}: ${l},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,l])=>{typeof l=="string"?s.push(` ${i}: "${l}",`):typeof l=="boolean"&&s.push(` ${i}: ${l},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([i,l])=>{s.push(` ${i}: ${l},`)}),s.push(" },")),s.push(...Tu(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{s.push(` "${i}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...xu(e," ")),s.push(...Eu(e," ",n)),s.push(...Mu(e," ")),s.push(...Pu(e," ")),s.push(...Bh(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n?.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push("});"),s.join(`
|
|
230
|
+
`)}function qH(e,t){let n=t?.hooks,o=Au(e),r=o!=="plain",s=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({",` target: '${vc(t)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),r&&s.push(` parserType: "${o}",`),ku(s,e," "),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Os(s,"theme",e.theme," "),e.launcher&&Os(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([i,l])=>{s.push(` ${i}: "${l}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,l])=>{typeof l=="string"?s.push(` ${i}: "${l}",`):typeof l=="boolean"&&s.push(` ${i}: ${l},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,l])=>{typeof l=="string"?s.push(` ${i}: "${l}",`):typeof l=="boolean"?s.push(` ${i}: ${l},`):typeof l=="number"&&s.push(` ${i}: ${l},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,l])=>{typeof l=="string"?s.push(` ${i}: "${l}",`):typeof l=="boolean"&&s.push(` ${i}: ${l},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([i,l])=>{s.push(` ${i}: ${l},`)}),s.push(" },")),s.push(...Tu(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{s.push(` "${i}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...xu(e," ")),s.push(...Eu(e," ",n)),s.push(...Mu(e," ")),s.push(...Pu(e," ")),s.push(...Bh(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n?.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push(""),s.push(" // Cleanup on unmount"),s.push(" return () => {"),s.push(" if (handle) {"),s.push(" handle.destroy();"),s.push(" }"),s.push(" };"),s.push(" }, []);"),s.push(""),s.push(" return null; // Widget injects itself into the DOM"),s.push("}"),s.push(""),s.push("// Usage in your app:"),s.push("// import { ChatWidget } from './components/ChatWidget';"),s.push("//"),s.push("// export default function App() {"),s.push("// return ("),s.push("// <div>"),s.push("// {/* Your app content */}"),s.push("// <ChatWidget />"),s.push("// </div>"),s.push("// );"),s.push("// }"),s.join(`
|
|
231
|
+
`)}function zH(e,t){let n=t?.hooks,o=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({",` target: '${vc(t)}',`," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.agentId&&o.push(` agentId: "${e.agentId}",`),e.target&&o.push(` target: "${e.target}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),ku(o,e," "),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Os(o,"theme",e.theme," "),e.launcher&&Os(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([r,s])=>{o.push(` ${r}: "${s}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([r,s])=>{typeof s=="string"?o.push(` ${r}: "${s}",`):typeof s=="boolean"&&o.push(` ${r}: ${s},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([r,s])=>{typeof s=="string"?o.push(` ${r}: "${s}",`):typeof s=="boolean"?o.push(` ${r}: ${s},`):typeof s=="number"&&o.push(` ${r}: ${s},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([r,s])=>{typeof s=="string"?o.push(` ${r}: "${s}",`):typeof s=="boolean"&&o.push(` ${r}: ${s},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([r,s])=>{o.push(` ${r}: ${s},`)}),o.push(" },")),o.push(...Tu(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(r=>{o.push(` "${r}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...xu(e," ")),o.push(...Eu(e," ",n)),o.push(...Mu(e," ")),o.push(...Pu(e," ")),n?.getHeaders&&o.push(` getHeaders: ${n.getHeaders},`),n?.contextProviders&&o.push(` contextProviders: ${n.contextProviders},`),e.debug&&o.push(` debug: ${e.debug},`),o.push(" initialMessages: loadSavedMessages(),"),n?.streamParser?o.push(` streamParser: ${n.streamParser},`):(o.push(" // Flexible JSON stream parser for handling structured actions"),o.push(` streamParser: () => createFlexibleJsonStreamParser(${$H}),`)),n?.actionParsers?(o.push(" // Action parsers (custom merged with defaults)"),o.push(` actionParsers: [...(${n.actionParsers}), defaultJsonActionParser,`),o.push(" // Built-in parser for markdown-wrapped JSON"),o.push(` ${Nx}`),o.push(" ],")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" actionParsers: ["),o.push(" defaultJsonActionParser,"),o.push(" // Parser for markdown-wrapped JSON"),o.push(` ${Nx}`),o.push(" ],")),n?.actionHandlers?(o.push(" // Action handlers (custom merged with defaults)"),o.push(` actionHandlers: [...(${n.actionHandlers}),`),o.push(" defaultActionHandlers.message,"),o.push(" defaultActionHandlers.messageAndClick,"),o.push(" // Built-in handler for nav_then_click action"),o.push(` ${$x}`),o.push(" ],")):(o.push(" // Action handlers for navigation and other actions"),o.push(" actionHandlers: ["),o.push(" defaultActionHandlers.message,"),o.push(" defaultActionHandlers.messageAndClick,"),o.push(" // Handler for nav_then_click action"),o.push(` ${$x}`),o.push(" ],")),n?.postprocessMessage?o.push(` postprocessMessage: ${n.postprocessMessage},`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),n?.requestMiddleware?(o.push(" // Request middleware (custom merged with DOM context)"),o.push(" requestMiddleware: ({ payload, config }) => {"),o.push(` const customResult = (${n.requestMiddleware})({ payload, config });`),o.push(" const merged = customResult || payload;"),o.push(" return {"),o.push(" ...merged,"),o.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),o.push(" };"),o.push(" }")):(o.push(" requestMiddleware: ({ payload }) => {"),o.push(" return {"),o.push(" ...payload,"),o.push(" metadata: collectDOMContext()"),o.push(" };"),o.push(" }")),o.push(" }"),o.push(" });"),o.push(""),o.push(" // Save state on message events"),o.push(" const handleMessage = () => {"),o.push(" const session = handle?.getSession?.();"),o.push(" if (session) {"),o.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),o.push(" messages: session.messages,"),o.push(" timestamp: new Date().toISOString()"),o.push(" }));"),o.push(" }"),o.push(" };"),o.push(""),o.push(" // Clear state on clear chat"),o.push(" const handleClearChat = () => {"),o.push(" localStorage.removeItem(STORAGE_KEY);"),o.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),o.push(" };"),o.push(""),o.push(" window.addEventListener('persona:message', handleMessage);"),o.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),o.push(""),o.push(" // Cleanup on unmount"),o.push(" return () => {"),o.push(" window.removeEventListener('persona:message', handleMessage);"),o.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),o.push(" if (handle) {"),o.push(" handle.destroy();"),o.push(" }"),o.push(" };"),o.push(" }, []);"),o.push(""),o.push(" return null; // Widget injects itself into the DOM"),o.push("}"),o.push(""),o.push("// Usage: Collects DOM context for AI-powered navigation"),o.push("// Features:"),o.push("// - Extracts page elements (products, buttons, links)"),o.push("// - Persists chat history across page loads"),o.push("// - Handles navigation actions (nav_then_click)"),o.push("// - Processes structured JSON actions from AI"),o.push("//"),o.push("// Example usage in Next.js:"),o.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),o.push("//"),o.push("// export default function RootLayout({ children }) {"),o.push("// return ("),o.push('// <html lang="en">'),o.push("// <body>"),o.push("// {children}"),o.push("// <ChatWidgetAdvanced />"),o.push("// </body>"),o.push("// </html>"),o.push("// );"),o.push("// }"),o.join(`
|
|
232
|
+
`)}function qx(e){let t=Au(e),n=t!=="plain",o={};if(e.apiUrl&&(o.apiUrl=e.apiUrl),e.clientToken&&(o.clientToken=e.clientToken),e.agentId&&(o.agentId=e.agentId),e.target&&(o.target=e.target),e.flowId&&(o.flowId=e.flowId),n&&(o.parserType=t),e.future?.v5Defaults!==void 0&&(o.future={v5Defaults:e.future.v5Defaults===!0}),e.theme&&(o.theme=e.theme),e.launcher&&(o.launcher=e.launcher),e.copy&&(o.copy=e.copy),e.sendButton&&(o.sendButton=e.sendButton),e.voiceRecognition&&(o.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(o.statusIndicator=e.statusIndicator),e.features&&(o.features=e.features),e.suggestions&&(o.suggestions=e.suggestions),e.suggestionChips?.length>0&&(o.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(o.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(o.debug=e.debug),e.toolCall){let r={};Object.entries(e.toolCall).forEach(([s,i])=>{typeof i=="string"&&(r[s]=i)}),Object.keys(r).length>0&&(o.toolCall=r)}if(e.messageActions){let r={};Object.entries(e.messageActions).forEach(([s,i])=>{s!=="onFeedback"&&s!=="onCopy"&&i!==void 0&&(typeof i=="string"||typeof i=="boolean")&&(r[s]=i)}),Object.keys(r).length>0&&(o.messageActions=r)}if(e.markdown){let r={};e.markdown.options&&(r.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(r.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(r).length>0&&(o.markdown=r)}if(e.layout){let r={};if(e.layout.header){let s={};Object.entries(e.layout.header).forEach(([i,l])=>{i!=="render"&&(typeof l=="string"||typeof l=="boolean")&&(s[i]=l)}),Object.keys(s).length>0&&(r.header=s)}if(e.layout.messages){let s={};Object.entries(e.layout.messages).forEach(([i,l])=>{if(i!=="renderUserMessage"&&i!=="renderAssistantMessage")if(i==="avatar"&&typeof l=="object"&&l!==null)s.avatar=l;else if(i==="timestamp"&&typeof l=="object"&&l!==null){let c={};Object.entries(l).forEach(([p,d])=>{p!=="format"&&(typeof d=="string"||typeof d=="boolean")&&(c[p]=d)}),Object.keys(c).length>0&&(s.timestamp=c)}else(typeof l=="string"||typeof l=="boolean")&&(s[i]=l)}),Object.keys(s).length>0&&(r.messages=s)}Object.keys(r).length>0&&(o.layout=r)}return o}function KH(e,t){let n=qx(e),r=!!(t?.windowKey||t?.target)?{config:n,...t?.windowKey?{windowKey:t.windowKey}:{},...t?.target?{target:t.target}:{}}:n,s=JSON.stringify(r,null,0).replace(/'/g,"'");return`<script src="${_h(t)}/install.global.js" data-config='${s}'></script>`}function GH(e,t){let n=t?.hooks,o=Au(e),r=o!=="plain",s=_h(t),i=["<!-- Load CSS -->",`<link rel="stylesheet" href="${s}/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="${s}/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${vc(t)}',`,...t?.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: {"];return e.apiUrl&&i.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&i.push(` clientToken: "${e.clientToken}",`),e.agentId&&i.push(` agentId: "${e.agentId}",`),e.target&&i.push(` target: "${e.target}",`),e.flowId&&i.push(` flowId: "${e.flowId}",`),r&&i.push(` parserType: "${o}",`),ku(i,e," "),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Os(i,"theme",e.theme," "),e.launcher&&Os(i,"launcher",e.launcher," "),e.copy&&(i.push(" copy: {"),Object.entries(e.copy).forEach(([l,c])=>{i.push(` ${l}: "${c}",`)}),i.push(" },")),e.sendButton&&(i.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([l,c])=>{typeof c=="string"?i.push(` ${l}: "${c}",`):typeof c=="boolean"&&i.push(` ${l}: ${c},`)}),i.push(" },")),e.voiceRecognition&&(i.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([l,c])=>{typeof c=="string"?i.push(` ${l}: "${c}",`):typeof c=="boolean"?i.push(` ${l}: ${c},`):typeof c=="number"&&i.push(` ${l}: ${c},`)}),i.push(" },")),e.statusIndicator&&(i.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([l,c])=>{typeof c=="string"?i.push(` ${l}: "${c}",`):typeof c=="boolean"&&i.push(` ${l}: ${c},`)}),i.push(" },")),e.features&&(i.push(" features: {"),Object.entries(e.features).forEach(([l,c])=>{i.push(` ${l}: ${c},`)}),i.push(" },")),i.push(...Tu(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(i.push(" suggestionChips: ["),e.suggestionChips.forEach(l=>{i.push(` "${l}",`)}),i.push(" ],")),e.suggestionChipsConfig&&(i.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&i.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&i.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&i.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&i.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),i.push(" },")),i.push(...xu(e," ")),i.push(...Eu(e," ",n)),i.push(...Mu(e," ")),i.push(...Pu(e," ")),i.push(...Bh(n," ")),e.debug&&i.push(` debug: ${e.debug},`),n?.postprocessMessage?i.push(` postprocessMessage: ${n.postprocessMessage}`):i.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),i.push(" }"),i.push(" });"),i.push("</script>"),i.join(`
|
|
233
|
+
`)}function YH(e,t){let n=t?.hooks,o=qx(e),s=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(o,null,2).split(`
|
|
234
234
|
`).map((i,l)=>l===0?i:" "+i).join(`
|
|
235
|
-
`)};`,""," // Constants",` var CDN_BASE = '${
|
|
236
|
-
`)}
|
|
235
|
+
`)};`,""," // Constants",` var CDN_BASE = '${_h(t)}';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return n?.getHeaders&&(s.push(` widgetConfig.getHeaders = ${n.getHeaders};`),s.push("")),n?.contextProviders&&(s.push(` widgetConfig.contextProviders = ${n.contextProviders};`),s.push("")),n?.streamParser?s.push(` widgetConfig.streamParser = ${n.streamParser};`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(" widgetConfig.streamParser = function() {"),s.push(` return agentWidget.createFlexibleJsonStreamParser(${UH});`),s.push(" };")),s.push(""),n?.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` var customParsers = ${n.actionParsers};`),s.push(" widgetConfig.actionParsers = customParsers.concat(["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${Fx}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${Fx}`),s.push(" ];")),s.push(""),n?.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` var customHandlers = ${n.actionHandlers};`),s.push(" widgetConfig.actionHandlers = customHandlers.concat(["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${Ux}`),s.push(" ]);")):(s.push(" // Action handlers for navigation and other actions"),s.push(" widgetConfig.actionHandlers = ["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${Ux}`),s.push(" ];")),s.push(""),n?.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(` var customResult = (${n.requestMiddleware})(ctx);`),s.push(" var merged = customResult || ctx.payload;"),s.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),s.push(" };")):(s.push(" // Send DOM context with each request"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),s.push(" };")),s.push(""),n?.postprocessMessage?s.push(` widgetConfig.postprocessMessage = ${n.postprocessMessage};`):(s.push(" // Markdown postprocessor"),s.push(" widgetConfig.postprocessMessage = function(ctx) {"),s.push(" return agentWidget.markdownPostprocessor(ctx.text);"),s.push(" };")),s.push(""),(n?.onFeedback||n?.onCopy)&&(s.push(" // Message action callbacks"),s.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),n?.onFeedback&&s.push(` widgetConfig.messageActions.onFeedback = ${n.onFeedback};`),n?.onCopy&&s.push(` widgetConfig.messageActions.onCopy = ${n.onCopy};`),s.push("")),s.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({",` target: '${vc(t)}',`," useShadowDom: false,",...t?.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),s.join(`
|
|
236
|
+
`)}Ze();var Qx=require("lucide");Lr();var zx={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Kx=.1,Gx=.15,Yx=1.5,Dh=24,Xx=40,XH=`
|
|
237
237
|
/* \u2500\u2500 Root \u2500\u2500 */
|
|
238
238
|
.persona-dc-root {
|
|
239
239
|
display: flex;
|
|
@@ -384,7 +384,7 @@ ${s.join(`
|
|
|
384
384
|
.persona-dc-stage {
|
|
385
385
|
height: 550px;
|
|
386
386
|
min-height: 400px;
|
|
387
|
-
padding: ${
|
|
387
|
+
padding: ${Dh}px;
|
|
388
388
|
overflow: auto;
|
|
389
389
|
background: #f0f1f3;
|
|
390
390
|
background-image: radial-gradient(circle, #e0e1e5 1px, transparent 1px);
|
|
@@ -474,14 +474,14 @@ ${s.join(`
|
|
|
474
474
|
min-height: 300px;
|
|
475
475
|
}
|
|
476
476
|
}
|
|
477
|
-
`;function
|
|
477
|
+
`;function QH(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=XH,document.head.appendChild(e)}function JH(e,t){let n=e.clientWidth-Dh*2-Xx,o=e.clientHeight-Dh*2-Xx;return n<=0||o<=0?1:Math.min(n/t.w,o/t.h,1)}function ZH(e,t,n,o,r){e.style.width=`${n.w*o}px`,e.style.height=`${n.h*o}px`,e.style.borderRadius=r==="mobile"?`${32*o}px`:"10px",t.style.width=`${n.w}px`,t.style.height=`${n.h}px`,t.style.transformOrigin="top left",t.style.transform=`scale(${o})`}function Jx(e,t){let{items:n,initialIndex:o=0,initialDevice:r="desktop",initialColorScheme:s="light",showZoomControls:i=!0,showDeviceToggle:l=!0,showColorSchemeToggle:c=!0,onChange:p}=t;if(n.length===0)throw new Error("createDemoCarousel: items array must not be empty");QH();let d=Math.max(0,Math.min(o,n.length-1)),g=r,f=s,h=null,y=1,v=!1,C=x("div","persona-dc-root"),A=x("div","persona-dc-toolbar"),L=x("div","persona-dc-toolbar-lead"),I=x("div","persona-dc-toolbar-trail"),H=eo({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>_e(-1)}),B=x("div");B.style.position="relative";let V=x("button","persona-dc-title-btn");V.type="button",V.setAttribute("aria-expanded","false"),V.setAttribute("aria-haspopup","listbox");let oe=x("span","persona-dc-title-text"),W=x("span","persona-dc-title-chevron"),j=Nt(Qx.ChevronDown,12,"currentColor",2);j&&W.appendChild(j),V.append(oe,W);let X=x("div","persona-dc-dropdown");X.setAttribute("role","listbox"),X.style.display="none";let M=!1;function T(){X.innerHTML="";for(let xe=0;xe<n.length;xe++){let Wt=n[xe],vt=x("button","persona-dc-dropdown-item");vt.type="button",vt.setAttribute("role","option"),vt.setAttribute("aria-current",xe===d?"true":"false");let Le=x("span");if(Le.textContent=Wt.title,vt.appendChild(Le),Wt.description){let Xe=x("span","persona-dc-dropdown-desc");Xe.textContent=Wt.description,vt.appendChild(Xe)}vt.addEventListener("click",()=>{P(),ye(xe)}),X.appendChild(vt)}}function _(){M=!M,X.style.display=M?"":"none",V.setAttribute("aria-expanded",M?"true":"false"),M&&T()}function P(){M&&(M=!1,X.style.display="none",V.setAttribute("aria-expanded","false"))}V.addEventListener("click",xe=>{xe.stopPropagation(),_()});let J=()=>P();document.addEventListener("click",J),B.append(V,X);let U=eo({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>_e(1)}),ue=x("span","persona-dc-counter");L.append(H,B,U,ue);let fe=null;l&&(fe=lc({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:g,onSelect:xe=>{g=xe,yt.dataset.device=g,h=null,ut()}}),I.appendChild(fe.element));let me=null;if(i){let xe=x("div","persona-dc-zoom-controls"),Wt=eo({icon:"minus",label:"Zoom out",size:14,onClick:()=>{h=Math.max(Gx,(h??y)-Kx),ut()}});me=x("span","persona-dc-zoom-level"),me.title="Reset to 100%",me.style.cursor="pointer",me.addEventListener("click",()=>{h=1,ut()});let vt=eo({icon:"plus",label:"Zoom in",size:14,onClick:()=>{h=Math.min(Yx,(h??y)+Kx),ut()}}),Le=eo({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{h=null,ut()}});xe.append(Wt,me,vt,Le),I.appendChild(xe)}if(c){let xe=x("div","persona-dc-separator");I.appendChild(xe);let Wt=lc({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:f,onSelect:vt=>{f=vt,yt.dataset.colorScheme=f,Oe()}});I.appendChild(Wt.element)}let He=x("div","persona-dc-separator");I.appendChild(He);let Ee=eo({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[d].url,"_blank")}});I.appendChild(Ee),A.append(L,I);let Ie=x("div","persona-dc-stage"),yt=x("div","persona-dc-iframe-wrapper");yt.dataset.device=g,yt.dataset.colorScheme=f;let qe=x("iframe","persona-dc-iframe");qe.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),qe.setAttribute("loading","lazy"),qe.title=n[d].title,yt.appendChild(qe),Ie.appendChild(yt),C.append(A,Ie),e.appendChild(C);function Oe(){try{let xe=qe.contentDocument?.body;if(!xe)return;f==="dark"?xe.classList.add("theme-dark"):xe.classList.remove("theme-dark")}catch{}}qe.addEventListener("load",()=>Oe());function $(){let xe=n[d];oe.textContent=xe.title,ue.textContent=`${d+1} / ${n.length}`,qe.title=xe.title}function _e(xe){let Wt=((d+xe)%n.length+n.length)%n.length;ye(Wt)}function ye(xe){xe<0||xe>=n.length||(d=xe,qe.src=n[d].url,$(),p?.(d,n[d]))}function ut(){if(v)return;let xe=zx[g]??zx.desktop;y=JH(Ie,xe);let Wt=Math.max(Gx,Math.min(Yx,h??y));ZH(yt,qe,xe,Wt,g),me&&(me.textContent=`${Math.round(Wt*100)}%`)}let Zt=new ResizeObserver(()=>ut());Zt.observe(Ie),$(),qe.src=n[d].url,requestAnimationFrame(()=>ut());function xt(){v||(v=!0,Zt.disconnect(),document.removeEventListener("click",J),C.remove())}return{element:C,goTo:ye,next:()=>_e(1),prev:()=>_e(-1),getIndex:()=>d,setDevice(xe){g=xe,yt.dataset.device=xe,fe?.setSelected(xe),h=null,ut()},setColorScheme(xe){f=xe,yt.dataset.colorScheme=xe},setZoom(xe){h=xe,ut()},destroy:xt}}gm();Sa();var Nh=16e3,eI=24e3,tI=4096,nI=Nh*2*8,oI=4,rI=1380533830,sI=3e4,iI=1e3,aI=5e3,lI=3e4,cI=3e4,dI=6e5,pI="full-duplex-v1",uI=300,gI=2e3,fI=2e3,mI="runtype-browser-v1",hI=54e4,yI="You're talking to an AI assistant. Voice is processed by OpenAI.",bI=new Map([["idle_timeout","Voice call ended after a quiet period."],["max_duration","This voice call reached its time limit."],["provider_ended","The voice session ended."],["quota","Voice is unavailable right now."],["auth_expired","Voice session expired. Tap the mic to reconnect."]]),Zx=["provider_error","server_restart"],Lu="Voice connection lost.",vI=8e3,CI=4e3,wI=12,eE=2e3;function SI(e,t){let n="Conversation so far:",o=t.slice(0,CI).trim(),r=vI-(o?o.length+2:0)-n.length,s=[];for(let l of e.slice(-wI).reverse()){let c=l.content.replace(/\s+/g," ").trim();if(!c)continue;c.length>eE&&(c=`${c.slice(0,eE-1)}\u2026`);let p=`${l.role==="user"?"User":"Assistant"}: ${c}`;if(p.length+1>r)break;r-=p.length+1,s.unshift(p)}let i=s.length>0?[`${n}
|
|
478
478
|
${s.join(`
|
|
479
479
|
`)}`]:[];return o&&i.push(o),i.join(`
|
|
480
480
|
|
|
481
|
-
`)}function mI(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===JH?new Uint8Array(e,44):new Uint8Array(e)}function Xx(e){let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window<"u"&&window.location?.protocol==="https:"?"wss:":"ws:"}//${t}`}function hI(e){return Xx(e).replace(/^ws/i,"http")}function yI(e){return typeof e!="number"||!Number.isFinite(e)?tI:Math.min(oI,Math.max(nI,Math.round(e)))}var vc=class{constructor(t){this.config=t;this.type="runtype";this.#e=null;this.#n=null;this.#o=[];this.#t=null;this.#s=null;this.#r=null;this.#p=[];this.#f=0;this.#i=null;this.#g=!1;this.#l=!1;this.#c=0;this.#a=!1;this.#E=Number.NEGATIVE_INFINITY;this.#h=null;this.#S=!1;this.#v=!1;this.#A=0;this.#d=0;this.#m=!1;this.bridge=null;this.#C=!1;this.#x=new Set;this.#y=new Map;this.#b=new Set;this.#k=!1;this.#M=null;this.#I=null;this.#Y=Promise.resolve();this.#j=new Set;this.#B=!1;this.#T=new Set;this.#K=new Set;this.#_=[];this.#F=[];this.#ee=[];this.#te=[];this.#D=[]}#e;#n;#o;#t;#s;#r;#p;#f;#i;#g;#l;#c;#a;#E;#h;#S;#v;#A;#d;#u;#m;#C;#x;#y;#b;#H;#k;#M;#I;#Y;#j;#B;#T;#K;#_;#F;#ee;#te;#D;async connect(){}setSessionBridge(t){this.bridge=t}prewarm(){if(this.#g||this.#h)return;let t=this.config?.agentId,n=this.config?.clientToken,o=this.config?.host;if(!t||!n||!o)return;let r=Date.now();if(!(r-this.#E<ZH)){this.#E=r;try{this.config?.prewarmMode==="attach"?this.#Z(o,t,n):this.#X(o,t,n)}catch{}}}#X(t,n,o){if(typeof fetch!="function")return;let r=`${hI(t)}/v1/client/agents/${encodeURIComponent(n)}/voice/prewarm`;fetch(r,{method:"POST",headers:{Authorization:`Bearer ${o}`},keepalive:!0}).catch(()=>{})}#Z(t,n,o){let r=new URLSearchParams,s=this.config?.attachIdleMs,i=yI(s);s!==void 0&&r.set("attachIdleMs",String(i));let l=new WebSocket(this.#de(t,n,r),["runtype.bearer","runtype.attach",o]);l.binaryType="arraybuffer";let c=()=>{},p=new Promise(g=>{c=g}),d={ws:l,state:"connecting",ready:p,settle:c,openedAt:0,idleTimer:void 0};this.#h=d,l.onopen=()=>{this.#h===d&&(d.state=l.protocol==="runtype.attach"?"attached":"live",d.openedAt=Date.now(),this.#ne(d,i),d.state==="attached"&&l.send('{"type":"ping"}'),d.settle())},l.onmessage=g=>{if(this.#h!==d||typeof g.data!="string")return;let f;try{f=JSON.parse(g.data)}catch{return}f.type==="attached"&&typeof f.idleMs=="number"&&this.#ne(d,f.idleMs-(Date.now()-d.openedAt))},l.onerror=()=>{},l.onclose=()=>{this.#h===d&&this.#$()}}#ne(t,n){clearTimeout(t.idleTimer),t.idleTimer=setTimeout(()=>{this.#h===t&&this.#$()},Math.max(0,n))}#$(){let t=this.#h;if(!t)return;this.#h=null,clearTimeout(t.idleTimer);let{ws:n}=t;if(n.onopen=null,n.onmessage=null,n.onerror=null,n.onclose=null,t.settle(),n.readyState===WebSocket.CONNECTING||n.readyState===WebSocket.OPEN)try{n.close(1e3,"prewarm released")}catch{}}async#U(){let t=this.#h;if(!t)return null;if(t.state==="connecting"){let n;await Promise.race([t.ready,new Promise(o=>{n=setTimeout(o,eI)})]),clearTimeout(n)}return this.#h!==t?null:t.state==="connecting"||t.ws.readyState!==WebSocket.OPEN?(this.#$(),null):(this.#h=null,clearTimeout(t.idleTimer),{ws:t.ws,live:t.state==="live"})}#de(t,n,o){let r=["partial_transcript","context"];this.bridge&&this.config?.clientDelegation!==!1&&r.push("client_delegation","delegation_update","delegation_read_back"),o&&r.unshift("attach");let s=new URLSearchParams({voiceProtocol:lI,clientVersion:`persona/${Yn}`,voiceCapabilities:rI,clientCapabilities:r.join(",")});return o?.forEach((i,l)=>s.set(l,i)),`${Xx(t)}/ws/agents/${encodeURIComponent(n)}/voice?${s}`}async startListening(){if(this.#g)return;let t=this.config?.agentId,n=this.config?.clientToken,o=this.config?.host;if(!t)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.#c;this.#a=!1,this.#g=!0;try{let s=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:Bh,channelCount:1,echoCancellation:!0}});if(r!==this.#c){s.getTracks().forEach(g=>g.stop());return}this.#t=s;let i=window.AudioContext||window.webkitAudioContext,l=new i({sampleRate:Bh});l.state==="suspended"&&await l.resume().catch(()=>{}),this.#n=l;let c=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new Ra(GH);if(r!==this.#c){c.destroy(),s.getTracks().forEach(g=>g.stop()),l.close().catch(()=>{});return}this.#i=c,this.#G(),this.#be(l,s,r);let p=await this.#U();if(r!==this.#c){p?.ws.close(1e3,"client ended call");return}if(p){let{ws:g}=p;this.#e=g,this.#W(g,r),p.live||g.send('{"type":"start"}'),this.#oe(g),this.#w("listening");return}let d=new WebSocket(this.#de(o,t),["runtype.bearer",n]);d.binaryType="arraybuffer",this.#e=d,d.onopen=()=>{r===this.#c&&(this.#oe(d),this.#w("listening"))},this.#W(d,r)}catch(s){throw this.#Q(),this.#ie(s),this.#w("error"),s}}#W(t,n){t.onmessage=o=>this.#pe(o,n),t.onerror=()=>{n===this.#c&&(this.#ie(new Error("Voice connection failed")),this.#w("error"),this.#Q())},t.onclose=o=>{if(this.#a){this.#a=!1;return}if(n===this.#c){if(o.code!==1e3){let r=o.code?` (code ${o.code})`:"";this.#ie(new Error(`Voice connection closed${r}`)),this.#w("error")}else this.#w("idle");this.#Q()}}}getDisclosure(){let t=this.config?.disclosureText;return this.#g&&this.#S&&t!==!1?t||dI:null}async stopListening(){this.#Q(),this.#w("idle")}async disconnect(){this.#Q(),this.#w("disconnected"),this.#_=[],this.#F=[],this.#ee=[],this.#te=[],this.#D=[]}stopPlayback(){this.#ve();let t=this.#e;t&&t.readyState===WebSocket.OPEN&&(this.#S&&(this.#A=Date.now()+iI,t.send('{"type":"cancel"}')),this.#w("listening"))}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.#g}onLevel(t){this.#o.push(t)}async deactivateBargeIn(){this.#Q(),this.#w("idle")}#be(t,n,o){let r=t.createMediaStreamSource(n);this.#s=r;let s=t.createScriptProcessor(YH,1,1);this.#r=s,s.onaudioprocess=i=>{if(o!==this.#c)return;let l=this.#e,c=l?.readyState===WebSocket.OPEN;if(l&&!c&&l.readyState!==WebSocket.CONNECTING)return;let p=i.inputBuffer.getChannelData(0),d=new Int16Array(p.length),g=0;for(let f=0;f<p.length;f++){let h=Math.max(-1,Math.min(1,p[f]));g+=h*h,d[f]=h<0?h*32768:h*32767}if(l&&c)this.#oe(l),l.send(d.buffer);else for(this.#p.push(d.buffer),this.#f+=d.byteLength;this.#f>XH;)this.#f-=this.#p.shift().byteLength;if(this.#o.length>0){let f=Math.sqrt(g/p.length),h=Math.max(0,Math.min(1,f*QH));for(let y of this.#o)y(h)}},r.connect(s),s.connect(t.destination)}#oe(t){for(let n of this.#p)t.send(n);this.#p=[],this.#f=0}#pe(t,n){if(n!==this.#c)return;if(t.data instanceof ArrayBuffer){this.#L(t.data,n);return}let o;try{o=JSON.parse(t.data)}catch{return}switch(o.type){case"session_config":o.speechMode&&(this.#S=o.speechMode==="speech_to_speech",this.#i?.setContinuousMode?.(this.#S)),Array.isArray(o.capabilities)&&(this.#x=new Set(o.capabilities)),typeof o.callId=="string"&&(this.#H=o.callId),this.#C=this.#S&&this.#x.has("client_delegation")&&!!this.bridge,this.#S&&!this.#l&&this.#w("listening"),this.#x.has("context")&&!this.#k&&(this.#k=!0,this.#M=this.#re());break;case"transcript_update":{let r=o.role==="assistant"?"assistant":"user",s=o.utteranceId??o.turnId;if(!s||r==="assistant"&&this.#N())break;let i=String(s);if(r==="user")o.final===!0&&this.#se(n),this.#B=!1;else{if(this.#x.has("delegation_read_back")){let l=o.delegationId;typeof l=="string"&&this.#j.has(l)&&!this.#T.has(i)&&this.#K.add(i)}else this.#B&&!this.#T.has(i)&&(this.#K.add(i),this.#B=!1);if(this.#T.add(i),this.#K.has(i))break}this.#ae(r,o.text??"",o.final===!0,{turnId:i,...typeof o.startMs=="number"&&{startMs:o.startMs},...typeof o.endMs=="number"&&{endMs:o.endMs},...this.#C&&{caption:!0}});break}case"delegation_started":case"delegation_completed":{let r=String(o.delegationId??o.turnId);if(o.type==="delegation_started"){this.#se(n);let s=o.input;this.#C&&s&&this.#O(r,{delegationId:r,userText:String(s.text??""),userUtteranceIds:Array.isArray(s.userUtteranceIds)?s.userUtteranceIds.filter(i=>typeof i=="string"):[],messages:Array.isArray(s.messages)?s.messages:[]},n)}else o.speak!==!1&&this.#j.has(r)&&(this.#B=!0);this.#v=o.type==="delegation_started",!this.#l&&!this.#N()&&this.#w(this.#v?"processing":"listening");break}case"delegation_cancelled":this.#R(String(o.delegationId),o.reason!=="session_ending"&&o.reason!=="provider_cancelled");break;case"warning":console.warn(`[Persona voice] ${o.code}: ${o.message??""}`,this.#H??""),o.delegationId&&(o.code==="UNKNOWN_DELEGATION"||o.code==="LATE_RESULT_LIMIT")&&this.#R(String(o.delegationId));break;case"audio_clear":this.#ve(),this.#A=0,this.#w("listening");break;case"transcript_interim":this.#w("listening"),this.#ae("user",o.text??"",!1);break;case"transcript_final":{let r=o.role==="assistant"?"assistant":"user";this.#w(r==="user"?"processing":"speaking"),this.#ae(r,o.text??"",!0);break}case"audio_end":this.#i?this.#i.markStreamEnd():(this.#l=!1,this.#w("listening"));break;case"metrics":this.#we({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.#ie(new Error(o.error||"Voice error")),this.#w("error");break}}async#re(){let t=this.bridge?.getHistory()??[],n="";try{let o=this.config?.callContext;n=String((typeof o=="function"?await o():o)??"")}catch{}return fI(t,n)}#se(t){let n=this.#M;if(!n)return;this.#M=null;let o=!1,r=n.then(s=>{let i=this.#e;o||!s||t!==this.#c||i?.readyState!==WebSocket.OPEN||i.send(JSON.stringify({type:"context",text:s}))});this.#I={done:r,drop:()=>o=!0}}async#q(){let t=this.#I;if(!t)return;let n,o=await Promise.race([t.done.then(()=>!1),new Promise(r=>{n=setTimeout(()=>r(!0),aI)})]);clearTimeout(n),o&&t.drop()}#R(t,n=!1){this.#b.add(t),this.bridge?.dropDelegation?.(t,n),this.#y.get(t)?.abort()}#O(t,n,o){let r=this.bridge,s=(i,l,c)=>{let p=this.#e;return o!==this.#c||p?.readyState!==WebSocket.OPEN||this.#b.has(t)?!1:(p.send(JSON.stringify({type:i,delegationId:t,status:l,text:c})),!0)};this.#Y=this.#Y.then(async()=>{if(o!==this.#c||this.#b.has(t))return;let i=await r.runDelegatedTurn(n).catch(()=>({status:"failed",text:""}));await this.#q();let l=!!i.followUp,c=l&&this.#x.has("delegation_update");if(!s(c?"delegation_update":"delegation_result",l&&!c?"completed":i.status,i.text)||(i.status!=="failed"&&i.inChat!==!1&&this.#j.add(t),!i.followUp))return;let d=new AbortController;this.#y.set(t,d),i.followUp({signal:d.signal,approvalTimeoutMs:this.config?.approvalTimeoutMs&&Math.min(this.config.approvalTimeoutMs,cI),readBack:c,onUpdate:g=>s("delegation_update","pending_approval",g)}).then(g=>{this.#y.delete(t),c&&g&&!d.signal.aborted&&s("delegation_result",g.status,g.text)})})}#L(t,n){if(n!==this.#c||!this.#i||this.#N())return;let o=mI(t);o.length!==0&&(this.#l||(this.#l=!0,this.#w("speaking")),this.#G(),this.#i.enqueue(o),this.#S&&this.#xe(o.length))}#N(){return Date.now()<this.#A}#G(){if(this.#m||!this.#i)return;this.#m=!0;let t=this.#c;this.#i.onFinished(()=>{t===this.#c&&(this.#m=!1,this.#ue())})}#xe(t){let n=Date.now();this.#d=Math.max(n,this.#d)+t/48,clearTimeout(this.#u),this.#u=setTimeout(()=>this.#ue(),this.#d-n+sI)}#ue(){this.#l=!1,this.#d=0,this.#e&&this.#e.readyState===WebSocket.OPEN&&this.#w(this.#v?"processing":"listening")}#ve(){this.#i?.flush(),this.#m=!1,this.#G(),this.#l=!1,this.#d=0,clearTimeout(this.#u)}#Q(){this.#c+=1,this.#g=!1,this.#l=!1,this.#$(),this.#S=!1,this.#v=!1,this.#C=!1,this.#x=new Set;for(let t of this.#y.values())t.abort();if(this.#y.clear(),this.#b.clear(),this.#H=void 0,this.#k=!1,this.#M=null,this.#I=null,this.#Y=Promise.resolve(),this.#j.clear(),this.#B=!1,this.#T.clear(),this.#K.clear(),this.#m=!1,this.#A=0,this.#d=0,clearTimeout(this.#u),this.#p=[],this.#f=0,this.#r&&(this.#r.onaudioprocess=null,this.#r.disconnect(),this.#r=null),this.#s&&(this.#s.disconnect(),this.#s=null),this.#t&&(this.#t.getTracks().forEach(t=>t.stop()),this.#t=null),this.#n&&(this.#n.close().catch(()=>{}),this.#n=null),this.#i&&(this.#i.destroy(),this.#i=null),this.#e){this.#a=!0;try{this.#e.close(1e3,"client ended call")}catch{}this.#e=null}}onResult(t){this.#_.push(t)}onError(t){this.#F.push(t)}onStatusChange(t){this.#ee.push(t)}onTranscript(t){this.#te.push(t)}onMetrics(t){this.#D.push(t)}#w(t){this.#ee.forEach(n=>n(t))}#ie(t){this.#F.forEach(n=>n(t))}#ae(t,n,o,r){this.#te.forEach(s=>s(t,n,o,r))}#we(t){this.#D.forEach(n=>n(t))}};var Oi=class{constructor(t={}){this.config=t;this.type="browser";this.#e=null;this.#n=[];this.#o=[];this.#t=[];this.#s=!1;this.#r=typeof window<"u"?window:void 0}#e;#n;#o;#t;#s;#r;async connect(){this.#t.forEach(t=>t("connected"))}async startListening(){try{if(this.#s)throw new Error("Already listening");if(!this.#r)throw new Error("Window object not available");let t=this.#r.SpeechRecognition||this.#r.webkitSpeechRecognition;if(!t)throw new Error("Browser speech recognition not supported");this.#e=new t,this.#e.lang=this.config?.language||"en-US",this.#e.continuous=this.config?.continuous||!1,this.#e.interimResults=!0,this.#e.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.#n.forEach(s=>s({text:o,confidence:r?.8:.5,provider:"browser"})),r&&!this.config?.continuous&&this.stopListening()},this.#e.onerror=n=>{this.#o.forEach(o=>o(new Error(n.error))),this.#t.forEach(o=>o("error"))},this.#e.onstart=()=>{this.#s=!0,this.#t.forEach(n=>n("listening"))},this.#e.onend=()=>{this.#s=!1,this.#t.forEach(n=>n("idle"))},this.#e.start()}catch(t){throw this.#o.forEach(n=>n(t)),this.#t.forEach(n=>n("error")),t}}async stopListening(){this.#e&&(this.#e.stop(),this.#e=null),this.#s=!1,this.#t.forEach(t=>t("idle"))}onResult(t){this.#n.push(t)}onError(t){this.#o.push(t)}onStatusChange(t){this.#t.push(t)}async disconnect(){await this.stopListening(),this.#t.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Xa(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new vc(e.runtype);case"browser":if(!Oi.isSupported())throw new Error("Browser speech recognition not supported");return new Oi(e.browser||{});case"custom":{let t=e.custom;if(!t)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof t=="function"?t():t;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: ${e.type}`)}}function Pu(e){if(e?.type==="custom"&&e.custom)return Xa({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return Xa({type:"runtype",runtype:e.runtype});if(Oi.isSupported())return Xa({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function _h(e){try{return Pu(e),!0}catch{return!1}}var Qx="webmcp:",bI=e=>e.startsWith(Qx)?e.slice(Qx.length):e,ku={warn(e,...t){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},Hu=class{constructor(t,n){this.config=t;this.#r=n,this.#e=t.onConfirm??null,this.#n=3e4}#e;#n;#o=!1;#t=null;#s=!1;#r;setConfirmHandler(t){this.#e=t}isOperational(){return this.config.enabled!==!0||!this.#o?!1:this.#i()!==null}async snapshotForDispatch(){if(await this.#p(),this.config.enabled!==!0)return[];let t=this.#i();if(!t)return[];let n;try{n=await t.getTools()}catch(r){return ku.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}this.#r.recordToolDisplayTitles(n);let o=typeof location<"u"?location.origin:"";return n.filter(r=>this.#l(r.name)).map(r=>{let s=CI(r.annotations);return{name:r.name,description:r.description,parametersSchema:wI(r.inputSchema),origin:"webmcp",...o?{pageOrigin:o}:{},...s?{annotations:s}:{},...s?.untrustedContentHint===!0?{untrustedContentHint:!0}:{}}})}async executeToolCall(t,n,o){if(await this.#p(),this.config.enabled!==!0)return $o("WebMCP is not enabled on this widget.");let r=this.#i();if(!r){let y=typeof document<"u"&&!!document.modelContext;return $o(y?"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=bI(t),i;try{i=await r.getTools()}catch(y){let v=y instanceof Error?y.message:String(y);return $o(`Failed to read WebMCP registry: ${v}`)}this.#r.recordToolDisplayTitles(i);let l=i.find(y=>y.name===s);if(!l)return $o(`WebMCP tool not registered on this page: ${s}`);if(!this.#l(s))return $o(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return $o("Aborted by cancel()");let c=this.#r.getToolDisplayTitle(s),p={toolName:s,args:n,description:l.description,...c?{title:c}:{},reason:"gate"};if(!await this.#g(p))return $o("User declined the tool call.");if(o?.aborted)return $o("Aborted by cancel()");let d=new AbortController,g=!1,f=setTimeout(()=>{g=!0,d.abort()},this.#n),h=()=>d.abort();o&&(o.aborted?d.abort():o.addEventListener("abort",h,{once:!0}));try{let y=await r.executeTool(l,MI(n),{signal:d.signal});return SI(y)}catch(y){if(g)return $o(`WebMCP tool '${s}' timed out after ${this.#n}ms`);if(o?.aborted)return $o("Aborted by cancel()");let v=y instanceof Error?y.message:String(y);return $o(v)}finally{clearTimeout(f),o&&o.removeEventListener("abort",h)}}#p(){return this.config.enabled!==!0?Promise.resolve():(this.#t||(this.#t=this.#f()),this.#t)}async#f(){try{if(this.#i()){this.#o=!0;return}(await this.#r.loadPolyfill()).initializeWebMCPPolyfill(),this.#o=!0}catch(t){ku.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",t),this.#o=!1}}#i(){if(typeof document>"u")return null;let t=document.modelContext;if(!t||typeof t!="object")return null;let n=t;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.#s||(this.#s=!0,ku.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):t}async#g(t){let n=this.#e??AI;try{return await n(t)}catch(o){return ku.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,o),!1}}#l(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(o=>vI(t,o))}},vI=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Lu={type:"object",properties:{}},CI=e=>{if(!e||typeof e!="object")return;let t={...typeof e.readOnlyHint=="boolean"?{readOnlyHint:e.readOnlyHint}:{},...typeof e.untrustedContentHint=="boolean"?{untrustedContentHint:e.untrustedContentHint}:{}};return Object.keys(t).length>0?t:void 0},wI=e=>{if(e===void 0||e==="")return{...Lu};if(typeof e=="object")return e!==null&&!Array.isArray(e)?e:{...Lu};try{let t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:{...Lu}}catch{return{...Lu}}},SI=e=>{if(e==null)return{content:[{type:"text",text:""}]};let t;try{t=JSON.parse(e)}catch{return{content:[{type:"text",text:e}]}}return t!==null&&typeof t=="object"&&Array.isArray(t.content)?t:{content:[{type:"text",text:typeof t=="string"?t:EI(t)}]}},$o=e=>({isError:!0,content:[{type:"text",text:e}]}),AI=async e=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let t=xI(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
|
|
481
|
+
`)}function AI(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===rI?new Uint8Array(e,44):new Uint8Array(e)}function tE(e){let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window<"u"&&window.location?.protocol==="https:"?"wss:":"ws:"}//${t}`}function xI(e){return tE(e).replace(/^ws/i,"http")}function EI(e){return typeof e!="number"||!Number.isFinite(e)?lI:Math.min(dI,Math.max(cI,Math.round(e)))}var Cc=class{constructor(t){this.config=t;this.type="runtype";this.#e=null;this.#n=null;this.#o=[];this.#t=null;this.#s=null;this.#r=null;this.#p=[];this.#f=0;this.#i=null;this.#u=!1;this.#c=!1;this.#l=0;this.#a=!1;this.#M=Number.NEGATIVE_INFINITY;this.#h=null;this.#A=!1;this.#w=!1;this.#x=0;this.#d=0;this.#m=!1;this.bridge=null;this.#S=!1;this.#E=new Set;this.#b=new Map;this.#v=new Set;this.#T=null;this.#C=null;this.#Y=!1;this.#z=!1;this.#$=!1;this.#P=null;this.#X=null;this.#W=Promise.resolve();this.#D=new Set;this.#Q=!1;this.#ne=new Set;this.#O=new Set;this.#K=[];this.#G=[];this.#oe=[];this.#U=[];this.#_=[]}#e;#n;#o;#t;#s;#r;#p;#f;#i;#u;#c;#l;#a;#M;#h;#A;#w;#x;#d;#g;#m;#S;#E;#b;#v;#H;#T;#C;#R;#Y;#z;#$;#P;#X;#W;#D;#Q;#ne;#O;#K;#G;#oe;#U;#_;async connect(){}setSessionBridge(t){this.bridge=t}prewarm(){if(this.#u||this.#h)return;let t=this.config?.agentId,n=this.config?.clientToken,o=this.config?.host;if(!t||!n||!o)return;let r=Date.now();if(!(r-this.#M<sI)){this.#M=r;try{this.config?.prewarmMode==="attach"?this.#N(o,t,n):this.#be(o,t,n)}catch{}}}#be(t,n,o){if(typeof fetch!="function")return;let r=`${xI(t)}/v1/client/agents/${encodeURIComponent(n)}/voice/prewarm`;fetch(r,{method:"POST",headers:{Authorization:`Bearer ${o}`},keepalive:!0}).catch(()=>{})}#N(t,n,o){let r=new URLSearchParams,s=this.config?.attachIdleMs,i=EI(s);s!==void 0&&r.set("attachIdleMs",String(i));let l=new WebSocket(this.#se(t,n,r),["runtype.bearer","runtype.attach",o]);l.binaryType="arraybuffer";let c=()=>{},p=new Promise(g=>{c=g}),d={ws:l,state:"connecting",ready:p,settle:c,openedAt:0,idleTimer:void 0};this.#h=d,l.onopen=()=>{this.#h===d&&(d.state=l.protocol==="runtype.attach"?"attached":"live",d.openedAt=Date.now(),this.#de(d,i),d.state==="attached"&&l.send('{"type":"ping"}'),d.settle())},l.onmessage=g=>{if(this.#h!==d||typeof g.data!="string")return;let f;try{f=JSON.parse(g.data)}catch{return}f.type==="attached"&&typeof f.idleMs=="number"&&this.#de(d,f.idleMs-(Date.now()-d.openedAt))},l.onerror=()=>{},l.onclose=()=>{this.#h===d&&this.#re()}}#de(t,n){clearTimeout(t.idleTimer),t.idleTimer=setTimeout(()=>{this.#h===t&&this.#re()},Math.max(0,n))}#re(){let t=this.#h;if(!t)return;this.#h=null,clearTimeout(t.idleTimer);let{ws:n}=t;if(n.onopen=null,n.onmessage=null,n.onerror=null,n.onclose=null,t.settle(),n.readyState===WebSocket.CONNECTING||n.readyState===WebSocket.OPEN)try{n.close(1e3,"prewarm released")}catch{}}async#pe(){let t=this.#h;if(!t)return null;if(t.state==="connecting"){let n;await Promise.race([t.ready,new Promise(o=>{n=setTimeout(o,aI)})]),clearTimeout(n)}return this.#h!==t?null:t.state==="connecting"||t.ws.readyState!==WebSocket.OPEN?(this.#re(),null):(this.#h=null,clearTimeout(t.idleTimer),{ws:t.ws,live:t.state==="live"})}#se(t,n,o){let r=["partial_transcript","context"];this.bridge&&this.config?.clientDelegation!==!1&&r.push("client_delegation","delegation_update","delegation_read_back"),o&&r.unshift("attach");let s=new URLSearchParams({voiceProtocol:mI,clientVersion:`persona/${Xn}`,voiceCapabilities:pI,clientCapabilities:r.join(",")});return o?.forEach((i,l)=>s.set(l,i)),`${tE(t)}/ws/agents/${encodeURIComponent(n)}/voice?${s}`}async startListening(){if(this.#u)return;let t=this.#z;t||(this.#Y=!1,this.#C=null),this.#z=!1;let n=this.config?.agentId,o=this.config?.clientToken,r=this.config?.host;if(!n)throw new Error("Runtype voice requires an agentId");if(!o)throw new Error("Runtype voice requires a clientToken");if(!r)throw new Error("Runtype voice requires a host (or widget apiUrl)");let s=++this.#l;this.#a=!1,this.#u=!0;try{let i=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:Nh,channelCount:1,echoCancellation:!0}});if(s!==this.#l){i.getTracks().forEach(f=>f.stop());return}this.#t=i;let l=window.AudioContext||window.webkitAudioContext,c=new l({sampleRate:Nh});if(this.#n=c,c.state==="suspended"){if(await Promise.race([c.resume().catch(()=>{}),new Promise(f=>setTimeout(f,t?500:iI))]),s!==this.#l)return;if(c.state!=="running")throw t?new Error(this.#C=`${Lu} Tap the mic to reconnect.`):new Error("Audio blocked until a tap")}let p=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new Ra(eI);if(s!==this.#l){p.destroy(),i.getTracks().forEach(f=>f.stop()),c.close().catch(()=>{});return}this.#i=p,this.#ge(),this.#B(c,i,s);let d=await this.#pe();if(s!==this.#l){d?.ws.close(1e3,"client ended call");return}if(d){let{ws:f}=d;this.#e=f,this.#ie(f,s),d.live||f.send('{"type":"start"}'),this.#I(f),this.#y("listening");return}let g=new WebSocket(this.#se(r,n),["runtype.bearer",o]);g.binaryType="arraybuffer",this.#e=g,g.onopen=()=>{s===this.#l&&(this.#I(g),this.#y("listening"))},this.#ie(g,s)}catch(i){throw this.#ee(),this.#ae(i),this.#y("error"),i}}#ie(t,n){t.onmessage=o=>this.#L(o,n),t.onerror=()=>{n!==this.#l||this.#T||(this.#ae(new Error("Voice connection failed")),this.#y("error"),this.#ee())},t.onclose=o=>{if(this.#a){this.#a=!1;return}if(n!==this.#l)return;let r=this.#T??(o.code===4408?{reason:"idle_timeout"}:null);if(!r){if(o.code!==1e3){let s=o.code?` (code ${o.code})`:"";this.#ae(new Error(`Voice connection closed${s}`)),this.#y("error")}else this.#y("idle");this.#ee();return}this.#V(r.reason,r.message)}}#V(t,n){let o=Zx.includes(t)&&!this.#Y;if(this.#ee(),o){this.#Y=!0,this.#u=!0,this.#C=t==="provider_error"?`${Lu} Reconnecting\u2026`:"Reconnecting\u2026",this.#R=setTimeout(()=>{this.#u=!1,this.#z=!0,this.startListening().catch(()=>{})},1e3+Math.random()*1e3),this.#y("idle");return}if(Zx.includes(t))return this.#C=Lu,this.#ae(new Error(Lu)),this.#y("error");if(t==="error")return this.#y("error");this.#C=t==="quota"&&n||bI.get(t)||null,this.#y("idle")}takeNotice(){let t=this.#C;return this.#C=null,t}getDisclosure(){let t=this.config?.disclosureText;return this.#u&&this.#A&&t!==!1?t||yI:null}async stopListening(){this.#ee(),this.#y("idle")}async disconnect(){this.#ee(),this.#y("disconnected"),this.#K=[],this.#G=[],this.#oe=[],this.#U=[],this.#_=[]}stopPlayback(){this.#Z();let t=this.#e;t&&t.readyState===WebSocket.OPEN&&(this.#A&&(this.#x=Date.now()+gI,t.send('{"type":"cancel"}')),this.#y("listening"))}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.#u}onLevel(t){this.#o.push(t)}async deactivateBargeIn(){this.#ee(),this.#y("idle")}#B(t,n,o){let r=t.createMediaStreamSource(n);this.#s=r;let s=t.createScriptProcessor(tI,1,1);this.#r=s,s.onaudioprocess=i=>{if(o!==this.#l)return;let l=this.#e,c=l?.readyState===WebSocket.OPEN;if(l&&!c&&l.readyState!==WebSocket.CONNECTING)return;let p=i.inputBuffer.getChannelData(0),d=new Int16Array(p.length),g=0;for(let f=0;f<p.length;f++){let h=Math.max(-1,Math.min(1,p[f]));g+=h*h,d[f]=h<0?h*32768:h*32767}if(l&&c)this.#I(l),l.send(d.buffer);else for(this.#p.push(d.buffer),this.#f+=d.byteLength;this.#f>nI;)this.#f-=this.#p.shift().byteLength;if(this.#o.length>0){let f=Math.sqrt(g/p.length),h=Math.max(0,Math.min(1,f*oI));for(let y of this.#o)y(h)}},r.connect(s),s.connect(t.destination)}#I(t){for(let n of this.#p)t.send(n);this.#p=[],this.#f=0}#L(t,n){if(n!==this.#l)return;if(t.data instanceof ArrayBuffer){this.#Ee(t.data,n);return}let o;try{o=JSON.parse(t.data)}catch{return}switch(o.type){case"session_config":o.speechMode&&(this.#A=o.speechMode==="speech_to_speech",this.#i?.setContinuousMode?.(this.#A)),Array.isArray(o.capabilities)&&(this.#E=new Set(o.capabilities)),typeof o.callId=="string"&&(this.#H=o.callId),this.#S=this.#A&&this.#E.has("client_delegation")&&!!this.bridge,this.#A&&!this.#c&&this.#y("listening"),this.#E.has("context")&&!this.#$&&(this.#$=!0,this.#P=this.#j());break;case"transcript_update":{let r=o.role==="assistant"?"assistant":"user",s=o.utteranceId??o.turnId;if(!s||r==="assistant"&&this.#ve())break;let i=String(s);if(r==="user")o.final===!0&&this.#J(n),this.#Q=!1;else{if(this.#E.has("delegation_read_back")){let l=o.delegationId;typeof l=="string"&&this.#D.has(l)&&!this.#ne.has(i)&&this.#O.add(i)}else this.#Q&&!this.#ne.has(i)&&(this.#O.add(i),this.#Q=!1);if(this.#ne.add(i),this.#O.has(i))break}this.#Se(r,o.text??"",o.final===!0,{turnId:i,...typeof o.startMs=="number"&&{startMs:o.startMs},...typeof o.endMs=="number"&&{endMs:o.endMs},...this.#S&&{caption:!0}});break}case"delegation_started":case"delegation_completed":{let r=String(o.delegationId??o.turnId);if(o.type==="delegation_started"){this.#J(n);let s=o.input;this.#S&&s&&this.#xe(r,{delegationId:r,userText:String(s.text??""),userUtteranceIds:Array.isArray(s.userUtteranceIds)?s.userUtteranceIds.filter(i=>typeof i=="string"):[],messages:Array.isArray(s.messages)?s.messages:[]},n)}else o.speak!==!1&&this.#D.has(r)&&(this.#Q=!0);this.#w=o.type==="delegation_started",!this.#c&&!this.#ve()&&this.#y(this.#w?"processing":"listening");break}case"delegation_cancelled":this.#ue(String(o.delegationId),o.reason!=="session_ending"&&o.reason!=="provider_cancelled");break;case"warning":console.warn(`[Persona voice] ${o.code}: ${o.message??""}`,this.#H??""),o.delegationId&&(o.code==="UNKNOWN_DELEGATION"||o.code==="LATE_RESULT_LIMIT")&&this.#ue(String(o.delegationId));break;case"audio_clear":this.#Z(),this.#x=0,this.#y("listening");break;case"transcript_interim":this.#y("listening"),this.#Se("user",o.text??"",!1);break;case"transcript_final":{let r=o.role==="assistant"?"assistant":"user";this.#y(r==="user"?"processing":"speaking"),this.#Se(r,o.text??"",!0);break}case"audio_end":this.#i?this.#i.markStreamEnd():(this.#c=!1,this.#y("listening"));break;case"metrics":this.#ke({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.#ae(new Error(o.error||"Voice error")),this.#y("error");break;case"session_end":this.#T={reason:String(o.reason),...typeof o.message=="string"&&{message:o.message}};break}}async#j(){let t=this.bridge?.getHistory()??[],n="";try{let o=this.config?.callContext;n=String((typeof o=="function"?await o():o)??"")}catch{}return SI(t,n)}#J(t){let n=this.#P;if(!n)return;this.#P=null;let o=!1,r=n.then(s=>{let i=this.#e;o||!s||t!==this.#l||i?.readyState!==WebSocket.OPEN||i.send(JSON.stringify({type:"context",text:s}))});this.#X={done:r,drop:()=>o=!0}}async#Pe(){let t=this.#X;if(!t)return;let n,o=await Promise.race([t.done.then(()=>!1),new Promise(r=>{n=setTimeout(()=>r(!0),fI)})]);clearTimeout(n),o&&t.drop()}#ue(t,n=!1){this.#v.add(t),this.bridge?.dropDelegation?.(t,n),this.#b.get(t)?.abort()}#xe(t,n,o){let r=this.bridge,s=(i,l,c)=>{let p=this.#e;return o!==this.#l||p?.readyState!==WebSocket.OPEN||this.#v.has(t)?!1:(p.send(JSON.stringify({type:i,delegationId:t,status:l,text:c})),!0)};this.#W=this.#W.then(async()=>{if(o!==this.#l||this.#v.has(t))return;let i=await r.runDelegatedTurn(n).catch(()=>({status:"failed",text:""}));await this.#Pe();let l=!!i.followUp,c=l&&this.#E.has("delegation_update");if(!s(c?"delegation_update":"delegation_result",l&&!c?"completed":i.status,i.text)||(i.status!=="failed"&&i.inChat!==!1&&this.#D.add(t),!i.followUp))return;let d=new AbortController;this.#b.set(t,d),i.followUp({signal:d.signal,approvalTimeoutMs:this.config?.approvalTimeoutMs&&Math.min(this.config.approvalTimeoutMs,hI),readBack:c,onUpdate:g=>s("delegation_update","pending_approval",g)}).then(g=>{this.#b.delete(t),c&&g&&!d.signal.aborted&&s("delegation_result",g.status,g.text)})})}#Ee(t,n){if(n!==this.#l||!this.#i||this.#ve())return;let o=AI(t);o.length!==0&&(this.#c||(this.#c=!0,this.#y("speaking")),this.#ge(),this.#i.enqueue(o),this.#A&&this.#Ce(o.length))}#ve(){return Date.now()<this.#x}#ge(){if(this.#m||!this.#i)return;this.#m=!0;let t=this.#l;this.#i.onFinished(()=>{t===this.#l&&(this.#m=!1,this.#we())})}#Ce(t){let n=Date.now();this.#d=Math.max(n,this.#d)+t/48,clearTimeout(this.#g),this.#g=setTimeout(()=>this.#we(),this.#d-n+uI)}#we(){this.#c=!1,this.#d=0,this.#e&&this.#e.readyState===WebSocket.OPEN&&this.#y(this.#w?"processing":"listening")}#Z(){this.#i?.flush(),this.#m=!1,this.#ge(),this.#c=!1,this.#d=0,clearTimeout(this.#g)}#ee(){this.#l+=1,this.#u=!1,this.#c=!1,this.#re(),this.#A=!1,this.#w=!1,this.#S=!1,this.#E=new Set;for(let t of this.#b.values())t.abort();if(this.#b.clear(),this.#v.clear(),this.#H=void 0,this.#T=null,clearTimeout(this.#R),this.#$=!1,this.#P=null,this.#X=null,this.#W=Promise.resolve(),this.#D.clear(),this.#Q=!1,this.#ne.clear(),this.#O.clear(),this.#m=!1,this.#x=0,this.#d=0,clearTimeout(this.#g),this.#p=[],this.#f=0,this.#r&&(this.#r.onaudioprocess=null,this.#r.disconnect(),this.#r=null),this.#s&&(this.#s.disconnect(),this.#s=null),this.#t&&(this.#t.getTracks().forEach(t=>t.stop()),this.#t=null),this.#n&&(this.#n.close().catch(()=>{}),this.#n=null),this.#i&&(this.#i.destroy(),this.#i=null),this.#e){this.#a=!0;try{this.#e.close(1e3,"client ended call")}catch{}this.#e=null}}onResult(t){this.#K.push(t)}onError(t){this.#G.push(t)}onStatusChange(t){this.#oe.push(t)}onTranscript(t){this.#U.push(t)}onMetrics(t){this.#_.push(t)}#y(t){this.#oe.forEach(n=>n(t))}#ae(t){this.#G.forEach(n=>n(t))}#Se(t,n,o,r){this.#U.forEach(s=>s(t,n,o,r))}#ke(t){this.#_.forEach(n=>n(t))}};var Oi=class{constructor(t={}){this.config=t;this.type="browser";this.#e=null;this.#n=[];this.#o=[];this.#t=[];this.#s=!1;this.#r=typeof window<"u"?window:void 0}#e;#n;#o;#t;#s;#r;async connect(){this.#t.forEach(t=>t("connected"))}async startListening(){try{if(this.#s)throw new Error("Already listening");if(!this.#r)throw new Error("Window object not available");let t=this.#r.SpeechRecognition||this.#r.webkitSpeechRecognition;if(!t)throw new Error("Browser speech recognition not supported");this.#e=new t,this.#e.lang=this.config?.language||"en-US",this.#e.continuous=this.config?.continuous||!1,this.#e.interimResults=!0,this.#e.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.#n.forEach(s=>s({text:o,confidence:r?.8:.5,provider:"browser"})),r&&!this.config?.continuous&&this.stopListening()},this.#e.onerror=n=>{this.#o.forEach(o=>o(new Error(n.error))),this.#t.forEach(o=>o("error"))},this.#e.onstart=()=>{this.#s=!0,this.#t.forEach(n=>n("listening"))},this.#e.onend=()=>{this.#s=!1,this.#t.forEach(n=>n("idle"))},this.#e.start()}catch(t){throw this.#o.forEach(n=>n(t)),this.#t.forEach(n=>n("error")),t}}async stopListening(){this.#e&&(this.#e.stop(),this.#e=null),this.#s=!1,this.#t.forEach(t=>t("idle"))}onResult(t){this.#n.push(t)}onError(t){this.#o.push(t)}onStatusChange(t){this.#t.push(t)}async disconnect(){await this.stopListening(),this.#t.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Xa(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Cc(e.runtype);case"browser":if(!Oi.isSupported())throw new Error("Browser speech recognition not supported");return new Oi(e.browser||{});case"custom":{let t=e.custom;if(!t)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof t=="function"?t():t;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: ${e.type}`)}}function Hu(e){if(e?.type==="custom"&&e.custom)return Xa({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return Xa({type:"runtype",runtype:e.runtype});if(Oi.isSupported())return Xa({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function Fh(e){try{return Hu(e),!0}catch{return!1}}var nE="webmcp:",MI=e=>e.startsWith(nE)?e.slice(nE.length):e,Iu={warn(e,...t){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},Wu=class{constructor(t,n){this.config=t;this.#r=n,this.#e=t.onConfirm??null,this.#n=3e4}#e;#n;#o=!1;#t=null;#s=!1;#r;setConfirmHandler(t){this.#e=t}isOperational(){return this.config.enabled!==!0||!this.#o?!1:this.#i()!==null}async snapshotForDispatch(){if(await this.#p(),this.config.enabled!==!0)return[];let t=this.#i();if(!t)return[];let n;try{n=await t.getTools()}catch(r){return Iu.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}this.#r.recordToolDisplayTitles(n);let o=typeof location<"u"?location.origin:"";return n.filter(r=>this.#c(r.name)).map(r=>{let s=PI(r.annotations);return{name:r.name,description:r.description,parametersSchema:kI(r.inputSchema),origin:"webmcp",...o?{pageOrigin:o}:{},...s?{annotations:s}:{},...s?.untrustedContentHint===!0?{untrustedContentHint:!0}:{}}})}async executeToolCall(t,n,o){if(await this.#p(),this.config.enabled!==!0)return $o("WebMCP is not enabled on this widget.");let r=this.#i();if(!r){let y=typeof document<"u"&&!!document.modelContext;return $o(y?"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=MI(t),i;try{i=await r.getTools()}catch(y){let v=y instanceof Error?y.message:String(y);return $o(`Failed to read WebMCP registry: ${v}`)}this.#r.recordToolDisplayTitles(i);let l=i.find(y=>y.name===s);if(!l)return $o(`WebMCP tool not registered on this page: ${s}`);if(!this.#c(s))return $o(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return $o("Aborted by cancel()");let c=this.#r.getToolDisplayTitle(s),p={toolName:s,args:n,description:l.description,...c?{title:c}:{},reason:"gate"};if(!await this.#u(p))return $o("User declined the tool call.");if(o?.aborted)return $o("Aborted by cancel()");let d=new AbortController,g=!1,f=setTimeout(()=>{g=!0,d.abort()},this.#n),h=()=>d.abort();o&&(o.aborted?d.abort():o.addEventListener("abort",h,{once:!0}));try{let y=await r.executeTool(l,RI(n),{signal:d.signal});return LI(y)}catch(y){if(g)return $o(`WebMCP tool '${s}' timed out after ${this.#n}ms`);if(o?.aborted)return $o("Aborted by cancel()");let v=y instanceof Error?y.message:String(y);return $o(v)}finally{clearTimeout(f),o&&o.removeEventListener("abort",h)}}#p(){return this.config.enabled!==!0?Promise.resolve():(this.#t||(this.#t=this.#f()),this.#t)}async#f(){try{if(this.#i()){this.#o=!0;return}(await this.#r.loadPolyfill()).initializeWebMCPPolyfill(),this.#o=!0}catch(t){Iu.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",t),this.#o=!1}}#i(){if(typeof document>"u")return null;let t=document.modelContext;if(!t||typeof t!="object")return null;let n=t;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.#s||(this.#s=!0,Iu.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):t}async#u(t){let n=this.#e??HI;try{return await n(t)}catch(o){return Iu.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,o),!1}}#c(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(o=>TI(t,o))}},TI=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Ru={type:"object",properties:{}},PI=e=>{if(!e||typeof e!="object")return;let t={...typeof e.readOnlyHint=="boolean"?{readOnlyHint:e.readOnlyHint}:{},...typeof e.untrustedContentHint=="boolean"?{untrustedContentHint:e.untrustedContentHint}:{}};return Object.keys(t).length>0?t:void 0},kI=e=>{if(e===void 0||e==="")return{...Ru};if(typeof e=="object")return e!==null&&!Array.isArray(e)?e:{...Ru};try{let t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:{...Ru}}catch{return{...Ru}}},LI=e=>{if(e==null)return{content:[{type:"text",text:""}]};let t;try{t=JSON.parse(e)}catch{return{content:[{type:"text",text:e}]}}return t!==null&&typeof t=="object"&&Array.isArray(t.content)?t:{content:[{type:"text",text:typeof t=="string"?t:WI(t)}]}},$o=e=>({isError:!0,content:[{type:"text",text:e}]}),HI=async e=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let t=II(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
|
|
482
482
|
|
|
483
483
|
Arguments:
|
|
484
484
|
${t}`:"")+(e.description?`
|
|
485
485
|
|
|
486
|
-
${e.description}`:"");return window.confirm(n)},
|
|
486
|
+
${e.description}`:"");return window.confirm(n)},II=e=>{if(e==null)return"";try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+"\u2026":t}catch{return String(e)}},RI=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},WI=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};pi();var Ou=class extends Wu{constructor(t){super(t,{recordToolDisplayTitles:Sd,getToolDisplayTitle:ma,loadPolyfill:Ad})}};function OI(e,t){if(!e)return!0;let n=0;for(let o=0;o<t.length&&n<e.length;o++)t[o]===e[n]&&n++;return n===e.length}function _I(e,t){let n=e.toLowerCase(),o=t.toLowerCase();return n.startsWith(o)?0:e.replace(/([a-z])([A-Z])/g,"$1 $2").split(/[\s\-_/.]+/).some(s=>s.toLowerCase().startsWith(o))?1:OI(o,n)?2:3}function oE(e,t){let n=e.recencyScore??0,o=t.recencyScore??0;return o!==n?o-n:e.label.localeCompare(t.label)}function _u(e,t){let n=t.trim();if(!n)return[...e].sort(oE);let o=[];for(let r of e){let s=_I(r.label,n);s!==3&&o.push({item:r,tier:s})}return o.sort((r,s)=>r.tier!==s.tier?r.tier-s.tier:oE(r.item,s.item)),o.map(r=>r.item)}function BI(e){let t=e.replace(/^\s+/,""),n=t.search(/\s/);return n===-1?{name:t,args:""}:{name:t.slice(0,n),args:t.slice(n+1).trim()}}function rE(e){return{id:e.id,label:e.label,resolveOn:e.resolveOn,search:t=>_u(e.items,t),resolve:e.resolve}}function sE(e){let t=e.commands.map(r=>({id:r.name,label:r.name,description:r.description,iconName:r.iconName,command:r.kind??"prompt",insertMode:r.insertMode,submitOnSelect:r.submitOnSelect,action:r.action,commandArgsPlaceholder:r.argsPlaceholder})),n=new Map(e.commands.map(r=>[r.name,r])),o=new Map(t.map(r=>[r.id,r]));return{id:e.id,label:e.label,matchCommand:r=>o.get(r),resolveOn:"submit",search:r=>_u(t,BI(r).name),resolve:(r,s)=>{let i=n.get(r.id);return i?i.kind==="server"?{context:(typeof i.data=="function"?i.data(s.args):i.data)??{}}:{insertText:typeof i.prompt=="function"?i.prompt(s.args):i.prompt??""}:{}}}}function iE(e,t){let n=t.orientation??"horizontal",o=n==="vertical"?"ArrowUp":"ArrowLeft",r=n==="vertical"?"ArrowDown":"ArrowRight";e.setAttribute("role","tablist");let s=[],i=!1,l=g=>{typeof g.scrollIntoView=="function"&&g.scrollIntoView({block:"nearest",inline:"nearest"})},c=g=>{let f=g;return s.findIndex(h=>h===f||h.contains(f))},p=g=>{let f=c(g.target);if(f<0)return;let h=f;if(g.key===r)h=Math.min(f+1,s.length-1);else if(g.key===o)h=Math.max(f-1,0);else if(g.key==="Home")h=0;else if(g.key==="End")h=s.length-1;else return;g.preventDefault(),h!==f&&t.onSelect(h)},d=g=>{let f=c(g.target);f>=0&&l(s[f])};return e.addEventListener("keydown",p),e.addEventListener("focusin",d),{beforeRender(){i=typeof document<"u"&&e.contains(document.activeElement)},render(g,f){if(s=g,g.forEach((h,y)=>{h.setAttribute("role","tab");let v=y===f;h.setAttribute("aria-selected",v?"true":"false"),h.tabIndex=v||f<0&&y===0?0:-1}),i){let h=(f>=0?g[f]:void 0)??g[0];h&&typeof h.focus=="function"&&(l(h),h.focus())}},destroy(){e.removeEventListener("keydown",p),e.removeEventListener("focusin",d)}}}0&&(module.exports={ASK_USER_QUESTION_CLIENT_TOOL,ASK_USER_QUESTION_PARAMETERS_SCHEMA,ASK_USER_QUESTION_TOOL_NAME,AgentWidgetClient,AgentWidgetSession,AttachmentManager,BrowserSpeechEngine,DEFAULT_COMPONENTS,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,DEFAULT_FLOATING_LAUNCHER_WIDTH,DEFAULT_PALETTE,DEFAULT_SEMANTIC,DEFAULT_WIDGET_CONFIG,HistoryProviderError,PRESETS,PRESET_FULLSCREEN,PRESET_MINIMAL,PRESET_SHOP,ReadAloudController,SUGGEST_REPLIES_CLIENT_TOOL,SUGGEST_REPLIES_PARAMETERS_SCHEMA,SUGGEST_REPLIES_TOOL_NAME,THEME_ZONES,VERSION,WEBMCP_TOOL_PREFIX,WebMcpBridge,accessibilityPlugin,animationsPlugin,applyFeaturePreferences,applyThemeVariables,attachHeaderToContainer,brandPlugin,buildComposer,buildDefaultHeader,buildHeader,buildHeaderWithLayout,buildMinimalHeader,builtInClientToolsForDispatch,canonicalArtifactDisplayMode,collectEnrichedPageContext,componentRegistry,createActionManager,createAgentExperience,createAskUserQuestionBubble,createBestAvailableVoiceProvider,createBubbleWithLayout,createCSATFeedback,createComboButton,createComponentMiddleware,createComponentStreamParser,createDefaultSanitizer,createDemoCarousel,createDirectivePostprocessor,createDropdownMenu,createFlexibleJsonStreamParser,createIconButton,createImagePart,createJsonStreamParser,createLabelButton,createLocalStorageAdapter,createMarkdownProcessor,createMarkdownProcessorFromConfig,createMessageActions,createNPSFeedback,createPlainTextParser,createPlugin,createRegexJsonParser,createRovingTablist,createSlashCommandsSource,createSplitButton,createStandardBubble,createStaticMentionSource,createTextPart,createTheme,createThemeObserver,createToggleGroup,createTypingIndicator,createVoiceProvider,createWidgetHostLayout,createXmlParser,defaultActionHandlers,defaultJsonActionParser,defaultMentionFilter,defaultParseRules,detectColorScheme,directivePostprocessor,ensureAskUserQuestionSheet,escapeHtml,extractComponentDirectiveFromMessage,fileToImagePart,formatEnrichedContext,generateAssistantMessageId,generateCodeSnippet,generateMessageId,generateStableSelector,generateUserMessageId,getActiveTheme,getAgentWidgetHandles,getColorScheme,getDisplayText,getHeaderLayout,getImageParts,getPreset,hasComponentDirective,hasImages,headerLayouts,highContrastPlugin,initAgentWidget,isAskUserQuestionMessage,isComponentDirectiveType,isDockedMountMode,isHistoryProviderError,isSuggestRepliesMessage,isVoiceSupported,isWebMcpToolName,isWelcomeVisible,latestAgentSuggestions,listRegisteredStreamAnimations,loadMarkdownParsers,markdownPostprocessor,mergeWithDefaults,normalizeContent,normalizeMediaType,onMarkdownParsersReady,parseAskUserQuestionPayload,parseSuggestRepliesPayload,parseWidgetPreferenceSlice,pickBestVoice,pluginRegistry,reducedMotionPlugin,registerIcons,registerStreamAnimationPlugin,removeAskUserQuestionSheet,renderComponentDirective,renderLoadingIndicatorWithFallback,renderLucideIcon,resolveArtifactDisplay,resolveArtifactDisplayMode,resolveConfigPreferences,resolveDockConfig,resolveSanitizer,resolveTokens,resolveWelcomeConfig,stripWebMcpPrefix,themeToCssVariables,unregisterStreamAnimationPlugin,validateImageFile,validateTheme});
|
|
487
487
|
//# sourceMappingURL=index.cjs.map
|