@runtypelabs/persona 4.26.0 → 4.26.1

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.
Files changed (48) hide show
  1. package/dist/approval-ui.d.cts +6 -0
  2. package/dist/approval-ui.d.ts +6 -0
  3. package/dist/artifacts-ui.d.cts +6 -0
  4. package/dist/artifacts-ui.d.ts +6 -0
  5. package/dist/chunk-GKPCIQPB.js +1 -0
  6. package/dist/{client-history-YPEG45Q4.js → client-history-GOZWBDA5.js} +1 -1
  7. package/dist/client-history.js +1 -1
  8. package/dist/codegen.cjs +1 -1
  9. package/dist/codegen.js +1 -1
  10. package/dist/context-mentions.d.cts +6 -0
  11. package/dist/context-mentions.d.ts +6 -0
  12. package/dist/event-stream-view.d.cts +6 -0
  13. package/dist/event-stream-view.d.ts +6 -0
  14. package/dist/forms-ui.d.cts +6 -0
  15. package/dist/forms-ui.d.ts +6 -0
  16. package/dist/index.cjs +7 -7
  17. package/dist/index.cjs.map +1 -1
  18. package/dist/index.d.cts +6 -0
  19. package/dist/index.d.ts +6 -0
  20. package/dist/index.global.js +1 -1
  21. package/dist/index.global.js.map +1 -1
  22. package/dist/index.js +7 -7
  23. package/dist/index.js.map +1 -1
  24. package/dist/session-reconnect.d.cts +6 -0
  25. package/dist/session-reconnect.d.ts +6 -0
  26. package/dist/smart-dom-reader.d.cts +6 -0
  27. package/dist/smart-dom-reader.d.ts +6 -0
  28. package/dist/theme-editor-preview.cjs +14 -14
  29. package/dist/theme-editor-preview.d.cts +6 -0
  30. package/dist/theme-editor-preview.d.ts +6 -0
  31. package/dist/theme-editor-preview.js +5 -5
  32. package/dist/theme-editor.d.cts +6 -0
  33. package/dist/theme-editor.d.ts +6 -0
  34. package/dist/voice-runtime-XLU6YK2N.js +17 -0
  35. package/dist/voice-runtime.cjs +3 -3
  36. package/dist/voice-runtime.d.cts +6 -0
  37. package/dist/voice-runtime.d.ts +6 -0
  38. package/dist/voice-runtime.js +3 -3
  39. package/package.json +1 -1
  40. package/src/approval-paused-tool-settle.test.ts +108 -4
  41. package/src/session.ts +51 -10
  42. package/src/session.voice.test.ts +1 -0
  43. package/src/types.ts +6 -0
  44. package/src/voice/runtype-voice-provider.ts +19 -9
  45. package/src/voice/voice-delegation.ts +1 -1
  46. package/src/voice/voice.test.ts +81 -2
  47. package/dist/chunk-QPPJUSZH.js +0 -1
  48. package/dist/voice-runtime-UOQOFAFY.js +0 -17
package/dist/index.js CHANGED
@@ -4,28 +4,28 @@ var RM=Object.defineProperty;var $e=(e,t)=>()=>(e&&(t=e(e=0)),t);var Qs=(e,t)=>{
4
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()=>{}}},dl=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Sg=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Ag=()=>{let e=cP();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)}},xg=()=>{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=Pb(n,kb|Lb);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?Zc(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=Zc(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},dP=e=>{let t=null,n=0,r=e||(s=>{if(!s||typeof s!="object")return null;let i=l=>typeof l=="string"?Zc(l):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Zc(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=Pb(s,kb|Lb),c=r(l);c!==null&&(t=c)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},Mg=()=>{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,X,Wn,Xe=$e(()=>{"use strict";x=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},X=(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},Wn=(...e)=>e.filter(Boolean).join(" ")});import{parse as pP,ARR as uP,OBJ as gP,STR as fP}from"partial-json";var od,pl,Qi,mP,hP,Ob,Bb,yP,bP,vP,CP,wP,Eg,Tg,_b,Pg,Db,SP,AP,Wb,Nb,is,rd,as,ul,xP,MP,Fb,$b,EP,TP,PP,Ub,kP,LP,ni,Vb,yo,HP,Ji,ls,IP,RP,sd,jb,qb,kg,WP,OP,BP,Lg,cs,Hg,ds,id,gl=$e(()=>{"use strict";Xe();od="ask_user_question",pl=8,Qi="data-persona-ask-sheet-for",mP="Other",hP="Other\u2026",Ob="Type your own answer here",Bb="Send",yP="Next",bP="Back",vP="Submit all",CP="Skip",wP=3,Eg="data-ask-current-index",Tg="data-ask-question-count",_b="data-ask-answers",Pg="data-ask-grouped",Db="data-ask-layout",SP=e=>e.layout==="pills"?"pills":"rows",AP=e=>e.getAttribute(Db)==="pills"?"pills":"rows",Wb=!1,Nb=e=>e.replace(/["\\]/g,"\\$&"),is=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===od,rd=e=>e?.features?.askUserQuestion??{},as=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=pP(r,fP|gP|uP);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},ul=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>pl&&!Wb&&(Wb=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${pl}.`)),t.slice(0,pl)},xP=e=>ul(e)[0]??null,MP=(e,t)=>ul(e)[t]??null,Fb=(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))},$b=(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},EP=(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=$b(n,o,t);c&&s.appendChild(c)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},TP=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},PP=(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<wP;d++)s.appendChild(TP(o));return s}if(c.forEach((d,g)=>{s.appendChild(EP(d,g,o,i))}),e?.allowFreeText!==!1){let d=o==="rows"?mP:hP;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??Ob,h.setAttribute("data-ask-free-text-input","true"),h.setAttribute("aria-label",t.freeTextLabel??d),f.appendChild(h),g.appendChild(f);let y=$b(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},Ub=(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??Ob,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??Bb,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},kP=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??Bb,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},LP=(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??bP,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??CP,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??vP:n.nextLabel??yP,l.setAttribute("data-ask-user-action",c?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},ni=e=>{let t=e.getAttribute(_b);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Vb=(e,t)=>{e.setAttribute(_b,JSON.stringify(t))},yo=e=>{let t=Number(e.getAttribute(Eg)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},HP=(e,t)=>{e.setAttribute(Eg,String(Math.max(0,Math.floor(t))))},Ji=e=>{let t=Number(e.getAttribute(Tg)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},ls=e=>e.getAttribute(Pg)==="true",IP=(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},RP=(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)))},sd=(e,t)=>{let{payload:n}=as(t),o=ul(n),r=ni(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},jb=e=>{let t=ni(e),n=yo(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="")},qb=e=>{if(!ls(e))return;let t=ni(e),n=yo(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}},kg=(e,t,n)=>{let o=rd(n),r=AP(e),{payload:s,complete:i}=as(t),l=ls(e),c=yo(e),p=Ji(e),d=l?MP(s,c):xP(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=PP(d,o,i,r);v.replaceWith(L)}if(r!=="rows"){let L=e.querySelector('[data-ask-free-text-row="true"]');L&&L.replaceWith(Ub(o,r))}let C=e.querySelector('[data-ask-multi-actions="true"]');!l&&g&&!C?e.appendChild(kP(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=LP(c,p,o);A?A.replaceWith(L):e.appendChild(L)}else A&&A.remove();jb(e),qb(e)},WP=(e,t,n)=>{let o=rd(t),r=SP(o),s=e.toolCall.id,i=ul(n),l=Math.max(1,i.length),c=l>1,p=IP(e,i),d=c?RP(e,l):0,g=x("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));g.setAttribute(Qi,s),g.setAttribute("data-tool-call-id",s),g.setAttribute("data-message-id",e.id),g.setAttribute(Tg,String(l)),g.setAttribute(Eg,String(d)),g.setAttribute(Pg,c?"true":"false"),g.setAttribute(Db,r),Vb(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`),Fb(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(Ub(o,r)),kg(g,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>g.classList.remove("persona-ask-sheet-enter"))}),g},OP=(e,t,n)=>{let{payload:o}=as(t),r=Math.max(1,ul(o).length);r>Ji(e)&&(e.setAttribute(Tg,String(r)),r>1&&!ls(e)&&e.setAttribute(Pg,"true")),kg(e,t,n)},BP=(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=rd(t);Fb(n,o);let r=x("span","persona-ask-stub-label"),{complete:s}=as(e);return r.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(r),n},Lg=(e,t,n)=>{if(!n||!is(e)||rd(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${Qi}]`).forEach(p=>{p.getAttribute(Qi)!==r&&p.remove()});let i=n.querySelector(`[${Qi}="${Nb(r)}"]`);if(i){OP(i,e,t);return}let{payload:l}=as(e),c=WP(e,t,l);n.appendChild(c)},cs=(e,t)=>{if(!e)return;let n=t?`[${Qi}="${Nb(t)}"]`:`[${Qi}]`;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)})},Hg=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),ds=(e,t)=>{let n=ni(e),o=yo(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,Vb(e,n),jb(e),qb(e)},id=(e,t,n,o)=>{let r=Ji(e),s=Math.max(0,Math.min(r-1,o));HP(e,s),kg(e,t,n)}});var Xo,Kb,Ig,Gb,Zi,Yb,Rg,zb,_P,ps,ea=$e(()=>{"use strict";Xo="suggest_replies",Kb={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},Ig={name:Xo,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:Kb,origin:"sdk",annotations:{readOnlyHint:!0}},Gb=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Zi=e=>e.variant==="tool"&&e.toolCall?.name===Xo,Yb=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},Rg=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!Zi(n))continue;let o=Yb(n.toolCall?.args);return o.length>0?o:null}return null},zb=new Set,_P=(e,t,n)=>{let o=`${e}:${t}:${n}`;zb.has(o)||(zb.add(o),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},ps=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&&_P(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 Xb,Qb,ta,ad=$e(()=>{"use strict";gl();ea();Xb={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:pl,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},Qb={name:od,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:Xb,origin:"sdk",annotations:{readOnlyHint:!0}},ta=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(Qb),ps(e).expose&&t.push(Ig),t}});var Kt,Tn,na,ld,Lo=$e(()=>{"use strict";Kt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},Tn=1e5,na=Tn+1,ld="https://api.runtype.com"});async function Jb(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 Zb(e,t,n,o){let r=e.isClientTokenMode(),s=r?e.getClientApiUrl("resume"):`${e.config.apiUrl?.replace(/\/+$/,"")||ld}/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=[...ta(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 ev=$e(()=>{"use strict";ad();Lo()});var cd={};Qs(cd,{preferFinalStructuredContent:()=>nv,resolveApproval:()=>Jb,resumeFlow:()=>Zb,streamResponse:()=>FP});function DP(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 nv(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=tv(n);if(!tv(o))return e;if(!r||o===n||o.startsWith(n))return t;let i=dl(e);return dl(t)!==null&&i===null?t:e}async function NP(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 FP(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,te=new Map,W=new Map,j=o,Y=!1,E=()=>{if(y)return y;let D,S="",F=L;return!Y&&j?(D=j,Y=!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=te.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 te.set(D,F),h(F),F},B=new Set,P=new Map,Q=new Set,U=new Map,de=D=>{if(!D)return!1;let S=D.replace(/_+/g,"_").replace(/^_|_$/g,"");return S==="emit_artifact_markdown"||S==="emit_artifact_component"},pe=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},ge=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()},ke=D=>{if(typeof D=="string")return D;if(D==null)return"";try{return JSON.stringify(D)}catch{return String(D)}},xe=new Map,Le=new Map,mt=(D,S)=>{let F=ke(S),z=Le.get(D.id),K=nv(z,F);D.rawContent=K;let Z=xe.get(D.id),ye=Be=>{let Ge=D.content??"";Be.trim()!==""&&(Ge.trim().length===0||Be.startsWith(Ge)||Be.trimStart().startsWith(Ge.trim()))&&(D.content=Be)},be=()=>{if(Z){let Be=Z.close?.();Be instanceof Promise&&Be.catch(()=>{})}xe.delete(D.id),Le.delete(D.id),D.streaming=!1,h(D)};if(!Z){ye(F),be();return}let Ae=dl(K);if(Ae!==null&&Ae.trim()!==""){ye(Ae),be();return}let tt=Be=>{let Ge=typeof Be=="string"?Be:Be?.text??null;if(Ge!==null&&Ge.trim()!=="")return Ge;let cn=Z.getExtractedText();return cn!==null&&cn.trim()!==""?cn:F},bt;try{bt=Z.processChunk(K)}catch{ye(F),be();return}if(bt instanceof Promise){bt.then(Be=>{ye(tt(Be)),be()}).catch(()=>{ye(F),be()});return}ye(tt(bt)),be()},Ve=null,Re=(D,S,F,z)=>{D.rawContent=S,xe.has(D.id)||xe.set(D.id,e.createStreamParser());let K=xe.get(D.id),Z=S.trim().startsWith("{")||S.trim().startsWith("[");if(Z&&Le.set(D.id,S),K.__isPlainTextParser===!0){D.content=z!==void 0?S:D.content+F,Le.delete(D.id),xe.delete(D.id),D.rawContent=void 0,h(D);return}let be=K.processChunk(S);if(be instanceof Promise)be.then(Ae=>{let tt=typeof Ae=="string"?Ae:Ae?.text??null;tt!==null&&tt.trim()!==""?(D.content=tt,h(D)):!Z&&!S.trim().startsWith("<")&&(D.content=z!==void 0?S:D.content+F,Le.delete(D.id),xe.delete(D.id),D.rawContent=void 0,h(D))}).catch(()=>{D.content=z!==void 0?S:D.content+F,Le.delete(D.id),xe.delete(D.id),D.rawContent=void 0,h(D)});else{let Ae=typeof be=="string"?be:be?.text??null;Ae!==null&&Ae.trim()!==""?(D.content=Ae,h(D)):!Z&&!S.trim().startsWith("<")&&(D.content=z!==void 0?S:D.content+F,Le.delete(D.id),xe.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=Le.get(D.id)??ke(F);D.rawContent=K;let Z=xe.get(D.id),ye=null,be=!1;if(Z&&(ye=Z.getExtractedText(),ye===null&&(ye=dl(K)),ye===null)){let Ae=Z.processChunk(K);Ae instanceof Promise?(be=!0,Ae.then(tt=>{let bt=typeof tt=="string"?tt:tt?.text??null;bt!==null&&(D.content=bt,D.streaming=!1,xe.delete(D.id),Le.delete(D.id),h(D))}).catch(()=>{})):ye=typeof Ae=="string"?Ae:Ae?.text??null}if(!be){ye!==null&&ye.trim()!==""?D.content=ye:Le.has(D.id)||(D.content=ke(F));let Ae=xe.get(D.id);if(Ae){let tt=Ae.close?.();tt instanceof Promise&&tt.catch(()=>{}),xe.delete(D.id)}Le.delete(D.id),D.streaming=!1,h(D)}},We=(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},me=[],dt,Qt=new Map,St=0,Se="agent",It=!1,yt=null,Pe=null,Ke=e.config().iterationDisplay??"separate";for(dt=()=>{for(let D=0;D<me.length;D++){let S=me[D];if(!It&&Se!=="flow"&&typeof S.stepType=="string"&&(Se="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),We(F,z,"reasoning");continue}let K=S.id,Z=T(K);Z.reasoning=Z.reasoning??{id:K,status:"streaming",chunks:[]},Z.reasoning.startedAt=Z.reasoning.startedAt??Date.now(),Z.reasoning.completedAt=void 0,Z.reasoning.durationMs=void 0,(S.scope==="loop"||S.scope==="turn")&&(Z.reasoning.scope=S.scope),Z.streaming=!0,Z.reasoning.status="streaming",h(Z)}else if(S.type==="reasoning_delta"){let F=typeof S.id=="string"?S.id:null;if(F&&H.has(F)&&_.has(F)){let Z=_.get(F),ye=S.delta;ye&&Z.reasoning&&(Z.reasoning.chunks.push(String(ye)),h(Z));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 ye=_.get(F);if(ye.reasoning){let be=typeof S.text=="string"?S.text:"";be&&ye.reasoning.chunks.length===0&&ye.reasoning.chunks.push(be),ye.reasoning.status="complete",ye.streaming=!1,h(ye)}H.delete(F),_.delete(F);continue}let z=S.id,K=typeof S.text=="string"?S.text:"";!te.get(z)&&(K||S.scope==="loop")&&T(z);let Z=te.get(z);if(Z?.reasoning){(S.scope==="loop"||S.scope==="turn")&&(Z.reasoning.scope=S.scope),K&&Z.reasoning.chunks.length===0&&Z.reasoning.chunks.push(K),Z.reasoning.status="complete",Z.reasoning.completedAt=Date.now();let ye=Z.reasoning.startedAt??Date.now();Z.reasoning.durationMs=Math.max(0,(Z.reasoning.completedAt??Date.now())-ye),Z.streaming=!1,h(Z)}}else if(S.type==="tool_start"){y&&(y.streaming=!1,h(y),y=null),typeof S.iteration=="number"&&(St=S.iteration);let F=S.toolCallId,z=S.toolName;if(de(z)){B.add(F);continue}let K=pe(F),Z=K.toolCall??{id:F,status:"pending"};Z.name=z??Z.name,Z.status="running",Z.success=void 0,Z.error=void 0,Z.duration=void 0,S.parameters!==void 0&&(Z.args=S.parameters),Z.startedAt=Z.startedAt??ge(S.startedAt),Z.completedAt=void 0,Z.durationMs=void 0,K.toolCall=Z,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=pe(F),K=z.toolCall??{id:F,status:"running"};K.startedAt=K.startedAt??Date.now();let Z=S.delta;Z&&(K.chunks=K.chunks??[],K.chunks.push(String(Z))),K.status="running",z.toolCall=K,z.streaming=!0,S.executionId&&(z.agentMetadata=z.agentMetadata??{executionId:S.executionId,iteration:St}),h(z)}else if(S.type==="tool_complete"){let F=S.toolCallId;if(B.has(F)){B.delete(F);continue}let z=pe(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 Z=S.executionTime;if(typeof Z=="number")K.durationMs=Z,K.duration=Z;else{let ye=K.startedAt??Date.now();K.durationMs=Math.max(0,(K.completedAt??Date.now())-ye)}z.toolCall=K,z.streaming=!1,S.executionId&&(z.agentMetadata=z.agentMetadata??{executionId:S.executionId,iteration:S.iteration??St}),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=pe(z),Z=S.toolName,ye=S.origin==="webmcp"&&!Zs(Z)?`webmcp:${Z}`:Z,be=Zs(ye),Ae=K.toolCall??{id:z,status:"pending"};Ae.name=ye,Ae.args=S.parameters,Ae.status=be?"running":"complete",Ae.chunks=Ae.chunks??[],Ae.startedAt=Ae.startedAt??ge(S.awaitedAt),be?(Ae.completedAt=void 0,Ae.duration=void 0,Ae.durationMs=void 0):Ae.completedAt=Ae.completedAt??Ae.startedAt,K.toolCall=Ae,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&&(Se==="flow"?($(K),Ve=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 ye=typeof S.delta=="string"?S.delta:"",be=(V.get(F)??"")+ye;if(V.set(F,be),be.trim()==="")continue;let Ae=We(F,z);Ae.agentMetadata={...Ae.agentMetadata,executionId:S.executionId,parentToolId:z},Re(Ae,be,ye,void 0);continue}if(L=typeof S.id=="string"?S.id:L,Se==="flow"){let ye=typeof S.delta=="string"?S.delta:"";if(I+=ye,I.trim()==="")continue;let be=E();be.agentMetadata={executionId:S.executionId,iteration:St},Re(be,I,ye,void 0),v=be;continue}let K=typeof S.delta=="string"?S.delta:"";I+=K;let Z=E();Z.agentMetadata={executionId:S.executionId,iteration:St,turnId:yt??void 0,agentName:Pe?.agentName},Re(Z,I,K,void 0),v=Z}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&&(Se==="flow"?($(z),Ve=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=Ve;Ve=null;let z=S.stopReason,Z=(S.result&&typeof S.result=="object"?S.result:null)?.response;if(F)z&&(F.stopReason=z),Z!=null?mt(F,Z):F.streaming!==!1&&(xe.delete(F.id),Le.delete(F.id),F.streaming=!1,h(F));else{let ye=Z!=null&&Z!=="";if(ye||z){let be=E();z&&(be.stopReason=z),ye?$(be,Z):(be.streaming=!1,h(be))}}continue}}else if(S.type==="execution_start")Se=S.kind==="flow"?"flow":"agent",It=!0,Se==="agent"&&(Pe={executionId:S.executionId,agentId:S.agentId??"virtual",agentName:S.agentName??""});else if(S.type==="turn_start"){let F=typeof S.iteration=="number"?S.iteration:St;if(F!==St){if(Ke==="separate"&&F>1){let z=y;z&&(z.streaming=!1,h(z),y=null)}St=F}yt=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=pe(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))}yt===S.id&&(yt=null)}else if(S.type==="media_start"){let F=String(S.id);Qt.set(F,{mediaType:typeof S.mediaType=="string"?S.mediaType:void 0,toolCallId:S.toolCallId,parts:[]})}else if(S.type==="media_delta"){let F=Qt.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=Qt.get(F);Qt.delete(F);let K=(typeof S.mediaType=="string"?S.mediaType:void 0)??z?.mediaType??"application/octet-stream",Z=typeof S.data=="string"?S.data:void 0,ye=typeof S.url=="string"?S.url:z&&z.parts.length>0?z.parts.join(""):void 0,be=null;if(Z)be={type:"media",data:Z,mediaType:K};else if(ye){let Be=K.toLowerCase();be={type:Be==="image"||Be.startsWith("image/")?"image-url":"file-url",url:ye,mediaType:K}}let Ae=S.toolCallId??z?.toolCallId,tt=be?[be]:[],bt=[];for(let Be of tt){if(!Be||typeof Be!="object")continue;let Ge=Be,cn=typeof Ge.type=="string"?Ge.type:void 0,vo=typeof Ge.mediaType=="string"?Ge.mediaType.toLowerCase():"",ut=null,ht="";if(cn==="media"){let Dt=typeof Ge.data=="string"?Ge.data:void 0;if(!Dt)continue;ht=vo.length>0?vo:"application/octet-stream",ut=`data:${ht};base64,${Dt}`}else if(cn==="image-url"){let Dt=typeof Ge.url=="string"?Ge.url:void 0;if(!Dt)continue;ht=vo,ut=Dt}else if(cn==="file-url"){let Dt=typeof Ge.url=="string"?Ge.url:void 0;if(!Dt)continue;ht=vo,ut=Dt}else continue;if(ut)if(cn==="image-url"||ht.startsWith("image/"))bt.push({type:"image",image:ut,...ht.includes("/")?{mimeType:ht}:{}});else if(ht.startsWith("audio/"))bt.push({type:"audio",audio:ut,mimeType:ht});else if(ht.startsWith("video/"))bt.push({type:"video",video:ut,mimeType:ht});else{let Dt=ht||"application/octet-stream";bt.push({type:"file",data:ut,mimeType:Dt,filename:DP(Dt)})}}if(bt.length>0){let Be=d(),Ge=Ae,vo={id:`agent-media-${typeof Ge=="string"&&Ge.length>0?`${Ge}-${Be}`:String(Be)}`,role:"assistant",content:"",contentParts:bt,createdAt:new Date().toISOString(),streaming:!1,sequence:Be,agentMetadata:{executionId:S.executionId,iteration:St}};h(vo);let ut=y;ut&&(ut.streaming=!1,h(ut)),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="",Ve=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:Pe?.agentId??"virtual",executionId:S.executionId??Pe?.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:Pe?.agentId??"virtual",executionId:S.executionId??Pe?.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,Z=S.file,ye;if(Z&&typeof Z=="object"&&!Array.isArray(Z)&&typeof Z.path=="string"&&typeof Z.mimeType=="string"&&(ye={path:Z.path,mimeType:Z.mimeType,...typeof Z.language=="string"?{language:Z.language}:{}}),n({type:"artifact_start",id:z,artifactType:F,title:K,component:typeof S.component=="string"?S.component:void 0,...ye?{file:ye}:{}}),U.set(z,{markdown:"",title:K,file:ye}),!Q.has(z)){Q.add(z);let be=Er(e.config().features?.artifacts,{artifactType:F,...ye?{file:ye}:{}}),Ae=typeof S.component=="string"?S.component:void 0,tt={id:`artifact-ref-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),rawContent:al(be,{artifactId:z,title:K,artifactType:F,status:"streaming",...ye?{file:ye}:{},...Ae?{component:Ae}:{}})};P.set(z,tt),h(tt)}}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 Z=U.get(F);Z?.markdown&&(K.props.markdown=Z.markdown),Z?.file&&(K.props.file=Z.file),K.component==="PersonaArtifactInline"&&Z?.props&&Object.keys(Z.props).length>0&&(K.props.componentProps=Z.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"})}}}me.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
6
  `);l=F.pop()??"";for(let z of F){let K=z.split(`
7
- `),Z="message",ye="",be=null;for(let Ge of K)Ge.startsWith("event:")?Z=Ge.replace("event:","").trim():Ge.startsWith("data:")?ye+=Ge.replace("data:","").trim():Ge.startsWith("id:")&&(be=Ge.slice(3).trim());let Ae=()=>{be!==null&&be!==""&&n({type:"cursor",id:be})};if(!ye){Ae();continue}let tt;try{tt=JSON.parse(ye)}catch(Ge){n({type:"error",error:Ge instanceof Error?Ge:new Error("Failed to parse chat stream payload")});continue}let bt=tt!==null&&typeof tt=="object"&&!Array.isArray(tt)?tt:null,Be=Z!=="message"?Z:typeof bt?.type=="string"?bt.type:"message";if(e.onSSEEvent?.(Be,tt),e.parseSSEEvent){C.current=y;let Ge=await NP(e,tt,n,C,h,d,A);if(C.current&&C.current!==y&&(y=C.current),Ge){Ae();continue}}bt&&(me.push({...bt,type:Be}),dt()),Ae()}}dt()}var tv,Wg=$e(()=>{"use strict";ei();Yi();ss();ev();tv=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<")});var iv,sv=$e(()=>{iv="4.26.0"});var Jn,oa=$e(()=>{"use strict";sv();Jn=iv});var dd={};Qs(dd,{deleteAllConversations:()=>ek,deleteConversation:()=>ZP,finalizeDisplayProjections:()=>JP,getConversation:()=>QP,historyErrorFor:()=>fv,listConversations:()=>XP,readErrorCode:()=>Bg,recoverFromUnauthorized:()=>gv,resetVisitor:()=>tk});function qP(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 zP(e,t){if(t)return t;let n=e.config.features?.history?.scope;return n||(e.config.getIdentityProof?"verified-user":"browser")}async function KP(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 GP(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",cv);return r}async function Bg(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",dv);if(r.includes("visitor token required"))throw new e.HistoryClientError("visitor_token_missing",pv);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",uv);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 fv(e,t,n){let o=await Bg(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",cv);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",dv)):r.includes("visitor token required")?new e.HistoryClientError("visitor_token_missing",pv):r.includes("visitor_identity_mismatch")?new e.HistoryClientError("visitor_identity_mismatch",uv):new e.HistoryClientError("unauthorized",o||"History request was not authorized")}return new e.HistoryClientError("request_failed",o||`History request failed (${t.status})`)}function YP(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 ra(e,t,n){_g(e);let o=n.trackIdentity!==!1,r=await e.initSession(),s=null;zP(e,n.scope)==="verified-user"&&(s=await KP(e,r,o),s&&(r=await GP(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(qP(e,t,{...n.query,sessionId:r.sessionId}),{method:n.method,headers:{"X-Persona-Version":Jn,...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 Bg(e,d),s,o);continue}if(!d.ok)throw await fv(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 YP(e,g,s!==null,o),f}}function _g(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 XP(e,t){let n=await ra(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(lv),nextCursor:typeof n?.nextCursor=="string"?n.nextCursor:null}}async function QP(e,t,n){let o=await ra(e,`conversations/${encodeURIComponent(t)}`,{method:"GET",query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}});return{summary:lv(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 JP(e,t,n){_g(e);let o=0;for(let c of n){let p=c.displayContent.length;if(p>av)throw new e.HistoryClientError("payload_too_large",`displayContent exceeds the ${av} character limit`);o+=p}if(o>Og)throw new e.HistoryClientError("payload_too_large",`Display projection batch exceeds the ${Og} character limit`);await e.initSession();let r=e.historyInternals.visitorStore,s=r?.revision()??0,i=await ra(e,`conversations/${encodeURIComponent(t)}/display-projections`,{method:"PATCH",body:{messages:n},scope:"browser",keepalive:o<=Og,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 ZP(e,t,n){let o=await ra(e,`conversations/${encodeURIComponent(t)}`,{method:"DELETE",...n?.scope?{scope:n.scope}:{}});return{deleted:typeof o?.deleted=="number"?o.deleted:0}}async function ek(e,t){let n=await ra(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 tk(e){_g(e),e.setHistoryIdentityStatus({state:"resetting"});try{await ra(e,"visitor/reset",{method:"POST",scope:"browser",visitorTokenOptional:!0})}finally{await e.historyInternals.visitorStore?.clear(),e.setHistoryIdentityStatus(e.derivedBrowserOnly())}return{reset:!0}}var av,Og,lv,cv,dv,pv,uv,Dg=$e(()=>{"use strict";oa();av=32768,Og=49152,lv=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:""}},cv="The identity proof was not admitted; account history is unavailable",dv="The identity proof was rejected",pv="The request carried no visitor credential",uv="The stored visitor belongs to a different signed-in user"});var hv,yv=$e(()=>{"use strict";gl();hv=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})),cs(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:sd(d,h),currentIndex:yo(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=yo(d),f=Ji(d);if(g>=f-1)return;let h=o.current?.getMessages().find(y=>y.toolCall?.id===d.getAttribute("data-tool-call-id"));h&&(id(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})),cs(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=ls(h);if(A&&C){let L=ni(h)[yo(h)],I=new Set(Array.isArray(L)?L:[]);I.has(v)?I.delete(v):I.add(v),ds(h,Array.from(I)),s(h);return}if(A){ds(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=Hg(h).length===0);return}r(h,v,{source:"pick",values:[v]});return}if(y==="submit-multi"){let v=Hg(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(ls(h)){ds(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 _=ni(h)[yo(h)];(typeof _!="string"||_!==L)&&ds(h,L)}let I=y==="next"?1:-1,H=yo(h)+I;id(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&&ds(h,L);let I=sd(h,C);o.current.persistAskUserQuestionProgress(C,{answers:I,currentIndex:yo(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=ls(h),L=yo(h),I=Ji(h),H=L>=I-1;if(!A){t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:v},bubbles:!0,composed:!0})),cs(n,v),C.agentMetadata?.awaitingLocalTool&&(o.current.markAskUserQuestionResolved(C),o.current.resolveAskUserQuestion(C,"(dismissed)"));return}ds(h,"");let _=h.querySelector('[data-ask-free-text-input="true"]');if(_&&(_.value=""),H){let V=sd(h,C),te=i(V);r(h,te||"(skipped)",{source:"submit-all",structured:V});return}id(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(ls(h)){ds(h,y.trim()),s(h),l(h);return}r(h,y,{source:"free-text"})}}}}});function rk(e,t,n){if(n==="input-start")return t===0;let o=t>0?e[t-1]:"";return n==="line-start"?o===""||o===`
7
+ `),Z="message",ye="",be=null;for(let Ge of K)Ge.startsWith("event:")?Z=Ge.replace("event:","").trim():Ge.startsWith("data:")?ye+=Ge.replace("data:","").trim():Ge.startsWith("id:")&&(be=Ge.slice(3).trim());let Ae=()=>{be!==null&&be!==""&&n({type:"cursor",id:be})};if(!ye){Ae();continue}let tt;try{tt=JSON.parse(ye)}catch(Ge){n({type:"error",error:Ge instanceof Error?Ge:new Error("Failed to parse chat stream payload")});continue}let bt=tt!==null&&typeof tt=="object"&&!Array.isArray(tt)?tt:null,Be=Z!=="message"?Z:typeof bt?.type=="string"?bt.type:"message";if(e.onSSEEvent?.(Be,tt),e.parseSSEEvent){C.current=y;let Ge=await NP(e,tt,n,C,h,d,A);if(C.current&&C.current!==y&&(y=C.current),Ge){Ae();continue}}bt&&(me.push({...bt,type:Be}),dt()),Ae()}}dt()}var tv,Wg=$e(()=>{"use strict";ei();Yi();ss();ev();tv=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<")});var iv,sv=$e(()=>{iv="4.26.1"});var Jn,oa=$e(()=>{"use strict";sv();Jn=iv});var dd={};Qs(dd,{deleteAllConversations:()=>ek,deleteConversation:()=>ZP,finalizeDisplayProjections:()=>JP,getConversation:()=>QP,historyErrorFor:()=>fv,listConversations:()=>XP,readErrorCode:()=>Bg,recoverFromUnauthorized:()=>gv,resetVisitor:()=>tk});function qP(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 zP(e,t){if(t)return t;let n=e.config.features?.history?.scope;return n||(e.config.getIdentityProof?"verified-user":"browser")}async function KP(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 GP(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",cv);return r}async function Bg(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",dv);if(r.includes("visitor token required"))throw new e.HistoryClientError("visitor_token_missing",pv);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",uv);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 fv(e,t,n){let o=await Bg(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",cv);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",dv)):r.includes("visitor token required")?new e.HistoryClientError("visitor_token_missing",pv):r.includes("visitor_identity_mismatch")?new e.HistoryClientError("visitor_identity_mismatch",uv):new e.HistoryClientError("unauthorized",o||"History request was not authorized")}return new e.HistoryClientError("request_failed",o||`History request failed (${t.status})`)}function YP(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 ra(e,t,n){_g(e);let o=n.trackIdentity!==!1,r=await e.initSession(),s=null;zP(e,n.scope)==="verified-user"&&(s=await KP(e,r,o),s&&(r=await GP(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(qP(e,t,{...n.query,sessionId:r.sessionId}),{method:n.method,headers:{"X-Persona-Version":Jn,...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 Bg(e,d),s,o);continue}if(!d.ok)throw await fv(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 YP(e,g,s!==null,o),f}}function _g(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 XP(e,t){let n=await ra(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(lv),nextCursor:typeof n?.nextCursor=="string"?n.nextCursor:null}}async function QP(e,t,n){let o=await ra(e,`conversations/${encodeURIComponent(t)}`,{method:"GET",query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}});return{summary:lv(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 JP(e,t,n){_g(e);let o=0;for(let c of n){let p=c.displayContent.length;if(p>av)throw new e.HistoryClientError("payload_too_large",`displayContent exceeds the ${av} character limit`);o+=p}if(o>Og)throw new e.HistoryClientError("payload_too_large",`Display projection batch exceeds the ${Og} character limit`);await e.initSession();let r=e.historyInternals.visitorStore,s=r?.revision()??0,i=await ra(e,`conversations/${encodeURIComponent(t)}/display-projections`,{method:"PATCH",body:{messages:n},scope:"browser",keepalive:o<=Og,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 ZP(e,t,n){let o=await ra(e,`conversations/${encodeURIComponent(t)}`,{method:"DELETE",...n?.scope?{scope:n.scope}:{}});return{deleted:typeof o?.deleted=="number"?o.deleted:0}}async function ek(e,t){let n=await ra(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 tk(e){_g(e),e.setHistoryIdentityStatus({state:"resetting"});try{await ra(e,"visitor/reset",{method:"POST",scope:"browser",visitorTokenOptional:!0})}finally{await e.historyInternals.visitorStore?.clear(),e.setHistoryIdentityStatus(e.derivedBrowserOnly())}return{reset:!0}}var av,Og,lv,cv,dv,pv,uv,Dg=$e(()=>{"use strict";oa();av=32768,Og=49152,lv=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:""}},cv="The identity proof was not admitted; account history is unavailable",dv="The identity proof was rejected",pv="The request carried no visitor credential",uv="The stored visitor belongs to a different signed-in user"});var hv,yv=$e(()=>{"use strict";gl();hv=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})),cs(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:sd(d,h),currentIndex:yo(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=yo(d),f=Ji(d);if(g>=f-1)return;let h=o.current?.getMessages().find(y=>y.toolCall?.id===d.getAttribute("data-tool-call-id"));h&&(id(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})),cs(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=ls(h);if(A&&C){let L=ni(h)[yo(h)],I=new Set(Array.isArray(L)?L:[]);I.has(v)?I.delete(v):I.add(v),ds(h,Array.from(I)),s(h);return}if(A){ds(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=Hg(h).length===0);return}r(h,v,{source:"pick",values:[v]});return}if(y==="submit-multi"){let v=Hg(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(ls(h)){ds(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 _=ni(h)[yo(h)];(typeof _!="string"||_!==L)&&ds(h,L)}let I=y==="next"?1:-1,H=yo(h)+I;id(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&&ds(h,L);let I=sd(h,C);o.current.persistAskUserQuestionProgress(C,{answers:I,currentIndex:yo(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=ls(h),L=yo(h),I=Ji(h),H=L>=I-1;if(!A){t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:v},bubbles:!0,composed:!0})),cs(n,v),C.agentMetadata?.awaitingLocalTool&&(o.current.markAskUserQuestionResolved(C),o.current.resolveAskUserQuestion(C,"(dismissed)"));return}ds(h,"");let _=h.querySelector('[data-ask-free-text-input="true"]');if(_&&(_.value=""),H){let V=sd(h,C),te=i(V);r(h,te||"(skipped)",{source:"submit-all",structured:V});return}id(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(ls(h)){ds(h,y.trim()),s(h),l(h);return}r(h,y,{source:"free-text"})}}}}});function rk(e,t,n){if(n==="input-start")return t===0;let o=t>0?e[t-1]:"";return n==="line-start"?o===""||o===`
8
8
  `:o===""||bv.test(o)}function sk(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 rk(e,s,o)?{triggerIndex:s,query:e.slice(s+1,t)}:null;if(i===`
9
9
  `||i==="\uFFFC"||!r&&bv.test(i))return null;s--}return null}function vv(e,t,n){for(let o of n){let r=sk(e,t,o.trigger,o.position??"anywhere",o.allowSpaces??!1);if(r)return{channel:o,match:r}}return null}function Cv(e){return e?e!=="insertFromPaste"&&e!=="insertFromDrop":!0}var bv,wv=$e(()=>{"use strict";bv=/\s/});function Sv(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 Av=$e(()=>{"use strict"});var pd=$e(()=>{"use strict"});function Tv(e){e.delayMs!==void 0&&(xv=gd(e.delayMs)),e.skipDelayMs!==void 0&&(Mv=gd(e.skipDelayMs))}function Pv(e){ud.get(e)?.hide()}function yn(e){ud.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:o,hint:r,enabled:s=!0,gap:i=ik,viewportPadding:l=ak}=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=()=>gd(e.delayMs??xv),_=()=>gd(e.skipDelayMs??Mv),V=()=>{y!==void 0&&(p().clearTimeout(y),y=void 0)},te=()=>{V();let ge=d!==null;h?.(),h=null,d?.remove(),d=null,g=null,f=null,ge&&ck(_())},W=()=>{if(!d)return;let ge=c(),ke=p(),xe=t.getBoundingClientRect(),Le=d.getBoundingClientRect(),mt=ge.documentElement.clientWidth||ke.innerWidth,Ve=ge.documentElement.clientHeight||ke.innerHeight,Re=mt-l-Le.width,$=xe.left+xe.width/2-Le.width/2,We=Fg($,l,Re),me=xe.top-l,dt=Ve-l-xe.bottom,Qt=Le.height+i,St=me>=Qt||me>=dt?"top":"bottom",Se=St==="top"?xe.top-i-Le.height:xe.bottom+i,It=Ve-l-Le.height,yt=Fg(Se,l,It),Pe=xe.left+xe.width/2,Ke=Math.max(Ng,Le.width-Ng),D=Fg(Pe-We,Ng,Ke);d.dataset.placement=St,d.style.left=`${We}px`,d.style.top=`${yt}px`,d.style.setProperty("--persona-tooltip-arrow-x",`${D}px`)},j=()=>{if(A||!s||d||!t.isConnected||dk(t))return;let ge=L(),ke=pk(t);if(!ge||!ke)return;let xe=c(),Le=p();d=xe.createElement("div"),d.className="persona-control-tooltip",d.setAttribute("role","tooltip"),d.dataset.state="measuring",d.style.zIndex=String(na);let mt=Le.getComputedStyle?.(t);if(mt){for(let Qt of uk){let St=mt.getPropertyValue(Qt).trim();St&&d.style.setProperty(Qt,St)}mt.fontFamily&&(d.style.fontFamily=mt.fontFamily)}g=xe.createElement("span"),g.className="persona-control-tooltip__label",g.textContent=ge,d.appendChild(g);let Ve=I();Ve&&(f=xe.createElement("span"),f.className="persona-control-tooltip__hint",f.textContent=Ve,d.appendChild(f));let Re=xe.createElement("span");Re.className="persona-control-tooltip__arrow",d.appendChild(Re),ke.appendChild(d),W(),d.dataset.state="open";let $=()=>{if(!t.isConnected){te();return}g&&(g.textContent=L()),f&&(f.textContent=I()),W()};Le.addEventListener("scroll",$,!0),Le.addEventListener("resize",$);let We=t.getRootNode(),me=kv(We)?We:xe.documentElement,dt=typeof MutationObserver>"u"?null:new MutationObserver(()=>{t.isConnected||te()});dt?.observe(me,{childList:!0,subtree:!0}),h=()=>{Le.removeEventListener("scroll",$,!0),Le.removeEventListener("resize",$),dt?.disconnect()}},Y=ge=>{if(!(A||d)){if(V(),ge||H()<=0||lk()){j();return}y=p().setTimeout(()=>{y=void 0,j()},H())}},E=()=>{v||C?Y(C):te()},T=()=>{let ge=p();(!ge.matchMedia||!ge.matchMedia("(hover: none)").matches)&&(v=!0,E())},B=()=>{v=!1,E()},P=()=>{try{C=t.matches(":focus-visible")}catch{C=!0}E()},Q=()=>{C=!1,E()},U=()=>{v=!1,C=!1,te()},de=ge=>{ge.key==="Escape"&&U()};n.addEventListener("mouseenter",T),n.addEventListener("mouseleave",B),t.addEventListener("focus",P),t.addEventListener("blur",Q),t.addEventListener("keydown",de),t.addEventListener("click",U);let pe={get isOpen(){return d!==null},show:j,hide:te,reposition:W,destroy:()=>{A||(A=!0,te(),n.removeEventListener("mouseenter",T),n.removeEventListener("mouseleave",B),t.removeEventListener("focus",P),t.removeEventListener("blur",Q),t.removeEventListener("keydown",de),t.removeEventListener("click",U),ud.delete(t))}};return ud.set(t,pe),pe}var ik,ak,Ng,xv,Mv,Ev,gd,lk,ck,ud,$g,dk,kv,pk,Fg,uk,sa=$e(()=>{"use strict";Lo();pd();ik=8,ak=8,Ng=10,xv=200,Mv=300,Ev=0,gd=e=>Math.max(0,e);lk=()=>Date.now()<Ev,ck=e=>{Ev=e>0?Date.now()+e:0},ud=new WeakMap,$g="data-persona-tooltip-suppressed",dk=e=>typeof e.closest=="function"&&e.closest(`[${$g}]`)!==null;kv=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,pk=e=>{let t=e.getRootNode?.();return kv(t)?t:e.ownerDocument.body},Fg=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n)),uk=[...["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 gk,ri,Ug,Vg=$e(()=>{"use strict";gk=(e,t)=>e.visible!==!1&&(e.mode!=="transient"||t==="connecting"||t==="paused"||t==="resuming"||t==="error"),ri=(e,t,n)=>{let o=t.mode==="transient",r=e.hasAttribute("data-persona-composer-reason")||e.hasAttribute("data-persona-composer-notice");e.style.display=gk(t,n)||o&&r&&t.visible!==!1?"":"none",e.classList.toggle("persona-mt-2",!o),e.classList.toggle("persona-mb-2",o)},Ug=(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 Ho(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];Lv(s)&&Lv(r)?n[o]=Ho(s,r):n[o]=r}return n}var Lv,fd=$e(()=>{"use strict";Lv=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});function md(e,t=""){return Object.entries(e).flatMap(([n,o])=>{let r=t?`${t}.${n}`:n;return qg(o)?md(o,r):[r]})}function Hv(e,t){for(let n of t.split(".")){if(!qg(e)||!Object.prototype.hasOwnProperty.call(e,n))return"absent";if(e=e[n],e===void 0)return"clear"}return"explicit"}function Iv(e,t){return e?.[jg]??t.filter(n=>Hv(e,n)==="explicit")}function zg(e,t){return Object.defineProperty(e,jg,{value:t,enumerable:!0,configurable:!0}),e}function Kg(e,t,n){return zg(e,Iv(t,md(n)))}function Rv(e,t,n){let o=t[jg];if(o)return o;let r=new Set(Iv(e,n));for(let s of n){let i=Hv(t,s);i==="clear"&&r.delete(s),i==="explicit"&&r.add(s)}return[...r]}function Wv(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(!qg(c)){i=void 0;break}i[l]={...c},i=i[l]}i&&delete i[s[s.length-1]]}return o}var jg,qg,Gg=$e(()=>{"use strict";jg=Symbol("persona.defaultsProvenance"),qg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});var Ov,Yg,si,hd,fk,Pr,Xg,Qg,Bv,ia=$e(()=>{"use strict";Ov="var(--persona-components-panel-width)",Yg=Symbol("persona.panelAliasProvenance"),si=(e,t)=>e!=null&&Object.prototype.hasOwnProperty.call(e,t),hd=(e,t)=>si(e,t)&&e[t]!==void 0,fk=e=>({launcherWidth:hd(e?.launcher,"width"),legacyLauncherWidth:hd(e,"launcherWidth"),sidebarWidth:hd(e?.launcher,"sidebarWidth"),dockWidth:hd(e?.launcher?.dock,"width")}),Pr=e=>{let t=e?.[Yg];return t?{...t}:fk(e)},Xg=(e,t)=>(Object.defineProperty(e,Yg,{value:t,enumerable:!0,configurable:!0}),e),Qg=(e,t)=>Xg(e,Pr(t)),Bv=(e,t)=>{let n=t[Yg];if(n)return{...n};let o=Pr(e);return si(t,"launcherWidth")&&(o.legacyLauncherWidth=t.launcherWidth!==void 0),si(t,"launcher")&&t.launcher===void 0?(o.launcherWidth=!1,o.sidebarWidth=!1,o.dockWidth=!1,o):(si(t.launcher,"width")&&(o.launcherWidth=t.launcher?.width!==void 0),si(t.launcher,"sidebarWidth")&&(o.sidebarWidth=t.launcher?.sidebarWidth!==void 0),si(t.launcher,"dock")&&t.launcher?.dock===void 0?o.dockWidth=!1:si(t.launcher?.dock,"width")&&(o.dockWidth=t.launcher?.dock?.width!==void 0),o)}});function us(e){return e?.future?.v5Defaults===!0?"v5":"v4"}function Dv(e){let t=us(e)==="v5"?ii:bk;return Ho(yk,t)}function _v(e,t){if(!(!e&&!t))return e?t?Ho(e,t):e:t}function yl(e){let t=Dv(e);return e?Kg(Qg({...t,...e,theme:_v(t.theme,e.theme),darkTheme:_v(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,ii):Kg(Qg(t),void 0,ii)}var aa,mk,hl,Jg,kr,ai,hk,yk,bk,vk,ii,Ck,bo=$e(()=>{"use strict";fd();Gg();ia();pd();aa="min(440px, calc(100vw - 24px))",mk="440px",hl="40px",Jg="How can I help...",kr={collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",previewMaxLines:3,expandable:!0,loadingAnimation:"none"},ai={activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},hk={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:aa,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:hl,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)"},yk={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:hk,copy:{inputPlaceholder:Jg,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:kr,reasoningDisplay:ai,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},bk={},vk={variant:"circle",width:"min(400px, calc(100vw - 24px))",headerIconSize:"20px"},ii={launcher:vk,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"}}}};Ck=Dv()});function wk(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Zg(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function bl(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function Sk(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function Io(e){return{type:"text",text:e}}function ef(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function Ak(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 xk(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 Ek(e){return Nv.includes(e)||e.startsWith("image/")}function yd(e){return Ek(e.type)}function Fv(e,t,n){return{type:"file",data:e,mimeType:t,filename:n}}async function $v(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;yd(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 Uv(e,t=Lr,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 Tk(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Vv(e,t){let n=Tk(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 la,Nv,Mk,Lr,Hr=$e(()=>{"use strict";la="[Image]";Nv=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Mk=["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"],Lr=[...Nv,...Mk]});function tf(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 bd(e,t){return typeof e!="number"||!Number.isFinite(e)?t:e>0?e:t}function jv(e,t){e.style.maxHeight=`${t*tf(e)}px`,e.style.overflowY="auto"}function vl(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 qv(e){return e.insertNewlineOnTouchEnter===!0&&e.coarsePointer===!0}function zv(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||!qv(t)}function Pk(e){return(e.submitKey??"enter")!=="enter"||qv(e)?"enter":"send"}function vd(e,t){e.setAttribute("enterkeyhint",Pk(t))}function Cd(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 wd=$e(()=>{"use strict"});var Zn,Ro,rf,qn,Sd,Ad,Lk,sf,xd,ca,Md,Ed,Td,gs=$e(()=>{"use strict";Vg();Xe();Tt();bo();Hr();sa();wd();Zn="persona-composer-control",Ro="persona-composer-control--glyph",rf=40,qn=24,Sd=(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)}},Ad=(e,t)=>{let n=x("textarea");n.setAttribute("data-persona-composer-input",""),n.placeholder=e?.copy?.inputPlaceholder??Jg,n.dir="auto",vd(n,{submitKey:e?.composer?.submitKey,insertNewlineOnTouchEnter:e?.composer?.insertNewlineOnTouchEnter,coarsePointer:vl(n)}),Cd(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=bd(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*tf(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}},Lk="[data-persona-glyph-stack]",sf=(e,t,n="send")=>{let o=X("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},xd=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??"")||rf,h=t.backgroundColor,y=t.textColor,v=x("div","persona-send-button-wrapper"),C=X("button",{className:Wn("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?`persona-flex persona-items-center persona-justify-center ${Zn}`:"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),te=t.iconStrokeWidth??2,W=y?.trim()||"currentColor";if(r&&(A=ue(r,V,W,te)),L=ue(s,V,W,te),!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=sf(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),yn({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 te=V==="stop"?l:i;C.setAttribute("aria-label",te),C.setAttribute("data-persona-send-mode",V),n?(C.querySelector(Lk)??I)?.setAttribute("data-mode",V):C.textContent=V==="stop"?p:c},glyphStack:I}},ca=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=X("button",{className:Wn("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Zn,!c&&Ro),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=ue(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 yn({anchor:h,trigger:f,text:()=>h.getAttribute("aria-label")??C,enabled:A}),{button:h,wrapper:f}},Md=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??Lr).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=X("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Zn} ${Ro}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),l=ue(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 yn({anchor:i,trigger:s,text:()=>i.getAttribute("aria-label")??c}),{button:i,wrapper:s,input:o,previewsContainer:n}},Ed=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",""),ri(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},Td=()=>X("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}})});function Pd(e){let{config:t,onOpen:n}=e,o=t.buttonIconName??"plus",r=t.buttonTooltipText??"Add context",s=x("div","persona-send-button-wrapper"),i=X("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${Zn} ${Ro}`,attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":r,"aria-haspopup":"listbox","aria-expanded":"false"},style:{fontSize:"18px",lineHeight:"1"}}),l=ue(o,qn,"currentColor",1.5);return l?i.appendChild(l):i.textContent="+",i.addEventListener("click",c=>{c.preventDefault(),c.stopPropagation(),n()}),s.appendChild(i),yn({anchor:i,trigger:s,text:()=>i.getAttribute("aria-label")??r}),{button:i,wrapper:s}}var af=$e(()=>{"use strict";Xe();Tt();sa();gs()});var LB,Hk,kd,lf=$e(()=>{"use strict";ln();({setLoader:LB,load:Hk}=it({fallbackImport:()=>import("@runtypelabs/persona/context-mentions")})),kd=Hk});var RB,Ik,Ld,cf=$e(()=>{"use strict";ln();({setLoader:RB,load:Ik}=it({fallbackImport:()=>import("@runtypelabs/persona/context-mentions-inline"),resetOnSetLoader:!0})),Ld=Ik});function Cl(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=X("span",{className:Wn("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=ue(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(X("span",{className:"persona-mention-token-label",text:`@${e.label}`})),n}var df=$e(()=>{"use strict";Xe();Tt()});function Kv(e){let{loadContextMentions:t,loadContextMentionsInline:n,renderLucideIcon:o,createMentionButton:r}=e.deps??Rk,s=e.config.contextMentions;if(!s?.enabled)return null;let i=Sv(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
10
  `).some(E=>E.startsWith(j.trigger)):(j.position==="anywhere"?W:W.split(`
11
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??X("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:te,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=>Cl(E,{render:s.renderMentionToken}),onMentionRemoved:E=>f?.untrackMention(E)});v=j.input,C=j.destroy;let Y=y;Y.replaceWith(j.element),y=j.element,L={next:j.element,prev:Y},A?.(j.element,Y),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(Y=>Y?.openMenu(W.trigger))}});_.push(j),V.set(W.trigger,j.button)}let te=(W,j,Y)=>{let E=V.get(j);E&&(E.setAttribute("aria-expanded",W?"true":"false"),W?E.setAttribute("aria-controls",Y):E.removeAttribute("aria-controls"))};return{affordanceButtons:_.map(W=>W.wrapper),contextRow:g,handleInput:W=>{if(f){f.handleInput();return}if(!Cv(W))return;let j=y,Y=j.selectionStart??0;vv(j.value,Y,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,Y=j.selectionStart===0&&j.selectionEnd===0;if((j.value.length===0||Y)&&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 Rk,Gv=$e(()=>{"use strict";Xe();wv();Av();af();lf();Tt();cf();df();Rk={loadContextMentions:()=>kd(),loadContextMentionsInline:()=>Ld(),renderLucideIcon:(...e)=>ue(...e),createMentionButton:(...e)=>Pd(...e)}});var Hd={};Qs(Hd,{createAskUserSheetHandlers:()=>hv,createContextMentionOrchestrator:()=>Kv});var pf=$e(()=>{"use strict";yv();Gv()});var Wd={};Qs(Wd,{resolveApproval:()=>Dk,resolveAskUserQuestion:()=>Nk,resolveWebMcpToolCall:()=>Uk,resolveWebMcpToolCallBatch:()=>Qv});async function Dk(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 Nk(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 Fk(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 Xv(e,t){return t.toolCall?.name!==Xo?!1:(e.s.messages.find(o=>o.id===t.id)??t).agentMetadata?.suggestRepliesResolved===!0}function $k(e,t){let n=Fk(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 Rd(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 Qv(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)||Xv(e,c))return null;e.s.webMcpInflightKeys.add(g),o.push(g);let f=$k(e,c),h=c.agentMetadata?.webMcpToolCallId??p;if(p===Xo)return{dedupeKey:g,resumeKey:h,output:Gb(),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))),Rd(e,c,gf(A?"Aborted by cancel()":_k(C)),f),e.s.webMcpInflightKeys.delete(g),null}return r.signal.aborted?(Rd(e,c,gf("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;Rd(e,g.toolMessage,g.output,g.startedAt,g.completedAt,{...f===Xo?{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)Rd(e,d.toolMessage,gf("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 Uk(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 Vk(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)||Xv(e,t)))return Qv(e,n,[t])}async function Vk(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 gf,_k,ff=$e(()=>{"use strict";ea();gf=e=>({isError:!0,content:[{type:"text",text:e}]}),_k=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t});function hf(e){if(!e)return eC;let t={...eC};for(let n of Kk){let o=e[n];typeof o=="string"&&o.length>0&&(t[n]=o)}return t}var Kk,eC,tC=$e(()=>{"use strict";Kk=["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"],eC={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 rC(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(_){yf("renderHistoryView cleanup",_)}},d=(H,_)=>{for(let V of t){let te=V[H];if(te)try{let W=te(_);if(W)return W}catch(W){yf(H,W)}}return null},g=()=>({presentation:e.getPresentation(),config:n}),f={header:H=>i?d("renderHistoryHeader",Object.freeze({...g(),returnSurface:e.getReturnSurface(),identityStatus:Ir(H.identityStatus),pendingAction:oC(H.pendingAction),copy:Ir(H.copy),actions:Object.freeze({close:v.close,startNewConversation:v.startNewConversation}),defaultRenderer:H.defaultRenderer})):null,conversation:H=>i?d("renderHistoryConversation",Object.freeze({...g(),conversation:nC(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:Ir(H.state),identityStatus:Ir(H.identityStatus),copy:Ir(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(nC)),activeConversationId:H.activeConversationId,state:Ir(H.state),pendingAction:oC(H.pendingAction),identityStatus:Ir(H.identityStatus),nextCursor:H.nextCursor,presentation:e.getPresentation(),returnSurface:e.getReturnSurface(),config:n,copy:Ir(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(te){yf("renderHistoryView",te),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 yf,Ir,nC,oC,sC=$e(()=>{"use strict";yf=(e,t)=>{console.warn(`[persona] ${e} threw`,t)},Ir=e=>Object.freeze({...e}),nC=e=>Object.freeze({id:e.id,title:e.title,targetId:e.targetId,preview:e.preview,messageCount:e.messageCount,createdAt:e.createdAt,updatedAt:e.updatedAt}),oC=e=>e?Ir(e):null});var iC,bf,Gk,Od,Bd,Yk,aC,_d,wl,Xk,Qk,lC,Dd=$e(()=>{"use strict";iC=null,bf=()=>{if(iC!==null)return iC;if(typeof navigator>"u")return!1;let t=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(t)},Gk="ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space",Od=(e,t)=>{console.warn(`[persona] ${e} shortcut: ${t}`)},Bd=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 Od("unknown modifier in",e),null;return!o.mod||o.shift&&o.alt||/^(enter|esc(ape)?)$/.test(n)||!/^([^+\s]|[a-z]{2,12})$/.test(n)?(Od("unsupported",e),null):(n==="space"&&(o.key=" "),o)},Yk=e=>Gk.split(" ").find(t=>t.toLowerCase()===e)??(e===" "?"Space":e.length===1?e.toUpperCase():e[0].toUpperCase()+e.slice(1)),aC=(e,t)=>{let n=Bd(e);if(!n)return"";let o=bf(),r=Yk(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("+")},_d=e=>aC(e,!1),wl=e=>aC(e,!0),Xk=(e,t)=>t.key?.toLowerCase()===e.key&&(bf()?t.metaKey:t.ctrlKey)===e.mod&&!(bf()?t.ctrlKey:t.metaKey)&&t.shiftKey===e.shift&&t.altKey===e.alt,Qk=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable},lC=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(Xk(l.parsed,s)&&l.when?.()!==!1&&o(l,s)&&!(!l.allowInInput&&Qk(i))){s.preventDefault();try{l.run(s)}catch(c){Od(`${l.id} threw on`,l.combo),console.warn(c)}return}};return n?.addEventListener("keydown",r),{register(s){let i=Bd(s.combo);if(!i)return()=>{};let l=`${i.mod?"m":""}${i.shift?"s":""}${i.alt?"a":""}${i.key}`,c=t.get(l);return c?(Od(`${c.id} already owns`,s.combo),()=>{}):(t.set(l,{...s,parsed:i}),s.element?.setAttribute("aria-keyshortcuts",wl(s.combo)),()=>{t.get(l)?.id===s.id&&t.delete(l),s.element?.removeAttribute("aria-keyshortcuts")})},destroy(){t.clear(),n?.removeEventListener("keydown",r)}}}});function cC(e){if(typeof e!="string"||e==="")return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function Nd(e){return typeof e=="string"?e:void 0}function e0(e){if(typeof e!="object"||e===null)return null;let t=e;switch(t.type){case"text":return typeof t.text=="string"?Io(t.text):null;case"image":return typeof t.image=="string"?ef(t.image,{mimeType:Nd(t.mimeType),alt:Nd(t.alt)}):null;case"file":return typeof t.data=="string"&&typeof t.mimeType=="string"&&typeof t.filename=="string"?Fv(t.data,t.mimeType,t.filename):null;case"audio":return typeof t.audio=="string"?{type:"audio",audio:t.audio,...Nd(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;case"video":return typeof t.video=="string"?{type:"video",video:t.video,...Nd(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;default:return null}}function t0(e,t){let n=cC(t),o=e.map(i=>cC(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:Zk+f;s=l+1}return r.map(i=>new Date(i).toISOString())}function dC(e,t){let n=t0(e,t?.beforeCreatedAt),o=[];return e.forEach((r,s)=>{if(typeof r?.id!="string"||r.id===""||!Jk.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(e0).filter(d=>d!==null),p=Zg(c);o.push({id:r.id,role:i,content:p||(bl(c)?la:""),createdAt:l,...c.length>0&&{contentParts:c}});return}o.push({id:r.id,role:i,content:"",createdAt:l})}),o}function Sl(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 Al(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 Jk,Zk,Fd=$e(()=>{"use strict";Hr();Jk=["user","assistant","system"],Zk=0});function r0(e,{HistoryClientError:t,HistoryProviderError:n}){if(e instanceof n)return e;if(e instanceof t){let o=n0.get(e.code)??"unavailable";return new n(o,vf(o),{...e.retryAfterSeconds!==void 0?{retryAfterSeconds:e.retryAfterSeconds}:{}})}return new n("unavailable",vf("unavailable"))}function pC(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",vf("unsupported_scope"))},i=async(c,p)=>{s(c);try{return await p()}catch(d){throw r0(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=dC(d.messages,{...p.beforeCreatedAt?{beforeCreatedAt:p.beforeCreatedAt}:{}});return{summary:d.summary,messages:Al([],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 n0,o0,vf,uC=$e(()=>{"use strict";Fd();n0=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"]]),o0=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."]]),vf=e=>o0.get(e)??"Conversation history is unavailable right now."});var $d={};Qs($d,{createHistoryShell:()=>s0});var s0,Cf=$e(()=>{"use strict";tC();sC();Xe();Dd();Lo();uC();s0=e=>{let o=hf(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",ee=r?.capabilities.scopes;return!ee||ee.includes(N)?N:ee[0]??N},_=()=>l?.scope??H(),V=()=>e.session.getClientSession()?.targetId??null,te=M=>`${M.state}:${"reason"in M?M.reason:""}`,W=M=>{let N=te(M);N!==f&&(f=N,e.eventBus.emit("history:identityStatusChanged",{status:M,timestamp:Date.now()}))},j=null,Y=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,Y=N()),Y):e.session.isClientTokenMode()?pC({errors:e.historyErrors,client:e.session.getClient(),getIdentityProofConfigured:()=>typeof e.config.getIdentityProof=="function",onActivationCommitted:ee=>e.session.bindActivatedSession(ee),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||Sn({restoreFocus:!1}),$n()})??null,C=r.subscribeIdentityStatus(N=>W(N)),f=te(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"))},Q="data-persona-history-suppressed",U=null,de=null,pe=null,ge=null,ke=null,xe="",Le=()=>e.header===ke?xe:e.config.layout?.showHeader===!1?"none":"",mt=()=>e.historyPresentation==="panel"&&!!pe&&ge===pe.element&&e.config.layout?.showHeader!==!1&&Le()!=="none",Ve=()=>{for(let M of Array.from(e.header.children))M!==U&&M.setAttribute(Q,"")},Re=()=>{for(let M of Array.from(e.container.querySelectorAll(`[${Q}]`)))M.removeAttribute(Q)},$=()=>{let M=pe;if(!M)return;if(Array.from(e.header.children).some(ce=>ce!==U&&!ce.hasAttribute(Q))){de&&de!==e.header&&(de.style.removeProperty("min-height"),de=null);let ce=e.header.offsetHeight;ce>0&&(e.header.style.minHeight=`${ce}px`,de=e.header)}U||(U=x("div","persona-history-header-host")),M.setHeaderPlacement("external");let ee=M.getHeaderElement();ee.parentNode!==U&&U.replaceChildren(ee),U.parentNode!==e.header&&e.header.appendChild(U),Ve()},We=()=>{de&&(de.style.removeProperty("min-height"),de=null),U&&(pe?.setHeaderPlacement("inline"),U.remove(),U=null,Re())},me=null,dt=()=>{if(me){if(e.body.style.display="none",P(e.body,!0),e.footer.hidden=!0,P(e.footer,!0),mt()){$(),e.header.style.display=Le(),P(e.header,!1);return}We(),e.header.style.display="none",P(e.header,!0)}};e.reapplyHistoryHostChrome=dt;let Qt=M=>{let N=e.body.style.display,ee=e.footer.hidden,ce=e.footer,He=e.header,Nt=e.header.style.display;ke=He,xe=Nt,me=()=>{me=null,We(),ke=null,e.body.style.display=N,P(e.body,!1),ce.hidden=ee,P(ce,!1),e.footer!==ce&&(e.footer.hidden=!1,P(e.footer,!1)),He.style.display=Nt,P(He,!1),e.header!==He&&(e.header.style.display=e.config.layout?.showHeader===!1?"none":"",P(e.header,!1))},e.footer.parentNode?.insertBefore(M,e.footer),dt()},St=null,Se=null,It=null,yt=null,Pe=()=>[e.header,e.panelElements.closeButtonWrapper,e.panelElements.clearChatButtonWrapper,e.body,e.footer],Ke=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))),Z=()=>e.config.features?.history?.rail?.resizable===!0,ye,be=()=>{if(ye===void 0&&(ye=null,e.config.persistState!==!1))try{let M=Number(window.localStorage.getItem(`${e.currentKeyPrefix()}rail-width`));M&&(ye=M)}catch{}return ye},Ae=()=>K(be()??e.config.features?.history?.rail?.width??260),tt=M=>{if(ye=M,e.config.persistState!==!1)try{window.localStorage.setItem(`${e.currentKeyPrefix()}rail-width`,String(M))}catch{}},bt=()=>D()&&e.config.features?.history?.rail?.collapsedBehavior==="overlay",Be=!1,Ge=M=>{let N=x("img");return N.src=M,N.alt="",N.setAttribute("aria-hidden","true"),N},cn=()=>{let M=e.config.features?.history?.rail?.brand;if(!M)return;let N=!1,ee;return ce=>{if(M.render)try{return M.render({collapsed:ce})??null}catch(He){return N||(N=!0,console.warn("[persona] history rail brand threw",He)),null}return ee===void 0&&(M.iconUrl?ee=Ge(M.iconUrl):ee=M.icon?e.renderLucideIcon(M.icon,20):null),ee?ee.cloneNode(!0):null}},vo=()=>e.config.features?.history?.rail?.sections?.map(M=>{let N=!1,ee=ce=>{N||(N=!0,console.warn("[persona] history rail section threw",M.id,ce))};return{id:M.id,title:M.title,placement:M.placement??"above-conversations",items:M.items.map(ce=>{let He;return{id:ce.id,label:ce.label,badge:ce.badge,iconNode:()=>{if(He!==void 0)return He;try{ce.renderIcon?He=ce.renderIcon()??null:ce.iconUrl?He=Ge(ce.iconUrl):He=ce.icon?e.renderLucideIcon(ce.icon,20):null}catch(Nt){ee(Nt),He=null}return He},onSelect:()=>{try{ce.onSelect()}catch(Nt){ee(Nt)}}}})}})??[],ut=M=>{let N=vo();for(let ee of M)N.some(ce=>ce.id===ee.id)?console.warn("[persona] duplicate history rail section id",ee.id):N.push(ee);return N.length?N:void 0},ht=null,Dt=()=>`${e.currentKeyPrefix()}rail-collapsed`,hi=()=>{if(ht===null&&(ht=e.config.features?.history?.rail?.defaultCollapsed===!0,e.config.persistState!==!1))try{let M=window.localStorage.getItem(Dt());M&&(ht=M==="1")}catch{}return ht},nn=M=>{if(ht=M,e.config.persistState!==!1)try{window.localStorage.setItem(Dt(),M?"1":"0")}catch{}},Cn=()=>e.historyPresentation==="rail"&&D()&&!bt()&&hi(),ro=()=>{},yi=()=>{if(bt()){ro();return}nn(!hi()),i?.view.setCollapsed(Cn()),e.applyRailChrome(),e.repinAnchoredMessage()},bi=()=>{let M=e.config.features?.history?.rail?.collapseShortcut;return!M||!Bd(M)?null:{combo:M,hint:_d(M),aria:wl(M)}},Ia=300,rr="var(--persona-history-overlay-margin,8px)",dn=null,Nn=null,sr=0,Fn=null,ir=null,Oo=!1,_r=0,Jl=()=>window.matchMedia?.("(pointer: coarse)").matches===!0,Kn=()=>L()&&bt()&&(e.historyPresentation??B())==="rail",nh=()=>e.historyVisible&&!Be,ar=()=>{ir!==null&&clearTimeout(ir),ir=null},As=()=>{e.loadHistoryView().catch(()=>{})},Pn=()=>{ar(),Be&&(ir=setTimeout(()=>{ir=null,!(Oo||!Be)&&(Fn?.contains(document.activeElement)||Sn({restoreFocus:!1}))},Ia))},Ye=(M,N)=>{let ee=Fn?.getBoundingClientRect();if(!ee)return!1;let ce=dn?.getBoundingClientRect(),He=ce?Math.min(ce.top,ee.top):ee.top;return M>=ee.left&&M<=ee.right&&N>=He&&N<=ee.bottom||!!ce&&M>=ce.left&&M<=ce.right&&N>=ce.top&&N<=ce.bottom},we=M=>{Be&&(Oo=Ye(M.clientX,M.clientY),Oo?ar():ir===null&&Pn())},Gt=M=>{e.historyVisible||!Kn()||(Be=!0,qe({invoker:dn,keyboard:M?.keyboard===!0}).then(()=>{e.historyVisible?!Oo&&document.activeElement!==dn&&Sn():Be=!1}))},Qe=()=>{let M=ge?.querySelector('[data-persona-history-focus="collapse"]');M&&(M.setAttribute("aria-label",Be?o.expandLabel:o.collapseLabel),M.setAttribute("aria-expanded",Be?"false":"true"))},ve=()=>{nn(!1);let M=i;if(!Be||!M){qe({invoker:dn});return}let N=document.activeElement===dn;Be=!1,vi(),M.element.remove(),Pt(M.element),Qe(),N&&gt(),e.repinAnchoredMessage(),$n()},se=()=>{nn(!0),Sn()};ro=()=>{!e.historyVisible||Be?ve():se()};let Me=()=>{let M=bi(),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}:{}}}),ee=N.button;ee.addEventListener("mouseenter",()=>{Oo=!0,ar(),!(Jl()||Date.now()<_r)&&Gt()}),ee.addEventListener("mouseleave",()=>{Oo=!1,_r=0,Pn()}),ee.addEventListener("focus",()=>{e.historyVisible||As()}),ee.addEventListener("click",ce=>{L()&&(ce.detail!==0&&Jl()&&!e.historyVisible?Gt():ve())}),dn=ee,Nn=N.wrapper},lr=()=>{if(Nn&&!Nn.isConnected&&(Nn=null,dn=null),!Kn()){Nn?.remove(),Nn=null,dn=null;return}dn||Me();let M=Nn,N=dn;if(!M||!N)return;let ee=S()!=="right"?e.header.firstChild:null;(ee??e.header.lastChild)!==M&&e.header.insertBefore(M,ee),M.style.display=nh()||sr>0?"none":"",N.setAttribute("aria-label",o.expandLabel),N.setAttribute("aria-expanded",e.historyVisible?"true":"false"),Fn&&e.applyRailChrome()},Dr=M=>{if(!Be)return;let N=M.target;N instanceof Node&&(Fn?.contains(N)||Nn?.contains(N)||N instanceof Element&&N.closest('.persona-dropdown-menu,[role="alertdialog"]')||Sn({restoreFocus:!1}))};document.addEventListener("pointerdown",Dr,!0),e.destroyCallbacks.push(()=>{document.removeEventListener("pointerdown",Dr,!0),document.removeEventListener("pointermove",we),ae?.(),ar()});let so=null,ae=null,Ee=16,wn=M=>{tt(K(M)),e.applyRailChrome(),e.repinAnchoredMessage()},nt=()=>{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 ee=Se;if(!ee||N.button!==0)return;N.preventDefault(),ae?.();let ce=N.clientX,He=ee.getBoundingClientRect().width||Ae(),Nt=S()==="right"?-1:1,Rt=He,Wt=e.mount.ownerDocument;ee.style.transition="none";let Ue=he=>{Rt=K(He+Nt*(he.clientX-ce)),ee.style.flex=`0 0 ${Rt}px`,M.setAttribute("aria-valuenow",String(Rt))},st=()=>{ae=null,Wt.removeEventListener("pointermove",Ue),Wt.removeEventListener("pointerup",st),Wt.removeEventListener("pointercancel",st),ee.style.removeProperty("transition");try{M.releasePointerCapture(N.pointerId)}catch{}wn(Rt)};ae=st,Wt.addEventListener("pointermove",Ue),Wt.addEventListener("pointerup",st),Wt.addEventListener("pointercancel",st);try{M.setPointerCapture(N.pointerId)}catch{}}),M.addEventListener("keydown",N=>{let ee=S()==="right"?-Ee:Ee,ce=Ae(),He=N.key==="ArrowRight"?ce+ee:N.key==="ArrowLeft"?ce-ee:N.key==="Home"?F:N.key==="End"?z:null;He!==null&&(N.preventDefault(),wn(He))}),M},Jt=(M,N)=>{if(!Z()||Cn()){ae?.(),so?.remove();return}let ee=so??nt();so=ee,ee.setAttribute("aria-label",o.resizeLabel),ee.setAttribute("aria-valuenow",String(Ae())),ee.nextElementSibling!==N&&M.insertBefore(ee,N)};e.applyRailChrome=()=>{i?.view.setRailSide(S());let M=S()==="right",N=Fn;if(N){let Wt=dn?dn.getBoundingClientRect().bottom-e.container.getBoundingClientRect().top:0;N.style.top=`calc(${Math.max(0,Math.round(Wt))}px + ${rr})`,N.style.width=`${Ae()}px`,N.style.left=M?"":rr,N.style.right=M?rr:""}let ee=Se,ce=St,He=It;if(!ee||!ce||!He)return;ee.style.flex=`0 0 ${Cn()?Ke:Ae()}px`;let Nt="1px solid var(--persona-divider,#e5e7eb)";ee.style.borderRight=M?"":Nt,ee.style.borderLeft=M?Nt:"";let Rt=M?He:ee;ce.firstElementChild!==Rt&&ce.append(Rt,M?ee:He),Jt(ce,M?ee:He)};let Zl=M=>{if(yt&&Se){yt.replaceWith(M),yt=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 ee=x("div","persona-history-rail-conversation");ee.style.cssText="display:flex;flex-direction:column;flex:1 1 auto;min-width:0;min-height:0;position:relative";let ce=x("div","persona-history-rail-host");ce.style.cssText="display:flex;min-height:0;overflow:hidden",e.container.insertBefore(N,e.header.parentNode===e.container?e.header:e.body);for(let He of Pe())He?.parentNode===e.container&&ee.appendChild(He);N.append(ce,ee),ce.appendChild(M),St=N,Se=ce,It=ee,e.applyRailChrome()},Ln=()=>{if(St)return;let M=x("div","persona-history-rail-placeholder");M.style.cssText="flex:1 1 auto;min-height:0",yt=M,Zl(M),e.repinAnchoredMessage()},ec=()=>{yt&&(vi(),e.repinAnchoredMessage())},Qp=M=>{let N=x("div","persona-history-rail-overlay");N.style.cssText=`position:absolute;bottom:${rr};display:flex;overflow:hidden;z-index:${na-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",we),Fn=N,e.applyRailChrome(),Qe()},vi=()=>{me?.(),Fn&&(Oo&&(_r=Date.now()+150),document.removeEventListener("pointermove",we),Fn.remove(),Fn=null);let M=St;if(M){ae?.();for(let N of Pe())N&&M.contains(N)&&e.container.insertBefore(N,M);M.remove(),St=null,Se=null,It=null,yt=null}},je=M=>{ge=M,M.id=A,M.style.flex="1 1 auto",M.style.minHeight="0"},Pt=M=>{je(M),(e.historyPresentation!=="rail"||Be)&&ec(),e.historyPresentation!=="rail"?Qt(M):Be?Qp(M):Zl(M)},Bo=()=>{if(lr(),Fr(),!e.historyVisible||!i)return;let M=B();if(M===e.historyPresentation)return;let N=document.activeElement,ee=N instanceof HTMLElement&&(i.element.contains(N)||U?.contains(N)===!0)?N:null;vi(),i.element.remove(),i.view.setHeaderPlacement("inline"),e.historyPresentation=M,i.view.setPresentation(M),i.view.setCollapsed(Cn()),i.requestRender(),i.element.isConnected||Pt(i.element),ee?.isConnected?ee.focus():gt(),e.syncScrollToBottomButton(),e.repinAnchoredMessage(),$n()},_o=(M,N)=>U?.querySelector(N)??M.querySelector(N),gt=()=>{let M=i?.element??ge;if(!M)return;let N=_o(M,'[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]');if(N){N.focus();return}let ee=_o(M,".persona-history-title")??M;ee.tabIndex=-1,ee.focus()},qe=async M=>{if(!L()||e.historyVisible)return;let N=r;if(!N)return;if(!Be&&Kn()&&hi()){lr();return}Ci();let ee=++h;c=M?.returnSurface??"conversation",p=M?.invoker??d;let ce=Kn()&&!Be;ce&&(sr+=1,lr(),Ln());let He;try{He=await e.loadHistoryView()}catch{e.announceHistory(o.openHistoryLabel),ce&&(sr-=1,ee===h&&(ec(),lr()));return}if(ce&&(sr-=1),ee!==h||e.historyVisible)return;l={scope:H()},e.historyPresentation=B(),e.historyVisible=!0;let Nt=e.historyPresentation==="panel"&&e.config.layout?.showHeader!==!1&&e.header.style.display!=="none"?"external":"inline",Rt=e.config.features?.history?.rowAvatar,Wt=bi(),Ue=Wt?{hint:Wt.hint,aria:Wt.aria}:null,st={provider:N,context:l,targetId:V(),presentation:e.historyPresentation,collapsible:D(),collapsed:Cn(),railSide:S(),renderRailHeader:e.config.features?.history?.rail?.renderHeader,railBrand:cn(),onToggleCollapse:yi,...Ue?{collapseShortcut:Ue}:{},headerPlacement:Nt,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:Rt===!1?!1:typeof Rt=="string"?Rt: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:he=>An(he,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:he=>e.setActiveConversationSummary(he),attachTooltip:e.attachTooltip,onStartNew:()=>Co({focusComposer:!0}),onClose:()=>Sn(),onRequestDeleteConversation:he=>$t(he),onRequestClearHistory:()=>Ts(),...N.resetDevice?{onRequestResetIdentity:()=>Oa()}:{}};i=rC({plugins:e.plugins,config:e.config,getPresentation:()=>e.historyPresentation??"panel",getReturnSurface:()=>c,close:()=>Sn(),createView:({slots:he,renderDom:Si,onModelChange:io,railSections:dr})=>(pe=He.createHistoryView({...st,railSections:ut(dr),slots:he,renderDom:Si,onModelChange:io,onAnnounce:e.announceHistory}),pe),onElementChanged:(he,Si)=>{if(!Si?.isConnected)return Pt(he);je(he),Si.replaceWith(he),dt()}}),i.view.setNewConversationRequired(e.historySessionState.recovery==="new_conversation_required"),M?.focus!==!1&&(e.historyPresentation!=="rail"||M?.keyboard===!0)&&gt(),e.syncScrollToBottomButton(),e.repinAnchoredMessage(),$n(),e.eventBus.emit("history:opened",{presentation:e.historyPresentation,returnSurface:c,timestamp:Date.now()})},Ci=()=>{},Sn=M=>{if(!e.historyVisible)return;h+=1;let N=c,ee=p,ce=i,He=M?.restoreFocus!==!1;e.historyVisible=!1;let Nt=!1,Rt=null,Wt=()=>{if(!Nt){if(Nt=!0,Ci=()=>{},Rt!==null&&clearTimeout(Rt),Be=!1,ar(),vi(),ce?.dispose(),ce?.view.destroy(),ce?.element.remove(),i===ce&&(i=null,pe=null,ge=null,e.historyPresentation=null,l=null,p=null),e.syncScrollToBottomButton(),e.repinAnchoredMessage(),$n(),He){let st=ee??d;st?.isConnected?st.focus():e.maybeFocusInput()}e.eventBus.emit("history:closed",{returnSurface:N,timestamp:Date.now()})}},Ue=ce&&ce.element===ce.view.element?ce.view.playExit():null;if(!Ue){Wt();return}Ci=Wt,Rt=setTimeout(Wt,250),Ue.then(Wt)},xs=M=>{if(!(M.key!=="Escape"||!e.historyVisible||!i)){if(e.historyPresentation==="rail"){let N=M.target;if(!(N instanceof Node)||!(i.element.contains(N)||Be&&Nn?.contains(N)===!0))return}M.preventDefault(),M.stopPropagation(),Sn()}};e.container.addEventListener("keydown",xs),e.destroyCallbacks.push(()=>e.container.removeEventListener("keydown",xs));let Hn=0,tc=250,fe=null,pn=()=>{fe&&clearTimeout(fe),fe=null};e.destroyCallbacks.push(pn);let kt=()=>{pn();let M=e.conversationOpenPendingEl;M&&(e.conversationOpenTakeover=!0,M.hidden=!1,e.messagesWrapper.style.display="none",e.updateWelcome())},on=()=>{Hn+=1,pn(),e.conversationOpenPendingEl&&(e.conversationOpenPendingEl.remove(),e.conversationOpenPendingEl=null,e.conversationOpenTakeover=!1,e.messagesWrapper.style.removeProperty("display"),P(e.footer,!1),e.updateWelcome())},At=()=>{try{if(window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches)return;e.messagesWrapper.animate([{opacity:0},{opacity:1}],{duration:150,easing:"ease-out"})}catch{}},un=(M,N)=>X("div",{className:Wn("persona-conversation-loading-bubble",N&&"persona-conversation-loading-bubble--trailing"),attrs:{"aria-hidden":"true"},style:{width:M}}),nc=()=>X("div",{className:"persona-conversation-loading-body"},un("58%",!1),un("72%",!0),un("44%",!1)),Nr=M=>{e.conversationOpenPendingEl?.remove(),e.conversationOpenPendingEl=M,M.hidden=!e.conversationOpenTakeover,e.body.insertBefore(M,e.messagesWrapper),pn(),e.conversationOpenTakeover||(fe=setTimeout(kt,tc)),P(e.footer,!0)},Jp=()=>{let M={config:e.config,streaming:!1,location:"conversation-open",defaultRenderer:nc},N=null,ee=e.plugins.find(ce=>ce.renderLoadingIndicator);ee?.renderLoadingIndicator&&(N=ee.renderLoadingIndicator(M)),N===null&&e.config.loadingIndicator?.render&&(N=e.config.loadingIndicator.render(M)),Nr(X("div",{className:"persona-conversation-loading",attrs:{role:"status","aria-label":o.openConversationLoadingLabel}},N??nc()))},Zp=M=>{let N=()=>{An(M,{focusComposer:!0}).catch(()=>{})},ee=L()?()=>{on(),qe()}:void 0,ce=(Wt,Ue)=>{let st=X("button",{className:"persona-conversation-loading-error-action",attrs:{type:"button"},text:Wt});return st.addEventListener("click",Ue),st},He=()=>X("div",{className:"persona-conversation-loading-error-body"},X("p",{className:"persona-conversation-loading-error-title",text:o.openConversationErrorTitle}),X("div",{className:"persona-conversation-loading-error-actions"},ce(o.openConversationRetryLabel,N),ee?ce(o.openConversationBackLabel,ee):null)),Nt=Object.freeze({conversationId:M,config:e.config,copy:Object.freeze({title:o.openConversationErrorTitle,retryLabel:o.openConversationRetryLabel,backLabel:o.openConversationBackLabel}),retry:N,...ee?{back:ee}:{},defaultRenderer:He}),Rt=null;for(let Wt of e.plugins)if(Wt.renderHistoryOpenError){try{Rt=Wt.renderHistoryOpenError(Nt)}catch(Ue){console.warn("[persona] renderHistoryOpenError threw",Ue),Rt=null}if(Rt)break}Nr(X("div",{className:"persona-conversation-loading-error",attrs:{role:"alert"}},Rt??He())),kt()};e.eventBus.on("history:closed",()=>{e.conversationOpenPendingEl&&P(e.footer,!0)});let An=async(M,{focusComposer:N=!1}={})=>{let ee=_(),ce=!!i;i?.view.setActiveConversationId(M),on();let He=Hn;Jp(),e.historyVisible&&(e.historyPresentation==="panel"||Be)&&Sn({restoreFocus:!1}),e.suppressScrollSend=!0;try{await e.session.openConversation(M,{scope:ee})}catch(Nt){throw He===Hn&&Zp(M),Nt}finally{e.suppressScrollSend=!1}He===Hn&&(on(),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),e.restoreScrollPosition()||e.jumpToBottomInstant(),At(),Yt(),ce||e.setActiveConversationSummary(null),e.eventBus.emit("history:conversationOpened",{conversationId:M,title:e.activeConversationTitle,scope:ee,timestamp:Date.now()}),N&&e.maybeFocusInput())},Co=async({focusComposer:M=!1}={})=>{on(),await e.session.startNewConversation({scope:_()}),e.setActiveConversationSummary(null),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),e.jumpToBottomInstant(),Yt();let N=e.session.getActiveConversationId();i?.view.setActiveConversationId(N),e.eventBus.emit("history:conversationStarted",{conversationId:N,timestamp:Date.now()}),e.historyVisible&&(e.historyPresentation==="panel"||Be)&&Sn({restoreFocus:!1}),M&&e.maybeFocusInput()},Ms=async(M,N)=>{let ee=await e.session.updateConversation(M,{...N,...N.title!==void 0?{title:N.title.trim()}:{}});return i?.view.applyConversationSummary(ee),!i&&M===e.session.getActiveConversationId()&&e.setActiveConversationSummary(ee),ee},oc=async M=>{let N=_(),ee=e.session.getActiveConversationId()===M;await e.session.deleteConversation(M,{scope:N}),i?.view.removeConversationSummary(M),ee&&(e.setActiveConversationSummary(null),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),Yt()),e.eventBus.emit("history:conversationDeleted",{conversationId:M,scope:N,wasActive:ee,timestamp:Date.now()})},Ra=async M=>{let N=M?.scope??_(),ee=M?.allTargets?null:M?.targetId??V(),ce=await e.session.clearConversationHistory({...ee?{targetId:ee}:{},scope:N});return e.setActiveConversationSummary(null),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),Yt(),e.eventBus.emit("history:cleared",{deleted:ce.deleted,scope:N,targetId:ee,timestamp:Date.now()}),ce},Wa=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(),Yt(),Sn({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}},wi=()=>e.artifactSplitRoot?e.panel:e.container,Es=async M=>{let N=await e.loadHistoryView().catch(()=>null);return typeof N?.showHistoryConfirm=="function"?N.showHistoryConfirm(M):window.confirm(`${M.title}
12
12
 
13
- ${M.description}`)},$t=async M=>await Es({host:wi(),title:o.deleteConversationConfirmTitle,description:o.deleteConversationConfirm,confirmLabel:o.deleteConversationConfirmLabel,cancelLabel:o.confirmCancelLabel})?(await oc(M),"deleted"):"cancelled",Ts=async()=>{let M=_()==="verified-user";return await Es({host:wi(),title:o.clearHistoryConfirmTitle,description:M?o.clearHistoryVerifiedConfirm:o.clearHistoryConfirm,confirmLabel:o.clearHistoryConfirmLabel,cancelLabel:o.confirmCancelLabel})?(await Ra(),"cleared"):"cancelled"},Oa=async()=>{if(!await Es({host:wi(),title:o.resetIdentityConfirmTitle,description:o.resetIdentityConfirm,confirmLabel:o.resetIdentityConfirmLabel,cancelLabel:o.confirmCancelLabel}))return{outcome:"cancelled"};let{remoteRevocationConfirmed:N}=await Wa();return{outcome:"reset",remoteRevocationConfirmed:N}},Zt=x("button","persona-history-earlier");Zt.type="button",Zt.textContent=o.showEarlierMessagesLabel,Zt.setAttribute("data-persona-history-earlier",""),Object.assign(Zt.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 Yt=()=>{if(!(L()&&!!e.historySessionState.nextMessageCursor&&!!e.session.getActiveConversationId())){Zt.remove();return}Zt.textContent=o.showEarlierMessagesLabel,Zt.parentNode!==e.body&&e.body.insertBefore(Zt,e.body.firstChild)};Zt.addEventListener("click",()=>{let M=e.session.getActiveConversationId(),N=e.historySessionState.nextMessageCursor;if(!M||!N||Zt.disabled)return;Zt.disabled=!0;let ee=e.body.scrollHeight,ce=e.body.scrollTop;e.session.loadOlderMessages(M,N,{scope:_()}).then(()=>{e.body.scrollTop=ce+(e.body.scrollHeight-ee),e.repinAnchoredMessage()}).catch(()=>{}).finally(()=>{Zt.disabled=!1,Yt()})});let wo=()=>{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){Sn();return}qe({invoker:M.button,keyboard:N.detail===0})}}),M},Fr=()=>{if(!L()){g?.remove(),d=null,g=null;return}if(g&&!g.isConnected&&(d=null,g=null),!d&&e.header){let ce=wo();d=ce.button,g=ce.wrapper;let He=e.panelElements.clearChatButtonWrapper||e.panelElements.closeButtonWrapper;He?.parentNode&&e.header.contains(He)?He.parentNode.insertBefore(g,He):e.header.appendChild(g)}if(!d||!g)return;let M=Kn()||e.historyVisible&&e.historyPresentation==="rail";if(g.style.display=M?"none":"",M){document.activeElement===d&&gt();return}let N=I();d.disabled=N,d.setAttribute("aria-disabled",N?"true":"false");let ee=N?o.openHistoryBusyLabel:o.openHistoryLabel;d.setAttribute("aria-label",ee),(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))},cr=!1,Ps=()=>{let M=e.panelElements.clearChatButton;if(M){if(L()){cr||(y=M.getAttribute("aria-label")??"",cr=!0),M.setAttribute("aria-label",o.newConversationLabel),M.removeAttribute("title");return}cr&&(cr=!1,y&&M.setAttribute("aria-label",y))}},$n=()=>{o=hf(e.config.features?.history?.copy),Fr(),lr(),Ps(),Yt()};return e.historyChromeSync=$n,T(),$n(),e.destroyCallbacks.push(()=>{v?.(),C?.(),h+=1,Ci(),i?.dispose(),i?.view.destroy(),i=null}),{historyAvailable:L,historyScope:H,installHistoryProvider:T,syncHistoryChromeImpl:$n,syncHistoryPresentation:Bo,syncEarlierMessagesPill:Yt,openHistory:qe,closeHistory:Sn,openHistoryConversation:An,startNewConversation:Co,updateHistoryConversation:Ms,deleteHistoryConversation:oc,requestDeleteConversation:$t,clearConversationHistory:Ra,resetHistoryIdentity:Wa,railCollapseShortcut:bi,railCollapsible:D,railTriggerApplies:Kn,railOverlayMode:bt,toggleRailCollapsed:yi,toggleRailPinned:()=>ro(),get historyProvider(){return r},get historySurface(){return i},get railShell(){return St},get railHost(){return Se},get railColumn(){return It}}}});var ga,Lf=$e(()=>{"use strict";ga=class{#e=null;#t=0;#o=[];#n=[];#l=[];#i=!1;#c=!1;#u=0;#d=!1;#A=!1;#r;#s=[];#g=0;#H=!1;#b;#w;#a;#p=null;constructor(t=24e3,n={}){this.#w=t;let o=Math.max(0,n.prebufferMs??0);this.#a=Math.round(t*o/1e3),this.#r=this.#a>0}#f(){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.#w})}let t=this.#e;return t.state==="suspended"&&!this.#A&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.#p){let r=new Uint8Array(this.#p.length+t.length);r.set(this.#p),r.set(t,this.#p.length),n=r,this.#p=null}if(n.length%2!==0&&(this.#p=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let o=this.#m(n);o.length!==0&&(this.#r?(this.#s.push(o),this.#g+=o.length,clearTimeout(this.#b),this.#g>=this.#a?this.#h():this.#H&&(this.#b=setTimeout(()=>this.#h(),this.#a/this.#w*1e3))):this.#x(o))}markStreamEnd(){this.#s.length>0&&this.#h(),this.#c=!0,this.#y()}flush(){for(let t of this.#o){t.onended=null;try{t.stop(),t.disconnect()}catch{}}this.#o=[],this.#u=0,this.#t=0,this.#i=!1,this.#c=!1,this.#n=[],this.#l=[],this.#p=null,this.#s=[],this.#g=0,this.#r=this.#a>0,this.#d=!1,clearTimeout(this.#b)}setContinuousMode(t){this.#H=t}isPlaying(){return this.#i}onFinished(t){this.#n.push(t)}onStarted(t){this.#l.push(t)}pause(){this.#A=!0,this.#e&&this.#e.state==="running"&&this.#e.suspend()}resume(){this.#A=!1,this.#e&&this.#e.state==="suspended"&&this.#e.resume()}async destroy(){this.flush(),this.#e&&(await this.#e.close(),this.#e=null)}#h(){this.#r=!1;let t=this.#s;this.#s=[],this.#g=0;for(let n of t)this.#x(n)}#x(t){if(t.length===0)return;let n=this.#f(),o=n.createBuffer(1,t.length,this.#w);o.getChannelData(0).set(t);let r=n.createBufferSource();r.buffer=o,r.connect(n.destination);let s=n.currentTime;if(this.#t===0?this.#t=s:this.#t<s&&(this.#t=s,this.#a>0&&(this.#r=!0)),r.start(this.#t),this.#t+=o.duration,this.#o.push(r),this.#u++,this.#i=!0,!this.#d){this.#d=!0;let i=this.#l.slice();this.#l=[];for(let l of i)l()}r.onended=()=>{let i=this.#o.indexOf(r);i!==-1&&(this.#o.splice(i,1),this.#u--,this.#y())}}#y(){if(this.#c&&this.#u<=0&&this.#s.length===0){this.#i=!1,this.#c=!1;let t=this.#n.slice();this.#n=[];for(let n of t)n()}}#m(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 j0(e){return e.replace(/\/+$/,"")}async function q0(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 Jd,qC=$e(()=>{"use strict";Lf();Jd=class{constructor(t){this.id="runtype-tts";this.supportsPause=!0;this.#e=null;this.#t=null;this.#o=0;this.#n=t}#e;#t;#o;#n;#l(){return this.#t??=Promise.resolve(this.#n.createPlaybackEngine?this.#n.createPlaybackEngine():new ga(24e3,{prebufferMs:this.#n.prebufferMs??200})).then(t=>this.#e=t)}speak(t,n){let o=++this.#o;this.#i(o,t,n)}async#i(t,n,o){try{let r=await this.#l();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=`${j0(this.#n.host)}/v1/agents/${encodeURIComponent(this.#n.agentId)}/speak`,i=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.#n.clientToken}`},body:JSON.stringify({text:n.text,voice:n.voice??this.#n.voice,format:"pcm"})});if(t!==this.#o)return;if(!i.ok||!i.body)throw new Error(await q0(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.#n.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.#t=null}}});var Zd,zC=$e(()=>{"use strict";Zd=class{constructor(t,n,o={}){this.id="fallback";this.#t=t,this.#o=n,this.#n=o,this.#e=t}#e;#t;#o;#n;get supportsPause(){return this.#e.supportsPause}speak(t,n){this.#e=this.#t;let o=!1;this.#t.speak(t,{onStart:()=>{o=!0,n.onStart?.()},onEnd:()=>n.onEnd?.(),onError:r=>{if(o){n.onError?.(r);return}this.#n.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.#t.destroy?.(),this.#o.destroy?.()}}});var KC={};Qs(KC,{FallbackSpeechEngine:()=>Zd,RuntypeSpeechEngine:()=>Jd});var GC=$e(()=>{"use strict";qC();zC()});import{Marked as DM}from"marked";import NM from"dompurify";ln();var{setLoader:nO,load:BM,provide:_M,getSync:fg}=it({fallbackImport:()=>Promise.resolve().then(()=>(yb(),hb))}),Kc=new Set,bb=()=>{let e=[...Kc];Kc.clear();for(let t of e)try{t()}catch{}};var mg=()=>{let e=fg();return e?Promise.resolve(e):BM().then(t=>(bb(),t))},il=e=>fg()?()=>{}:(Kc.add(e),()=>{Kc.delete(e)}),vb=e=>{_M(e),bb()},Yo=fg;vb({Marked:DM,DOMPurify:NM});import{Ban as FM,Bell as $M,Bookmark as UM,Building as VM,Calendar as jM,CalendarDays as qM,Camera as zM,ChartColumn as KM,CircleCheck as GM,CircleX as YM,Clock as XM,CreditCard as QM,DollarSign as JM,EyeOff as ZM,Files as eE,Film as tE,Flag as nE,Folder as oE,FolderOpen as rE,Funnel as sE,Gift as iE,Globe as aE,Hash as lE,Headphones as cE,Heart as dE,House as pE,Image as uE,Info as gE,Key as fE,Lightbulb as mE,Link as hE,Lock as yE,Mail as bE,MapPin as vE,MessageCircle as CE,Monitor as wE,Moon as SE,Package as AE,Pause as xE,PenLine as ME,Percent as EE,Phone as TE,Play as PE,Receipt as kE,RotateCw as LE,Save as HE,Settings as IE,Share as RE,Shield as WE,ShoppingBag as OE,ShoppingCart as BE,Smartphone as _E,Sparkles as DE,Store as NE,Sun as FE,Tag as $E,Timer as UE,TriangleAlert as VE,Truck as jE,User as qE,VolumeX as zE,Wallet as KE,Zap as GE}from"lucide";var Cb={user:qE,mail:bE,phone:TE,calendar:jM,clock:XM,building:VM,"map-pin":vE,lock:yE,key:fE,"credit-card":QM,hash:lE,globe:aE,link:hE,"circle-check":GM,"circle-x":YM,"triangle-alert":VE,info:gE,ban:FM,shield:WE,house:pE,"pen-line":ME,save:HE,share:RE,funnel:sE,settings:IE,"rotate-cw":LE,"shopping-cart":BE,"shopping-bag":OE,package:AE,truck:jE,tag:$E,gift:iE,receipt:kE,wallet:KE,store:NE,"dollar-sign":JM,percent:EE,play:PE,pause:xE,"volume-x":zE,camera:zM,image:uE,film:tE,headphones:cE,"message-circle":CE,bell:$M,heart:dE,"eye-off":ZM,bookmark:UM,"calendar-days":qM,timer:UE,folder:oE,"folder-open":rE,files:eE,"chart-column":KM,sparkles:DE,zap:GE,sun:FE,moon:SE,flag:nE,lightbulb:mE,monitor:wE,smartphone:_E};Tt();Sb(Cb);Wg();ln();var{setLoader:FO,load:$P,provide:UP,getSync:VP}=it({fallbackImport:()=>Promise.resolve().then(()=>(Wg(),cd))});var oi=$P,ov=UP,rv=VP;ov(cd);Dg();ln();var{setLoader:GO,load:nk,provide:ok}=it({fallbackImport:()=>Promise.resolve().then(()=>(Dg(),dd))});var Tr=nk,mv=ok;mv(dd);pf();ln();var{setLoader:XB,load:Wk,provide:Ok,getSync:Bk}=it({fallbackImport:()=>Promise.resolve().then(()=>(pf(),Hd))});var Id=Wk,Yv=Ok,uf=Bk;Yv(Hd);ff();ln();var{setLoader:t_,load:jk,provide:qk,getSync:zk}=it({fallbackImport:()=>Promise.resolve().then(()=>(ff(),Wd))});var mf=jk,Jv=qk,Zv=zk;Jv(Wd);Cf();ln();var{setLoader:b_,load:i0,provide:a0,getSync:l0}=it({fallbackImport:()=>Promise.resolve().then(()=>(Cf(),$d))});var gC=i0,fC=a0,Ud=l0;fC($d);Mr();bo();Xe();Tt();import{Circle as m0,Clock as h0}from"lucide";Xe();Mr();import{ChevronDown as c0,ChevronUp as d0}from"lucide";var p0=["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"],u0="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",g0="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",f0=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Vd=(e,t)=>{let n=x("div",["persona-message-bubble",e,...p0].join(" "));return n.id=`bubble-${t}`,n.setAttribute("data-message-id",t),n},jd=e=>{let t=x("button",e.expandable?u0:g0);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},wf=(e,t,n)=>{e.innerHTML="";let o=_t(t?d0:c0,16,n,2);o?e.appendChild(o):e.textContent=t?"Hide":"Show"},da=(e,t,n)=>{if(!n.expandable)return e.append(t),null;let o=x("div","persona-flex persona-items-center");wf(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},qd=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?.();f0(t,n)||(t.textContent=e.previewText),t.style.display=""}return!e.expanded&&e.isActive&&e.activeMinHeight&&(e.bubble.style.minHeight=e.activeMinHeight),t},zd=e=>{e.header.setAttribute("aria-expanded",e.expanded?"true":"false"),e.toggleIcon&&wf(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"},Kd=(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&&wf(c,o,n.iconColor),s.style.display=o?"":"none",i&&(i.style.display=o?"none":i.textContent||i.childNodes.length?"":"none")};function Gd(e,t){let n=t==="tool"?"toolCallDisplay":"reasoningDisplay";return{...e,features:{...e?.features,[n]:{...t==="tool"?kr:ai,...e?.future?.v5Defaults===!0?ii.features?.[n]:{},...e?.features?.[n]}}}}function fs(e,t){let n=t==="tool"?"toolCallDisplay":"reasoningDisplay";return e?.features?.[n]?.variant??(e?.future?.v5Defaults?"row":"card")}function xl(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 Rr(e,t,n,o){if(fs(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?ue(g,16,"currentColor",2):c==="pending"?_t(m0,16,"currentColor",2):c==="awaiting-approval"?_t(h0,16,"currentColor",2):ue(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?"":xl(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 mC(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 hC(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),da(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),Rr(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}}Vg();function yC(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 On(e){return e?.type==="runtype"||e?.type==="custom"}var y0=()=>typeof window<"u"&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window);function bC(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:y0()}catch{return!1}}var b0=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},Yd=e=>{let t=null;return n=>{let o=Yo();if(!o)return ms(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=b0(e?.renderer);i&&t.use({renderer:i})}return t.parse(n)}},Xd=e=>e?Yd({markedOptions:e.options,renderer:e.renderer}):Yd(),v0=Yd(),CC=e=>v0(e),ms=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),wC=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),vC=e=>`%%FORM_PLACEHOLDER_${e}%%`,SC=(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=vC(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=vC(t.length);return t.push({token:s,type:r}),s}),n},C0=e=>{let t=Xd(e);return n=>{let o=[],r=SC(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="${wC(l)}"></div>`;s=s.replace(c,d)}),s}},w0=e=>{let t=[],n=SC(e,t),o=CC(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="${wC(s)}"></div>`;o=o.replace(i,c)}),o};var S0={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"]},A0=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,AC=()=>{let e=null;return t=>{let n=Yo();if(!n)return ms(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:")&&!A0.test(i)&&(s.attrValue="",s.keepAttr=!1)}})}return e.sanitize(t,S0)}},Sf=e=>e===!1?null:typeof e=="function"?e:AC();var xC=/^\s*\|?[\s:|-]*-[\s:|-]*$/,MC=e=>e.includes("|"),EC=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())},x0=e=>`| ${e.join(" | ")} |`,M0=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,E0=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),TC=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
13
+ ${M.description}`)},$t=async M=>await Es({host:wi(),title:o.deleteConversationConfirmTitle,description:o.deleteConversationConfirm,confirmLabel:o.deleteConversationConfirmLabel,cancelLabel:o.confirmCancelLabel})?(await oc(M),"deleted"):"cancelled",Ts=async()=>{let M=_()==="verified-user";return await Es({host:wi(),title:o.clearHistoryConfirmTitle,description:M?o.clearHistoryVerifiedConfirm:o.clearHistoryConfirm,confirmLabel:o.clearHistoryConfirmLabel,cancelLabel:o.confirmCancelLabel})?(await Ra(),"cleared"):"cancelled"},Oa=async()=>{if(!await Es({host:wi(),title:o.resetIdentityConfirmTitle,description:o.resetIdentityConfirm,confirmLabel:o.resetIdentityConfirmLabel,cancelLabel:o.confirmCancelLabel}))return{outcome:"cancelled"};let{remoteRevocationConfirmed:N}=await Wa();return{outcome:"reset",remoteRevocationConfirmed:N}},Zt=x("button","persona-history-earlier");Zt.type="button",Zt.textContent=o.showEarlierMessagesLabel,Zt.setAttribute("data-persona-history-earlier",""),Object.assign(Zt.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 Yt=()=>{if(!(L()&&!!e.historySessionState.nextMessageCursor&&!!e.session.getActiveConversationId())){Zt.remove();return}Zt.textContent=o.showEarlierMessagesLabel,Zt.parentNode!==e.body&&e.body.insertBefore(Zt,e.body.firstChild)};Zt.addEventListener("click",()=>{let M=e.session.getActiveConversationId(),N=e.historySessionState.nextMessageCursor;if(!M||!N||Zt.disabled)return;Zt.disabled=!0;let ee=e.body.scrollHeight,ce=e.body.scrollTop;e.session.loadOlderMessages(M,N,{scope:_()}).then(()=>{e.body.scrollTop=ce+(e.body.scrollHeight-ee),e.repinAnchoredMessage()}).catch(()=>{}).finally(()=>{Zt.disabled=!1,Yt()})});let wo=()=>{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){Sn();return}qe({invoker:M.button,keyboard:N.detail===0})}}),M},Fr=()=>{if(!L()){g?.remove(),d=null,g=null;return}if(g&&!g.isConnected&&(d=null,g=null),!d&&e.header){let ce=wo();d=ce.button,g=ce.wrapper;let He=e.panelElements.clearChatButtonWrapper||e.panelElements.closeButtonWrapper;He?.parentNode&&e.header.contains(He)?He.parentNode.insertBefore(g,He):e.header.appendChild(g)}if(!d||!g)return;let M=Kn()||e.historyVisible&&e.historyPresentation==="rail";if(g.style.display=M?"none":"",M){document.activeElement===d&&gt();return}let N=I();d.disabled=N,d.setAttribute("aria-disabled",N?"true":"false");let ee=N?o.openHistoryBusyLabel:o.openHistoryLabel;d.setAttribute("aria-label",ee),(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))},cr=!1,Ps=()=>{let M=e.panelElements.clearChatButton;if(M){if(L()){cr||(y=M.getAttribute("aria-label")??"",cr=!0),M.setAttribute("aria-label",o.newConversationLabel),M.removeAttribute("title");return}cr&&(cr=!1,y&&M.setAttribute("aria-label",y))}},$n=()=>{o=hf(e.config.features?.history?.copy),Fr(),lr(),Ps(),Yt()};return e.historyChromeSync=$n,T(),$n(),e.destroyCallbacks.push(()=>{v?.(),C?.(),h+=1,Ci(),i?.dispose(),i?.view.destroy(),i=null}),{historyAvailable:L,historyScope:H,installHistoryProvider:T,syncHistoryChromeImpl:$n,syncHistoryPresentation:Bo,syncEarlierMessagesPill:Yt,openHistory:qe,closeHistory:Sn,openHistoryConversation:An,startNewConversation:Co,updateHistoryConversation:Ms,deleteHistoryConversation:oc,requestDeleteConversation:$t,clearConversationHistory:Ra,resetHistoryIdentity:Wa,railCollapseShortcut:bi,railCollapsible:D,railTriggerApplies:Kn,railOverlayMode:bt,toggleRailCollapsed:yi,toggleRailPinned:()=>ro(),get historyProvider(){return r},get historySurface(){return i},get railShell(){return St},get railHost(){return Se},get railColumn(){return It}}}});var ga,Lf=$e(()=>{"use strict";ga=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 j0(e){return e.replace(/\/+$/,"")}async function q0(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 Jd,qC=$e(()=>{"use strict";Lf();Jd=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 ga(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=`${j0(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 q0(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 Zd,zC=$e(()=>{"use strict";Zd=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 KC={};Qs(KC,{FallbackSpeechEngine:()=>Zd,RuntypeSpeechEngine:()=>Jd});var GC=$e(()=>{"use strict";qC();zC()});import{Marked as DM}from"marked";import NM from"dompurify";ln();var{setLoader:nO,load:BM,provide:_M,getSync:fg}=it({fallbackImport:()=>Promise.resolve().then(()=>(yb(),hb))}),Kc=new Set,bb=()=>{let e=[...Kc];Kc.clear();for(let t of e)try{t()}catch{}};var mg=()=>{let e=fg();return e?Promise.resolve(e):BM().then(t=>(bb(),t))},il=e=>fg()?()=>{}:(Kc.add(e),()=>{Kc.delete(e)}),vb=e=>{_M(e),bb()},Yo=fg;vb({Marked:DM,DOMPurify:NM});import{Ban as FM,Bell as $M,Bookmark as UM,Building as VM,Calendar as jM,CalendarDays as qM,Camera as zM,ChartColumn as KM,CircleCheck as GM,CircleX as YM,Clock as XM,CreditCard as QM,DollarSign as JM,EyeOff as ZM,Files as eE,Film as tE,Flag as nE,Folder as oE,FolderOpen as rE,Funnel as sE,Gift as iE,Globe as aE,Hash as lE,Headphones as cE,Heart as dE,House as pE,Image as uE,Info as gE,Key as fE,Lightbulb as mE,Link as hE,Lock as yE,Mail as bE,MapPin as vE,MessageCircle as CE,Monitor as wE,Moon as SE,Package as AE,Pause as xE,PenLine as ME,Percent as EE,Phone as TE,Play as PE,Receipt as kE,RotateCw as LE,Save as HE,Settings as IE,Share as RE,Shield as WE,ShoppingBag as OE,ShoppingCart as BE,Smartphone as _E,Sparkles as DE,Store as NE,Sun as FE,Tag as $E,Timer as UE,TriangleAlert as VE,Truck as jE,User as qE,VolumeX as zE,Wallet as KE,Zap as GE}from"lucide";var Cb={user:qE,mail:bE,phone:TE,calendar:jM,clock:XM,building:VM,"map-pin":vE,lock:yE,key:fE,"credit-card":QM,hash:lE,globe:aE,link:hE,"circle-check":GM,"circle-x":YM,"triangle-alert":VE,info:gE,ban:FM,shield:WE,house:pE,"pen-line":ME,save:HE,share:RE,funnel:sE,settings:IE,"rotate-cw":LE,"shopping-cart":BE,"shopping-bag":OE,package:AE,truck:jE,tag:$E,gift:iE,receipt:kE,wallet:KE,store:NE,"dollar-sign":JM,percent:EE,play:PE,pause:xE,"volume-x":zE,camera:zM,image:uE,film:tE,headphones:cE,"message-circle":CE,bell:$M,heart:dE,"eye-off":ZM,bookmark:UM,"calendar-days":qM,timer:UE,folder:oE,"folder-open":rE,files:eE,"chart-column":KM,sparkles:DE,zap:GE,sun:FE,moon:SE,flag:nE,lightbulb:mE,monitor:wE,smartphone:_E};Tt();Sb(Cb);Wg();ln();var{setLoader:FO,load:$P,provide:UP,getSync:VP}=it({fallbackImport:()=>Promise.resolve().then(()=>(Wg(),cd))});var oi=$P,ov=UP,rv=VP;ov(cd);Dg();ln();var{setLoader:GO,load:nk,provide:ok}=it({fallbackImport:()=>Promise.resolve().then(()=>(Dg(),dd))});var Tr=nk,mv=ok;mv(dd);pf();ln();var{setLoader:XB,load:Wk,provide:Ok,getSync:Bk}=it({fallbackImport:()=>Promise.resolve().then(()=>(pf(),Hd))});var Id=Wk,Yv=Ok,uf=Bk;Yv(Hd);ff();ln();var{setLoader:t_,load:jk,provide:qk,getSync:zk}=it({fallbackImport:()=>Promise.resolve().then(()=>(ff(),Wd))});var mf=jk,Jv=qk,Zv=zk;Jv(Wd);Cf();ln();var{setLoader:b_,load:i0,provide:a0,getSync:l0}=it({fallbackImport:()=>Promise.resolve().then(()=>(Cf(),$d))});var gC=i0,fC=a0,Ud=l0;fC($d);Mr();bo();Xe();Tt();import{Circle as m0,Clock as h0}from"lucide";Xe();Mr();import{ChevronDown as c0,ChevronUp as d0}from"lucide";var p0=["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"],u0="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",g0="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",f0=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Vd=(e,t)=>{let n=x("div",["persona-message-bubble",e,...p0].join(" "));return n.id=`bubble-${t}`,n.setAttribute("data-message-id",t),n},jd=e=>{let t=x("button",e.expandable?u0:g0);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},wf=(e,t,n)=>{e.innerHTML="";let o=_t(t?d0:c0,16,n,2);o?e.appendChild(o):e.textContent=t?"Hide":"Show"},da=(e,t,n)=>{if(!n.expandable)return e.append(t),null;let o=x("div","persona-flex persona-items-center");wf(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},qd=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?.();f0(t,n)||(t.textContent=e.previewText),t.style.display=""}return!e.expanded&&e.isActive&&e.activeMinHeight&&(e.bubble.style.minHeight=e.activeMinHeight),t},zd=e=>{e.header.setAttribute("aria-expanded",e.expanded?"true":"false"),e.toggleIcon&&wf(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"},Kd=(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&&wf(c,o,n.iconColor),s.style.display=o?"":"none",i&&(i.style.display=o?"none":i.textContent||i.childNodes.length?"":"none")};function Gd(e,t){let n=t==="tool"?"toolCallDisplay":"reasoningDisplay";return{...e,features:{...e?.features,[n]:{...t==="tool"?kr:ai,...e?.future?.v5Defaults===!0?ii.features?.[n]:{},...e?.features?.[n]}}}}function fs(e,t){let n=t==="tool"?"toolCallDisplay":"reasoningDisplay";return e?.features?.[n]?.variant??(e?.future?.v5Defaults?"row":"card")}function xl(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 Rr(e,t,n,o){if(fs(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?ue(g,16,"currentColor",2):c==="pending"?_t(m0,16,"currentColor",2):c==="awaiting-approval"?_t(h0,16,"currentColor",2):ue(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?"":xl(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 mC(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 hC(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),da(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),Rr(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}}Vg();function yC(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 On(e){return e?.type==="runtype"||e?.type==="custom"}var y0=()=>typeof window<"u"&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window);function bC(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:y0()}catch{return!1}}var b0=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},Yd=e=>{let t=null;return n=>{let o=Yo();if(!o)return ms(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=b0(e?.renderer);i&&t.use({renderer:i})}return t.parse(n)}},Xd=e=>e?Yd({markedOptions:e.options,renderer:e.renderer}):Yd(),v0=Yd(),CC=e=>v0(e),ms=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),wC=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),vC=e=>`%%FORM_PLACEHOLDER_${e}%%`,SC=(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=vC(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=vC(t.length);return t.push({token:s,type:r}),s}),n},C0=e=>{let t=Xd(e);return n=>{let o=[],r=SC(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="${wC(l)}"></div>`;s=s.replace(c,d)}),s}},w0=e=>{let t=[],n=SC(e,t),o=CC(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="${wC(s)}"></div>`;o=o.replace(i,c)}),o};var S0={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"]},A0=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,AC=()=>{let e=null;return t=>{let n=Yo();if(!n)return ms(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:")&&!A0.test(i)&&(s.attrValue="",s.keepAttr=!1)}})}return e.sanitize(t,S0)}},Sf=e=>e===!1?null:typeof e=="function"?e:AC();var xC=/^\s*\|?[\s:|-]*-[\s:|-]*$/,MC=e=>e.includes("|"),EC=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())},x0=e=>`| ${e.join(" | ")} |`,M0=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,E0=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),TC=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
14
14
  `),n=!1;for(let o=0;o<t.length-1;o++){let r=t[o],s=t[o+1];if(!MC(r)||xC.test(r)||!xC.test(s))continue;let i=EC(r).length;if(i<1)continue;let l=M0(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()===""||!MC(p))break;let d=x0(E0(EC(p),i));t[c]!==d&&(t[c]=d,n=!0)}o=c-1}return n?t.join(`
15
- `):e};var PC="var(--persona-md-table-scroll-fade, 24px)",kC=new WeakSet;function HC(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 LC(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":PC),e.style.setProperty("--persona-fade-r",r<=1?"0px":PC)}function Af(e){kC.has(e)||(kC.add(e),e.addEventListener("scroll",t=>{let n=t.target;n?.classList?.contains("persona-table-scroll")&&LC(n)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(LC)}ei();ln();var{setLoader:$_,load:T0}=it({fallbackImport:()=>import("@runtypelabs/persona/webmcp-runtime")});var IC=T0;var P0="agent_",k0="flow_";function RC(e){return e.startsWith(P0)?{kind:"agentId",agentId:e}:e.startsWith(k0)?{kind:"flowId",flowId:e}:null}function WC(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=RC(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=RC(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 L0(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Ml(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function li(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}function OC(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`turn_${e}_${t}`}ad();var H0=e=>e.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase().replace(/_+/g,"_").replace(/^_|_$/g,""),I0=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),R0=e=>{if(e.variant!=="tool")return null;let t=e.agentMetadata?.clientToolAnswer;if(!t||!t.toolCallId||t.result===void 0)return null;let n=H0(t.toolName);return n?{call:{toolCallId:t.toolCallId,toolName:n,args:I0(t.args)?t.args:{}},result:{toolCallId:t.toolCallId,toolName:n,result:t.result}}:null},xf=(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=R0(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};ss();oa();Fd();Lo();var W0="https://api.runtype.com/v1/dispatch",tn=class extends Error{constructor(t,n,o){super(n),this.name="HistoryClientError",this.code=t,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}},BC=e=>"reason"in e?e.reason:void 0,O0="The identity proof was rejected",Mf=(e,t)=>e instanceof tn&&e.code===t,Ef=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),_C=e=>e.slice().sort((t,n)=>new Date(t.createdAt).getTime()-new Date(n.createdAt).getTime()),DC=e=>({role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,createdAt:e.createdAt});function B0(e){switch(e){case"json":return xg;case"regex-json":return Ag;case"xml":return Mg;default:return Sg}}var pa=class{constructor(t={},n={}){this.config=t;this.historyInternals=n;this.#A=null;this.clientSession=null;this.#r=null;this.#s=!1;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.#g=null;this.#H=!1;this.#b=!1;this.#w=!1;this.#a=null;this.#p=new Set;this.#f=new Set;this.webMcpBridge=null;this.#h=null;this.#te=null;this.#ce=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??W0,this.#t={"Content-Type":"application/json","X-Persona-Version":Jn,...t.headers},this.debug=!!t.debug,this.#o=t.streamParser??B0(t.parserType),this.#n=t.contextProviders??[],this.#l=t.requestMiddleware,this.#i=t.customFetch,this.#c=t.parseSSEEvent,this.#u=t.getHeaders,t.webmcp?.enabled===!0&&(this.#h=this.#y(t.webmcp))}#e;#t;#o;#n;#l;#i;#c;#u;#d;#A;#r;#s;#g;#H;#b;#w;#a;#p;#f;#h;#x;#y(t){return IC().then(n=>{let o=new n.WebMcpBridge(t,{recordToolDisplayTitles:Qc,getToolDisplayTitle:Gi,loadPolyfill:Jc});return this.#x!==void 0&&o.setConfirmHandler(this.#x),this.webMcpBridge=o,o}).catch(n=>(this.#h=null,console.warn("[Persona] Failed to load the WebMCP runtime chunk",n),null))}#m(){return this.webMcpBridge?Promise.resolve(this.webMcpBridge):this.config.webmcp?.enabled!==!0?Promise.resolve(null):(this.#h||(this.#h=this.#y(this.config.webmcp)),this.#h)}updateConfig(t){this.config=t}setHistoryInternals(t){this.historyInternals=t}setSSEEventCallback(t){this.#d=t}setWebMcpConfirmHandler(t){this.#x=t,this.webMcpBridge?.setConfirmHandler(t)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(t,n,o){return this.config.webmcp?.enabled!==!0?null:this.#m().then(r=>r?r.executeToolCall(t,n,o):{isError:!0,content:[{type:"text",text:"WebMCP runtime failed to load."}]})}getSSEEventCallback(){return this.#d}isClientTokenMode(){return!!this.config.clientToken}#M(){let{agentId:t,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:t,flowId:n};let s=WC(o,r);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.#M().agentId)}#k(){return this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||ld}#S(t){return`${this.#k()}/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 tn("visitor_token_missing","Durable recovery is not enabled for this client session");let i=`${this.#k()}/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":Jn,"X-Visitor-Token":s},signal:t.signal});if(c.status===401&&!o){o=!0;let p=await Tr();n=await p.recoverFromUnauthorized(this.#I(),await p.readErrorCode(this.#I(),c),null,!0);continue}if(!c.ok)throw await(await Tr()).historyErrorFor(this.#I(),c,!0);return c}}async warmSession(){let t=this.clientSession;return!this.isClientTokenMode()||this.#r||t&&new Date<t.expiresAt||this.#s===t?null:(this.#s=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.#r)return this.#r;let t=this.#r=this.#F().then(n=>this.#r!==t?this.initSession():(this.clientSession=n,this.#s=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(n),n)).finally(()=>{this.#r===t&&(this.#r=null)});return t}#C(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()&&!this.#H}async readVisitorToken(){let t=this.historyInternals.visitorStore;return t?(await t.ready,await t.get()??null):null}#G(){if(!this.#H){this.#O({state:"unavailable",reason:"history_disabled"}),this.#H=!0,!this.#b&&typeof console<"u"&&(this.#b=!0,console.warn("[Persona] Visitor history is disabled for this surface; continuing without it.")),this.historyInternals.onHistoryAvailabilityChanged?.(!1);for(let t of[...this.#f])t(!1)}}getHistoryIdentityStatus(){return this.#a??this.#J()}subscribeHistoryIdentityStatus(t){return this.#p.add(t),()=>{this.#p.delete(t)}}subscribeHistoryAvailability(t){return this.#f.add(t),this.#H&&t(!1),()=>{this.#f.delete(t)}}#J(){return this.isClientTokenMode()?this.config.features?.history?.enabled!==!0||this.#H?{state:"unavailable",reason:"history_disabled"}:this.#V():{state:"unavailable",reason:"ineligible_mode"}}#V(){let t=this.#a;return t?.state==="browser_only"?t:this.#W()}#W(){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"}}#O(t){let n=this.getHistoryIdentityStatus(),o=n.state===t.state&&BC(n)===BC(t);if(this.#a=t,!o){this.historyInternals.onHistoryIdentityStatusChanged?.(t);for(let r of[...this.#p])r(t)}}async#E(t){let n=this.#C()&&!t.omitVisitorFields,o=!t.omitVisitorFields,r=null;(n||o)&&(await this.historyInternals.historyBootstrapReady,r=await this.readVisitorToken());let s=this.#M(),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.#S("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Jn},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.#G(),l)throw new tn("history_disabled","Visitor history is disabled for this surface");return this.#E({...t,omitVisitorFields:!0})}throw p.status===403&&g.error==="durable_recovery_disabled"?new tn("history_disabled","Durable recovery is disabled for this surface"):(n||t.durableResume)&&p.status===401&&g.error==="visitor_required"?new tn("visitor_required","Visitor credential no longer resolves"):l&&p.status===404?new tn("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#F(){await this.historyInternals.historyBootstrapReady;let t=this.config.getStoredConversationId?.()||null,n=this.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.#C()&&!n)return this.#Z(t,!1);let o=await this.readVisitorToken();if(t&&o)try{let r=await this.#E({conversationId:t,durableResume:n});return n&&r.durableRecovery?.enabled!==!0&&this.historyInternals.setStoredResumableHandle?.(null),this.#B(r,t,!1)}catch(r){if(!Mf(r,"not_found")&&!Mf(r,"visitor_required")&&!Mf(r,"history_disabled"))throw r;return n&&this.historyInternals.setStoredResumableHandle?.(null),this.#Z(t,!0)}return this.#Z(t,!1)}async#Z(t,n){let o=this.historyInternals.visitorStore;return o&&!await this.readVisitorToken()?o.withFirstInitLock(()=>this.#ee(t,n)):this.#ee(t,n)}async#ee(t,n){let o=this.config.getStoredSessionId?.()||null,r=await this.#E({storedSessionId:o}),s=await this.#q(r);return this.#B(s,t,n)}async#j(t){let n=this.config.getStoredSessionId?.()||null,o=this.config.getStoredConversationId?.()||null,r=await this.#E({storedSessionId:n,identityProof:t}),s=this.#B(r,o,!1);return this.clientSession=s,this.#r=null,this.#s=!1,this.resetClientToolsFingerprint(),s}async#q(t){if(!t.visitor?.token||this.#w||!this.#C()&&t.durableRecovery?.enabled!==!0)return t;this.#w=!0;try{return await this.#E({storedSessionId:t.sessionId})}catch{return t}finally{this.#w=!1}}#B(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}#re(t){let n=!1;return{session:t,commit:()=>{n||(n=!0,this.clientSession=t,this.#s=!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.#C())throw new tn("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 tn("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let s=await this.#E({conversationId:t,identityProof:o});return this.#re(s)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw new Error("prepareNewConversationSession() only available in client token mode");await this.historyInternals.historyBootstrapReady;let t=await this.#E({});return this.#re(t)}handleExternalCredentialChange(){this.clearClientSession(),this.#C()&&this.#O(this.#W())}clearClientSession(){this.clientSession=null,this.#r=null,this.#s=!1,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.#g=null}#Y(){return`${this.#k()}/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.#Y(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Jn},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.#s=!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#_(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}}#te;#le(){let t=this;return this.#te??={get config(){return t.config},headers:this.#t,getHeaders:this.#u,debug:this.debug,clientApiBase:()=>t.#k(),getClientApiUrl:n=>t.#S(n),getWebMcpBridge:()=>t.#m(),sendWithClientToolsDiff:(n,o,r,s)=>t.#$(n,o,r,s),initSession:()=>t.initSession(),readVisitorToken:()=>t.readVisitorToken(),isClientTokenMode:()=>t.isClientTokenMode()}}#ce;#I(){let t=this;return this.#ce??={HistoryClientError:tn,get config(){return t.config},get historyInternals(){return t.historyInternals},get clientSession(){return t.clientSession},clientApiBase:()=>t.#k(),setHistoryIdentityStatus:n=>t.#O(n),browserOnlyStatus:()=>t.#V(),derivedBrowserOnly:()=>t.#W(),reinitWithProof:n=>t.#j(n),isHistoryCapable:()=>t.#C(),clearClientSession:()=>t.clearClientSession(),initSession:()=>t.initSession(),readVisitorToken:()=>t.readVisitorToken(),isClientTokenMode:()=>t.isClientTokenMode()}}async listConversations(t){return(await Tr()).listConversations(this.#I(),t)}async getConversation(t,n){return(await Tr()).getConversation(this.#I(),t,n)}async finalizeDisplayProjections(t,n){return(await Tr()).finalizeDisplayProjections(this.#I(),t,n)}async deleteConversation(t,n){return(await Tr()).deleteConversation(this.#I(),t,n)}async deleteAllConversations(t){return(await Tr()).deleteAllConversations(this.#I(),t)}async resetVisitor(){return(await Tr()).resetVisitor(this.#I())}async dispatch(t,n){return t.signal?.throwIfAborted(),oi().catch(()=>{}),this.isClientTokenMode()?this.#de(t,n):this.isAgentMode()?this.#pe(t,n):this.#ne(t,n)}async#de(t,n){let o=OC();this.#A=o;let r=()=>this.#A===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.#E({...L||this.#C()?{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.#B(I,A.conversationId??null,!1),this.clientSession=l,this.#s=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(l)};Date.now()>=l.expiresAt.getTime()-6e4&&await c();let p=await this.#oe(t.messages),d=p.metadata?Object.fromEntries(Object.entries(p.metadata).filter(([A])=>A!=="sessionId"&&A!=="session_id")):void 0,g=this.#C(),f={sessionId:l.sessionId,messages:t.messages.filter(Ef).map(A=>{let L=g?Sl(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.#$(l.sessionId,p.clientTools,async L=>{i();let I=await this.#_(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.#S("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Jn,...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 tn("invalid_identity_proof",O0);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 tn("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.#D(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 tn)&&!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&s({type:"error",error:l}),l}}async#ne(t,n){n({type:"status",status:"connecting"});let o=await this.#oe(t.messages,t.composerOptions);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.#t};if(this.#u)try{let i=await this.#u();r={...r,...i}}catch(i){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.#i)try{s=await this.#i(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.#D(s.body,n)}finally{n({type:"status",status:"idle"})}}async#pe(t,n){n({type:"status",status:"connecting"});let o=await this.#he(t.messages,t.composerOptions);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.#t};if(this.#u)try{let i=await this.#u();r={...r,...i}}catch(i){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.#i)try{s=await this.#i(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.#D(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.#D(t,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){return(await oi()).resolveApproval(this.#le(),t,n)}async#$(t,n,o,r){let s=!!(n&&n.length>0),i=s?Mb(n):void 0,l=this.clientToolsFingerprintSessionId===t,c=s&&l&&this.lastSentClientToolsFingerprint===i,p=!s&&r?.emptyMeansReplace===!0&&this.#g===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.#g=t:p&&(this.#g=null)}}}async resumeFlow(t,n,o){return(await oi()).resumeFlow(this.#le(),t,n,o)}#R(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#L(t){let n={};this.#n.length&&await Promise.all(this.#n.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.#R(t);return o&&Object.assign(n,o),Object.keys(n).length?n:null}#T(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}#z(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#he(t,n){let o=this.#M().agentId;if(!this.config.agent&&!o)throw new Error("Agent configuration required for agent mode");let r=xf(_C(t),p=>Ef(p)&&(p.role==="user"||p.role==="assistant"||p.role==="system")&&(!p.variant||p.variant==="assistant")?DC(p):null),s=this.#T(n),i={agent:this.#z(this.config.agent??{agentId:o},s),messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};s&&(i.composerOptions=s);let l=[...ta(this.config),...await(await this.#m())?.snapshotForDispatch()??[]];l.length>0&&(i.clientTools=l);let c=await this.#L(t);return c&&(i.context=c),i}async#oe(t,n){let o=xf(_C(t),p=>Ef(p)?DC(p):null),r=this.#M(),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=[...ta(this.config),...await(await this.#m())?.snapshotForDispatch()??[]];i.length>0&&(s.clientTools=i);let l=await this.#L(t);l&&(s.context=l);let c=this.#T(n);if(c&&(s.composerOptions=c),this.#l)try{let p=await this.#l({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#D(t,n,o,r){let{streamResponse:s}=rv()??await oi();return s({config:()=>this.config,createStreamParser:this.#o,parseSSEEvent:this.#c,onSSEEvent:(i,l)=>this.#d?.(i,l)},t,n,o,r)}};var hs=class extends Error{constructor(t,n,o){super(n),this.name="HistoryProviderError",this.code=t,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}};function _0(e){return e instanceof hs}ei();ea();Hr();Yi();Hr();function D0(e){let t=0;for(let n of e.split(`
15
+ `):e};var PC="var(--persona-md-table-scroll-fade, 24px)",kC=new WeakSet;function HC(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 LC(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":PC),e.style.setProperty("--persona-fade-r",r<=1?"0px":PC)}function Af(e){kC.has(e)||(kC.add(e),e.addEventListener("scroll",t=>{let n=t.target;n?.classList?.contains("persona-table-scroll")&&LC(n)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(LC)}ei();ln();var{setLoader:$_,load:T0}=it({fallbackImport:()=>import("@runtypelabs/persona/webmcp-runtime")});var IC=T0;var P0="agent_",k0="flow_";function RC(e){return e.startsWith(P0)?{kind:"agentId",agentId:e}:e.startsWith(k0)?{kind:"flowId",flowId:e}:null}function WC(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=RC(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=RC(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 L0(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Ml(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function li(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}function OC(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`turn_${e}_${t}`}ad();var H0=e=>e.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase().replace(/_+/g,"_").replace(/^_|_$/g,""),I0=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),R0=e=>{if(e.variant!=="tool")return null;let t=e.agentMetadata?.clientToolAnswer;if(!t||!t.toolCallId||t.result===void 0)return null;let n=H0(t.toolName);return n?{call:{toolCallId:t.toolCallId,toolName:n,args:I0(t.args)?t.args:{}},result:{toolCallId:t.toolCallId,toolName:n,result:t.result}}:null},xf=(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=R0(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};ss();oa();Fd();Lo();var W0="https://api.runtype.com/v1/dispatch",tn=class extends Error{constructor(t,n,o){super(n),this.name="HistoryClientError",this.code=t,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}},BC=e=>"reason"in e?e.reason:void 0,O0="The identity proof was rejected",Mf=(e,t)=>e instanceof tn&&e.code===t,Ef=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),_C=e=>e.slice().sort((t,n)=>new Date(t.createdAt).getTime()-new Date(n.createdAt).getTime()),DC=e=>({role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,createdAt:e.createdAt});function B0(e){switch(e){case"json":return xg;case"regex-json":return Ag;case"xml":return Mg;default:return Sg}}var pa=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??W0,this.#n={"Content-Type":"application/json","X-Persona-Version":Jn,...t.headers},this.debug=!!t.debug,this.#o=t.streamParser??B0(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 IC().then(n=>{let o=new n.WebMcpBridge(t,{recordToolDisplayTitles:Qc,getToolDisplayTitle:Gi,loadPolyfill:Jc});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=WC(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$/,"")||ld}#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 tn("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":Jn,"X-Visitor-Token":s},signal:t.signal});if(c.status===401&&!o){o=!0;let p=await Tr();n=await p.recoverFromUnauthorized(this.#W(),await p.readErrorCode(this.#W(),c),null,!0);continue}if(!c.ok)throw await(await Tr()).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&&BC(n)===BC(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":Jn},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 tn("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 tn("history_disabled","Durable recovery is disabled for this surface"):(n||t.durableResume)&&p.status===401&&g.error==="visitor_required"?new tn("visitor_required","Visitor credential no longer resolves"):l&&p.status===404?new tn("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(!Mf(r,"not_found")&&!Mf(r,"visitor_required")&&!Mf(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 tn("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 tn("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":Jn},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:tn,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 Tr()).listConversations(this.#W(),t)}async getConversation(t,n){return(await Tr()).getConversation(this.#W(),t,n)}async finalizeDisplayProjections(t,n){return(await Tr()).finalizeDisplayProjections(this.#W(),t,n)}async deleteConversation(t,n){return(await Tr()).deleteConversation(this.#W(),t,n)}async deleteAllConversations(t){return(await Tr()).deleteAllConversations(this.#W(),t)}async resetVisitor(){return(await Tr()).resetVisitor(this.#W())}async dispatch(t,n){return t.signal?.throwIfAborted(),oi().catch(()=>{}),this.isClientTokenMode()?this.#be(t,n):this.isAgentMode()?this.#pe(t,n):this.#oe(t,n)}async#be(t,n){let o=OC();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(Ef).map(A=>{let L=g?Sl(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":Jn,...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 tn("invalid_identity_proof",O0);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 tn("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 tn)&&!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 oi()).resolveApproval(this.#U(),t,n)}async#re(t,n,o,r){let s=!!(n&&n.length>0),i=s?Mb(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 oi()).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=xf(_C(t),p=>Ef(p)&&(p.role==="user"||p.role==="assistant"||p.role==="system")&&(!p.variant||p.variant==="assistant")?DC(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=[...ta(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=xf(_C(t),p=>Ef(p)?DC(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=[...ta(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}=rv()??await oi();return s({config:()=>this.config,createStreamParser:this.#o,parseSSEEvent:this.#p,onSSEEvent:(i,l)=>this.#i?.(i,l)},t,n,o,r)}};var hs=class extends Error{constructor(t,n,o){super(n),this.name="HistoryProviderError",this.code=t,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}};function _0(e){return e instanceof hs}ei();ea();Hr();Yi();Hr();function D0(e){let t=0;for(let n of e.split(`
16
16
  `)){let o=/^ {0,3}(`+)/.exec(n);o&&o[1].length>t&&(t=o[1].length)}return t}function NC(e,t){let n="`".repeat(Math.max(3,D0(t)+1));return`${n}${e}
17
17
  ${t}
18
18
  ${n}`}var N0=e=>e.sourceLabel?`quoted-text source=${e.sourceLabel}`:"quoted-text";function F0(e){let t=e?.text?.trim()??"";return t?NC(N0(e),t):""}function FC(e){let t=F0(e.quote);return t?e.contentParts&&e.contentParts.length>0?{contentParts:[Io(t),...e.contentParts]}:{llmContent:[t,e.text].filter(Boolean).join(`
19
19
 
20
- `)}:{}}function Qd(e,t=140){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function $C(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 Tf(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 UC(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 Tf(e,n.id)?n.id:null}return null}function Pf(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}Fd();function El(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 ci=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):El(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 ua=class{#e=null;#t=null;#o="idle";#n=new Set;#l=0;#i;constructor(t){this.#i=t}get supportsPause(){return this.#e?.supportsPause??!0}stateFor(t){return this.#t===t?this.#o:"idle"}activeMessageId(){return this.#t}onChange(t){return this.#n.add(t),()=>this.#n.delete(t)}toggle(t,n){if(this.#t===t){if(this.#o==="playing"){this.#e?.supportsPause?(this.#e.pause(),this.#c(t,"paused")):this.stop();return}if(this.#o==="paused"){this.#e?.resume(),this.#c(t,"playing");return}if(this.#o==="loading"){this.stop();return}}this.play(t,n)}async play(t,n){let o=++this.#l;this.#e?.stop(),this.#c(t,"loading");try{if(!this.#e){let r=await this.#i();if(o!==this.#l)return;if(!r){this.#c(null,"idle");return}this.#e=r}this.#e.speak(n,{onStart:()=>{o===this.#l&&this.#c(t,"playing")},onEnd:()=>{o===this.#l&&this.#c(null,"idle")},onError:()=>{o===this.#l&&this.#c(null,"idle")}})}catch{o===this.#l&&this.#c(null,"idle")}}stop(){this.#l++,this.#e?.stop(),this.#c(null,"idle")}destroy(){this.stop(),this.#e?.destroy?.(),this.#e=null,this.#n.clear()}#c(t,n){this.#t=n==="idle"?null:t,this.#o=n;for(let o of this.#n)o(this.#t,this.#o)}};var Tl=class{#e;#t=!1;start(t){this.#e=t,this.#t=!1}cancel(){this.#t=!0}accepts(t){return!this.#t&&(!t||!this.#e||t===this.#e)}};ln();var{setLoader:mD,load:$0,getSync:U0}=it({fallbackImport:()=>import("@runtypelabs/persona/voice-runtime")});var Pl=$0,VC=U0;function kf(e){if(!e)return"";let t=V0(e);return jC(t!==null?t:e)}function V0(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 jC(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(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
20
+ `)}:{}}function Qd(e,t=140){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function $C(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 Tf(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 UC(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 Tf(e,n.id)?n.id:null}return null}function Pf(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}Fd();function El(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 ci=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):El(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 ua=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 Tl=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)}};ln();var{setLoader:mD,load:$0,getSync:U0}=it({fallbackImport:()=>import("@runtypelabs/persona/voice-runtime")});var Pl=$0,VC=U0;function kf(e){if(!e)return"";let t=V0(e);return jC(t!==null?t:e)}function V0(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 jC(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(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
21
21
  `),t=t.replace(/\n{2,}/g,`
22
22
  `),t.trim()}var YC=null;var Hf=()=>YC?YC():Promise.resolve().then(()=>(GC(),KC));ln();var{setLoader:ED,load:z0}=it({fallbackImport:()=>import("@runtypelabs/persona/session-reconnect")});var XC=z0;var K0=["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 G0(e,t){return K0.some(n=>e[n]!==t[n])}var Qo=class extends Error{constructor(t,n){super(n),this.name="SessionHistoryError",this.code=t}};function If(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 QC=e=>Zs(e)||e===Xo,kl=class e{constructor(t={},n,o={}){this.config=t;this.callbacks=n;this.historyInternals=o;this.status="idle";this.streaming=!1;this.abortController=null;this.#e=Date.now();this.clientSession=null;this.agentExecution=null;this.#t=null;this.#o=null;this.#n=!1;this.#l=null;this.#i=null;this.#c=null;this.artifacts=new Map;this.#u=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.#d=0;this.webMcpApprovalResolvers=new Map;this.#A=0;this.approvalTokens=new Map;this.webMcpAwaitBatches=new Map;this.#r=null;this.#s=null;this.#g=0;this.#H=0;this.#b=!1;this.#w="disconnected";this.#a=null;this.#p=null;this.#f=null;this.#h=0;this.#x=!1;this.#y=null;this.#m=!1;this.#M=null;this.#k=new Map;this.#S=null;this.#C=new Map;this.#G=null;this.#J=null;this.#V=!1;this.#W=null;this.#O=null;this.#E=!1;this.#F=null;this.#j=null;this.#q=null;this.#B=new Tl;this.#re=Promise.resolve();this.#Y=null;this.#_=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new ua(()=>this.#te());this.#Xe=null;this.#ie=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(t.message.id),t.message.role==="assistant"&&!t.message.variant&&t.message.streaming&&(this.#o=t.message.id),(t.message.variant==="approval"||t.message.agentMetadata?.awaitingLocalTool===!0)&&mf().catch(()=>{});let o=t.message.toolCall,r=!!o?.name&&(Zs(o.name)||o.name===Xo&&ps(this.config).enabled);t.message.agentMetadata?.awaitingLocalTool===!0&&r&&this.#Qe(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.#nt(t.id);else if(t.type==="status"){if(t.status==="idle"&&!t.terminal&&this.#ot()){this.#Te();return}if(this.#U(t.status),t.status==="connecting")this.#P(!0);else if(t.status==="idle"||t.status==="error"){this.#Be()||this.#Se(),this.webMcpResolveControllers.size===0&&(this.#P(!1),this.abortController=null,this.#je(),this.#Ue());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.#Je()}}else t.type==="error"?(this.#U("error"),this.#Se(),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.#tt(t)};this.historyInternals=this.#pe(o),this.messages=[...t.initialMessages??[]].map(r=>({...r,sequence:r.sequence??this.#N()})),this.messages=this.#ae(this.messages),this.client=new pa(t,this.historyInternals),this.#Pe(),this.#We();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.#fe(),this.callbacks.onStatusChanged(this.status),this.#ee(),this.#Z()}#e;#t;#o;#n;#l;#i;#c;#u;#d;#A;#r;#s;#g;#H;#b;#w;#a;#p;#f;#h;#x;#y;#m;#M;#k;#S;#C;#G;#J;#V;#W;#O;#E;#F;#Z(){this.config.voiceRecognition?.provider&&Pl().catch(()=>{})}#ee(){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||Hf().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 bC(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.#b}getVoiceStatus(){return this.#w}getVoiceDisclosure(){return this.#r?.getDisclosure?.()??null}getVoiceLevel(){return this.#r?.onLevel?this.#H:null}getVoiceInterruptionMode(){return this.#r?.getInterruptionMode?this.#r.getInterruptionMode():"none"}stopVoicePlayback(){this.#r?.stopPlayback&&(this.#B.cancel(),this.#Y?.cancel(),this.#r.stopPlayback())}isBargeInActive(){return this.#r?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.#r?.deactivateBargeIn&&await this.#r.deactivateBargeIn()}#j;#q;#B;#re;#Y;#_;#te(){let t=this.config.textToSpeech;if(t?.createEngine)return t.createEngine();let n=ci.isSupported()?new ci({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 Hf().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.#re,r=++this.#g;this.#s=Pl().then(async s=>{await o,r===this.#g&&this.#le(s,s.createVoiceProvider(n))}).catch(s=>{console.error("Failed to setup voice:",s)}).finally(()=>{r===this.#g&&(this.#s=null)})}catch(n){console.error("Failed to setup voice:",n)}}#le(t,n){this.#r=n;let o=this;t.wireSessionVoice({session:this,provider:()=>o.#r,generation:()=>o.#g,get keyed(){return o.#Y},set keyed(r){o.#Y=r},get pendingUser(){return o.#j},set pendingUser(r){o.#j=r},get pendingAssistant(){return o.#q},set pendingAssistant(r){o.#q=r},turns:()=>o.#B,busy:()=>o.#ce(),setStreaming:r=>o.#P(r),setDelegation:r=>{o.#_=r},setLevel:r=>{o.#H=r},setStatus:r=>{o.#w=r,o.#b=r==="listening"},settlePending:r=>o.#de(r)},n,t.KeyedVoiceTranscript,t.createVoiceSessionBridge)}async toggleVoice(){if(!this.#r&&this.#s&&await this.#s,!this.#r){console.error("Voice not configured");return}if(this.#b)await this.#r.stopListening();else{this.stopSpeaking();try{await this.#r.startListening()}catch(t){console.error("Failed to start voice:",t)}}}prewarmVoice(){if(!On(this.config.voiceRecognition?.provider)){this.warmClientSession();return}let t=this.#g,n=()=>{let o=this.#r;!o?.prewarm||t!==this.#g||this.#b||this.isBargeInActive()||Promise.resolve().then(()=>o.prewarm?.()).catch(()=>{})};if(!this.#r&&this.#s){this.#s.then(n,()=>{});return}n()}#ce(){return!!this.abortController||this.webMcpResolveControllers.size>0||this.webMcpAwaitBatches.size>0||this.#n||this.status==="resuming"}cleanupVoice(){let t=this.#r!==null;if(this.#g++,this.#s=null,this.#r){let n=this.#r;this.#r=null,this.#re=this.#I(n)}this.#b=!1,this.#w="disconnected",this.#de(!0),this.#Y?.settle(),this.#Y=null,this.#B=new Tl,t&&this.callbacks.onVoiceStatusChanged?.("disconnected")}async#I(t){try{await t.disconnect()}catch(n){console.error("Failed to disconnect voice:",n)}}#de(t){let n=t?this.#j:null,o=this.#q;!n&&!o||(o&&this.#B.cancel(),t&&(this.#j=null),this.#q=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.#V=!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.#ne(t,n)}#ne(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.#N()};this.#Q(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.#pe(t),this.client.setHistoryInternals(this.historyInternals),this.#Pe()}destroy(){this.cleanupVoice(),this.#W?.(),this.#W=null,this.#O=null}#pe(t){let n=t.onHistoryContinuityChanged;return{...t,onHistoryContinuityChanged:o=>{this.#Ae(o),n?.(o)}}}get#$(){return this.historyInternals.historyProvider??null}#R(){let t=this.#$;if(!t)throw new Qo("history_unavailable","No conversation history provider is installed");return t}#L(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 hs("unsupported_scope","This history scope is not supported.");return{scope:s}}getHistoryState(){return{activeConversationId:this.#a,conversationRevision:this.#p,nextMessageCursor:this.#f,recovery:this.#y,sendBlocked:this.#m}}getActiveConversationId(){return this.#a}#T(){this.callbacks.onHistoryStateChanged?.(this.getHistoryState())}#z(t,n){this.callbacks.onHistoryNotice?.({code:t,message:n})}async awaitHistorySettled(){let t=this.#M;t&&await t.catch(()=>{});let n=this.#S;n&&await n.catch(()=>{})}#he(){if(this.streaming||this.status==="paused"||this.status==="resuming")throw new Qo("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.#L(t?.scope)})}async openConversation(t,n){let o=this.#R();this.#he();let r=this.#L(n?.scope);await this.awaitHistorySettled();let s=++this.#h,i=await o.getPage(t,{context:r});if(s!==this.#h)throw new Qo("superseded","A later selection won");let l=await o.prepareOpen(t,{context:r});if(s!==this.#h)throw l.discard(),new Qo("superseded","A later selection won");this.#x=!0;try{await this.#X(l)}finally{this.#x=!1}this.#a=l.conversationId||t,this.#p=l.conversationRevision||i.conversationRevision||null,this.#f=i.nextCursor,this.#y=null,this.#m=!1,this.#se();for(let c of i.messages)this.#C.set(c.id,c.content);return this.#v(),this.hydrateMessages(i.messages),this.#T(),{summary:i.summary,nextMessageCursor:i.nextCursor}}loadOlderMessages(t,n,o){let r=this.#R(),s=this.#L(o?.scope),i=n??this.#f;if(!i)return Promise.resolve({messages:[],nextMessageCursor:null});let l=`${t} ${i}`,c=this.#k.get(l);if(c)return c;let p=this.#oe(r,t,i,s).finally(()=>{this.#k.delete(l)});return this.#k.set(l,p),p}async#oe(t,n,o,r){let s=this.messages[0]?.createdAt,i=await t.getPage(n,{cursor:o,...s?{beforeCreatedAt:s}:{},context:r});if(this.#a&&this.#a!==n)return{messages:[],nextMessageCursor:i.nextCursor};let l=Al(this.messages,i.messages);this.messages=this.#ae(l.map(c=>this.#be(c))),this.#f=i.nextCursor;for(let c of i.messages)this.#C.set(c.id,c.content);return this.historyInternals.setStoredMessageCursor?.(i.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.#T(),{messages:i.messages,nextMessageCursor:i.nextCursor}}async startNewConversation(t){let n=this.#R(),o=this.#L(t?.scope);await this.awaitHistorySettled();let r=++this.#h,s=await n.prepareStartNew({context:o});if(r!==this.#h)throw s.discard(),new Qo("superseded","A later action won");await this.#D(s)}async#D(t){this.#K(),await this.#X(t),this.#a=t.conversationId||null,this.#p=t.conversationRevision||null,this.#f=null,this.#y=null,this.#m=!1,this.#v(),this.#T()}async deleteConversation(t,n){let o=this.#R(),r=this.#L(n?.scope);await this.awaitHistorySettled(),await o.delete(t,{context:r}),t===this.#a&&await this.#ve(r)}async updateConversation(t,n,o){let r=this.#R();if(!r.update)throw new Qo("history_unavailable","This history provider cannot update conversations");let s=this.#L(o?.scope);return await this.awaitHistorySettled(),r.update(t,n,{context:s})}canUpdateConversations(){return typeof this.#$?.update=="function"}async clearConversationHistory(t){let n=this.#R(),o=this.#L(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 Qo("history_unavailable","This history provider cannot reset the device");this.#h+=1,this.#S=null;try{return await t.resetDevice()}finally{this.#K(),this.#a=null,this.#p=null,this.#f=null,this.#y=null,this.#m=!1,this.#T()}}async#ve(t){this.#h+=1,this.#S=null,this.#K(),this.#a=null,this.#p=null,this.#f=null,this.#m=!0,this.#y=null,this.#T(),await this.#ye(t)}async#ye(t){let n=this.#$;if(!n){this.#m=!1,this.#T();return}try{let o=await n.prepareStartNew({context:t});await this.#D(o)}catch{this.#m=!0,this.#y="new_conversation_required",this.#T(),this.#z("new_conversation_required","That conversation was deleted. Start a new conversation to continue.")}}async#Ce(){if(!(this.#y!=="new_conversation_required"||!this.#$)&&(this.#y=null,await this.#ye(this.#L()),this.#y==="new_conversation_required"))throw new Qo("new_conversation_required","A new conversation is required before sending")}async#X(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.#a=t.conversationId,this.#p=t.conversationRevision??null,this.config.setStoredConversationId?.(t.conversationId),this.historyInternals.setStoredConversationRevision?.(t.conversationRevision??null)),this.#x||this.#ne(t)}#v(){this.#a?this.config.setStoredConversationId?.(this.#a):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.#p),this.historyInternals.setStoredMessageCursor?.(this.#f)}#se(){this.historyInternals.setStoredResumableHandle?.(null),this.agentExecution=null,this.#Ee(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#C.clear(),this.#ue(null)}#K(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#me(),this.#ge(),this.#ie++,this.messages=[],this.#se(),this.#k.clear(),this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),this.#P(!1),this.#U("idle"),this.callbacks.onMessagesChanged([...this.messages])}#Ae(t){this.#h+=1,this.#S=null,this.#m=!0,this.#K(),this.#a=t.conversationId,this.#p=null,this.#f=null,this.#y=null,this.#T(),this.#z("history_continuity_reset","This browser was reconnected to a different conversation, so the previous messages were cleared."),this.#M=Promise.resolve().then(()=>{this.#m=!1,this.#M=null,this.#T()})}#Pe(){let t=this.historyInternals.visitorStore??null;t!==this.#O&&(this.#W?.(),this.#W=null,this.#O=t,t&&(this.#W=t.subscribe(n=>this.#De(n))))}#De(t){if(t.source!=="external"||t.previousToken===null)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.#h+=1,this.#S=null,this.#E=!0,this.#F=null;let n=this.messages.length>0;n||this.#a!==null||(this.config.getStoredConversationId?.()??null)!==null?this.#K():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.#k.clear(),this.#ue(null)),this.#a=null,this.#p=null,this.#f=null,this.#y=null,this.#T(),n&&this.#z("history_continuity_reset","This browser's conversation history was reset in another tab, so the previous messages were cleared.")}#Ne(){return this.#E?(this.#F||(this.#F=this.#Fe().finally(()=>{this.#F=null})),this.#F):Promise.resolve()}async#Fe(){if(!this.isClientTokenMode()){this.#E=!1;return}try{this.bindActivatedSession(await this.client.initSession()),this.#E=!1}catch{}}reconcileBootConversation(t){let n=this.#$,o=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.#a;if(!n||!o)return Promise.resolve();let r=this.#L(t?.scope);this.#m=!0,this.#T();let s=this.#$e(n,o,r).finally(()=>{this.#m=this.#y!==null,this.#M===s&&(this.#M=null),this.#T()});return this.#M=s,s}async#$e(t,n,o){this.#a=n;let r=this.clientSession?.conversationRevision??this.#p??null,s=this.#V?this.#J:this.historyInternals.getStoredConversationRevision?.()??null;if(this.#V=!1,this.#f=this.historyInternals.getStoredMessageCursor?.()??this.#f,await this.replayPendingProjections(),r&&s&&r===s){this.#p=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.#be(g));else{let g=this.#t?this.#o:null,f=this.messages.filter(h=>l.has(h.id)||h.id===g?!0:p!==void 0&&h.createdAt<p);d=Al(f,i.messages).map(h=>this.#be(h))}this.#f=i.nextCursor,this.#p=i.conversationRevision||r||null,this.#C.clear();for(let g of i.messages)this.#C.set(g.id,g.content);this.#v(),this.messages=this.#ae(d),this.callbacks.onMessagesChanged([...this.messages])}#xe(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}#ue(t){this.#G=t,this.historyInternals.setPendingDisplayProjections?.(t)}#ke(){return this.historyInternals.getPendingDisplayProjections?.()??this.#G}#Le(t){if(this.#xe())for(let n of t){let o=Sl(n);o!==void 0&&this.#C.set(n.id,o)}}#Ue(){if(!this.#xe())return;let t=this.#a;if(!t)return;let n=[];for(let o of this.messages){if(o.role!=="assistant"||o.streaming)continue;let r=Sl(o);r!==void 0&&this.#C.get(o.id)!==r&&n.push({id:o.id,displayContent:r})}n.length!==0&&(this.#ue({conversationId:t,messageIds:n.map(o=>o.id)}),this.#He(t,n))}#He(t,n){let r=(this.#S??Promise.resolve()).catch(()=>{}).then(()=>this.#Ie(t,n,!1)).finally(()=>{this.#S===r&&(this.#S=null)});this.#S=r}async#Ie(t,n,o){if(this.#a!==t)return;let r=n.filter(s=>this.#C.get(s.id)!==s.displayContent);if(r.length===0){this.#Me(t,n);return}try{let{conversationRevision:s}=await this.client.finalizeDisplayProjections(t,r);for(let i of r)this.#C.set(i.id,i.displayContent);this.#a===t&&s&&(this.#p=s),this.#Me(t,n)}catch(s){if(!o&&this.#Ve(s)){await this.#Ie(t,r,!0);return}if(s instanceof tn&&(s.code==="not_found"||s.code==="conversation_deleted")){this.#Me(t,n);return}this.#z("projection_finalization_failed","Some message formatting could not be saved for history; it will be retried.")}}#Ve(t){return t instanceof tn?t.code==="request_failed":t instanceof Error}#Me(t,n){let o=this.#ke();if(!o||o.conversationId!==t)return;let r=new Set(n.map(i=>i.id)),s=o.messageIds.filter(i=>!r.has(i));this.#ue(s.length?{conversationId:t,messageIds:s}:null)}async replayPendingProjections(){if(!this.#xe())return;let t=this.#ke();if(!t)return;if(this.#a&&t.conversationId!==this.#a){this.#ue(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.#ue(null);return}this.#He(t.conversationId,n),await this.#S?.catch(()=>{})}#je(){this.#a&&(this.#p=null,this.historyInternals.setStoredConversationRevision?.(null))}async#Re(){await this.awaitHistorySettled(),await this.#Ne(),this.#y==="new_conversation_required"&&await this.#Ce()}static#qe(t){return t instanceof tn&&t.code==="conversation_deleted"}async#ze(t,n,o,r,s){this.#Le(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.#qe(i))throw i;let l=await this.#Ke(r);if(!l)throw i;this.#Le([l]),await this.client.dispatch({messages:[l],signal:n.signal,assistantMessageId:o,composerOptions:s?.composerOptions},this.handleEvent)}}async#Ke(t){let n=this.messages.find(r=>r.id===t);if(!n)return null;let o={...n};this.#h+=1,this.#S=null,this.#K(),this.#a=null,this.#p=null,this.#f=null,this.#x=!0;try{let r=this.#$;if(r){let s=await r.prepareStartNew({context:this.#L()});await this.#D(s)}else{this.client.clearClientSession();let s=await this.client.initSession();this.bindActivatedSession(s)}}catch{return this.#m=!0,this.#y="new_conversation_required",this.#T(),this.#z("new_conversation_required","That conversation was deleted. Start a new conversation to continue."),null}finally{this.#x=!1}return this.#Q(o),this.#P(!0),this.#z("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=yC(this.config,o),s=G0(this.config,o);this.config=o,r&&(this.cleanupVoice(),o.voiceRecognition?.enabled===!0&&On(o.voiceRecognition.provider)&&this.setupVoice());let i=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!s){this.client.updateConfig(o),i&&this.#Oe();return}this.#ge(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let l=this.client.getSSEEventCallback();this.client=new pa(this.config,this.historyInternals),i&&this.#Oe(),this.#We(),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"?Ml():n==="assistant"?li():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:l??new Date().toISOString(),sequence:c??this.#N(),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"?Ml():r==="assistant"?li():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:s,createdAt:p??new Date().toISOString(),sequence:d??this.#N(),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.#ae([...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#Ge(t,n,o){let r;try{r=await o()}catch{return}let s=r.blocks.join(`
24
+ _Details: ${n.message}_`:o}var QC=e=>Zs(e)||e===Xo,kl=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 Tl;this.#ne=Promise.resolve();this.#$=null;this.#U=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new ua(()=>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)&&mf().catch(()=>{});let o=t.message.toolCall,r=!!o?.name&&(Zs(o.name)||o.name===Xo&&ps(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 pa(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&&Pl().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||Hf().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 bC(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=ci.isSupported()?new ci({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 Hf().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=Pl().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(!On(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 Tl,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 Qo("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 hs("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 Qo("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 Qo("superseded","A later selection won");let l=await o.prepareOpen(t,{context:r});if(s!==this.#C)throw l.discard(),new Qo("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=Al(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 Qo("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 Qo("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 Qo("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 Qo("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=Al(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=Sl(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=Sl(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 tn&&(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 tn?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 tn&&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=yC(this.config,o),s=G0(this.config,o);this.config=o,r&&(this.cleanupVoice(),o.voiceRecognition?.enabled===!0&&On(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 pa(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"?Ml():n==="assistant"?li():`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"?Ml():r==="assistant"?li():`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(`
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(Io(s)),p.push(...r.contentParts),p.push(...t.contentParts),t.contentParts=p}else if(c){let p=[];i&&p.push(Io(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.#M||this.#S||this.#m||this.#E)&&await this.#Re(),this.stopSpeaking(),this.abortController?.abort(),this.#ge(),this.#ie++,this.#me();let s=n?.voiceTurn?.userMessageId,i=s?this.messages.find(h=>h.id===s&&h.role==="user"):void 0,l=i?.id??Ml(),c=li();this.#o=null;let p=n?.contentParts&&bl(n.contentParts)?la:"",d={id:l,role:"user",content:o||p,createdAt:new Date().toISOString(),sequence:this.#N(),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.#Q(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.#Ge(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=FC({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.#ze(f,g,c,l,{composerOptions:n?.composerOptions,interrupt:n?.interrupt})}catch(h){if(this.status==="resuming"||this.#n)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=If(h,this.config.errorMessage);if(v){let C={id:c,role:"assistant",createdAt:new Date().toISOString(),content:v,sequence:this.#N()};this.#Q(C)}}this.#U("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=$C(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.#Ye(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}#Ye(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.#M||this.#S||this.#m||this.#E)&&await this.#Re(),this.abortController?.abort(),this.#me();let t=li();this.#o=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.#n)return;let s=r instanceof Error&&(r.name==="AbortError"||r.message.includes("aborted")||r.message.includes("abort"));if(!s){let i=If(r,this.config.errorMessage);if(i){let l={id:t,role:"assistant",createdAt:new Date().toISOString(),content:i,sequence:this.#N()};this.#Q(l)}}this.#U("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.#o=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,r=!1;for(let s of this.messages)s.streaming&&s.id!==o&&(s.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.#P(!0);try{await this.client.processStream(t,this.handleEvent,n?.assistantMessageId,n?.seedContent)}catch(s){if(this.status==="resuming"||this.#n)return;this.#U("error"),this.webMcpResolveControllers.size===0&&(this.#P(!1),this.abortController=null),this.callbacks.onError?.(s instanceof Error?s:new Error(String(s)))}}#We(){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.#A}`,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")}#Xe;#ie;#we(t){let n=this.#Xe??={s:this,setStreaming:s=>this.#P(s),appendMessage:s=>this.#Q(s),nextSequence:()=>this.#N(),settleApprovalPausedToolCall:s=>this.#_e(s),resumeAfter:s=>this.#t?.executionId===s?this.#t.lastEventId:void 0},o=Zv();if(o)return t(o,n);let r=this.#ie;return mf().then(s=>r===this.#ie?t(s,n):void 0,s=>{this.callbacks.onError?.(s instanceof Error?s:new Error(String(s)))})}resolveApproval(t,n,o){return this.#we((r,s)=>r.resolveApproval(s,t,n,o))}resolveAskUserQuestion(t,n){return this.#we((o,r)=>o.resolveAskUserQuestion(r,t,n))}resolveWebMcpToolCall(t){return this.#we((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}:{}}})}#Qe(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.id;if(!n||!o){let s=this.#d;queueMicrotask(()=>{s===this.#d&&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))}#Je(){if(this.webMcpAwaitBatches.size===0)return;let t=this.#d;queueMicrotask(()=>{if(t===this.#d)for(let n of[...this.webMcpAwaitBatches.keys()])this.#Ze(n)})}#Ze(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.#we((r,s)=>r.resolveWebMcpToolCallBatch(s,t,o))}#ge(){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.#d++}cancel(){this.abortController?.abort(),this.abortController=null,this.#me(),this.#ge(),this.#ie++,this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.#P(!1),this.#U("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#me(),this.#ge(),this.#ie++,this.messages=[],this.agentExecution=null,this.#Ee(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#P(!1),this.#U("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.#fe()}clearArtifacts(){this.#Ee()}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.#fe(),t.transcript!==!1&&this.#et(o),o}#et(t){let n=`artifact-ref-${t.id}`,o=Er(this.config.features?.artifacts,t),r=al(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})}#Oe(){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=Er(this.config.features?.artifacts,n),s=al(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])}#Ee(){this.artifacts.size===0&&this.#u===null||(this.artifacts.clear(),this.#u=null,this.#fe())}#fe(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.#u})}#tt(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.#fe()}hydrateMessages(t){this.abortController?.abort(),this.abortController=null,this.#me(),this.#ge(),this.#ie++,this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.#ae(t.map(n=>({...n,streaming:!1,sequence:n.sequence??this.#N()}))),this.#P(!1),this.#U("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.#fe()}#nt(t){let n=this.agentExecution?.executionId;if(!n||!this.#o||this.agentExecution?.status!=="running")return;let o=this.#t===null;this.#t={executionId:n,lastEventId:t,assistantMessageId:this.#o,status:"running"},this.#at(o)}#ot(){return this.#t!==null&&typeof this.config.reconnectStream=="function"&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.#Be()}#Be(){return this.messages.some(t=>t.agentMetadata?.awaitingLocalTool===!0&&t.agentMetadata?.askUserQuestionAnswered!==!0||t.variant==="approval"&&t.approval?.status==="pending")}#Te(){this.#n||!this.#t||typeof this.config.reconnectStream!="function"||(this.#n=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.#t}),this.#P(!0),this.#U("resuming"),this.#rt().then(t=>{this.#n&&this.#t&&t.begin()}))}#rt(){return this.#l?Promise.resolve(this.#l):(this.#i||(this.#i=XC().then(({createReconnectController:t})=>{let n=t(this.#st());return this.#l=n,n}),this.#i.catch(()=>{this.#i=null})),this.#i)}#st(){let t=this;return{get config(){return t.config},getResumable:()=>t.#t,clearResumable:()=>t.#Se(),getStatus:()=>t.status,setStatus:n=>t.#U(n),setStreaming:n=>t.#P(n),setReconnecting:n=>{t.#n=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.#Q(n),nextSequence:()=>t.#N(),emitReconnect:n=>t.callbacks.onReconnect?.(n),buildErrorContent:n=>If(new Error(n),t.config.errorMessage),onError:n=>t.callbacks.onError?.(n)}}reconnectNow(){if(this.#n){this.#l?.wake();return}this.#Te()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.#n)return;let n=this.#it();n||(n=li(),this.#Q({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.#N()})),this.#o=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.#Te()}#it(){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}#me(){this.#n=!1,this.#l?.teardown(),this.#Se()}#Se(){this.#c&&(clearTimeout(this.#c),this.#c=null);let t=this.#t!==null;this.#t=null,t&&this.config.onExecutionState?.(null)}#at(t){let n=this.config.onExecutionState;if(n){if(t){this.#c&&(clearTimeout(this.#c),this.#c=null),n(this.#t);return}this.#c||(this.#c=setTimeout(()=>{this.#c=null,this.config.onExecutionState?.(this.#t)},500))}}getResumableHandle(){return this.#t}#U(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.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=kf(r.content);s.trim()&&this.readAloud.play(r.id,{text:s,voice:n.voice,rate:n.rate,pitch:n.pitch})}static pickBestVoice(t){return El(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let o=kf(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()}#_e(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})}#Q(t){let n=this.#be(t);this.messages=this.#ae([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.#be(t),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.#Q(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&&QC(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&&QC(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.#ae(this.messages),this.callbacks.onMessagesChanged([...this.messages])}#be(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.#N()}}#N(){return this.#e++}#ae(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)})}};Xe();Mr();Tt();Hr();import{File as Y0,FileCode as X0,FileSpreadsheet as Q0,FileText as Rf,X as J0}from"lucide";var Z0={add:e=>$v(e)},eL=e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0,ep={allowedTypes:Lr,maxFileSize:10*1024*1024,maxFiles:4};function tL(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function nL(e){return e==="application/pdf"?Rf:e.startsWith("text/")?Rf:e.includes("word")?Rf:e.includes("excel")||e.includes("spreadsheet")?Q0:e==="application/json"?X0:Y0}var fa=class e{constructor(t={}){this.attachments=[];this.#e=null;this.#t=new Map;this.#o=!1;this.config={allowedTypes:t.allowedTypes??ep.allowedTypes,maxFileSize:t.maxFileSize??ep.maxFileSize,maxFiles:t.maxFiles??ep.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange,adapter:t.adapter}}#e;#t;#o;#n(){return typeof this.config.adapter?.add=="function"}#l(){return this.#n()?this.config.adapter:Z0}setPreviewsContainer(t){this.#e=t}remountPreviews(t){if(this.#e=t,t){t.innerHTML="";for(let n of this.attachments)this.#A(n)}this.#g()}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:ep.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=Uv(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:tL(),file:o,previewUrl:yd(o)?URL.createObjectURL(o):null,contentPart:null,status:this.#n()?"uploading":"processing",progress:this.#n()?0:void 0};this.attachments.push(s),this.#A(s),n.push(s)}this.#g(),this.#d(),await Promise.all(n.map(o=>this.#i(o)))}async#i(t){let n=new AbortController;this.#t.set(t.id,n);let o=()=>this.#o||n.signal.aborted||this.#t.get(t.id)!==n||!this.attachments.includes(t);try{let r=await this.#l().add(t.file,{signal:n.signal,onProgress:s=>{o()||t.status!=="uploading"||(t.progress=eL(s),this.#r(t),this.#d())}});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.#t.get(t.id)===n&&this.#t.delete(t.id)}this.#r(t),this.#d()}retryAttachment(t){let n=this.attachments.find(o=>o.id===t);!n||n.status!=="error"||this.#o||(n.status=this.#n()?"uploading":"processing",n.progress=this.#n()?0:void 0,n.error=void 0,this.#r(n),this.#d(),this.#i(n))}#c(t){let n=this.#t.get(t);n&&(this.#t.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.#c(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.#u(o.contentPart),this.#g(),this.#d()}#u(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.#c(t.id),t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.#t.clear(),this.#e&&(this.#e.innerHTML=""),this.#g(),this.#d()}destroy(){if(!this.#o){this.#o=!0;for(let t of this.#t.values())t.abort();this.#t.clear();for(let t of this.attachments)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.#e=null}}#d(){this.#o||this.config.onAttachmentsChange?.(this.getAttachments())}#A(t){if(!this.#e)return;let n=yd(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=nL(t.file.type),f=_t(g,20,"var(--persona-muted, #6b7280)",1.5);f&&d.appendChild(f);let h=x("span");h.textContent=Vv(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=X("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=X("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),l=ue("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=_t(J0,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.#s(o,t)}#r(t){let n=this.#e?.querySelector(`[data-attachment-id="${t.id}"]`);n&&this.#s(n,t)}#s(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)}%`:""}}#g(){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 JC=(e,t)=>e.length===t.length&&e.every((n,o)=>n===t[o]),oL=(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 ZC(){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=>{oL(e.attachments,d)||(e.attachments=[...d],p())},setMentionRefs:d=>{JC(e.mentionRefs,d)||(e.mentionRefs=[...d],p())},setSelectedModelId:d=>{e.selectedModelId!==d&&(e.selectedModelId=d,p())},setActiveModeIds:d=>{JC(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()}}}Xe();var zn=(e,...t)=>{for(let n of t){let o=e.querySelector(n);if(o)return o}return null},ew=(e,t)=>{let n=x("div",e);return n.setAttribute(t,""),n.setAttribute("data-persona-composer-synthesized",""),n.style.display="contents",n};function tw(e,t={}){let n=zn(e,"[data-persona-composer-form]"),o=zn(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:zn(e,"[data-persona-composer-header]"),body:zn(e,"[data-persona-composer-body]"),actionsStart:zn(e,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:zn(e,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:zn(e,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:zn(e,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:zn(e,"[data-persona-composer-status]")},s=new Set,i=r.header;i||(s.add("header"),i=ew("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 _=ew(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=zn(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:zn(e,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:zn(e,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:zn(e,"[data-persona-composer-submit]")??void 0,micButton:zn(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=[]}}}Xe();Tt();sa();gs();function rL(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function tp(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??rL(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,te=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);te=Math.min(Math.max(A.left+W,A.left),j)}n.style.top=`${_}px`,n.style.left=`${te}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 te=typeof V.composedPath=="function"?V.composedPath():[];te.includes(n)||te.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}}Xe();Tt();gs();var sL='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',iL=["--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"],Wf="data-persona-menu-focus",aL=new Set(["ArrowDown","ArrowUp","Home","End"]);function nw(e){return e.getAttribute("role")==="menuitem"?e:e.querySelector(sL)??e}var lL=e=>e.disabled===!0||e.getAttribute("aria-disabled")==="true";function ow(e){let t=e.label,n=!1,o=x("div","persona-send-button-wrapper"),r=X("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${Zn} ${Ro}`,attrs:{type:"button","aria-haspopup":"menu","aria-expanded":"false","data-persona-composer-overflow-trigger":""}});o.appendChild(r);let s=X("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 Q=ue("plus",qn,"currentColor",1.5);Q?r.appendChild(Q):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 Q=s.getRootNode().activeElement;return Q instanceof HTMLElement?Q:null},f=()=>{let P=g();for(let Q of c){let U=!!P&&nw(Q)===P;Q.toggleAttribute(Wf,U&&d)}},h=()=>c.filter(P=>P.isConnected||s.contains(P)).map(nw).filter(P=>!lL(P)),y=(P,Q)=>{P.forEach((U,de)=>{U.setAttribute("tabindex",de===Q?"0":"-1")})},v=P=>{let Q=h();if(Q.length===0)return;let U=(P%Q.length+Q.length)%Q.length;p=U,y(Q,U),Q[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,te=()=>(V||(V=tp({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 Q of c)Q.removeAttribute(Wf);P&&r.focus()}},Y=(P=0,Q=!1)=>{if(n||W())return;d=Q,Sd(r,s,iL),te().open(),r.setAttribute("aria-expanded","true");let U=h();y(U,-1),v(P<0?U.length-1:P),A=de=>{let pe=typeof de.composedPath=="function"?de.composedPath():[];pe.includes(s)||pe.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):Y(0)},T=P=>{if(P.key==="ArrowDown"||P.key==="Enter"||P.key===" "){P.preventDefault(),d=!0,W()?v(0):Y(0,!0);return}P.key==="ArrowUp"&&(P.preventDefault(),d=!0,W()?v(-1):Y(-1,!0))},B=P=>{switch(aL.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(Wf);if(c=[...P],!W())return;let Q=h();y(Q,Math.min(p,Q.length-1)),f()},isOpen:W,open:()=>Y(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 Jo={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},rw="data-persona-composer-action",Of="data-persona-composer-disable-when-streaming",cL="core:overflow",dL=e=>e==="core:attachment"?"attachments":e.startsWith("core:mention")?"mentions":null;function pL(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 Bf(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 sw=(e,t)=>{!e||typeof console>"u"||console.warn(t)},uL=(e,t)=>t.includes(":")?t:`${e}:${t}`;function gL(e){let{debug:t}=e,n=[],o=new Map,r=0,s=l=>{let c=o.get(l.id);if(c){sw(t,`[Persona] composer action "${l.id}" is already contributed by ${iw(c)}; the ${iw(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?uL(p,l.id):l.id,g=l.order??Jo.custom;l.placement==="end"&&g>=Jo.send&&(sw(t,`[Persona] composer action "${d}" ordered at ${g} would render after send; clamped to ${Jo.send-1}.`),g=Jo.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 iw=e=>e.source==="plugin"?`plugin "${e.pluginId}"`:e.source==="config"?"composer.actions":"a core built-in",aw=(e,t,n)=>e===void 0?n:typeof e=="function"?e(t)===!0:e===!0,fL=e=>e.phase==="streaming"||e.text.trim().length>0||e.attachments.length>0;function mL(e,t){if(!e||e==="always")return!0;let n=fL(t);return e==="when-text"?n:!n}var ys=e=>e.kind==="custom",_f=e=>e instanceof HTMLButtonElement?e:e.querySelector("button")??e,hL=e=>{let t=_f(e);return t.getAttribute("aria-label")?.trim()||t.getAttribute("title")?.trim()||""},yL='.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]';function bL(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(yL)||o.childNodes.forEach(n)};return n(e),t.trim()}var vL=e=>bL(e).length===0;function lw(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=ue(T.iconName,16,"currentColor",1.5);U&&P.appendChild(U)}let Q=x("span","persona-composer-overflow-menu__label");Q.textContent=T.shortLabel??T.label,B.append(P,Q)},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(Of,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(),Q=!!T.shortLabel;if(B.className=Wn("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",Zn,Ro,Q&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),B.style.width=P&&!Q?P:"",B.style.height=P??"",B.style.minWidth=P&&!Q?P:"",B.style.minHeight=P??"",B.style.fontSize=Q?"":"18px",B.style.lineHeight="1",B.style.color=T.iconColor??"",B.style.backgroundColor=T.backgroundColor??"",B.replaceChildren(),T.iconName){let U=ue(T.iconName,qn,"currentColor",1.5);U&&B.appendChild(U)}if(Q){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=yn({anchor:B,trigger:E.element,text:()=>T.tooltipText??T.label,enabled:!!T.tooltipText})},l=(E,T)=>{let B=E.action,P=X("button",{attrs:{type:"button"}}),Q=P;if(T==="bar"){let pe=x("div","persona-send-button-wrapper");pe.appendChild(P),Q=pe}Q.setAttribute(rw,E.id);let U={resolved:E,element:Q,button:P,owned:!0,managed:!0,busy:!1,visible:!0,mode:T},de=pe=>{if(pe.preventDefault(),pe.stopPropagation(),U.busy||P.disabled)return;let ge=U.resolved.action;U.mode==="menu"&&h?.close(!0);let ke;try{ke=ge.onSelect(e.actionContext,pe)}catch(xe){e.reportError(xe,{actionId:U.resolved.id});return}!ke||typeof ke.then!="function"||(U.busy=!0,P.setAttribute("aria-busy","true"),ke.catch(xe=>{e.reportError(xe,{actionId:U.resolved.id})}).finally(()=>{U.busy=!1,P.removeAttribute("aria-busy")}))};return P.addEventListener("click",de),U.detach=()=>P.removeEventListener("click",de),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(rw,E.id),B.element.toggleAttribute(Of,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?ys(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 Q=null;for(let U=B+1;U<T.length;U++){let de=T[U];if(!de.managed&&de.element.parentElement===E){Q=de.element;break}}Q?(P.element.parentElement!==E||P.element.nextSibling!==Q)&&E.insertBefore(P.element,Q):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=ow({label:e.getOverflowLabel?.()??"More actions",getButtonSize:r}),h),I=E=>{y!==E&&(v?.disconnect(),y=E,C=Bf(E),!(typeof ResizeObserver>"u")&&(v=new ResizeObserver(T=>{let P=T[T.length-1]?.contentRect?.width??Bf(E);P!==C&&(C=P,j())}),v.observe(E)))},H=(E,T)=>{let B=pL(E.collapseAutoActionsBelow,T);if(B===null)return!1;let P=C||Bf(T);return P>0&&P<B},_=(E,T,B)=>{if(!T)return"bar";if(E.resolved.builtIn){let Q=dL(E.resolved.id);return Q&&T.includeBuiltIns?.includes(Q)?"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(!vL(E.element)){E.menuLabel?.remove(),E.menuLabel=void 0;return}let B=hL(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)},te=(E,T)=>{if(E.mode===T)return E;let B=E.resolved.action;if(B&&!ys(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=X("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none",[$g]:""}});P.appendChild(E.element),Pv(_f(E.element)),E.menuSlot=P;let Q=U=>{let de=_f(E.element);if(de.disabled)return;let pe=U.target===de||de.contains(U.target);h?.close(!0),pe||de.click()};P.addEventListener("click",Q,!0),E.detachMenuSlot=()=>P.removeEventListener("click",Q,!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,Q)=>{let U=E.children[Q];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 Q=P?H(P,E.footer):!1,U={start:[],end:[]},de=[];for(let pe of n){let ge=t.get(pe.id);if(!ge)continue;let ke=pe.action,xe=ke?aw(ke.visible,T,!0)&&mL(ke.visibility,T):!0;if(ge.visible!==xe&&(ge.visible=xe,!xe&&ge.managed&&(ge.menuSlot??ge.element).remove()),!!xe){if(ge=te(ge,_(ge,P,Q)),ke){let Le=aw(ke.disabled,T,!1)||ke.disableWhenStreaming===!0&&B;f(ge,Le),!ys(ke)&&ke.pressed!==void 0&&ge.button?.setAttribute("aria-pressed",ke.pressed?"true":"false")}ge.mode==="menu"?(V(ge),de.push(ge)):U[pe.placement].push(ge)}}if(de.length>0){let pe=L();W(pe.panel,de),pe.setItems(de.map(Le=>Le.menuSlot??Le.element)),pe.applyButtonSize();let ge=Number.isFinite(P?.order)?P?.order:Jo.overflow,ke=U.start.findIndex(Le=>Le.resolved.order>ge),xe={resolved:{id:cL,placement:"start",presentation:"bar",order:ge,sequence:-1,source:"core"},element:pe.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};U.start.splice(ke<0?U.start.length:ke,0,xe)}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=gL(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 pe=p(B,"bar");pe&&t.set(B.id,pe);continue}let Q=P.resolved.action,U=B.action;if(!!Q!=!!U||Q&&U&&ys(Q)!==ys(U)||Q&&U&&ys(Q)&&ys(U)&&Q.render!==U.render){d(P),t.delete(B.id);let pe=p(B,P.mode);pe&&t.set(B.id,pe);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&&!ys(U)?i(P,U):U&&P.element.toggleAttribute(Of,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=[]}}}}Xe();Tt();gs();var CL="core:model",wL=700,cw=16,SL=["--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"],dw=()=>{let e=X("span",{className:"persona-composer-model-picker-wrapper",attrs:{"data-persona-composer-model-picker-wrapper":""}}),t=X("span",{className:"persona-composer-model-picker-chevron",attrs:{"aria-hidden":"true"}});return{wrapper:e,chevron:t}};function pw(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=X("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=X("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}=dw();return h.append(c,y),{element:h,destroy:()=>{o===d&&(o=null),c.removeEventListener("change",g),c.removeEventListener("click",f)}}},i=()=>{let c=X("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=X("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=tp({anchor:c,content:g,placement:"top-start",offset:6,onDismiss:()=>c.setAttribute("aria-expanded","false")})),Sd(c,g,SL),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=X("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 pe=ue(T.icon,cw,"currentColor",1.5);if(pe){let ge=x("span","persona-composer-model-option-icon");ge.appendChild(pe),B.appendChild(ge)}}let P=x("span","persona-composer-model-option-body"),Q=x("span","persona-composer-model-option-label");if(Q.textContent=T.label,P.appendChild(Q),T.description){let pe=x("span","persona-composer-model-option-description");pe.textContent=T.description,P.appendChild(pe)}B.appendChild(P);let U=x("span","persona-composer-model-option-check");U.setAttribute("aria-hidden","true");let de=ue("check",cw,"currentColor",2);return de&&U.appendChild(de),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 de=_(U);return f.set(U.id,de),de}))}let P=r(T);for(let[U,de]of f)de.setAttribute("aria-selected",String(U===P?.id));p.textContent=P?.label??"";let Q=e.getSuffix?.()??"";d.textContent=Q,c.setAttribute("aria-label",[t,[P?.label,Q].filter(Boolean).join(" ")].filter(Boolean).join(": "))};V(),o=V;let te=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",te),c.addEventListener("keydown",W),g.addEventListener("keydown",j);let{wrapper:Y,chevron:E}=dw();return Y.append(c,E),{element:Y,destroy:()=>{o===V&&(o=null),c.removeEventListener("click",te),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:CL,kind:"custom",placement:"end",order:wL,presentation:n==="popover"?"bar":"auto",label:t,render:()=>n==="popover"?i():s()},repaint:()=>o?.()}}Xe();Tt();Xe();var Df="[data-persona-composer-chip-row]";function np(e){e.style.display=e.childElementCount>0?"flex":"none"}function Nf(e){let t=e.querySelector(Df);if(t)return t;let n=X("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 AL=":scope > [data-persona-composer-mode]";function uw(e){let t=e.row,n="",o=!1,r=new Set(e.initialIds??[]),s=p=>{let d=X("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=ue(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=X("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${p.label}`}}),h=ue("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(AL)),l=p=>{p.setAttribute("data-persona-chip-exit",""),p.setAttribute("aria-hidden","true"),p.style.pointerEvents="none";let d=()=>{p.remove(),np(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}np(t)},destroy:()=>{o=!0,c(),np(t)}}}Xe();Tt();var gw=e=>`core:mode:${e}`;var Ff=e=>Math.min(300+e,499),fw=e=>`core:mode-group:${e}`;function op(e,t){return e?t?.find(n=>n.id===e)?.presentation==="segmented":!1}function xL(e,t){return e?t?.find(n=>n.id===e)?.chipVisibility==="hidden":!1}function mw(e,t){return e?.length?e.filter(n=>!op(n.groupId,t)&&!xL(n.groupId,t)):[]}var ML=(e,t)=>e.groupId?t?.find(n=>n.id===e.groupId)?.selection??null:null;function hw(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(ML(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 rp(e,t){return t?.length?t.filter(n=>e.includes(n.id)).map(n=>n.id):[]}function yw(e,t){return t?.length?t.filter(n=>e.includes(n.id)&&(n.persistence??"sticky")!=="once").map(n=>n.id):[]}function bw(e,t){if(!(!t?.length||e.length===0))return t.find(n=>e.includes(n.id)&&n.placeholder)?.placeholder}var EL=16;function vw(e){let t=null;return{action:{id:fw(e.groupId),kind:"custom",placement:"start",presentation:"bar",label:e.getGroup()?.label??e.groupId,render:()=>{let o=X("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=X("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":p.id,"aria-label":p.label}});if(p.iconName){let f=ue(p.iconName,EL,"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?.()}}Xe();Tt();function Cw(e){let t=X("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=X("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});c.textContent=Qd(s.text),l.appendChild(c);let p=X("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":e.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),d=ue("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()}}}Xe();Tt();function ww(e){let t=X("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=X("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":l,[c]:""}}),g=ue(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=Qd(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=X("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()}}}Xe();function Sw(e){let t=X("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":e.messageId,"data-preserve-runtime":""}}),n=X("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=X("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 Aw(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 xw(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 Mw(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 Ew(e){return e.wrapped||e.text.includes(`
28
+ `),l=Array.isArray(t.contentParts)&&t.contentParts.length>0,c=r.contentParts.length>0;if(l){let p=[];s&&p.push(Io(s)),p.push(...r.contentParts),p.push(...t.contentParts),t.contentParts=p}else if(c){let p=[];i&&p.push(Io(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??Ml(),c=li();this.#s=null;let p=n?.contentParts&&bl(n.contentParts)?la:"",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=FC({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=If(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=$C(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=li();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=If(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=Zv();if(o)return t(o,n);let r=this.#le;return mf().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=Er(this.config.features?.artifacts,t),r=al(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=Er(this.config.features?.artifacts,n),s=al(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=XC().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=>If(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=li(),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=kf(r.content);s.trim()&&this.readAloud.play(r.id,{text:s,voice:n.voice,rate:n.rate,pitch:n.pitch})}static pickBestVoice(t){return El(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let o=kf(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&&QC(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&&QC(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)})}};Xe();Mr();Tt();Hr();import{File as Y0,FileCode as X0,FileSpreadsheet as Q0,FileText as Rf,X as J0}from"lucide";var Z0={add:e=>$v(e)},eL=e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0,ep={allowedTypes:Lr,maxFileSize:10*1024*1024,maxFiles:4};function tL(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function nL(e){return e==="application/pdf"?Rf:e.startsWith("text/")?Rf:e.includes("word")?Rf:e.includes("excel")||e.includes("spreadsheet")?Q0:e==="application/json"?X0:Y0}var fa=class e{constructor(t={}){this.attachments=[];this.#e=null;this.#n=new Map;this.#o=!1;this.config={allowedTypes:t.allowedTypes??ep.allowedTypes,maxFileSize:t.maxFileSize??ep.maxFileSize,maxFiles:t.maxFiles??ep.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:Z0}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:ep.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=Uv(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:tL(),file:o,previewUrl:yd(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=eL(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=yd(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=nL(t.file.type),f=_t(g,20,"var(--persona-muted, #6b7280)",1.5);f&&d.appendChild(f);let h=x("span");h.textContent=Vv(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=X("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=X("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),l=ue("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=_t(J0,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 JC=(e,t)=>e.length===t.length&&e.every((n,o)=>n===t[o]),oL=(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 ZC(){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=>{oL(e.attachments,d)||(e.attachments=[...d],p())},setMentionRefs:d=>{JC(e.mentionRefs,d)||(e.mentionRefs=[...d],p())},setSelectedModelId:d=>{e.selectedModelId!==d&&(e.selectedModelId=d,p())},setActiveModeIds:d=>{JC(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()}}}Xe();var zn=(e,...t)=>{for(let n of t){let o=e.querySelector(n);if(o)return o}return null},ew=(e,t)=>{let n=x("div",e);return n.setAttribute(t,""),n.setAttribute("data-persona-composer-synthesized",""),n.style.display="contents",n};function tw(e,t={}){let n=zn(e,"[data-persona-composer-form]"),o=zn(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:zn(e,"[data-persona-composer-header]"),body:zn(e,"[data-persona-composer-body]"),actionsStart:zn(e,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:zn(e,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:zn(e,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:zn(e,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:zn(e,"[data-persona-composer-status]")},s=new Set,i=r.header;i||(s.add("header"),i=ew("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 _=ew(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=zn(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:zn(e,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:zn(e,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:zn(e,"[data-persona-composer-submit]")??void 0,micButton:zn(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=[]}}}Xe();Tt();sa();gs();function rL(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function tp(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??rL(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,te=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);te=Math.min(Math.max(A.left+W,A.left),j)}n.style.top=`${_}px`,n.style.left=`${te}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 te=typeof V.composedPath=="function"?V.composedPath():[];te.includes(n)||te.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}}Xe();Tt();gs();var sL='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',iL=["--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"],Wf="data-persona-menu-focus",aL=new Set(["ArrowDown","ArrowUp","Home","End"]);function nw(e){return e.getAttribute("role")==="menuitem"?e:e.querySelector(sL)??e}var lL=e=>e.disabled===!0||e.getAttribute("aria-disabled")==="true";function ow(e){let t=e.label,n=!1,o=x("div","persona-send-button-wrapper"),r=X("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${Zn} ${Ro}`,attrs:{type:"button","aria-haspopup":"menu","aria-expanded":"false","data-persona-composer-overflow-trigger":""}});o.appendChild(r);let s=X("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 Q=ue("plus",qn,"currentColor",1.5);Q?r.appendChild(Q):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 Q=s.getRootNode().activeElement;return Q instanceof HTMLElement?Q:null},f=()=>{let P=g();for(let Q of c){let U=!!P&&nw(Q)===P;Q.toggleAttribute(Wf,U&&d)}},h=()=>c.filter(P=>P.isConnected||s.contains(P)).map(nw).filter(P=>!lL(P)),y=(P,Q)=>{P.forEach((U,de)=>{U.setAttribute("tabindex",de===Q?"0":"-1")})},v=P=>{let Q=h();if(Q.length===0)return;let U=(P%Q.length+Q.length)%Q.length;p=U,y(Q,U),Q[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,te=()=>(V||(V=tp({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 Q of c)Q.removeAttribute(Wf);P&&r.focus()}},Y=(P=0,Q=!1)=>{if(n||W())return;d=Q,Sd(r,s,iL),te().open(),r.setAttribute("aria-expanded","true");let U=h();y(U,-1),v(P<0?U.length-1:P),A=de=>{let pe=typeof de.composedPath=="function"?de.composedPath():[];pe.includes(s)||pe.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):Y(0)},T=P=>{if(P.key==="ArrowDown"||P.key==="Enter"||P.key===" "){P.preventDefault(),d=!0,W()?v(0):Y(0,!0);return}P.key==="ArrowUp"&&(P.preventDefault(),d=!0,W()?v(-1):Y(-1,!0))},B=P=>{switch(aL.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(Wf);if(c=[...P],!W())return;let Q=h();y(Q,Math.min(p,Q.length-1)),f()},isOpen:W,open:()=>Y(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 Jo={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},rw="data-persona-composer-action",Of="data-persona-composer-disable-when-streaming",cL="core:overflow",dL=e=>e==="core:attachment"?"attachments":e.startsWith("core:mention")?"mentions":null;function pL(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 Bf(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 sw=(e,t)=>{!e||typeof console>"u"||console.warn(t)},uL=(e,t)=>t.includes(":")?t:`${e}:${t}`;function gL(e){let{debug:t}=e,n=[],o=new Map,r=0,s=l=>{let c=o.get(l.id);if(c){sw(t,`[Persona] composer action "${l.id}" is already contributed by ${iw(c)}; the ${iw(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?uL(p,l.id):l.id,g=l.order??Jo.custom;l.placement==="end"&&g>=Jo.send&&(sw(t,`[Persona] composer action "${d}" ordered at ${g} would render after send; clamped to ${Jo.send-1}.`),g=Jo.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 iw=e=>e.source==="plugin"?`plugin "${e.pluginId}"`:e.source==="config"?"composer.actions":"a core built-in",aw=(e,t,n)=>e===void 0?n:typeof e=="function"?e(t)===!0:e===!0,fL=e=>e.phase==="streaming"||e.text.trim().length>0||e.attachments.length>0;function mL(e,t){if(!e||e==="always")return!0;let n=fL(t);return e==="when-text"?n:!n}var ys=e=>e.kind==="custom",_f=e=>e instanceof HTMLButtonElement?e:e.querySelector("button")??e,hL=e=>{let t=_f(e);return t.getAttribute("aria-label")?.trim()||t.getAttribute("title")?.trim()||""},yL='.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]';function bL(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(yL)||o.childNodes.forEach(n)};return n(e),t.trim()}var vL=e=>bL(e).length===0;function lw(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=ue(T.iconName,16,"currentColor",1.5);U&&P.appendChild(U)}let Q=x("span","persona-composer-overflow-menu__label");Q.textContent=T.shortLabel??T.label,B.append(P,Q)},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(Of,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(),Q=!!T.shortLabel;if(B.className=Wn("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",Zn,Ro,Q&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),B.style.width=P&&!Q?P:"",B.style.height=P??"",B.style.minWidth=P&&!Q?P:"",B.style.minHeight=P??"",B.style.fontSize=Q?"":"18px",B.style.lineHeight="1",B.style.color=T.iconColor??"",B.style.backgroundColor=T.backgroundColor??"",B.replaceChildren(),T.iconName){let U=ue(T.iconName,qn,"currentColor",1.5);U&&B.appendChild(U)}if(Q){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=yn({anchor:B,trigger:E.element,text:()=>T.tooltipText??T.label,enabled:!!T.tooltipText})},l=(E,T)=>{let B=E.action,P=X("button",{attrs:{type:"button"}}),Q=P;if(T==="bar"){let pe=x("div","persona-send-button-wrapper");pe.appendChild(P),Q=pe}Q.setAttribute(rw,E.id);let U={resolved:E,element:Q,button:P,owned:!0,managed:!0,busy:!1,visible:!0,mode:T},de=pe=>{if(pe.preventDefault(),pe.stopPropagation(),U.busy||P.disabled)return;let ge=U.resolved.action;U.mode==="menu"&&h?.close(!0);let ke;try{ke=ge.onSelect(e.actionContext,pe)}catch(xe){e.reportError(xe,{actionId:U.resolved.id});return}!ke||typeof ke.then!="function"||(U.busy=!0,P.setAttribute("aria-busy","true"),ke.catch(xe=>{e.reportError(xe,{actionId:U.resolved.id})}).finally(()=>{U.busy=!1,P.removeAttribute("aria-busy")}))};return P.addEventListener("click",de),U.detach=()=>P.removeEventListener("click",de),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(rw,E.id),B.element.toggleAttribute(Of,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?ys(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 Q=null;for(let U=B+1;U<T.length;U++){let de=T[U];if(!de.managed&&de.element.parentElement===E){Q=de.element;break}}Q?(P.element.parentElement!==E||P.element.nextSibling!==Q)&&E.insertBefore(P.element,Q):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=ow({label:e.getOverflowLabel?.()??"More actions",getButtonSize:r}),h),I=E=>{y!==E&&(v?.disconnect(),y=E,C=Bf(E),!(typeof ResizeObserver>"u")&&(v=new ResizeObserver(T=>{let P=T[T.length-1]?.contentRect?.width??Bf(E);P!==C&&(C=P,j())}),v.observe(E)))},H=(E,T)=>{let B=pL(E.collapseAutoActionsBelow,T);if(B===null)return!1;let P=C||Bf(T);return P>0&&P<B},_=(E,T,B)=>{if(!T)return"bar";if(E.resolved.builtIn){let Q=dL(E.resolved.id);return Q&&T.includeBuiltIns?.includes(Q)?"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(!vL(E.element)){E.menuLabel?.remove(),E.menuLabel=void 0;return}let B=hL(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)},te=(E,T)=>{if(E.mode===T)return E;let B=E.resolved.action;if(B&&!ys(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=X("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none",[$g]:""}});P.appendChild(E.element),Pv(_f(E.element)),E.menuSlot=P;let Q=U=>{let de=_f(E.element);if(de.disabled)return;let pe=U.target===de||de.contains(U.target);h?.close(!0),pe||de.click()};P.addEventListener("click",Q,!0),E.detachMenuSlot=()=>P.removeEventListener("click",Q,!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,Q)=>{let U=E.children[Q];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 Q=P?H(P,E.footer):!1,U={start:[],end:[]},de=[];for(let pe of n){let ge=t.get(pe.id);if(!ge)continue;let ke=pe.action,xe=ke?aw(ke.visible,T,!0)&&mL(ke.visibility,T):!0;if(ge.visible!==xe&&(ge.visible=xe,!xe&&ge.managed&&(ge.menuSlot??ge.element).remove()),!!xe){if(ge=te(ge,_(ge,P,Q)),ke){let Le=aw(ke.disabled,T,!1)||ke.disableWhenStreaming===!0&&B;f(ge,Le),!ys(ke)&&ke.pressed!==void 0&&ge.button?.setAttribute("aria-pressed",ke.pressed?"true":"false")}ge.mode==="menu"?(V(ge),de.push(ge)):U[pe.placement].push(ge)}}if(de.length>0){let pe=L();W(pe.panel,de),pe.setItems(de.map(Le=>Le.menuSlot??Le.element)),pe.applyButtonSize();let ge=Number.isFinite(P?.order)?P?.order:Jo.overflow,ke=U.start.findIndex(Le=>Le.resolved.order>ge),xe={resolved:{id:cL,placement:"start",presentation:"bar",order:ge,sequence:-1,source:"core"},element:pe.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};U.start.splice(ke<0?U.start.length:ke,0,xe)}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=gL(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 pe=p(B,"bar");pe&&t.set(B.id,pe);continue}let Q=P.resolved.action,U=B.action;if(!!Q!=!!U||Q&&U&&ys(Q)!==ys(U)||Q&&U&&ys(Q)&&ys(U)&&Q.render!==U.render){d(P),t.delete(B.id);let pe=p(B,P.mode);pe&&t.set(B.id,pe);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&&!ys(U)?i(P,U):U&&P.element.toggleAttribute(Of,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=[]}}}}Xe();Tt();gs();var CL="core:model",wL=700,cw=16,SL=["--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"],dw=()=>{let e=X("span",{className:"persona-composer-model-picker-wrapper",attrs:{"data-persona-composer-model-picker-wrapper":""}}),t=X("span",{className:"persona-composer-model-picker-chevron",attrs:{"aria-hidden":"true"}});return{wrapper:e,chevron:t}};function pw(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=X("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=X("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}=dw();return h.append(c,y),{element:h,destroy:()=>{o===d&&(o=null),c.removeEventListener("change",g),c.removeEventListener("click",f)}}},i=()=>{let c=X("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=X("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=tp({anchor:c,content:g,placement:"top-start",offset:6,onDismiss:()=>c.setAttribute("aria-expanded","false")})),Sd(c,g,SL),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=X("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 pe=ue(T.icon,cw,"currentColor",1.5);if(pe){let ge=x("span","persona-composer-model-option-icon");ge.appendChild(pe),B.appendChild(ge)}}let P=x("span","persona-composer-model-option-body"),Q=x("span","persona-composer-model-option-label");if(Q.textContent=T.label,P.appendChild(Q),T.description){let pe=x("span","persona-composer-model-option-description");pe.textContent=T.description,P.appendChild(pe)}B.appendChild(P);let U=x("span","persona-composer-model-option-check");U.setAttribute("aria-hidden","true");let de=ue("check",cw,"currentColor",2);return de&&U.appendChild(de),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 de=_(U);return f.set(U.id,de),de}))}let P=r(T);for(let[U,de]of f)de.setAttribute("aria-selected",String(U===P?.id));p.textContent=P?.label??"";let Q=e.getSuffix?.()??"";d.textContent=Q,c.setAttribute("aria-label",[t,[P?.label,Q].filter(Boolean).join(" ")].filter(Boolean).join(": "))};V(),o=V;let te=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",te),c.addEventListener("keydown",W),g.addEventListener("keydown",j);let{wrapper:Y,chevron:E}=dw();return Y.append(c,E),{element:Y,destroy:()=>{o===V&&(o=null),c.removeEventListener("click",te),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:CL,kind:"custom",placement:"end",order:wL,presentation:n==="popover"?"bar":"auto",label:t,render:()=>n==="popover"?i():s()},repaint:()=>o?.()}}Xe();Tt();Xe();var Df="[data-persona-composer-chip-row]";function np(e){e.style.display=e.childElementCount>0?"flex":"none"}function Nf(e){let t=e.querySelector(Df);if(t)return t;let n=X("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 AL=":scope > [data-persona-composer-mode]";function uw(e){let t=e.row,n="",o=!1,r=new Set(e.initialIds??[]),s=p=>{let d=X("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=ue(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=X("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${p.label}`}}),h=ue("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(AL)),l=p=>{p.setAttribute("data-persona-chip-exit",""),p.setAttribute("aria-hidden","true"),p.style.pointerEvents="none";let d=()=>{p.remove(),np(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}np(t)},destroy:()=>{o=!0,c(),np(t)}}}Xe();Tt();var gw=e=>`core:mode:${e}`;var Ff=e=>Math.min(300+e,499),fw=e=>`core:mode-group:${e}`;function op(e,t){return e?t?.find(n=>n.id===e)?.presentation==="segmented":!1}function xL(e,t){return e?t?.find(n=>n.id===e)?.chipVisibility==="hidden":!1}function mw(e,t){return e?.length?e.filter(n=>!op(n.groupId,t)&&!xL(n.groupId,t)):[]}var ML=(e,t)=>e.groupId?t?.find(n=>n.id===e.groupId)?.selection??null:null;function hw(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(ML(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 rp(e,t){return t?.length?t.filter(n=>e.includes(n.id)).map(n=>n.id):[]}function yw(e,t){return t?.length?t.filter(n=>e.includes(n.id)&&(n.persistence??"sticky")!=="once").map(n=>n.id):[]}function bw(e,t){if(!(!t?.length||e.length===0))return t.find(n=>e.includes(n.id)&&n.placeholder)?.placeholder}var EL=16;function vw(e){let t=null;return{action:{id:fw(e.groupId),kind:"custom",placement:"start",presentation:"bar",label:e.getGroup()?.label??e.groupId,render:()=>{let o=X("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=X("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":p.id,"aria-label":p.label}});if(p.iconName){let f=ue(p.iconName,EL,"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?.()}}Xe();Tt();function Cw(e){let t=X("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=X("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});c.textContent=Qd(s.text),l.appendChild(c);let p=X("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":e.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),d=ue("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()}}}Xe();Tt();function ww(e){let t=X("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=X("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":l,[c]:""}}),g=ue(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=Qd(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=X("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()}}}Xe();function Sw(e){let t=X("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":e.messageId,"data-preserve-runtime":""}}),n=X("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=X("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 Aw(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 xw(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 Mw(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 Ew(e){return e.wrapped||e.text.includes(`
29
29
  `)?!1:!(e.hasAttachments||e.hasChips||e.hasQuote||e.hasPendingSubmission)}function Tw(){let e=!1;return{observe:(t,n)=>n?(t&&(e=!0),e):(e=!1,!1),release:()=>{e=!1}}}function Pw(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 kw(e){e&&(typeof e.requestSubmit=="function"?e.requestSubmit():e.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})))}wd();function $f(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 Hw(e){return e.inputDisabled===!0||e.sendDisabled===!0||e.hasAttachments&&!e.attachmentsReady?!1:!!e.text||e.hasAttachments||e.hasMentions||e.hasServerMentions}var TL=e=>typeof e?.then=="function";function Lw(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 Iw(e,t,n){let o;try{o=e($f(t),{signal:n})}catch(r){return{status:"error",error:r}}return TL(o)?Promise.resolve(o).then(r=>n.aborted?{status:"aborted"}:Lw(t,r),r=>n.aborted?{status:"aborted"}:{status:"error",error:r}):Lw(t,o)}lf();cf();af();Hr();var sp=e=>e?.launcher?.variant??(e?.future?.v5Defaults===!0?"circle":"pill"),ip={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"};bo();bo();var lp="16px",cp="transparent",PL=(()=>{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})(),Ll={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:PL,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"}},ap={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"}},eo={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:aa,maxWidth:"none",height:"min(640px, max(200px, calc(100vh - 64px)))",maxHeight:"none",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:lp,canvasBackground:cp,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"}}},kL=Ll.colors.gray,LL={50:"#fafafa",100:"#f5f5f5",200:"#e5e5e5",300:"#d4d4d4",400:"#a3a3a3",500:"#737373",600:"#525252",700:"#404040",800:"#262626",900:"#171717",950:"#0a0a0a"},Ww={...Ll,colors:{...Ll.colors,gray:kL}},HL={...Ll,colors:{...Ll.colors,gray:LL},radius:{none:"0px",sm:"4px",md:"8px",lg:"12px",xl:"16px","2xl":"24px",full:"9999px"}},IL=Ww,Ow=ap,RL={...ap,colors:{...ap.colors,surface:"#ffffff",background:"#ffffff",container:"semantic.colors.surface",textInverse:"#ffffff"},typography:{...ap.typography,fontSize:"14px",lineHeight:"1.5"}},WL=Ow,dp=eo,OL={...eo,launcher:ip,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:{...eo.input,borderRadius:"palette.radius.full"},introCard:{...eo.introCard,title:{fontSize:"22px",fontWeight:"500"}},suggestion:{chip:{...eo.suggestion.chip,fontWeight:"400"},card:{...eo.suggestion.card,fontWeight:"400"},list:{...eo.suggestion.list,fontWeight:"400"}},panel:{...eo.panel,width:"min(400px, calc(100vw - 24px))",height:"min(704px, calc(100dvh - 104px))",borderRadius:"palette.radius.xl"},header:{...eo.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:{...eo.message,gap:"20px",fullscreenGap:"28px",topFadeHeight:"18px",user:{...eo.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:{...eo.message.assistant,background:"transparent",border:"transparent",borderWidth:"0px",borderRadius:"0px",shadow:"none",padding:"0px",fontSize:"14px",lineHeight:"1.55"}},composer:{...eo.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)"}},BL=dp,_L=e=>us({future:e}),Vf=e=>_L(e)==="v5"?{palette:HL,semantic:RL,components:OL}:{palette:Ww,semantic:Ow,components:dp};function vn(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."))?vn(e,o):o}function jf(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=vn(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 Bw(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 _w(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]=_w(s,r):n[o]=r}return n}function DL(e,t){return t?_w(e,t):e}function pp(e,t={}){let n=Vf(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:DL(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=Bw(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 Uf=e=>e.trim()==="0"?"0px":e,Rw="--persona-",NL=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},FL=.179,bn=(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[Rw+s],r!==void 0)break;r!==void 0&&(e[Rw+n]=r)}};function qf(e){let t=jf(e),n={};for(let[$,We]of Object.entries(t)){let me=$.replace(/\./g,"-");n[`--persona-${me}`]=We.value}bn(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"],bn(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"]]),bn(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"]}`,bn(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"]??lp,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??cp,bn(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"]]),bn(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"],bn(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"],bn(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[$,We]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let me=n[`--persona-components-history-overlay-${$}`];me&&(n[`--persona-history-overlay-${We}`]=me)}for(let[$,We]of[["background","bg"],["borderRadius","radius"]]){let me=n[`--persona-components-history-menu-${$}`];me&&(n[`--persona-history-menu-${We}`]=me)}let g=e.components?.history?.motion;if(g){let $=dt=>{if(dt===void 0)return;let Qt=String(dt).trim();return/^\d+(\.\d+)?$/.test(Qt)?`${Qt}ms`:Qt},We=$(g.enterDurationMs);We!==void 0&&(n["--persona-history-enter-ms"]=We);let me=$(g.exitDurationMs);me!==void 0&&(n["--persona-history-exit-ms"]=me),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 We=n[`--persona-components-history-confirm-${$}`];We&&(n[`--persona-history-confirm-${$}`]=We)}for(let[$,We]of[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]]){let me=n[`--persona-components-tooltip-${$}`];me&&(n[`--persona-tooltip-${We}`]=me)}e.components?.tooltip?.arrow===!1&&(n["--persona-tooltip-arrow-display"]="none");for(let[$,We]of[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let me=n[`--persona-components-messageActions-${$}`];me&&(n[`--persona-message-action-${We}`]=me)}bn(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,bn(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"]]),bn(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"]=_),bn(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"]]),bn(n,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),bn(n,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),bn(n,[["md-hr-color","components-markdown-hr-color","divider"]]),bn(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[$,We]of V){let me=n[`--persona-components-collapsibleWidget-${$}`]??n[`--persona-${We}`];me!==void 0&&(n[`--persona-cw-${$}`]=me,n[`--cw-${$}`]=me)}bn(n,[["message-border","components-message-border","border"]]),bn(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 te=e.components,W=te?.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=te?.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 Y=te?.toggleGroup;Y&&(Y.gap&&(n["--persona-toggle-group-gap"]=Y.gap),Y.borderRadius&&(n["--persona-toggle-group-radius"]=Y.borderRadius));let E=te?.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"]=Uf($.toggleGroupGap)),$.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=$.toggleBorderRadius),$.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=Uf($.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"]=vn(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"]=Uf($.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 We=vn(e,$.toolbarBackground)??$.toolbarBackground;n["--persona-artifact-toolbar-bg"]=We}}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"]=vn(e,$.background)??$.background),$.border&&(n["--persona-artifact-inline-border"]=$.border),$.borderRadius&&(n["--persona-artifact-inline-radius"]=$.borderRadius),$.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=vn(e,$.chromeBackground)??$.chromeBackground),$.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=vn(e,$.chromeBorder)??$.chromeBorder),$.titleColor&&(n["--persona-artifact-inline-title-color"]=vn(e,$.titleColor)??$.titleColor),$.mutedColor&&(n["--persona-artifact-inline-muted-color"]=vn(e,$.mutedColor)??$.mutedColor),$.frameHeight&&(n["--persona-artifact-inline-frame-height"]=$.frameHeight)}let T=te?.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"]=vn(e,T.background)??T.background));let B=n["--persona-surface"],P=n["--persona-container"],Q=n["--persona-palette-colors-gray-100"]??"#f3f4f6",U=n["--persona-palette-colors-gray-200"]??"#e5e7eb",de=n["--persona-palette-colors-gray-300"]??"#d1d5db",pe=!P||P===B,ge=NL(B??n["--persona-background"]),ke=pe&&ge!==void 0&&ge<FL,xe=ke?"rgba(255, 255, 255, 0.08)":Q,Le=ke?"rgba(255, 255, 255, 0.12)":U,mt=ke?"rgba(255, 255, 255, 0.16)":de,Ve=pe?xe:P,Re=pe?Le:P;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??Ve,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??Re,pe&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??mt),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??Ve,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??Ve,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??Ve,n}var $L={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"};fd();var UL=e=>!!e&&"launcher"in e&&(e.launcher?.sidebarMode===!0||e.launcher?.mountMode==="docked"),Dw=(e,t)=>{if(!t||!UL(t))return e;let n=t.theme?.components?.panel?.width,o=t.darkTheme?.components?.panel?.width;return(ma(t)==="dark"?o??n:n)!=null?e:{...e,components:{...e.components,panel:{...e.components.panel,width:us(t)==="v5"?"400px":"420px"}}}},VL={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"}}},Hl={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)"}}}},zf=VL,jL={...zf,colors:{...zf.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"}}},qL=Hl,zL={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:{...Hl.components,button:{...Hl.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:{...Hl.components?.eventStream,badge:{...Hl.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"}}}}},KL=e=>us({future:e})==="v5"?{palette:jL,components:zL}:{palette:zf,components:qL},Nw=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},up=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",GL=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":up()},ma=e=>GL(e),YL=(e,t={})=>pp(e,t),XL=(e,t={})=>{let n=KL(t.future),o=Ho(n.components,e??{})??{};return pp({...o,palette:{...o.palette,colors:us(t)==="v5"?Ho(n.palette.colors,o.palette?.colors):{...n.palette.colors,...o.palette?.colors}}},{validate:!1,future:t.future})},Zo=e=>{let t=ma(e),n=Nw(e?.theme),o=sp(e)==="circle"?ip:{...dp.launcher,...e?.future?.v5Defaults?{offset:"1.5rem"}:{}},r=Ho({components:{launcher:o}},n),s=Nw(e?.darkTheme);return Dw(t==="dark"?XL(Ho(r??{},s??{}),{future:e?.future}):YL(r,{future:e?.future}),e)},QL=e=>qf(e),ha=(e,t)=>{let n=Zo(t),o=QL(n);for(let[r,s]of Object.entries(o))e.style.setProperty(r,s);e.setAttribute("data-persona-color-scheme",ma(t)),e.setAttribute("data-persona-defaults",us(t))},Il=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e(up())});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(up());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())}};fd();Tt();Mr();Xe();import{Activity as gA,Check as fA,Copy as mA}from"lucide";var bs=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");var gp="24px",Kf=(e,t)=>t||e?.composer?.placement!=="overlay"?"block":"overlay",Rl=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},Fw=e=>Math.max(0,Math.round(e.columnHeight*(1-e.fraction))-e.footerHeight);sa();pd();Dd();import{Idiomorph as JL}from"idiomorph";var fp=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;JL.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 $w=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var Gf={index:-1,draft:""};function Uw(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 Vw(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 jw(){return new Map}function qw(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function zw(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function Kw(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function Gw(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 Yw(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function er(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function di(e,t){return er(e)-e.scrollTop<=t}function Xw(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 Qw(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 Jw(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function Yf(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 Zw(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}Lo();var Wl={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},ZL=["pre","code","a","script","style"],mp=e=>({type:e?.type??Wl.type,placeholder:e?.placeholder??Wl.placeholder,speed:e?.speed??Wl.speed,duration:e?.duration??Wl.duration,buffer:e?.buffer??Wl.buffer}),tS=[{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"}],Ol=new Map;for(let e of tS)Ol.set(e.name,e);var nS=["wipe","glyph-cycle"],hp=e=>{Ol.set(e.name,e)},eH=e=>{tS.some(t=>t.name===e)||Ol.delete(e)},tH=()=>Array.from(Ol.keys()),Bl=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:Ol.get(e)??null,yp=(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
30
  `);return s<0?"":e.slice(0,s)}return e},nH=(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},oH=(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},Xf=/\s/,rH=(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},sH=(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(Xf.test(s[l])){let c=l;for(;c<s.length&&Xf.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&&!Xf.test(s[p]);)c.appendChild(nH(o,s[p],t,n.value)),n.value+=1,p+=1;i.appendChild(c),l=p}r.replaceChild(i,e)},iH=(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(oH(o,c,t,n.value)),n.value+=1));r.replaceChild(i,e)},_l=(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??ZL).map(g=>g.toLowerCase())),i=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],c=i.nextNode();for(;c;)rH(c,s)||l.push(c),c=i.nextNode();let p={value:o?.startIndex??0},d=t==="char"?sH:iH;for(let g of l)d(g,n,p);return r.innerHTML},bp=(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},Dl=(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},eS=new WeakMap,aH=(e,t)=>{if(!e.styles)return;let n=eS.get(t);if(n||(n=new Set,eS.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)},Qf=new WeakMap,lH=(e,t)=>{if(!e.onAttach)return;let n=Qf.get(t);if(n||(n=new Map,Qf.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},oS=e=>{let t=Qf.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},Nl=(e,t)=>{aH(e,t),lH(e,t)};ln();var{setLoader:d1,load:cH}=it({fallbackImport:()=>import("@runtypelabs/persona/animations-extra")});var rS=cH;Lo();function Jf(e,t=Tn){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 Fl=0,vs=null;function Zf(e=document){if(Fl++,Fl===1){let n=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;vs={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,Fl=Math.max(0,Fl-1),Fl===0&&vs)){let n=e.body,o=e.defaultView??window;n.style.overflow=vs.originalOverflow,n.style.position=vs.originalPosition,n.style.top=vs.originalTop,n.style.width=vs.originalWidth,o.scrollTo(0,vs.scrollY),vs=null}}}ia();var $l={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Ht=e=>(e?.launcher?.mountMode??"floating")==="docked",Cs=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",to=e=>{let t=e?.launcher?.dock,n=Pr(e).dockWidth?t?.width:vn(Zo(e),"components.panel.width");return{side:t?.side??$l.side,width:n??$l.width,animate:t?.animate??$l.animate,reveal:t?.reveal??$l.reveal,maxHeight:t?.maxHeight??$l.maxHeight}};Xe();Xe();Tt();Mr();import{ArrowRight as dH}from"lucide";var em=e=>e==="followUp"?"follow-up":e,tm=(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"}},sS=new WeakSet,pH=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,uH=e=>{pH()||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"})})},nm=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 _=ue(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(X("span",{className:"persona-suggestion__label",text:t.label})),t.description&&s!=="chip"&&H.appendChild(X("span",{className:"persona-suggestion__description",text:t.description})),I.appendChild(H),s!=="chip"){let _=_t(dH,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},Ul=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??{},te=v?.plugins??[],W=typeof v?.maxItems=="number"?Math.max(0,Math.floor(v.maxItems)):void 0,j=L?"followUps":"starters";!sS.has(V)&&V.debug===!0&&I!=="chip"&&V.suggestions?.[j]?.overflow!==void 0&&(sS.add(V),console.info(`[persona] suggestions.${j}.overflow applies to the "chip" variant only; the "${I}" variant manages its own stacking.`));let Y=U=>U.map(tm).filter(de=>de!==null).map(de=>({...de,behavior:de.behavior??H})),E=Y(d??[]);te.forEach(U=>{U.transformSuggestions&&(E=Y(U.transformSuggestions({suggestions:E.map(de=>({...de})),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(de=>de.role==="user")){e.hidden=!0,o=null;return}e.hidden=!1,e.classList.add("persona-suggestions"),e.dataset.personaSuggestionSurface=em(A),e.dataset.variant=I,e.dataset.overflow=_;let B=document.createDocumentFragment(),P=g.isStreaming();T.forEach((U,de)=>{let pe=nm({item:U,index:de,surface:A,source:C,variant:I,streaming:P,config:V,plugins:te,chipsConfig:y,session:g,getTextarea:()=>f,eventTarget:e,submitPrompt:v?.submitPrompt});B.appendChild(pe),n.push(pe),[...pe instanceof HTMLButtonElement?[pe]:[],...Array.from(pe.querySelectorAll("button"))].forEach(ke=>{t.includes(ke)||(ke.disabled=P,t.push(ke))})}),e.appendChild(B),i(),l();let Q=JSON.stringify({normalized:T,surface:A,variant:I,source:C});Q!==o&&(o=Q,uH(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 no={"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"};Lo();Xe();Tt();bo();Xe();Tt();sa();var gH="persona-header-control",fH="persona-header-control--glyph",mH="persona-header-control--sparse",hH=20,yH={x:[1.4,1.05]},iS="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",bH="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",vp=(e,t,n={})=>{let{iconSize:o,iconText:r}=n,[s,i]=yH[t]??[1,1.5],l=!o;e.classList.toggle(fH,l),e.classList.toggle(mH,l&&s!==1);let c=parseFloat(o??"")||hH,p=ue(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)},ya=e=>{let{ariaLabel:t,tooltip:n=!0,tooltipHint:o,iconName:r,iconText:s,wrapperClassName:i=iS,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),_=X("button",{className:Wn(gH,"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||Bn.actionIconColor,backgroundColor:d,border:H?`${g||"0px"} solid ${f||"transparent"}`:void 0,borderRadius:h,paddingLeft:y,paddingRight:y,paddingTop:v,paddingBottom:v}});return r?vp(_,r,{iconSize:c,iconText:s}):s&&(_.textContent=s),I.appendChild(_),yn({anchor:_,trigger:I,text:()=>_.getAttribute("aria-label")??t,hint:o,enabled:n}),{button:_,wrapper:I}},ba=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=iS,buttonSize:r,iconSize:s}=t,i=e?.launcher??{},l=i.closeButtonTooltipText??"Close chat",c=i.closeButtonShowTooltip??!0,{button:p,wrapper:d}=ya({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}},va=(e,t={})=>{let{wrapperClassName:n=bH,buttonSize:o,iconSize:r}=t,i=(e?.launcher??{}).clearChat??{},l=i.tooltipText??"Clear chat",c=i.showTooltip??!0,{button:p,wrapper:d}=ya({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 Bn={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)"},vH={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)"},ws=e=>{let{config:t,showClose:n=!0}=e,o=X("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:Bn.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??hl,i=r.closeButtonPlacement??"inline",l=r.headerIconHidden??!1,c=r.headerIconName,p=X("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=ue(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=X("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:Bn.titleColor,...om}}),f=X("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Bn.subtitleColor,...vH}});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=va(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}},Ca=(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))};Xe();Xe();Tt();Lo();function wa(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(na)):(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=ue(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}}Xe();Tt();function oo(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,chromeless:i,onClick:l,aria:c}=e,p=x("button",Wn(!i&&"persona-icon-btn",s));p.type="button",p.setAttribute("aria-label",n),p.title=n;let d=ue(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 aS(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=ue(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 Cp(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=oo({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 CH(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?oo({...C,icon:n,size:o??14}):aS({...C,icon:n,iconSize:o??14}),L=oo({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=wa({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 rm(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=ue(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=wa({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()}}}Dd();var lS=e=>{let t=ws({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 wH(e,t,n){if(t?.length)for(let o of t){let{button:r,wrapper:s}=ya({ariaLabel:o.ariaLabel??o.label??o.id,iconName:o.icon,iconText:o.icon?void 0:o.label,tooltipHint:o.shortcut?_d(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=wl(o.shortcut);i&&r.setAttribute("aria-keyshortcuts",i)}if(o.menuItems?.length){let i=wa({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 cS=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=Bn.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=rm({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:_}}))},te=c.onSelect(_);te instanceof Promise?te.then(V,()=>{}):V(te)},hover:c.hover,className:""});p=H.element,p.style.color=Bn.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=Bn.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}=ba(t,{showClose:n,wrapperClassName:g});o&&f.addEventListener("click",o);let y=x("div","persona-flex persona-items-center persona-gap-1");c||wH(y,r?.trailingActions,r?.onAction??s);let v=i.clearChat??{},C=null,A=null;if(v.enabled??!0){let H=v.placement??"inline",_=va(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}},sm={default:lS,minimal:cS},dS=e=>sm[e]??sm.default,Vl=(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=dS(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};Xe();gs();var Sa=e=>{let{config:t}=e,n=X("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=Td(),r=X("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}=Ad(t);i();let l=xd(t),c=ca(t),p=Md(t),d=Ed(t),g=X("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=X("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),h=X("div",{className:"persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-start":""}}),y=X("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}};Xe();Mr();gs();wd();import{ChevronUp as SH,MessageSquare as AH}from"lucide";var pS=()=>{let e=X("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=_t(AH,16,"currentColor",1.5);n&&t.appendChild(n);let o=x("span","persona-pill-peek__text"),r=x("span","persona-pill-peek__caret"),s=_t(SH,16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},wp=e=>{let{config:t}=e,n=X("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=Td(),r=Ed(t);r.style.display="none";let{textarea:s,attachAutoResize:i}=Ad(t,{defaultMaxLines:5});i();let l=xd(t),c=ca(t),p=Md(t);p&&p.previewsContainer.classList.add("persona-pill-composer__previews");let d=X("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""}}),g=X("div",{className:"persona-widget-composer__left-actions persona-pill-composer__left",attrs:{"data-persona-composer-actions-start":""}});p&&g.append(p.wrapper);let f=X("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=X("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}};Xe();Tt();Xe();df();Tt();Hr();var xH=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}},MH=(e,t)=>{if(!e)return null;let n=xH(e);if(n===null)return null;let o=t?.[e],r=o!==void 0?o:n;return r||null},EH=(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},TH=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},am=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(":"))},lm=320,hS=320,PH=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),kH=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),LH=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),HH=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),IH=e=>{if(!e||e.length===0)return null;let t=X("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let n of e){let o=X("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=x("span","persona-mention-chip-icon"),s=ue(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild(X("span",{className:"persona-mention-chip-label",text:n.label})),t.appendChild(o)}return t},RH=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(Cl(o.ref,{readonly:!0,render:t}))}return n},uS="\uE000",gS="\uE001",WH=(e,t,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=f=>`${uS}${r}:${f}${gS}`,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(RH(t,o));return}e.innerHTML=l;let p=new RegExp(`${uS}${r}:(\\d+)${gS}`),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(Cl(v.ref,{readonly:!0,render:o}),C),h=C}}},OH=(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=`${lm}px`,p.style.maxHeight=`${hS}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}),TH(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}},BH=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(!am(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=`${lm}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},_H=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(!am(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=`${lm}px`,r.style.maxHeight=`${hS}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}},DH=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(!am(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}},Aa=()=>{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},yS=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:Aa};if(t){let r=t(o);if(r!==null)return r}return Aa()},NH=(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},fS=(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},jl=(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},mS={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"}},FH=(e,t,n="bubble",o)=>{if(!o)return;let r=t==="user"?"user":"assistant",s=mS[n??"bubble"]??mS.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)`)},Sp="custom:",$H=e=>`${Sp}${e}`,bS=(e,t)=>t!=="user"&&t!=="assistant"?[]:(e?.custom??[]).filter(n=>(n.roles??["assistant"]).includes(t)),vS=(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=bS(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=oo({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,$H(I.id)));return A},ql=(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=jl(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=Vf(s?.widgetConfig?.future).components.message,A=s?.widgetConfig?.theme?.components?.message;FH(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=PH(e),I=e.content?.trim()??"",_=L.length>0&&I===la,V=mp(s?.widgetConfig?.features?.streamAnimation),te=s?.widgetConfig?.features?.streamAnimation?.plugins,W=e.role==="assistant"&&V.type!=="none"?Bl(V.type,te):null,j=e.role==="assistant"&&W?.isAnimating?.(e)===!0,Y=e.role==="assistant"&&W!==null&&(!!e.streaming||j);Y&&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"),Y&&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=Y?yp(e.content??"",V.buffer,W,e,!!e.streaming):e.content??"",B=()=>{let Re=t({text:T,message:e,streaming:!!e.streaming,raw:e.rawContent});return Y&&W?.wrap==="char"?_l(Re,"char",e.id,{skipTags:W.skipTags}):Y&&W?.wrap==="word"?_l(Re,"word",e.id,{skipTags:W.skipTags}):Re},P=null;if(_?(P=document.createElement("div"),P.innerHTML=B(),P.style.display="none",E.appendChild(P)):e.contentSegments?.length?WH(E,e.contentSegments,Re=>t({text:Re,message:e,streaming:!!e.streaming,raw:e.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):E.innerHTML=B(),Y&&W?.useCaret&&!_&&I){let Re=bp(),$=E.querySelectorAll(".persona-stream-char, .persona-stream-word"),We=$[$.length-1];if(We?.parentNode)We.parentNode.insertBefore(Re,We.nextSibling);else{let me=E.lastElementChild;me?me.appendChild(Re):E.appendChild(Re)}}if(g&&h==="inline"&&e.createdAt){let Re=fS(e,p,"span");Re.classList.add("persona-timestamp-inline");let $=E.lastElementChild;$?$.appendChild(Re):E.appendChild(Re)}if(L.length>0){let Re=OH(L,!_&&!!I,()=>{_&&P&&(P.style.display="")});Re?v.appendChild(Re):_&&P&&(P.style.display="")}let Q=kH(e);if(Q.length>0){let Re=BH(Q);Re&&v.appendChild(Re)}let U=LH(e);if(U.length>0){let Re=_H(U);Re&&v.appendChild(Re)}let de=HH(e);if(de.length>0){let Re=DH(de);Re&&v.appendChild(Re)}let pe=e.contentSegments?.length?null:IH(e.contextMentions);if(pe&&v.appendChild(pe),v.appendChild(E),g&&h==="below"&&e.createdAt){let Re=fS(e,p);Re.classList.add("persona-mt-1"),v.appendChild(Re)}let ge=e.role==="assistant"?MH(e.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let Re=!!(T&&T.trim()),$=V.placeholder==="skeleton",We=$&&V.buffer==="line"&&Re;if(Re)We&&v.appendChild(Dl());else if($)v.appendChild(Dl());else{let me=yS("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);me&&v.appendChild(me)}}ge&&e.stopReason&&!e.streaming&&(I||(E.style.display="none"),v.appendChild(EH(e.stopReason,ge)));let ke=e.role==="assistant"&&!e.streaming&&!e.voiceCaption&&e.content&&e.content.trim()&&o?.enabled!==!1,xe=s?.actionEligibility,Le=e.role==="user"&&!e.streaming&&o?.enabled!==!1&&(o?.showEdit===!0&&xe?.canEdit===!0||o?.showQuote===!0&&xe?.canQuote===!0||bS(o,"user").length>0);if((ke||Le)&&o){let Re=vS(e,Le?{...o,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:o,r,xe);v.appendChild(Re)}if(!d||e.role==="system")return v;let mt=x("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Ve=NH(c,e.role);return f==="right"||f==="left"&&e.role==="user"?mt.append(v,Ve):mt.append(Ve,v),mt},UH=(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}):ql(e,t,n,o,r,s)};var VH=40,jH=(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=ue(t.name,VH);if(!n){e.hidden=!0;return}e.appendChild(n)}else t.type==="image"?e.appendChild(X("img",{className:"persona-welcome-icon-image",attrs:{src:t.url,alt:t.alt}})):e.appendChild(X("span",{className:"persona-welcome-icon-text",text:t.text}));e.hidden=!1},CS=(e,t,n={})=>{let o=X("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=X("div",{className:"persona-welcome-head-text"},r,s),c=X("div",{className:"persona-welcome-title-row"},o,l);return{host:X("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}},xa=(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)},xp=(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==="",jH(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")},qH="data-persona-welcome-plugin",wS="data-persona-welcome-overlay",Ap="persona-welcome-overlay-active",cm=new WeakMap,dm=(e,t,n)=>{n.setAttribute(qH,""),t.appendChild(n),t.setAttribute("data-persona-welcome-content","plugin"),t.setAttribute(wS,""),e.classList.contains(Ap)||(cm.set(e,e.scrollTop),e.classList.add(Ap),e.scrollTop=0)},pm=(e,t,n)=>{n&&n!==t&&n.remove(),t.removeAttribute("data-persona-welcome-content"),t.removeAttribute(wS),e.classList.contains(Ap)&&(e.classList.remove(Ap),e.scrollTop=cm.get(e)??e.scrollTop,cm.delete(e))},SS=()=>{let e=X("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return e.hidden=!0,e},Mp=(e,t,n)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}let o=n?.layout?.messages?.layout??"bubble",r=X("div",{className:jl("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(X("div",{className:"persona-flex"},r)),e.hidden=!1},AS=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,xS=(e,t)=>{if(AS()||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},MS=(e,t,n,o=260)=>{if(t<=1||AS()||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 zH="Hello \u{1F44B}",KH="I can answer questions and help you get things done here.",ES=new WeakSet,_n=(e,t)=>!!e&&e[t]!==void 0,GH=(e,t)=>{!e||e.debug!==!0||!t.length||ES.has(e)||(ES.add(e),t.forEach(n=>console.warn(`[persona] ${n}`)))},zl=(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=_n(n,"variant")?n.variant:o?.showWelcomeCard===!1?"none":"card",l=i==="hero"&&!r&&n?.layout===void 0?"on-first-message":_n(n,"dismiss")?n.dismiss:r||i==="hero"?"on-first-message":"never",c=[];_n(n,"title")&&_n(o,"welcomeTitle")&&c.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),_n(n,"subtitle")&&_n(o,"welcomeSubtitle")&&c.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),_n(n,"variant")&&_n(o,"showWelcomeCard")&&c.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),i==="hero"&&_n(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"&&_n(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=Rl(n?.anchorComposerTop)!==null;return _n(n,"anchorComposerTop")&&!d&&c.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),p!=="center"&&(_n(n,"anchorComposerTop")||_n(n,"composerGap"))&&c.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),GH(e,c),{title:_n(n,"title")?n.title:o?.welcomeTitle??(r?"What can I help with?":zH),kicker:n?.kicker??"",subtitle:_n(n,"subtitle")?n.subtitle:o?.welcomeSubtitle??(r?"":KH),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()||gp}},TS=e=>(e??[]).some(t=>t.role==="user")?"active":"empty",pi=(e,t)=>e.variant==="none"?!1:e.dismiss==="never"?!0:!(t??[]).some(n=>n.role==="user");ia();var YH="var(--persona-components-panel-maxWidth)",PS="var(--persona-components-panel-height)",XH="var(--persona-components-panel-maxHeight)",ui=e=>{let t=Pr(e),n=t.launcherWidth?e?.launcher?.width:t.legacyLauncherWidth?e?.launcherWidth:void 0,o=e?.launcher?.heightOffset??0,r=o===0?`max(200px, ${PS})`:`max(200px, calc(${PS} - ${o}px))`;return{width:n??Ov,maxWidth:n??YH,height:r,maxHeight:XH}},kS="16px",gm="10px",fm="14px",LS=e=>{let t=e?.launcher?.enabled??!0,n=Ht(e);if(Cs(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??Tn);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??Tn),{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=Pr(e),h=g.launcherWidth||g.legacyLauncherWidth||e?.theme?.components?.panel?.width!==void 0?ui(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&&no[r.position]?no[r.position]:no["bottom-right"],i=x("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);i.style.zIndex=String(e?.launcher?.zIndex??Tn);let l=x("div","persona-widget-panel persona-relative persona-min-h-[320px]"),c=ui(e);return l.style.width=c.width,l.style.maxWidth=c.maxWidth,i.appendChild(l),{wrapper:i,panel:l}},mm=e=>{let t=X("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":em(e)}});return t.hidden=!0,t},HS=(e,t)=>{let n=mm("starter"),o=CS(e,n,{flatShadow:Ht(e)}),r=zl(e);xp(o,r),xa(t,o.host,pi(r,e?.initialMessages));let s=SS();return Mp(s,r.message,e),{welcome:o,greetingHost:s}},QH=(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:kS,iconSize:gm});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 te=va(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:kS,iconSize:fm});i=te.button,l=te.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let c=X("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),p=X("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}=HS(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=mm("followUp"),L=bs(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=X("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=wp({config:e}),{root:_,textNode:V}=pS();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}},IS=(e,t=!0)=>{if(Cs(e))return QH(e,t);let n=X("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?Vl(e,o,{showClose:t}):ws({config:e,showClose:t}),i=X("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}=HS(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=mm("followUp"),v=bs(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=Sa({config:e}),A=e?.layout?.showFooter!==!1;r?Ca(n,s,e):(s.header.style.display="none",Ca(n,s,e)),n.append(i);let L=X("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}};gs();Xe();Tt();Lo();var hm=(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>
@@ -478,7 +478,7 @@ ${s.join(`
478
478
  ${s.join(`
479
479
  `)}`]:[];return o&&i.push(o),i.join(`
480
480
 
481
- `)}function kW(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===uW?new Uint8Array(e,44):new Uint8Array(e)}function ex(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 LW(e){return ex(e).replace(/^ws/i,"http")}function HW(e){return typeof e!="number"||!Number.isFinite(e)?mW:Math.min(yW,Math.max(hW,Math.round(e)))}var Xl=class{constructor(t){this.config=t;this.type="runtype";this.#e=null;this.#t=null;this.#o=[];this.#n=null;this.#l=null;this.#i=null;this.#c=[];this.#u=0;this.#d=null;this.#A=!1;this.#r=!1;this.#s=0;this.#g=!1;this.#H=Number.NEGATIVE_INFINITY;this.#b=null;this.#w=!1;this.#a=!1;this.#p=0;this.#f=0;this.#x=!1;this.bridge=null;this.#y=!1;this.#m=new Set;this.#M=new Map;this.#k=new Set;this.#C=!1;this.#G=null;this.#J=null;this.#V=Promise.resolve();this.#W=new Set;this.#O=!1;this.#E=new Set;this.#F=new Set;this.#Z=[];this.#ee=[];this.#j=[];this.#q=[];this.#B=[]}#e;#t;#o;#n;#l;#i;#c;#u;#d;#A;#r;#s;#g;#H;#b;#w;#a;#p;#f;#h;#x;#y;#m;#M;#k;#S;#C;#G;#J;#V;#W;#O;#E;#F;#Z;#ee;#j;#q;#B;async connect(){}setSessionBridge(t){this.bridge=t}prewarm(){if(this.#A||this.#b)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.#H<gW)){this.#H=r;try{this.config?.prewarmMode==="attach"?this.#Y(o,t,n):this.#re(o,t,n)}catch{}}}#re(t,n,o){if(typeof fetch!="function")return;let r=`${LW(t)}/v1/client/agents/${encodeURIComponent(n)}/voice/prewarm`;fetch(r,{method:"POST",headers:{Authorization:`Bearer ${o}`},keepalive:!0}).catch(()=>{})}#Y(t,n,o){let r=new URLSearchParams,s=this.config?.attachIdleMs,i=HW(s);s!==void 0&&r.set("attachIdleMs",String(i));let l=new WebSocket(this.#ce(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.#b=d,l.onopen=()=>{this.#b===d&&(d.state=l.protocol==="runtype.attach"?"attached":"live",d.openedAt=Date.now(),this.#_(d,i),d.state==="attached"&&l.send('{"type":"ping"}'),d.settle())},l.onmessage=g=>{if(this.#b!==d||typeof g.data!="string")return;let f;try{f=JSON.parse(g.data)}catch{return}f.type==="attached"&&typeof f.idleMs=="number"&&this.#_(d,f.idleMs-(Date.now()-d.openedAt))},l.onerror=()=>{},l.onclose=()=>{this.#b===d&&this.#te()}}#_(t,n){clearTimeout(t.idleTimer),t.idleTimer=setTimeout(()=>{this.#b===t&&this.#te()},Math.max(0,n))}#te(){let t=this.#b;if(!t)return;this.#b=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#le(){let t=this.#b;if(!t)return null;if(t.state==="connecting"){let n;await Promise.race([t.ready,new Promise(o=>{n=setTimeout(o,fW)})]),clearTimeout(n)}return this.#b!==t?null:t.state==="connecting"||t.ws.readyState!==WebSocket.OPEN?(this.#te(),null):(this.#b=null,clearTimeout(t.idleTimer),{ws:t.ws,live:t.state==="live"})}#ce(t,n,o){let r=["partial_transcript","context"];this.bridge&&this.config?.clientDelegation!==!1&&r.push("client_delegation","delegation_update"),o&&r.unshift("attach");let s=new URLSearchParams({voiceProtocol:SW,clientVersion:`persona/${Jn}`,voiceCapabilities:bW,clientCapabilities:r.join(",")});return o?.forEach((i,l)=>s.set(l,i)),`${ex(t)}/ws/agents/${encodeURIComponent(n)}/voice?${s}`}async startListening(){if(this.#A)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.#s;this.#g=!1,this.#A=!0;try{let s=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:Jm,channelCount:1,echoCancellation:!0}});if(r!==this.#s){s.getTracks().forEach(g=>g.stop());return}this.#n=s;let i=window.AudioContext||window.webkitAudioContext,l=new i({sampleRate:Jm});l.state==="suspended"&&await l.resume().catch(()=>{}),this.#t=l;let c=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new ga(lW);if(r!==this.#s){c.destroy(),s.getTracks().forEach(g=>g.stop()),l.close().catch(()=>{});return}this.#d=c,this.#D(),this.#de(l,s,r);let p=await this.#le();if(r!==this.#s){p?.ws.close(1e3,"client ended call");return}if(p){let{ws:g}=p;this.#e=g,this.#I(g,r),p.live||g.send('{"type":"start"}'),this.#ne(g),this.#v("listening");return}let d=new WebSocket(this.#ce(o,t),["runtype.bearer",n]);d.binaryType="arraybuffer",this.#e=d,d.onopen=()=>{r===this.#s&&(this.#ne(d),this.#v("listening"))},this.#I(d,r)}catch(s){throw this.#X(),this.#se(s),this.#v("error"),s}}#I(t,n){t.onmessage=o=>this.#pe(o,n),t.onerror=()=>{n===this.#s&&(this.#se(new Error("Voice connection failed")),this.#v("error"),this.#X())},t.onclose=o=>{if(this.#g){this.#g=!1;return}if(n===this.#s){if(o.code!==1e3){let r=o.code?` (code ${o.code})`:"";this.#se(new Error(`Voice connection closed${r}`)),this.#v("error")}else this.#v("idle");this.#X()}}}getDisclosure(){let t=this.config?.disclosureText;return this.#A&&this.#w&&t!==!1?t||xW:null}async stopListening(){this.#X(),this.#v("idle")}async disconnect(){this.#X(),this.#v("disconnected"),this.#Z=[],this.#ee=[],this.#j=[],this.#q=[],this.#B=[]}stopPlayback(){this.#Ce();let t=this.#e;t&&t.readyState===WebSocket.OPEN&&(this.#w&&(this.#p=Date.now()+CW,t.send('{"type":"cancel"}')),this.#v("listening"))}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.#A}onLevel(t){this.#o.push(t)}async deactivateBargeIn(){this.#X(),this.#v("idle")}#de(t,n,o){let r=t.createMediaStreamSource(n);this.#l=r;let s=t.createScriptProcessor(cW,1,1);this.#i=s,s.onaudioprocess=i=>{if(o!==this.#s)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.#ne(l),l.send(d.buffer);else for(this.#c.push(d.buffer),this.#u+=d.byteLength;this.#u>dW;)this.#u-=this.#c.shift().byteLength;if(this.#o.length>0){let f=Math.sqrt(g/p.length),h=Math.max(0,Math.min(1,f*pW));for(let y of this.#o)y(h)}},r.connect(s),s.connect(t.destination)}#ne(t){for(let n of this.#c)t.send(n);this.#c=[],this.#u=0}#pe(t,n){if(n!==this.#s)return;if(t.data instanceof ArrayBuffer){this.#he(t.data,n);return}let o;try{o=JSON.parse(t.data)}catch{return}switch(o.type){case"session_config":o.speechMode&&(this.#w=o.speechMode==="speech_to_speech",this.#d?.setContinuousMode?.(this.#w)),Array.isArray(o.capabilities)&&(this.#m=new Set(o.capabilities)),typeof o.callId=="string"&&(this.#S=o.callId),this.#y=this.#w&&this.#m.has("client_delegation")&&!!this.bridge,this.#w&&!this.#r&&this.#v("listening"),this.#m.has("context")&&!this.#C&&(this.#C=!0,this.#G=this.#$());break;case"transcript_update":{let r=o.role==="assistant"?"assistant":"user",s=o.utteranceId??o.turnId;if(!s||r==="assistant"&&this.#oe())break;let i=String(s);if(r==="user")o.final===!0&&this.#R(n),this.#O=!1;else if(this.#O&&!this.#E.has(i)&&(this.#F.add(i),this.#O=!1),this.#E.add(i),this.#F.has(i))break;this.#K(r,o.text??"",o.final===!0,{turnId:i,...typeof o.startMs=="number"&&{startMs:o.startMs},...typeof o.endMs=="number"&&{endMs:o.endMs},...this.#y&&{caption:!0}});break}case"delegation_started":case"delegation_completed":{let r=String(o.delegationId??o.turnId);if(o.type==="delegation_started"){this.#R(n);let s=o.input;this.#y&&s&&this.#z(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.#W.has(r)&&(this.#O=!0);this.#a=o.type==="delegation_started",!this.#r&&!this.#oe()&&this.#v(this.#a?"processing":"listening");break}case"delegation_cancelled":this.#T(String(o.delegationId),o.reason!=="session_ending"&&o.reason!=="provider_cancelled");break;case"warning":console.warn(`[Persona voice] ${o.code}: ${o.message??""}`,this.#S??""),o.delegationId&&(o.code==="UNKNOWN_DELEGATION"||o.code==="LATE_RESULT_LIMIT")&&this.#T(String(o.delegationId));break;case"audio_clear":this.#Ce(),this.#p=0,this.#v("listening");break;case"transcript_interim":this.#v("listening"),this.#K("user",o.text??"",!1);break;case"transcript_final":{let r=o.role==="assistant"?"assistant":"user";this.#v(r==="user"?"processing":"speaking"),this.#K(r,o.text??"",!0);break}case"audio_end":this.#d?this.#d.markStreamEnd():(this.#r=!1,this.#v("listening"));break;case"metrics":this.#Ae({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.#se(new Error(o.error||"Voice error")),this.#v("error");break}}async#$(){let t=this.bridge?.getHistory()??[],n="";try{let o=this.config?.callContext;n=String((typeof o=="function"?await o():o)??"")}catch{}return PW(t,n)}#R(t){let n=this.#G;if(!n)return;this.#G=null;let o=!1,r=n.then(s=>{let i=this.#e;o||!s||t!==this.#s||i?.readyState!==WebSocket.OPEN||i.send(JSON.stringify({type:"context",text:s}))});this.#J={done:r,drop:()=>o=!0}}async#L(){let t=this.#J;if(!t)return;let n,o=await Promise.race([t.done.then(()=>!1),new Promise(r=>{n=setTimeout(()=>r(!0),wW)})]);clearTimeout(n),o&&t.drop()}#T(t,n=!1){this.#k.add(t),this.bridge?.dropDelegation?.(t,n),this.#M.get(t)?.abort()}#z(t,n,o){let r=this.bridge,s=(i,l,c)=>{let p=this.#e;return o!==this.#s||p?.readyState!==WebSocket.OPEN||this.#k.has(t)?!1:(p.send(JSON.stringify({type:i,delegationId:t,status:l,text:c})),!0)};this.#V=this.#V.then(async()=>{if(o!==this.#s||this.#k.has(t))return;let i=await r.runDelegatedTurn(n).catch(()=>({status:"failed",text:""}));await this.#L();let l=!!i.followUp,c=l&&this.#m.has("delegation_update");if(!s(c?"delegation_update":"delegation_result",l&&!c?"completed":i.status,i.text)||(i.status!=="failed"&&this.#W.add(t),!i.followUp))return;let d=new AbortController;this.#M.set(t,d),i.followUp({signal:d.signal,approvalTimeoutMs:this.config?.approvalTimeoutMs&&Math.min(this.config.approvalTimeoutMs,AW),readBack:c,onUpdate:g=>s("delegation_update","pending_approval",g)}).then(g=>{this.#M.delete(t),c&&g&&!d.signal.aborted&&s("delegation_result",g.status,g.text)})})}#he(t,n){if(n!==this.#s||!this.#d||this.#oe())return;let o=kW(t);o.length!==0&&(this.#r||(this.#r=!0,this.#v("speaking")),this.#D(),this.#d.enqueue(o),this.#w&&this.#ve(o.length))}#oe(){return Date.now()<this.#p}#D(){if(this.#x||!this.#d)return;this.#x=!0;let t=this.#s;this.#d.onFinished(()=>{t===this.#s&&(this.#x=!1,this.#ye())})}#ve(t){let n=Date.now();this.#f=Math.max(n,this.#f)+t/48,clearTimeout(this.#h),this.#h=setTimeout(()=>this.#ye(),this.#f-n+vW)}#ye(){this.#r=!1,this.#f=0,this.#e&&this.#e.readyState===WebSocket.OPEN&&this.#v(this.#a?"processing":"listening")}#Ce(){this.#d?.flush(),this.#x=!1,this.#D(),this.#r=!1,this.#f=0,clearTimeout(this.#h)}#X(){this.#s+=1,this.#A=!1,this.#r=!1,this.#te(),this.#w=!1,this.#a=!1,this.#y=!1,this.#m=new Set;for(let t of this.#M.values())t.abort();if(this.#M.clear(),this.#k.clear(),this.#S=void 0,this.#C=!1,this.#G=null,this.#J=null,this.#V=Promise.resolve(),this.#W.clear(),this.#O=!1,this.#E.clear(),this.#F.clear(),this.#x=!1,this.#p=0,this.#f=0,clearTimeout(this.#h),this.#c=[],this.#u=0,this.#i&&(this.#i.onaudioprocess=null,this.#i.disconnect(),this.#i=null),this.#l&&(this.#l.disconnect(),this.#l=null),this.#n&&(this.#n.getTracks().forEach(t=>t.stop()),this.#n=null),this.#t&&(this.#t.close().catch(()=>{}),this.#t=null),this.#d&&(this.#d.destroy(),this.#d=null),this.#e){this.#g=!0;try{this.#e.close(1e3,"client ended call")}catch{}this.#e=null}}onResult(t){this.#Z.push(t)}onError(t){this.#ee.push(t)}onStatusChange(t){this.#j.push(t)}onTranscript(t){this.#q.push(t)}onMetrics(t){this.#B.push(t)}#v(t){this.#j.forEach(n=>n(t))}#se(t){this.#ee.forEach(n=>n(t))}#K(t,n,o,r){this.#q.forEach(s=>s(t,n,o,r))}#Ae(t){this.#B.forEach(n=>n(t))}};var mi=class{constructor(t={}){this.config=t;this.type="browser";this.#e=null;this.#t=[];this.#o=[];this.#n=[];this.#l=!1;this.#i=typeof window<"u"?window:void 0}#e;#t;#o;#n;#l;#i;async connect(){this.#n.forEach(t=>t("connected"))}async startListening(){try{if(this.#l)throw new Error("Already listening");if(!this.#i)throw new Error("Window object not available");let t=this.#i.SpeechRecognition||this.#i.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.#t.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.#n.forEach(o=>o("error"))},this.#e.onstart=()=>{this.#l=!0,this.#n.forEach(n=>n("listening"))},this.#e.onend=()=>{this.#l=!1,this.#n.forEach(n=>n("idle"))},this.#e.start()}catch(t){throw this.#o.forEach(n=>n(t)),this.#n.forEach(n=>n("error")),t}}async stopListening(){this.#e&&(this.#e.stop(),this.#e=null),this.#l=!1,this.#n.forEach(t=>t("idle"))}onResult(t){this.#t.push(t)}onError(t){this.#o.push(t)}onStatusChange(t){this.#n.push(t)}async disconnect(){await this.stopListening(),this.#n.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Ql(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Xl(e.runtype);case"browser":if(!mi.isSupported())throw new Error("Browser speech recognition not supported");return new mi(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 Zm(e){if(e?.type==="custom"&&e.custom)return Ql({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return Ql({type:"runtype",runtype:e.runtype});if(mi.isSupported())return Ql({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function tx(e){try{return Zm(e),!0}catch{return!1}}var nx="webmcp:",IW=e=>e.startsWith(nx)?e.slice(nx.length):e,Gp={warn(e,...t){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},Xp=class{constructor(t,n){this.config=t;this.#i=n,this.#e=t.onConfirm??null,this.#t=3e4}#e;#t;#o=!1;#n=null;#l=!1;#i;setConfirmHandler(t){this.#e=t}isOperational(){return this.config.enabled!==!0||!this.#o?!1:this.#d()!==null}async snapshotForDispatch(){if(await this.#c(),this.config.enabled!==!0)return[];let t=this.#d();if(!t)return[];let n;try{n=await t.getTools()}catch(r){return Gp.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}this.#i.recordToolDisplayTitles(n);let o=typeof location<"u"?location.origin:"";return n.filter(r=>this.#r(r.name)).map(r=>{let s=WW(r.annotations);return{name:r.name,description:r.description,parametersSchema:OW(r.inputSchema),origin:"webmcp",...o?{pageOrigin:o}:{},...s?{annotations:s}:{},...s?.untrustedContentHint===!0?{untrustedContentHint:!0}:{}}})}async executeToolCall(t,n,o){if(await this.#c(),this.config.enabled!==!0)return Wo("WebMCP is not enabled on this widget.");let r=this.#d();if(!r){let y=typeof document<"u"&&!!document.modelContext;return Wo(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=IW(t),i;try{i=await r.getTools()}catch(y){let v=y instanceof Error?y.message:String(y);return Wo(`Failed to read WebMCP registry: ${v}`)}this.#i.recordToolDisplayTitles(i);let l=i.find(y=>y.name===s);if(!l)return Wo(`WebMCP tool not registered on this page: ${s}`);if(!this.#r(s))return Wo(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return Wo("Aborted by cancel()");let c=this.#i.getToolDisplayTitle(s),p={toolName:s,args:n,description:l.description,...c?{title:c}:{},reason:"gate"};if(!await this.#A(p))return Wo("User declined the tool call.");if(o?.aborted)return Wo("Aborted by cancel()");let d=new AbortController,g=!1,f=setTimeout(()=>{g=!0,d.abort()},this.#t),h=()=>d.abort();o&&(o.aborted?d.abort():o.addEventListener("abort",h,{once:!0}));try{let y=await r.executeTool(l,NW(n),{signal:d.signal});return BW(y)}catch(y){if(g)return Wo(`WebMCP tool '${s}' timed out after ${this.#t}ms`);if(o?.aborted)return Wo("Aborted by cancel()");let v=y instanceof Error?y.message:String(y);return Wo(v)}finally{clearTimeout(f),o&&o.removeEventListener("abort",h)}}#c(){return this.config.enabled!==!0?Promise.resolve():(this.#n||(this.#n=this.#u()),this.#n)}async#u(){try{if(this.#d()){this.#o=!0;return}(await this.#i.loadPolyfill()).initializeWebMCPPolyfill(),this.#o=!0}catch(t){Gp.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",t),this.#o=!1}}#d(){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.#l||(this.#l=!0,Gp.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#A(t){let n=this.#e??_W;try{return await n(t)}catch(o){return Gp.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,o),!1}}#r(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(o=>RW(t,o))}},RW=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Yp={type:"object",properties:{}},WW=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},OW=e=>{if(e===void 0||e==="")return{...Yp};if(typeof e=="object")return e!==null&&!Array.isArray(e)?e:{...Yp};try{let t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:{...Yp}}catch{return{...Yp}}},BW=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:FW(t)}]}},Wo=e=>({isError:!0,content:[{type:"text",text:e}]}),_W=async e=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let t=DW(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
481
+ `)}function kW(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===uW?new Uint8Array(e,44):new Uint8Array(e)}function ex(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 LW(e){return ex(e).replace(/^ws/i,"http")}function HW(e){return typeof e!="number"||!Number.isFinite(e)?mW:Math.min(yW,Math.max(hW,Math.round(e)))}var Xl=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<gW)){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=`${LW(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=HW(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,fW)})]),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:SW,clientVersion:`persona/${Jn}`,voiceCapabilities:bW,clientCapabilities:r.join(",")});return o?.forEach((i,l)=>s.set(l,i)),`${ex(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:Jm,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:Jm});l.state==="suspended"&&await l.resume().catch(()=>{}),this.#n=l;let c=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new ga(lW);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||xW: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()+CW,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(cW,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>dW;)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*pW));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 PW(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),wW)})]);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,AW),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=kW(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+vW)}#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 mi=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 Ql(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Xl(e.runtype);case"browser":if(!mi.isSupported())throw new Error("Browser speech recognition not supported");return new mi(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 Zm(e){if(e?.type==="custom"&&e.custom)return Ql({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return Ql({type:"runtype",runtype:e.runtype});if(mi.isSupported())return Ql({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function tx(e){try{return Zm(e),!0}catch{return!1}}var nx="webmcp:",IW=e=>e.startsWith(nx)?e.slice(nx.length):e,Gp={warn(e,...t){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},Xp=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 Gp.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=WW(r.annotations);return{name:r.name,description:r.description,parametersSchema:OW(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 Wo("WebMCP is not enabled on this widget.");let r=this.#i();if(!r){let y=typeof document<"u"&&!!document.modelContext;return Wo(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=IW(t),i;try{i=await r.getTools()}catch(y){let v=y instanceof Error?y.message:String(y);return Wo(`Failed to read WebMCP registry: ${v}`)}this.#r.recordToolDisplayTitles(i);let l=i.find(y=>y.name===s);if(!l)return Wo(`WebMCP tool not registered on this page: ${s}`);if(!this.#l(s))return Wo(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return Wo("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 Wo("User declined the tool call.");if(o?.aborted)return Wo("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,NW(n),{signal:d.signal});return BW(y)}catch(y){if(g)return Wo(`WebMCP tool '${s}' timed out after ${this.#n}ms`);if(o?.aborted)return Wo("Aborted by cancel()");let v=y instanceof Error?y.message:String(y);return Wo(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){Gp.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,Gp.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??_W;try{return await n(t)}catch(o){return Gp.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=>RW(t,o))}},RW=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Yp={type:"object",properties:{}},WW=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},OW=e=>{if(e===void 0||e==="")return{...Yp};if(typeof e=="object")return e!==null&&!Array.isArray(e)?e:{...Yp};try{let t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:{...Yp}}catch{return{...Yp}}},BW=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:FW(t)}]}},Wo=e=>({isError:!0,content:[{type:"text",text:e}]}),_W=async e=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let t=DW(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
482
482
 
483
483
  Arguments:
484
484
  ${t}`:"")+(e.description?`