@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.
- package/dist/approval-ui.d.cts +6 -0
- package/dist/approval-ui.d.ts +6 -0
- package/dist/artifacts-ui.d.cts +6 -0
- package/dist/artifacts-ui.d.ts +6 -0
- package/dist/chunk-GKPCIQPB.js +1 -0
- package/dist/{client-history-YPEG45Q4.js → client-history-GOZWBDA5.js} +1 -1
- package/dist/client-history.js +1 -1
- package/dist/codegen.cjs +1 -1
- package/dist/codegen.js +1 -1
- package/dist/context-mentions.d.cts +6 -0
- package/dist/context-mentions.d.ts +6 -0
- package/dist/event-stream-view.d.cts +6 -0
- package/dist/event-stream-view.d.ts +6 -0
- package/dist/forms-ui.d.cts +6 -0
- package/dist/forms-ui.d.ts +6 -0
- package/dist/index.cjs +7 -7
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +6 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.global.js +1 -1
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +7 -7
- package/dist/index.js.map +1 -1
- package/dist/session-reconnect.d.cts +6 -0
- package/dist/session-reconnect.d.ts +6 -0
- package/dist/smart-dom-reader.d.cts +6 -0
- package/dist/smart-dom-reader.d.ts +6 -0
- package/dist/theme-editor-preview.cjs +14 -14
- package/dist/theme-editor-preview.d.cts +6 -0
- package/dist/theme-editor-preview.d.ts +6 -0
- package/dist/theme-editor-preview.js +5 -5
- package/dist/theme-editor.d.cts +6 -0
- package/dist/theme-editor.d.ts +6 -0
- package/dist/voice-runtime-XLU6YK2N.js +17 -0
- package/dist/voice-runtime.cjs +3 -3
- package/dist/voice-runtime.d.cts +6 -0
- package/dist/voice-runtime.d.ts +6 -0
- package/dist/voice-runtime.js +3 -3
- package/package.json +1 -1
- package/src/approval-paused-tool-settle.test.ts +108 -4
- package/src/session.ts +51 -10
- package/src/session.voice.test.ts +1 -0
- package/src/types.ts +6 -0
- package/src/voice/runtype-voice-provider.ts +19 -9
- package/src/voice/voice-delegation.ts +1 -1
- package/src/voice/voice.test.ts +81 -2
- package/dist/chunk-QPPJUSZH.js +0 -1
- package/dist/voice-runtime-UOQOFAFY.js +0 -17
package/dist/index.cjs
CHANGED
|
@@ -4,28 +4,28 @@
|
|
|
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()=>{}}},kl=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Ed=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Td=()=>{let e=XE();return{processChunk:async t=>{let n=t.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:e.close?.bind(e)}},Pd=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let r=(0,Hr.parse)(n,Hr.STR|Hr.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?Sd(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=Sd(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},yv=e=>{let t=null,n=0,r=e||(s=>{if(!s||typeof s!="object")return null;let i=l=>typeof l=="string"?Sd(l):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Sd(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return i(s.on_load_text)||i(s.text)||null;case"message":case"message_and_click":case"checkout":return i(s.text)||null;default:return i(s.text)||i(s.display_text)||i(s.message)||null}return i(s.text)||i(s.display_text)||i(s.message)||i(s.content)||null});return{getExtractedText:()=>t,processChunk:s=>{let i=s.trim();if(!i.startsWith("{")&&!i.startsWith("["))return null;if(s.length<=n)return t!==null?{text:t,raw:s}:null;try{let l=(0,Hr.parse)(s,Hr.STR|Hr.OBJ),c=r(l);c!==null&&(t=c)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},kd=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let o=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(e=o[1],{text:e,raw:t}):null},getExtractedText:()=>e}}});var x,Q,_n,Je=Ve(()=>{"use strict";x=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Q=(e,t={},...n)=>{let o=document.createElement(e);if(t.className&&(o.className=t.className),t.text!==void 0&&(o.textContent=t.text),t.attrs)for(let[s,i]of Object.entries(t.attrs))o.setAttribute(s,i);if(t.style){let s=o.style,i=t.style;for(let l of Object.keys(i)){let c=i[l];c!=null&&(s[l]=c)}}let r=n.filter(s=>s!=null);return r.length>0&&o.append(...r),o},_n=(...e)=>e.filter(Boolean).join(" ")});var ws,Hl,Ll,ba,QE,JE,vv,Cv,ZE,eT,tT,nT,oT,af,lf,wv,cf,Sv,rT,sT,bv,Av,Ir,Ld,Rr,Il,iT,aT,xv,Mv,lT,cT,dT,Ev,pT,uT,ui,Tv,Co,gT,va,Ss,fT,mT,Hd,Pv,kv,df,hT,yT,Lv,Id,Wr,pf,As,Rd,Rl=Ve(()=>{"use strict";ws=require("partial-json");Je();Hl="ask_user_question",Ll=8,ba="data-persona-ask-sheet-for",QE="Other",JE="Other\u2026",vv="Type your own answer here",Cv="Send",ZE="Next",eT="Back",tT="Submit all",nT="Skip",oT=3,af="data-ask-current-index",lf="data-ask-question-count",wv="data-ask-answers",cf="data-ask-grouped",Sv="data-ask-layout",rT=e=>e.layout==="pills"?"pills":"rows",sT=e=>e.getAttribute(Sv)==="pills"?"pills":"rows",bv=!1,Av=e=>e.replace(/["\\]/g,"\\$&"),Ir=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Hl,Ld=e=>e?.features?.askUserQuestion??{},Rr=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=(0,ws.parse)(r,ws.STR|ws.OBJ|ws.ARR);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},Il=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>Ll&&!bv&&(bv=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Ll}.`)),t.slice(0,Ll)},iT=e=>Il(e)[0]??null,aT=(e,t)=>Il(e)[t]??null,xv=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},Mv=(e,t,n)=>{if(e!=="rows")return null;let o=x("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=x("span","persona-ask-row-check");o.appendChild(r)}else{let r=x("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},lT=(e,t,n,o)=>{let s=x("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",o?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(t)),s.setAttribute("data-option-label",e.label),n==="rows"){let i=x("span","persona-ask-row-content"),l=x("span","persona-ask-row-label");if(l.textContent=e.label,i.appendChild(l),e.description){let p=x("span","persona-ask-row-description");p.textContent=e.description,i.appendChild(p)}s.appendChild(i);let c=Mv(n,o,t);c&&s.appendChild(c)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},cT=e=>{let n=x("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},dT=(e,t,n,o)=>{let s=x("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let i=!!e?.multiSelect,c=(Array.isArray(e?.options)?e.options:[]).filter(d=>d&&typeof d.label=="string"&&d.label.length>0);if(c.length===0&&!n){for(let d=0;d<oT;d++)s.appendChild(cT(o));return s}if(c.forEach((d,g)=>{s.appendChild(lT(d,g,o,i))}),e?.allowFreeText!==!1){let d=o==="rows"?QE:JE;if(o==="rows"){let g=x("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");g.setAttribute("data-ask-user-action","focus-free-text"),g.setAttribute("data-option-index",String(c.length)),g.setAttribute("data-ask-other-row","true");let f=x("span","persona-ask-row-content"),h=document.createElement("input");h.type="text",h.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",h.placeholder=t.freeTextPlaceholder??vv,h.setAttribute("data-ask-free-text-input","true"),h.setAttribute("aria-label",t.freeTextLabel??d),f.appendChild(h),g.appendChild(f);let y=Mv(o,i,c.length);y&&g.appendChild(y),s.appendChild(g)}else{let g=x("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");g.type="button",g.setAttribute("data-ask-user-action","open-free-text"),g.textContent=t.freeTextLabel??d,s.appendChild(g)}}return s},Ev=(e,t)=>{let o=x("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");o.setAttribute("data-ask-free-text-row","true");let r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=e.freeTextPlaceholder??vv,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let s=x("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=e.submitLabel??Cv,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},pT=e=>{let t=x("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=x("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=e.submitLabel??Cv,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},uT=(e,t,n)=>{let o=x("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let r=x("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??eT,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let s=x("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),i=x("button","persona-ask-nav-skip persona-pointer-events-auto");i.type="button",i.textContent=n.skipLabel??nT,i.setAttribute("data-ask-user-action","skip"),s.appendChild(i);let l=x("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let c=e===t-1;return l.textContent=c?n.submitAllLabel??tT:n.nextLabel??ZE,l.setAttribute("data-ask-user-action",c?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},ui=e=>{let t=e.getAttribute(wv);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Tv=(e,t)=>{e.setAttribute(wv,JSON.stringify(t))},Co=e=>{let t=Number(e.getAttribute(af)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},gT=(e,t)=>{e.setAttribute(af,String(Math.max(0,Math.floor(t))))},va=e=>{let t=Number(e.getAttribute(lf)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},Ss=e=>e.getAttribute(cf)==="true",fT=(e,t)=>{let n=e.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return t.forEach((r,s)=>{let i=typeof r?.question=="string"?r.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let l=n[i];(typeof l=="string"||Array.isArray(l))&&(o[s]=l)}}),o},mT=(e,t)=>{let n=e.agentMetadata?.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},Hd=(e,t)=>{let{payload:n}=Rr(t),o=Il(n),r=ui(e),s={},i=new Set;return o.forEach((l,c)=>{let p=typeof l?.question=="string"?l.question:"";p&&(i.has(p)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${p}"; later answer wins.`),i.add(p),Object.prototype.hasOwnProperty.call(r,c)&&(s[p]=r[c]))}),s},Pv=e=>{let t=ui(e),n=Co(e),o=t[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(c=>r.add(c));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(c=>{let p=c.getAttribute("data-option-label")??"",d=r.has(p);c.setAttribute("aria-pressed",d?"true":"false"),c.classList.toggle("persona-ask-pill-selected",d)});let i=new Set(Array.from(s).map(c=>c.getAttribute("data-option-label")??"")),l=e.querySelector('[data-ask-free-text-input="true"]');l&&(typeof o=="string"&&o.length>0&&!i.has(o)?(l.value=o,l.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):l.value="")},kv=e=>{if(!Ss(e))return;let t=ui(e),n=Co(e),o=t[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);let i=e.querySelector('[data-ask-user-action="submit-multi"]');if(i){let l=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));i.disabled=l.length===0}},df=(e,t,n)=>{let o=Ld(n),r=sT(e),{payload:s,complete:i}=Rr(t),l=Ss(e),c=Co(e),p=va(e),d=l?aT(s,c):iT(s),g=!!d?.multiSelect,f=e.querySelector('[data-ask-step-inline="true"]');f&&(f.textContent=l?`${c+1}/${p}`:"");let h=e.querySelector('[data-ask-stepper="true"]');h&&h.remove();let y=e.querySelector('[data-ask-question="true"]');if(y){let L=typeof d?.question=="string"?d.question:"";y.textContent=L,y.classList.toggle("persona-ask-question-skeleton",!L&&!i)}let v=e.querySelector('[data-ask-pill-list="true"]');if(v){let L=dT(d,o,i,r);v.replaceWith(L)}if(r!=="rows"){let L=e.querySelector('[data-ask-free-text-row="true"]');L&&L.replaceWith(Ev(o,r))}let C=e.querySelector('[data-ask-multi-actions="true"]');!l&&g&&!C?e.appendChild(pT(o)):(!g||l)&&C&&C.remove(),e.setAttribute("data-multi-select",g?"true":"false");let A=e.querySelector('[data-ask-nav-row="true"]');if(l){let L=uT(c,p,o);A?A.replaceWith(L):e.appendChild(L)}else A&&A.remove();Pv(e),kv(e)},hT=(e,t,n)=>{let o=Ld(t),r=rT(o),s=e.toolCall.id,i=Il(n),l=Math.max(1,i.length),c=l>1,p=fT(e,i),d=c?mT(e,l):0,g=x("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));g.setAttribute(ba,s),g.setAttribute("data-tool-call-id",s),g.setAttribute("data-message-id",e.id),g.setAttribute(lf,String(l)),g.setAttribute(af,String(d)),g.setAttribute(cf,c?"true":"false"),g.setAttribute(Sv,r),Tv(g,p),g.setAttribute("role","group"),g.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&g.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),xv(g,o);let f=x("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),h=x("div","persona-ask-sheet-question persona-flex-1");h.setAttribute("data-ask-question","true"),h.textContent="",f.appendChild(h);let y=x("span","persona-ask-sheet-step-inline");y.setAttribute("data-ask-step-inline","true"),y.textContent="",f.appendChild(y),g.appendChild(f);let C=x("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return C.setAttribute("data-ask-pill-list","true"),C.setAttribute("role","group"),g.appendChild(C),r!=="rows"&&g.appendChild(Ev(o,r)),df(g,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>g.classList.remove("persona-ask-sheet-enter"))}),g},yT=(e,t,n)=>{let{payload:o}=Rr(t),r=Math.max(1,Il(o).length);r>va(e)&&(e.setAttribute(lf,String(r)),r>1&&!Ss(e)&&e.setAttribute(cf,"true")),df(e,t,n)},Lv=(e,t)=>{let n=x("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),n.setAttribute("data-bubble-type","ask-user-question");let o=Ld(t);xv(n,o);let r=x("span","persona-ask-stub-label"),{complete:s}=Rr(e);return r.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(r),n},Id=(e,t,n)=>{if(!n||!Ir(e)||Ld(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${ba}]`).forEach(p=>{p.getAttribute(ba)!==r&&p.remove()});let i=n.querySelector(`[${ba}="${Av(r)}"]`);if(i){yT(i,e,t);return}let{payload:l}=Rr(e),c=hT(e,t,l);n.appendChild(c)},Wr=(e,t)=>{if(!e)return;let n=t?`[${ba}="${Av(t)}"]`:`[${ba}]`;e.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(s)?s:180)})},pf=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),As=(e,t)=>{let n=ui(e),o=Co(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,Tv(e,n),Pv(e),kv(e)},Rd=(e,t,n,o)=>{let r=va(e),s=Math.max(0,Math.min(r-1,o));gT(e,s),df(e,t,n)}});var Oo,uf,Wd,Iv,gi,gf,Od,Hv,bT,xs,Ca=Ve(()=>{"use strict";Oo="suggest_replies",uf={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"object",properties:{label:{type:"string",minLength:1,maxLength:80},prompt:{type:"string",minLength:1,maxLength:500},description:{type:"string",minLength:1,maxLength:160}},required:["label"],additionalProperties:!1}}},required:["suggestions"],additionalProperties:!1},Wd={name:Oo,description:"Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the last action after your reply text is complete. Give each suggestion a `label` with the short visible text, an optional `prompt` with the fuller text placed as the user's message (defaults to the label), and an optional `description` with one line of supporting copy. Suggestions are sent as the user's next message, so phrase prompts in the user's voice (e.g. \"Tell me more about pricing\"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.",parametersSchema:uf,origin:"sdk",annotations:{readOnlyHint:!0}},Iv=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),gi=e=>e.variant==="tool"&&e.toolCall?.name===Oo,gf=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t?.suggestions;if(!Array.isArray(n))return[];let o=n.flatMap(r=>{if(typeof r=="string"){let l=r.trim();return l?[l]:[]}if(!r||typeof r!="object")return[];let s=r;if(typeof s.label!="string"||!s.label.trim())return[];let i={label:s.label.trim()};return typeof s.prompt=="string"&&s.prompt.trim()&&(i.prompt=s.prompt.trim()),typeof s.description=="string"&&s.description.trim()&&(i.description=s.description.trim()),[i]});return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},Od=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!gi(n))continue;let o=gf(n.toolCall?.args);return o.length>0?o:null}return null},Hv=new Set,bT=(e,t,n)=>{let o=`${e}:${t}:${n}`;Hv.has(o)||(Hv.add(o),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},xs=e=>{let t=e?.suggestions?.followUps,n=e?.features?.suggestReplies,o=i=>{let l=t?.[i],c=n?.[i];l===void 0||c===void 0||l!==c&&bT(i,c,l)};e&&(o("enabled"),o("expose"));let r=t?.enabled??n?.enabled??!0,s=r?t?.expose??n?.expose??!1:!1;return{enabled:r,expose:s}}});var ff,mf,fi,Bd=Ve(()=>{"use strict";Rl();Ca();ff={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Ll,description:"Questions to ask the user. Prefer a single question.",items:{type:"object",properties:{question:{type:"string",description:"The complete question, ending with a question mark."},header:{type:"string",maxLength:12,description:'Short topic label, e.g. "Auth method".'},options:{type:"array",minItems:2,maxItems:4,description:'2-4 distinct choices. Do NOT add an "Other" option: free text is automatic.',items:{type:"object",properties:{label:{type:"string",description:"Concise choice text (1-5 words)."},description:{type:"string",description:"What the option means or implies."}},required:["label"],additionalProperties:!1}},multiSelect:{type:"boolean",description:"Allow selecting multiple options. Default false."},allowFreeText:{type:"boolean",description:"Show a free-text input. Default true."}},required:["question","options"],additionalProperties:!1}}},required:["questions"],additionalProperties:!1},mf={name:Hl,description:"Ask the user multiple-choice questions and wait for their answers. Use only when blocked on a decision that is the user's to make: a preference, a choice between valid approaches, or information you cannot infer. Each question offers 2-4 options plus an automatic free-text input. The result maps each question to its answer (an array when multiSelect); a question absent from the result was skipped.",parametersSchema:ff,origin:"sdk",annotations:{readOnlyHint:!0}},fi=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(mf),xs(e).expose&&t.push(Wd),t}});var Yt,kn,wa,_d,Bo=Ve(()=>{"use strict";Yt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},kn=1e5,wa=kn+1,_d="https://api.runtype.com"});async function Rv(e,t,n){let o={"Content-Type":"application/json",...e.headers};e.getHeaders&&Object.assign(o,await e.getHeaders());let r={executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0},s=(p,d)=>fetch(`${e.clientApiBase()}${p}`,{method:"POST",headers:o,body:JSON.stringify({...d,...r})}),i=`/v1/agents/${t.agentId}/approve`;if(!e.isClientTokenMode())return s(i);let{sessionId:l}=await e.initSession(),c=await s("/v1/client/approve",{sessionId:l});if(c.status===404){let p=await c.clone().json().catch(()=>null);if(!p||p.error==="Not Found")return s(i)}return c}async function Wv(e,t,n,o){let r=e.isClientTokenMode(),s=r?e.getClientApiUrl("resume"):`${e.config.apiUrl?.replace(/\/+$/,"")||_d}/resume`,i,l=null;if(r){let d=await e.initSession();i=d.sessionId,d.durableRecovery?.enabled===!0&&(l=await e.readVisitorToken())}let c={"Content-Type":"application/json",...l?{"X-Visitor-Token":l}:{},...e.headers};e.getHeaders&&Object.assign(c,await e.getHeaders());let p={executionId:t,toolOutputs:n,streamResponse:o?.streamResponse??!0,...o?.after?{after:o.after}:{}};if(i&&(p.sessionId=i),r&&i){let d=[...fi(e.config),...await(await e.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:g,commit:f}=await e.sendWithClientToolsDiff(i,d,h=>{let y={...p,...h};return e.debug&&console.debug("[AgentWidgetClient] client token resume",y),fetch(s,{method:"POST",headers:c,body:JSON.stringify(y),signal:o?.signal})},{emptyMeansReplace:!0});return g.ok&&f(),g}return fetch(s,{method:"POST",headers:c,body:JSON.stringify(p),signal:o?.signal})}var Ov=Ve(()=>{"use strict";Bd();Bo()});var Dd={};ys(Dd,{preferFinalStructuredContent:()=>_v,resolveApproval:()=>Rv,resumeFlow:()=>Wv,streamResponse:()=>wT});function vT(e){let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;let r=t.indexOf("/");if(r>0){let s=t.slice(r+1).split(";")[0]?.trim()??"";if(s&&s!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(s))return`attachment.${s}`}return"attachment"}function _v(e,t){if(!e)return t;let n=e.trim(),o=t.trim();if(n.length===0)return t;if(o.length===0)return e;let r=Bv(n);if(!Bv(o))return e;if(!r||o===n||o.startsWith(n))return t;let i=kl(e);return kl(t)!==null&&i===null?t:e}async function CT(e,t,n,o,r,s,i){if(!e.parseSSEEvent)return!1;try{let l=await e.parseSSEEvent(t);if(l===null)return!1;let c=d=>{let g={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...d!==void 0&&{partId:d}};return o.current=g,r(g),g},p=d=>o.current?o.current:c(d);if(l.text!==void 0){l.partId!==void 0&&i.current!==null&&l.partId!==i.current&&(o.current&&(o.current.streaming=!1,r(o.current)),c(l.partId)),l.partId!==void 0&&(i.current=l.partId);let d=p(l.partId);l.partId!==void 0&&!d.partId&&(d.partId=l.partId),d.content+=l.text,r(d)}return l.done&&(o.current&&(o.current.streaming=!1,r(o.current)),i.current=null,n({type:"status",status:"idle"})),l.error&&(i.current=null,n({type:"error",error:new Error(l.error)})),!0}catch(l){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",l),!1}}async function wT(e,t,n,o,r){let s=t.getReader(),i=new TextDecoder,l="",c=Date.now(),p=0,d=()=>c+p++,g=D=>{let S=D.reasoning?{...D.reasoning,chunks:[...D.reasoning.chunks]}:void 0,F=D.toolCall?{...D.toolCall,chunks:D.toolCall.chunks?[...D.toolCall.chunks]:void 0}:void 0,z=D.tools?D.tools.map(K=>({...K,chunks:K.chunks?[...K.chunks]:void 0})):void 0;return{...D,reasoning:S,toolCall:F,tools:z}},f=D=>{if(D.role!=="assistant"||D.variant)return!0;let S=Array.isArray(D.contentParts)&&D.contentParts.length>0,F=typeof D.rawContent=="string"&&D.rawContent.trim()!=="";return typeof D.content=="string"&&D.content.trim()!==""||S||F||!!D.stopReason},h=D=>{f(D)&&n({type:"message",message:g(D)})},y=null,v=null,C={current:null},A={current:null},L=null,I="",H=new Map,_=new Map,V=new Map,oe=new Map,W=new Map,j=o,X=!1,E=()=>{if(y)return y;let D,S="",F=L;return!X&&j?(D=j,X=!0,S=r??""):j&&F?D=`${j}_${F}`:D=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,y={id:D,role:"assistant",content:S,createdAt:new Date().toISOString(),streaming:!0,sequence:d()},h(y),y},T=D=>{let S=oe.get(D);if(S)return S;let F={id:`reason-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:d(),reasoning:{id:D,status:"streaming",chunks:[]}};return oe.set(D,F),h(F),F},B=new Set,P=new Map,J=new Set,U=new Map,ue=D=>{if(!D)return!1;let S=D.replace(/_+/g,"_").replace(/^_|_$/g,"");return S==="emit_artifact_markdown"||S==="emit_artifact_component"},fe=D=>{let S=W.get(D);if(S)return S;let F={id:`tool-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:d(),toolCall:{id:D,status:"pending"}};return W.set(D,F),h(F),F},me=D=>{if(typeof D=="number"&&Number.isFinite(D))return D;if(typeof D=="string"){let S=Number(D);if(!Number.isNaN(S)&&Number.isFinite(S))return S;let F=Date.parse(D);if(!Number.isNaN(F))return F}return Date.now()},He=D=>{if(typeof D=="string")return D;if(D==null)return"";try{return JSON.stringify(D)}catch{return String(D)}},Ee=new Map,Ie=new Map,yt=(D,S)=>{let F=He(S),z=Ie.get(D.id),K=_v(z,F);D.rawContent=K;let te=Ee.get(D.id),ve=De=>{let Xe=D.content??"";De.trim()!==""&&(Xe.trim().length===0||De.startsWith(Xe)||De.trimStart().startsWith(Xe.trim()))&&(D.content=De)},Ce=()=>{if(te){let De=te.close?.();De instanceof Promise&&De.catch(()=>{})}Ee.delete(D.id),Ie.delete(D.id),D.streaming=!1,h(D)};if(!te){ve(F),Ce();return}let Me=kl(K);if(Me!==null&&Me.trim()!==""){ve(Me),Ce();return}let ot=De=>{let Xe=typeof De=="string"?De:De?.text??null;if(Xe!==null&&Xe.trim()!=="")return Xe;let pn=te.getExtractedText();return pn!==null&&pn.trim()!==""?pn:F},Ct;try{Ct=te.processChunk(K)}catch{ve(F),Ce();return}if(Ct instanceof Promise){Ct.then(De=>{ve(ot(De)),Ce()}).catch(()=>{ve(F),Ce()});return}ve(ot(Ct)),Ce()},qe=null,Oe=(D,S,F,z)=>{D.rawContent=S,Ee.has(D.id)||Ee.set(D.id,e.createStreamParser());let K=Ee.get(D.id),te=S.trim().startsWith("{")||S.trim().startsWith("[");if(te&&Ie.set(D.id,S),K.__isPlainTextParser===!0){D.content=z!==void 0?S:D.content+F,Ie.delete(D.id),Ee.delete(D.id),D.rawContent=void 0,h(D);return}let Ce=K.processChunk(S);if(Ce instanceof Promise)Ce.then(Me=>{let ot=typeof Me=="string"?Me:Me?.text??null;ot!==null&&ot.trim()!==""?(D.content=ot,h(D)):!te&&!S.trim().startsWith("<")&&(D.content=z!==void 0?S:D.content+F,Ie.delete(D.id),Ee.delete(D.id),D.rawContent=void 0,h(D))}).catch(()=>{D.content=z!==void 0?S:D.content+F,Ie.delete(D.id),Ee.delete(D.id),D.rawContent=void 0,h(D)});else{let Me=typeof Ce=="string"?Ce:Ce?.text??null;Me!==null&&Me.trim()!==""?(D.content=Me,h(D)):!te&&!S.trim().startsWith("<")&&(D.content=z!==void 0?S:D.content+F,Ie.delete(D.id),Ee.delete(D.id),D.rawContent=void 0,h(D))}},$=(D,S)=>{let F=S??D.content;if(F==null||F===""){D.streaming=!1,h(D);return}let K=Ie.get(D.id)??He(F);D.rawContent=K;let te=Ee.get(D.id),ve=null,Ce=!1;if(te&&(ve=te.getExtractedText(),ve===null&&(ve=kl(K)),ve===null)){let Me=te.processChunk(K);Me instanceof Promise?(Ce=!0,Me.then(ot=>{let Ct=typeof ot=="string"?ot:ot?.text??null;Ct!==null&&(D.content=Ct,D.streaming=!1,Ee.delete(D.id),Ie.delete(D.id),h(D))}).catch(()=>{})):ve=typeof Me=="string"?Me:Me?.text??null}if(!Ce){ve!==null&&ve.trim()!==""?D.content=ve:Ie.has(D.id)||(D.content=He(F));let Me=Ee.get(D.id);if(Me){let ot=Me.close?.();ot instanceof Promise&&ot.catch(()=>{}),Ee.delete(D.id)}Ie.delete(D.id),D.streaming=!1,h(D)}},Be=(D,S,F)=>{let z=_.get(D);if(z)return z;let K={id:`nested-${S}-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),...F?{variant:F}:{},...F==="reasoning"?{reasoning:{id:D,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:S}};return _.set(D,K),h(K),K},ye=[],ut,Zt=new Map,xt=0,xe="agent",Wt=!1,vt=null,Le=null,Ye=e.config().iterationDisplay??"separate";for(ut=()=>{for(let D=0;D<ye.length;D++){let S=ye[D];if(!Wt&&xe!=="flow"&&typeof S.stepType=="string"&&(xe="flow"),S.type==="reasoning_start"){let F=typeof S.id=="string"?S.id:null,z=typeof S.parentToolCallId=="string"&&S.parentToolCallId?S.parentToolCallId:null;if(F&&z){H.set(F,z),Be(F,z,"reasoning");continue}let K=S.id,te=T(K);te.reasoning=te.reasoning??{id:K,status:"streaming",chunks:[]},te.reasoning.startedAt=te.reasoning.startedAt??Date.now(),te.reasoning.completedAt=void 0,te.reasoning.durationMs=void 0,(S.scope==="loop"||S.scope==="turn")&&(te.reasoning.scope=S.scope),te.streaming=!0,te.reasoning.status="streaming",h(te)}else if(S.type==="reasoning_delta"){let F=typeof S.id=="string"?S.id:null;if(F&&H.has(F)&&_.has(F)){let te=_.get(F),ve=S.delta;ve&&te.reasoning&&(te.reasoning.chunks.push(String(ve)),h(te));continue}let z=S.id,K=T(z);K.reasoning=K.reasoning??{id:z,status:"streaming",chunks:[]},K.reasoning.startedAt=K.reasoning.startedAt??Date.now(),S.delta&&K.reasoning.chunks.push(S.delta),K.reasoning.status="streaming",K.streaming=!0,h(K)}else if(S.type==="reasoning_complete"){let F=typeof S.id=="string"?S.id:null;if(F&&H.has(F)&&_.has(F)){let ve=_.get(F);if(ve.reasoning){let Ce=typeof S.text=="string"?S.text:"";Ce&&ve.reasoning.chunks.length===0&&ve.reasoning.chunks.push(Ce),ve.reasoning.status="complete",ve.streaming=!1,h(ve)}H.delete(F),_.delete(F);continue}let z=S.id,K=typeof S.text=="string"?S.text:"";!oe.get(z)&&(K||S.scope==="loop")&&T(z);let te=oe.get(z);if(te?.reasoning){(S.scope==="loop"||S.scope==="turn")&&(te.reasoning.scope=S.scope),K&&te.reasoning.chunks.length===0&&te.reasoning.chunks.push(K),te.reasoning.status="complete",te.reasoning.completedAt=Date.now();let ve=te.reasoning.startedAt??Date.now();te.reasoning.durationMs=Math.max(0,(te.reasoning.completedAt??Date.now())-ve),te.streaming=!1,h(te)}}else if(S.type==="tool_start"){y&&(y.streaming=!1,h(y),y=null),typeof S.iteration=="number"&&(xt=S.iteration);let F=S.toolCallId,z=S.toolName;if(ue(z)){B.add(F);continue}let K=fe(F),te=K.toolCall??{id:F,status:"pending"};te.name=z??te.name,te.status="running",te.success=void 0,te.error=void 0,te.duration=void 0,S.parameters!==void 0&&(te.args=S.parameters),te.startedAt=te.startedAt??me(S.startedAt),te.completedAt=void 0,te.durationMs=void 0,K.toolCall=te,K.streaming=!0,S.executionId&&(K.agentMetadata={executionId:S.executionId,iteration:S.iteration}),h(K)}else if(S.type==="tool_output_delta"){let F=S.toolCallId;if(B.has(F))continue;let z=fe(F),K=z.toolCall??{id:F,status:"running"};K.startedAt=K.startedAt??Date.now();let te=S.delta;te&&(K.chunks=K.chunks??[],K.chunks.push(String(te))),K.status="running",z.toolCall=K,z.streaming=!0,S.executionId&&(z.agentMetadata=z.agentMetadata??{executionId:S.executionId,iteration:xt}),h(z)}else if(S.type==="tool_complete"){let F=S.toolCallId;if(B.has(F)){B.delete(F);continue}let z=fe(F),K=z.toolCall??{id:F,status:"running"};K.status="complete",S.result!==void 0&&(K.result=S.result),K.name=S.toolName??K.name,K.success=S.success,K.error=S.error,K.completedAt=Date.now();let te=S.executionTime;if(typeof te=="number")K.durationMs=te,K.duration=te;else{let ve=K.startedAt??Date.now();K.durationMs=Math.max(0,(K.completedAt??Date.now())-ve)}z.toolCall=K,z.streaming=!1,S.executionId&&(z.agentMetadata=z.agentMetadata??{executionId:S.executionId,iteration:S.iteration??xt}),h(z)}else if(S.type==="await"&&S.toolName){let F=typeof S.toolCallId=="string"&&S.toolCallId.length>0?S.toolCallId:void 0,z=F??S.toolId??`local-${d()}`,K=fe(z),te=S.toolName,ve=S.origin==="webmcp"&&!bs(te)?`webmcp:${te}`:te,Ce=bs(ve),Me=K.toolCall??{id:z,status:"pending"};Me.name=ve,Me.args=S.parameters,Me.status=Ce?"running":"complete",Me.chunks=Me.chunks??[],Me.startedAt=Me.startedAt??me(S.awaitedAt),Ce?(Me.completedAt=void 0,Me.duration=void 0,Me.durationMs=void 0):Me.completedAt=Me.completedAt??Me.startedAt,K.toolCall=Me,K.streaming=!1,K.agentMetadata={...K.agentMetadata,executionId:S.executionId??K.agentMetadata?.executionId,awaitingLocalTool:!0,...F?{webMcpToolCallId:F}:{}},h(K)}else if(S.type==="text_start"){let F=typeof S.id=="string"?S.id:null,z=typeof S.parentToolCallId=="string"&&S.parentToolCallId?S.parentToolCallId:null;if(F&&z){H.set(F,z);continue}let K=y;K&&(xe==="flow"?($(K),qe=K):(K.streaming=!1,h(K)),y=null),L=typeof S.id=="string"?S.id:L,I=""}else if(S.type==="text_delta"){let F=typeof S.id=="string"?S.id:null,z=F?H.get(F):void 0;if(F&&z){let ve=typeof S.delta=="string"?S.delta:"",Ce=(V.get(F)??"")+ve;if(V.set(F,Ce),Ce.trim()==="")continue;let Me=Be(F,z);Me.agentMetadata={...Me.agentMetadata,executionId:S.executionId,parentToolId:z},Oe(Me,Ce,ve,void 0);continue}if(L=typeof S.id=="string"?S.id:L,xe==="flow"){let ve=typeof S.delta=="string"?S.delta:"";if(I+=ve,I.trim()==="")continue;let Ce=E();Ce.agentMetadata={executionId:S.executionId,iteration:xt},Oe(Ce,I,ve,void 0),v=Ce;continue}let K=typeof S.delta=="string"?S.delta:"";I+=K;let te=E();te.agentMetadata={executionId:S.executionId,iteration:xt,turnId:vt??void 0,agentName:Le?.agentName},Oe(te,I,K,void 0),v=te}else if(S.type==="text_complete"){let F=typeof S.id=="string"?S.id:null;if(F&&H.has(F)){let K=_.get(F);K&&$(K),H.delete(F),V.delete(F),_.delete(F);continue}let z=y;z&&(xe==="flow"?($(z),qe=z):((z.content??"")===""&&typeof S.text=="string"&&(z.content=S.text),z.streaming=!1,h(z)),y=null),L=null,I=""}else if(S.type==="step_complete"){if(S.stepType==="tool")continue;if(S.success===!1){let F=S.error||"Step failed";n({type:"error",error:new Error(F)});let z=y;z&&z.streaming&&(z.streaming=!1,h(z)),n({type:"status",status:"idle"});continue}{let F=qe;qe=null;let z=S.stopReason,te=(S.result&&typeof S.result=="object"?S.result:null)?.response;if(F)z&&(F.stopReason=z),te!=null?yt(F,te):F.streaming!==!1&&(Ee.delete(F.id),Ie.delete(F.id),F.streaming=!1,h(F));else{let ve=te!=null&&te!=="";if(ve||z){let Ce=E();z&&(Ce.stopReason=z),ve?$(Ce,te):(Ce.streaming=!1,h(Ce))}}continue}}else if(S.type==="execution_start")xe=S.kind==="flow"?"flow":"agent",Wt=!0,xe==="agent"&&(Le={executionId:S.executionId,agentId:S.agentId??"virtual",agentName:S.agentName??""});else if(S.type==="turn_start"){let F=typeof S.iteration=="number"?S.iteration:xt;if(F!==xt){if(Ye==="separate"&&F>1){let z=y;z&&(z.streaming=!1,h(z),y=null)}xt=F}vt=typeof S.id=="string"?S.id:null,v=null}else if(S.type==="tool_input_delta"){let F=S.toolCallId;if(F){let z=W.get(F);z?.toolCall&&(z.toolCall.chunks=z.toolCall.chunks??[],z.toolCall.chunks.push(S.delta??""),h(z))}}else if(S.type==="tool_input_complete"){if(B.has(S.toolCallId))continue;let F=fe(S.toolCallId),z=F.toolCall;z.args=S.parameters,z.name=S.toolName??z.name,h(F)}else if(S.type==="turn_complete"){let F=S.stopReason,z=y??v;if(F&&z!==null){let K=S.id;(!K||z.agentMetadata?.turnId===K)&&(z.stopReason=F,h(z))}vt===S.id&&(vt=null)}else if(S.type==="media_start"){let F=String(S.id);Zt.set(F,{mediaType:typeof S.mediaType=="string"?S.mediaType:void 0,toolCallId:S.toolCallId,parts:[]})}else if(S.type==="media_delta"){let F=Zt.get(String(S.id));F&&typeof S.delta=="string"&&F.parts.push(S.delta)}else if(S.type==="media_complete"){let F=String(S.id),z=Zt.get(F);Zt.delete(F);let K=(typeof S.mediaType=="string"?S.mediaType:void 0)??z?.mediaType??"application/octet-stream",te=typeof S.data=="string"?S.data:void 0,ve=typeof S.url=="string"?S.url:z&&z.parts.length>0?z.parts.join(""):void 0,Ce=null;if(te)Ce={type:"media",data:te,mediaType:K};else if(ve){let De=K.toLowerCase();Ce={type:De==="image"||De.startsWith("image/")?"image-url":"file-url",url:ve,mediaType:K}}let Me=S.toolCallId??z?.toolCallId,ot=Ce?[Ce]:[],Ct=[];for(let De of ot){if(!De||typeof De!="object")continue;let Xe=De,pn=typeof Xe.type=="string"?Xe.type:void 0,xo=typeof Xe.mediaType=="string"?Xe.mediaType.toLowerCase():"",ft=null,bt="";if(pn==="media"){let Ft=typeof Xe.data=="string"?Xe.data:void 0;if(!Ft)continue;bt=xo.length>0?xo:"application/octet-stream",ft=`data:${bt};base64,${Ft}`}else if(pn==="image-url"){let Ft=typeof Xe.url=="string"?Xe.url:void 0;if(!Ft)continue;bt=xo,ft=Ft}else if(pn==="file-url"){let Ft=typeof Xe.url=="string"?Xe.url:void 0;if(!Ft)continue;bt=xo,ft=Ft}else continue;if(ft)if(pn==="image-url"||bt.startsWith("image/"))Ct.push({type:"image",image:ft,...bt.includes("/")?{mimeType:bt}:{}});else if(bt.startsWith("audio/"))Ct.push({type:"audio",audio:ft,mimeType:bt});else if(bt.startsWith("video/"))Ct.push({type:"video",video:ft,mimeType:bt});else{let Ft=bt||"application/octet-stream";Ct.push({type:"file",data:ft,mimeType:Ft,filename:vT(Ft)})}}if(Ct.length>0){let De=d(),Xe=Me,xo={id:`agent-media-${typeof Xe=="string"&&Xe.length>0?`${Xe}-${De}`:String(De)}`,role:"assistant",content:"",contentParts:Ct,createdAt:new Date().toISOString(),streaming:!1,sequence:De,agentMetadata:{executionId:S.executionId,iteration:xt}};h(xo);let ft=y;ft&&(ft.streaming=!1,h(ft)),y=null,C.current=null}}else if(S.type==="execution_complete"){let F=y;F&&(S.kind==="flow"&&F.streaming!==!1?$(F):(F.streaming=!1,h(F)),y=null),L=null,I="",qe=null,n({type:"status",status:"idle",terminal:!0})}else if(S.type==="execution_error"){let F=typeof S.error=="string"?S.error:S.error?.message??"Execution error";n({type:"error",error:new Error(F)})}else if(S.type!=="ping"){if(S.type==="approval_start"){let F=S.approvalId??`approval-${d()}`,z={id:`approval-${F}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:F,status:"pending",agentId:Le?.agentId??"virtual",executionId:S.executionId??Le?.executionId??"",toolName:S.toolName??"",toolType:S.toolType,description:S.description??`Execute ${S.toolName??"tool"}`,...typeof S.reason=="string"&&S.reason?{reason:S.reason}:{},parameters:S.parameters,...typeof S.toolCallId=="string"&&S.toolCallId?{toolCallId:S.toolCallId}:{}}};h(z)}else if(S.type==="approval_complete"){let F=S.approvalId;if(F){let K={id:`approval-${F}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:F,status:S.decision??"approved",agentId:Le?.agentId??"virtual",executionId:S.executionId??Le?.executionId??"",toolName:"",description:"",resolvedAt:Date.now()}};h(K)}}else if(S.type==="artifact_start"||S.type==="artifact_delta"||S.type==="artifact_update"||S.type==="artifact_complete"){if(S.type==="artifact_start"){let F=S.artifactType,z=String(S.id),K=typeof S.title=="string"?S.title:void 0,te=S.file,ve;if(te&&typeof te=="object"&&!Array.isArray(te)&&typeof te.path=="string"&&typeof te.mimeType=="string"&&(ve={path:te.path,mimeType:te.mimeType,...typeof te.language=="string"?{language:te.language}:{}}),n({type:"artifact_start",id:z,artifactType:F,title:K,component:typeof S.component=="string"?S.component:void 0,...ve?{file:ve}:{}}),U.set(z,{markdown:"",title:K,file:ve}),!J.has(z)){J.add(z);let Ce=or(e.config().features?.artifacts,{artifactType:F,...ve?{file:ve}:{}}),Me=typeof S.component=="string"?S.component:void 0,ot={id:`artifact-ref-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),rawContent:El(Ce,{artifactId:z,title:K,artifactType:F,status:"streaming",...ve?{file:ve}:{},...Me?{component:Me}:{}})};P.set(z,ot),h(ot)}}else if(S.type==="artifact_delta"){let F=String(S.id),z=typeof S.delta=="string"?S.delta:String(S.delta??"");n({type:"artifact_delta",id:F,artDelta:z});let K=U.get(F);K&&(K.markdown+=z)}else if(S.type==="artifact_update"){let F=S.props&&typeof S.props=="object"&&!Array.isArray(S.props)?S.props:{};n({type:"artifact_update",id:String(S.id),props:F,component:typeof S.component=="string"?S.component:void 0});let z=U.get(String(S.id));z&&(z.props={...z.props??{},...F})}else if(S.type==="artifact_complete"){let F=String(S.id);n({type:"artifact_complete",id:F});let z=P.get(F);if(z){z.streaming=!1;try{let K=JSON.parse(z.rawContent??"{}");if(K.props){K.props.status="complete";let te=U.get(F);te?.markdown&&(K.props.markdown=te.markdown),te?.file&&(K.props.file=te.file),K.component==="PersonaArtifactInline"&&te?.props&&Object.keys(te.props).length>0&&(K.props.componentProps=te.props)}z.rawContent=JSON.stringify(K)}catch{}U.delete(F),h(z),P.delete(F)}}}else if(S.type==="error"&&S.recoverable===!1&&S.error!=null&&S.error!==""){let F=typeof S.error=="string"?S.error:S.error?.message!=null?String(S.error.message):"Execution error";n({type:"error",error:new Error(F)});let z=y;z&&z.streaming&&(z.streaming=!1,h(z)),n({type:"status",status:"idle"})}}}ye.length=0};;){let{done:D,value:S}=await s.read();if(D)break;l+=i.decode(S,{stream:!0});let F=l.split(`
|
|
5
5
|
|
|
6
6
|
`);l=F.pop()??"";for(let z of F){let K=z.split(`
|
|
7
|
-
`),te="message",ve="",Ce=null;for(let Xe of K)Xe.startsWith("event:")?te=Xe.replace("event:","").trim():Xe.startsWith("data:")?ve+=Xe.replace("data:","").trim():Xe.startsWith("id:")&&(Ce=Xe.slice(3).trim());let Me=()=>{Ce!==null&&Ce!==""&&n({type:"cursor",id:Ce})};if(!ve){Me();continue}let ot;try{ot=JSON.parse(ve)}catch(Xe){n({type:"error",error:Xe instanceof Error?Xe:new Error("Failed to parse chat stream payload")});continue}let Ct=ot!==null&&typeof ot=="object"&&!Array.isArray(ot)?ot:null,De=te!=="message"?te:typeof Ct?.type=="string"?Ct.type:"message";if(e.onSSEEvent?.(De,ot),e.parseSSEEvent){C.current=y;let Xe=await CT(e,ot,n,C,h,d,A);if(C.current&&C.current!==y&&(y=C.current),Xe){Me();continue}}Ct&&(ye.push({...Ct,type:De}),ut()),Me()}}ut()}var Bv,hf=Ve(()=>{"use strict";pi();ha();Cs();Ov();Bv=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<")});var $v,Fv=Ve(()=>{$v="4.26.0"});var Yn,Sa=Ve(()=>{"use strict";Fv();Yn=$v});var Nd={};ys(Nd,{deleteAllConversations:()=>OT,deleteConversation:()=>WT,finalizeDisplayProjections:()=>RT,getConversation:()=>IT,historyErrorFor:()=>Yv,listConversations:()=>HT,readErrorCode:()=>bf,recoverFromUnauthorized:()=>Gv,resetVisitor:()=>BT});function ET(e,t,n){let o=new URLSearchParams;for(let[s,i]of Object.entries(n))i===void 0||i===""||o.set(s,String(i));let r=o.toString();return`${e.clientApiBase()}/v1/client/${t}${r?`?${r}`:""}`}function TT(e,t){if(t)return t;let n=e.config.features?.history?.scope;return n||(e.config.getIdentityProof?"verified-user":"browser")}async function PT(e,t,n){let o=e.config.getIdentityProof;if(!o)return n&&e.setHistoryIdentityStatus(e.browserOnlyStatus()),null;n&&e.setHistoryIdentityStatus({state:"verifying"});let r;try{r=await o()??null}catch{throw n&&e.setHistoryIdentityStatus({state:"identity_provider_failed"}),new e.HistoryClientError("identity_provider_failed","The identity proof provider failed")}if(r)return r;if(t.visitor?.endUserId!=null)throw n&&e.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new e.HistoryClientError("authentication_required","This browser is bound to a signed-in user and needs a fresh identity proof");return n&&e.setHistoryIdentityStatus({state:"browser_only",reason:"proof_unavailable_before_binding"}),null}async function kT(e,t,n,o){if(t.visitor?.endUserId!=null)return t;let r=await e.reinitWithProof(n);if(!(r.visitor?.identityStatus==="admitted"&&r.visitor?.endUserId!=null))throw o&&e.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new e.HistoryClientError("proof_not_admitted",jv);return r}async function bf(e,t){let n=await t.json().catch(()=>({}));return typeof n.error=="string"?n.error:typeof n.message=="string"?n.message:""}async function Gv(e,t,n,o){let r=t.toLowerCase();if(r.includes("invalid_identity_proof"))throw o&&e.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new e.HistoryClientError("invalid_identity_proof",qv);if(r.includes("visitor token required"))throw new e.HistoryClientError("visitor_token_missing",zv);if(r.includes("visitor_identity_mismatch")){if(!n)throw o&&e.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new e.HistoryClientError("visitor_identity_mismatch",Kv);return e.reinitWithProof(n)}if(r.includes("expired")||r.includes("not found"))return e.clearClientSession(),e.initSession();throw new e.HistoryClientError("unauthorized",t||"History request was not authorized")}async function Yv(e,t,n){let o=await bf(e,t);if(t.status===404)return new e.HistoryClientError("not_found","Conversation not found");if(t.status===429){let r=Number.parseInt(t.headers.get("Retry-After")??"",10);return new e.HistoryClientError("rate_limited","Too many history requests",{...Number.isFinite(r)?{retryAfterSeconds:r}:{}})}if(t.status===503&&o.includes("identity_proof_not_admitted"))return n&&e.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new e.HistoryClientError("proof_not_admitted",jv);if(t.status===401){let r=o.toLowerCase();return r.includes("invalid_identity_proof")?(n&&e.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new e.HistoryClientError("invalid_identity_proof",qv)):r.includes("visitor token required")?new e.HistoryClientError("visitor_token_missing",zv):r.includes("visitor_identity_mismatch")?new e.HistoryClientError("visitor_identity_mismatch",Kv):new e.HistoryClientError("unauthorized",o||"History request was not authorized")}return new e.HistoryClientError("request_failed",o||`History request failed (${t.status})`)}function LT(e,t,n,o){let r=t?.toLowerCase()??null;if(n){if(r==="admitted"){o&&e.setHistoryIdentityStatus({state:"verified"});return}throw o&&e.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),r==="ignored"?new e.HistoryClientError("identity_contract_violation","Server reported an ignored identity proof on a success response"):new e.HistoryClientError("proof_not_admitted","The response did not acknowledge the identity proof this request sent")}if(r==="admitted")throw new e.HistoryClientError("identity_contract_violation","Server admitted an identity proof that was never sent");o&&e.setHistoryIdentityStatus(e.browserOnlyStatus())}async function Aa(e,t,n){vf(e);let o=n.trackIdentity!==!1,r=await e.initSession(),s=null;TT(e,n.scope)==="verified-user"&&(s=await PT(e,r,o),s&&(r=await kT(e,r,s,o)));let i=e.historyInternals.visitorStore,l=!1;for(;;){let c=i?.revision()??0,p=await e.readVisitorToken();if(!p&&!n.visitorTokenOptional)throw new e.HistoryClientError("visitor_token_missing","No visitor credential is stored for this browser");let d=await fetch(ET(e,t,{...n.query,sessionId:r.sessionId}),{method:n.method,headers:{"X-Persona-Version":Yn,...p?{"X-Visitor-Token":p}:{},...s?{"X-Identity-Proof":s}:{},...n.body!==void 0?{"Content-Type":"application/json"}:{}},...n.body!==void 0?{body:JSON.stringify(n.body)}:{},...n.keepalive?{keepalive:!0}:{}});if(d.status===401&&!l){l=!0,r=await Gv(e,await bf(e,d),s,o);continue}if(!d.ok)throw await Yv(e,d,o);let g=d.headers.get("X-History-Identity-Status"),f=await d.json().catch(()=>{});if(i&&i.revision()!==c)throw new e.HistoryClientError("credential_changed","The visitor credential changed while the request was in flight");return LT(e,g,s!==null,o),f}}function vf(e){if(!e.isClientTokenMode())throw new Error("Conversation history is only available in client token mode");if(!e.isHistoryCapable())throw new e.HistoryClientError("history_disabled","Visitor history is disabled for this surface")}async function HT(e,t){let n=await Aa(e,"conversations",{method:"GET",query:{...t?.cursor?{cursor:t.cursor}:{},...t?.limit!==void 0?{limit:t.limit}:{},...t?.targetId?{targetId:t.targetId}:{}},...t?.scope?{scope:t.scope}:{}});return{data:(Array.isArray(n?.data)?n.data:[]).map(Vv),nextCursor:typeof n?.nextCursor=="string"?n.nextCursor:null}}async function IT(e,t,n){let o=await Aa(e,`conversations/${encodeURIComponent(t)}`,{method:"GET",query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}});return{summary:Vv(o),messages:Array.isArray(o?.messages)?o.messages:[],nextMessageCursor:typeof o?.nextMessageCursor=="string"?o.nextMessageCursor:null,conversationRevision:typeof o?.conversationRevision=="string"?o.conversationRevision:null}}async function RT(e,t,n){vf(e);let o=0;for(let c of n){let p=c.displayContent.length;if(p>Uv)throw new e.HistoryClientError("payload_too_large",`displayContent exceeds the ${Uv} character limit`);o+=p}if(o>yf)throw new e.HistoryClientError("payload_too_large",`Display projection batch exceeds the ${yf} character limit`);await e.initSession();let r=e.historyInternals.visitorStore,s=r?.revision()??0,i=await Aa(e,`conversations/${encodeURIComponent(t)}/display-projections`,{method:"PATCH",body:{messages:n},scope:"browser",keepalive:o<=yf,trackIdentity:!1}),l=typeof i?.conversationRevision=="string"?i.conversationRevision:null;return l&&e.clientSession?.conversationId===t&&(r?.revision()??0)===s&&e.historyInternals.setStoredConversationRevision?.(l),{conversationRevision:l}}async function WT(e,t,n){let o=await Aa(e,`conversations/${encodeURIComponent(t)}`,{method:"DELETE",...n?.scope?{scope:n.scope}:{}});return{deleted:typeof o?.deleted=="number"?o.deleted:0}}async function OT(e,t){let n=await Aa(e,"conversations",{method:"DELETE",query:{...t?.targetId!==void 0?{targetId:t.targetId}:{}},...t?.scope?{scope:t.scope}:{}});return{deleted:typeof n?.deleted=="number"?n.deleted:0}}async function BT(e){vf(e),e.setHistoryIdentityStatus({state:"resetting"});try{await Aa(e,"visitor/reset",{method:"POST",scope:"browser",visitorTokenOptional:!0})}finally{await e.historyInternals.visitorStore?.clear(),e.setHistoryIdentityStatus(e.derivedBrowserOnly())}return{reset:!0}}var Uv,yf,Vv,jv,qv,zv,Kv,Cf=Ve(()=>{"use strict";Sa();Uv=32768,yf=49152,Vv=e=>{let t=e??{},n=typeof t.targetId=="string"?t.targetId:null;return{id:typeof t.id=="string"?t.id:"",title:typeof t.title=="string"?t.title:"",targetId:n,preview:typeof t.preview=="string"?t.preview:null,messageCount:typeof t.messageCount=="number"?t.messageCount:0,createdAt:typeof t.createdAt=="string"?t.createdAt:"",updatedAt:typeof t.updatedAt=="string"?t.updatedAt:""}},jv="The identity proof was not admitted; account history is unavailable",qv="The identity proof was rejected",zv="The request carried no visitor credential",Kv="The stored visitor belongs to a different signed-in user"});var Qv,Jv=Ve(()=>{"use strict";Rl();Qv=e=>{let{mount:t,overlay:n,sessionRef:o}=e,r=(d,g,f)=>{let h=g.trim();if(!h||!o.current)return;let y=d.getAttribute("data-tool-call-id")??"",v=f.source==="free-text";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:y,answer:h,answers:f.structured,values:f.values??(f.source==="multi"?h.split(", "):[h]),isFreeText:v,source:f.source},bubbles:!0,composed:!0})),Wr(n,y);let C=o.current.getMessages().find(A=>A.toolCall?.id===y);C?.agentMetadata?.awaitingLocalTool?o.current.resolveAskUserQuestion(C,f.structured??h):o.current.sendMessage(h)},s=d=>{let g=o.current;if(!g)return;let f=d.getAttribute("data-tool-call-id")??"",h=g.getMessages().find(y=>y.toolCall?.id===f);h&&g.persistAskUserQuestionProgress(h,{answers:Hd(d,h),currentIndex:Co(d)})},i=d=>Object.entries(d).map(([g,f])=>`${g}: ${Array.isArray(f)?f.join(", "):f}`).join(" | "),l=d=>{if(e.config().features?.askUserQuestion?.groupedAutoAdvance===!1)return;let g=Co(d),f=va(d);if(g>=f-1)return;let h=o.current?.getMessages().find(y=>y.toolCall?.id===d.getAttribute("data-tool-call-id"));h&&(Rd(d,h,e.config(),g+1),s(d))};return{click:d=>{let f=d.target.closest("[data-ask-user-action]");if(!f)return;let h=f.closest("[data-persona-ask-sheet-for]");if(!h)return;let y=f.getAttribute("data-ask-user-action");if(d.preventDefault(),d.stopPropagation(),y==="dismiss"){let v=h.getAttribute("data-tool-call-id")??"";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:v},bubbles:!0,composed:!0})),Wr(n,v);let C=o.current?.getMessages().find(A=>A.toolCall?.id===v);C?.agentMetadata?.awaitingLocalTool&&(o.current?.markAskUserQuestionResolved(C),o.current?.resolveAskUserQuestion(C,"(dismissed)"));return}if(y==="pick"){let v=f.getAttribute("data-option-label");if(!v)return;let C=h.getAttribute("data-multi-select")==="true",A=Ss(h);if(A&&C){let L=ui(h)[Co(h)],I=new Set(Array.isArray(L)?L:[]);I.has(v)?I.delete(v):I.add(v),As(h,Array.from(I)),s(h);return}if(A){As(h,v),s(h),l(h);return}if(C){let L=f.getAttribute("aria-pressed")==="true";f.setAttribute("aria-pressed",L?"false":"true"),f.classList.toggle("persona-ask-pill-selected",!L);let I=h.querySelector('[data-ask-user-action="submit-multi"]');I&&(I.disabled=pf(h).length===0);return}r(h,v,{source:"pick",values:[v]});return}if(y==="submit-multi"){let v=pf(h);if(v.length===0)return;r(h,v.join(", "),{source:"multi",values:v});return}if(y==="open-free-text"){let v=h.querySelector('[data-ask-free-text-row="true"]');v&&(v.classList.remove("persona-hidden"),v.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(y==="focus-free-text"){h.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(y==="submit-free-text"){let C=h.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!C.trim())return;if(Ss(h)){As(h,C.trim()),s(h),l(h);return}r(h,C,{source:"free-text"});return}if(y==="next"||y==="back"){if(!o.current)return;let v=h.getAttribute("data-tool-call-id")??"",C=o.current.getMessages().find(_=>_.toolCall?.id===v);if(!C)return;let L=h.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(L){let _=ui(h)[Co(h)];(typeof _!="string"||_!==L)&&As(h,L)}let I=y==="next"?1:-1,H=Co(h)+I;Rd(h,C,e.config(),H),s(h);return}if(y==="submit-all"){if(!o.current)return;let v=h.getAttribute("data-tool-call-id")??"",C=o.current.getMessages().find(_=>_.toolCall?.id===v);if(!C)return;let L=h.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";L&&As(h,L);let I=Hd(h,C);o.current.persistAskUserQuestionProgress(C,{answers:I,currentIndex:Co(h)});let H=i(I);r(h,H||"(submitted)",{source:"submit-all",structured:I});return}if(y==="skip"){if(!o.current)return;let v=h.getAttribute("data-tool-call-id")??"",C=o.current.getMessages().find(V=>V.toolCall?.id===v);if(!C)return;let A=Ss(h),L=Co(h),I=va(h),H=L>=I-1;if(!A){t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:v},bubbles:!0,composed:!0})),Wr(n,v),C.agentMetadata?.awaitingLocalTool&&(o.current.markAskUserQuestionResolved(C),o.current.resolveAskUserQuestion(C,"(dismissed)"));return}As(h,"");let _=h.querySelector('[data-ask-free-text-input="true"]');if(_&&(_.value=""),H){let V=Hd(h,C),oe=i(V);r(h,oe||"(skipped)",{source:"submit-all",structured:V});return}Rd(h,C,e.config(),L+1),s(h);return}},keydown:d=>{if(d.key!=="Enter")return;let f=d.target;if(!f.matches?.('[data-ask-free-text-input="true"]'))return;let h=f.closest("[data-persona-ask-sheet-for]");if(!h)return;d.preventDefault();let y=f.value;if(y.trim()){if(Ss(h)){As(h,y.trim()),s(h),l(h);return}r(h,y,{source:"free-text"})}}}}});function NT(e,t,n){if(n==="input-start")return t===0;let o=t>0?e[t-1]:"";return n==="line-start"?o===""||o===`
|
|
7
|
+
`),te="message",ve="",Ce=null;for(let Xe of K)Xe.startsWith("event:")?te=Xe.replace("event:","").trim():Xe.startsWith("data:")?ve+=Xe.replace("data:","").trim():Xe.startsWith("id:")&&(Ce=Xe.slice(3).trim());let Me=()=>{Ce!==null&&Ce!==""&&n({type:"cursor",id:Ce})};if(!ve){Me();continue}let ot;try{ot=JSON.parse(ve)}catch(Xe){n({type:"error",error:Xe instanceof Error?Xe:new Error("Failed to parse chat stream payload")});continue}let Ct=ot!==null&&typeof ot=="object"&&!Array.isArray(ot)?ot:null,De=te!=="message"?te:typeof Ct?.type=="string"?Ct.type:"message";if(e.onSSEEvent?.(De,ot),e.parseSSEEvent){C.current=y;let Xe=await CT(e,ot,n,C,h,d,A);if(C.current&&C.current!==y&&(y=C.current),Xe){Me();continue}}Ct&&(ye.push({...Ct,type:De}),ut()),Me()}}ut()}var Bv,hf=Ve(()=>{"use strict";pi();ha();Cs();Ov();Bv=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<")});var $v,Fv=Ve(()=>{$v="4.26.1"});var Yn,Sa=Ve(()=>{"use strict";Fv();Yn=$v});var Nd={};ys(Nd,{deleteAllConversations:()=>OT,deleteConversation:()=>WT,finalizeDisplayProjections:()=>RT,getConversation:()=>IT,historyErrorFor:()=>Yv,listConversations:()=>HT,readErrorCode:()=>bf,recoverFromUnauthorized:()=>Gv,resetVisitor:()=>BT});function ET(e,t,n){let o=new URLSearchParams;for(let[s,i]of Object.entries(n))i===void 0||i===""||o.set(s,String(i));let r=o.toString();return`${e.clientApiBase()}/v1/client/${t}${r?`?${r}`:""}`}function TT(e,t){if(t)return t;let n=e.config.features?.history?.scope;return n||(e.config.getIdentityProof?"verified-user":"browser")}async function PT(e,t,n){let o=e.config.getIdentityProof;if(!o)return n&&e.setHistoryIdentityStatus(e.browserOnlyStatus()),null;n&&e.setHistoryIdentityStatus({state:"verifying"});let r;try{r=await o()??null}catch{throw n&&e.setHistoryIdentityStatus({state:"identity_provider_failed"}),new e.HistoryClientError("identity_provider_failed","The identity proof provider failed")}if(r)return r;if(t.visitor?.endUserId!=null)throw n&&e.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new e.HistoryClientError("authentication_required","This browser is bound to a signed-in user and needs a fresh identity proof");return n&&e.setHistoryIdentityStatus({state:"browser_only",reason:"proof_unavailable_before_binding"}),null}async function kT(e,t,n,o){if(t.visitor?.endUserId!=null)return t;let r=await e.reinitWithProof(n);if(!(r.visitor?.identityStatus==="admitted"&&r.visitor?.endUserId!=null))throw o&&e.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new e.HistoryClientError("proof_not_admitted",jv);return r}async function bf(e,t){let n=await t.json().catch(()=>({}));return typeof n.error=="string"?n.error:typeof n.message=="string"?n.message:""}async function Gv(e,t,n,o){let r=t.toLowerCase();if(r.includes("invalid_identity_proof"))throw o&&e.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new e.HistoryClientError("invalid_identity_proof",qv);if(r.includes("visitor token required"))throw new e.HistoryClientError("visitor_token_missing",zv);if(r.includes("visitor_identity_mismatch")){if(!n)throw o&&e.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new e.HistoryClientError("visitor_identity_mismatch",Kv);return e.reinitWithProof(n)}if(r.includes("expired")||r.includes("not found"))return e.clearClientSession(),e.initSession();throw new e.HistoryClientError("unauthorized",t||"History request was not authorized")}async function Yv(e,t,n){let o=await bf(e,t);if(t.status===404)return new e.HistoryClientError("not_found","Conversation not found");if(t.status===429){let r=Number.parseInt(t.headers.get("Retry-After")??"",10);return new e.HistoryClientError("rate_limited","Too many history requests",{...Number.isFinite(r)?{retryAfterSeconds:r}:{}})}if(t.status===503&&o.includes("identity_proof_not_admitted"))return n&&e.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new e.HistoryClientError("proof_not_admitted",jv);if(t.status===401){let r=o.toLowerCase();return r.includes("invalid_identity_proof")?(n&&e.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new e.HistoryClientError("invalid_identity_proof",qv)):r.includes("visitor token required")?new e.HistoryClientError("visitor_token_missing",zv):r.includes("visitor_identity_mismatch")?new e.HistoryClientError("visitor_identity_mismatch",Kv):new e.HistoryClientError("unauthorized",o||"History request was not authorized")}return new e.HistoryClientError("request_failed",o||`History request failed (${t.status})`)}function LT(e,t,n,o){let r=t?.toLowerCase()??null;if(n){if(r==="admitted"){o&&e.setHistoryIdentityStatus({state:"verified"});return}throw o&&e.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),r==="ignored"?new e.HistoryClientError("identity_contract_violation","Server reported an ignored identity proof on a success response"):new e.HistoryClientError("proof_not_admitted","The response did not acknowledge the identity proof this request sent")}if(r==="admitted")throw new e.HistoryClientError("identity_contract_violation","Server admitted an identity proof that was never sent");o&&e.setHistoryIdentityStatus(e.browserOnlyStatus())}async function Aa(e,t,n){vf(e);let o=n.trackIdentity!==!1,r=await e.initSession(),s=null;TT(e,n.scope)==="verified-user"&&(s=await PT(e,r,o),s&&(r=await kT(e,r,s,o)));let i=e.historyInternals.visitorStore,l=!1;for(;;){let c=i?.revision()??0,p=await e.readVisitorToken();if(!p&&!n.visitorTokenOptional)throw new e.HistoryClientError("visitor_token_missing","No visitor credential is stored for this browser");let d=await fetch(ET(e,t,{...n.query,sessionId:r.sessionId}),{method:n.method,headers:{"X-Persona-Version":Yn,...p?{"X-Visitor-Token":p}:{},...s?{"X-Identity-Proof":s}:{},...n.body!==void 0?{"Content-Type":"application/json"}:{}},...n.body!==void 0?{body:JSON.stringify(n.body)}:{},...n.keepalive?{keepalive:!0}:{}});if(d.status===401&&!l){l=!0,r=await Gv(e,await bf(e,d),s,o);continue}if(!d.ok)throw await Yv(e,d,o);let g=d.headers.get("X-History-Identity-Status"),f=await d.json().catch(()=>{});if(i&&i.revision()!==c)throw new e.HistoryClientError("credential_changed","The visitor credential changed while the request was in flight");return LT(e,g,s!==null,o),f}}function vf(e){if(!e.isClientTokenMode())throw new Error("Conversation history is only available in client token mode");if(!e.isHistoryCapable())throw new e.HistoryClientError("history_disabled","Visitor history is disabled for this surface")}async function HT(e,t){let n=await Aa(e,"conversations",{method:"GET",query:{...t?.cursor?{cursor:t.cursor}:{},...t?.limit!==void 0?{limit:t.limit}:{},...t?.targetId?{targetId:t.targetId}:{}},...t?.scope?{scope:t.scope}:{}});return{data:(Array.isArray(n?.data)?n.data:[]).map(Vv),nextCursor:typeof n?.nextCursor=="string"?n.nextCursor:null}}async function IT(e,t,n){let o=await Aa(e,`conversations/${encodeURIComponent(t)}`,{method:"GET",query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}});return{summary:Vv(o),messages:Array.isArray(o?.messages)?o.messages:[],nextMessageCursor:typeof o?.nextMessageCursor=="string"?o.nextMessageCursor:null,conversationRevision:typeof o?.conversationRevision=="string"?o.conversationRevision:null}}async function RT(e,t,n){vf(e);let o=0;for(let c of n){let p=c.displayContent.length;if(p>Uv)throw new e.HistoryClientError("payload_too_large",`displayContent exceeds the ${Uv} character limit`);o+=p}if(o>yf)throw new e.HistoryClientError("payload_too_large",`Display projection batch exceeds the ${yf} character limit`);await e.initSession();let r=e.historyInternals.visitorStore,s=r?.revision()??0,i=await Aa(e,`conversations/${encodeURIComponent(t)}/display-projections`,{method:"PATCH",body:{messages:n},scope:"browser",keepalive:o<=yf,trackIdentity:!1}),l=typeof i?.conversationRevision=="string"?i.conversationRevision:null;return l&&e.clientSession?.conversationId===t&&(r?.revision()??0)===s&&e.historyInternals.setStoredConversationRevision?.(l),{conversationRevision:l}}async function WT(e,t,n){let o=await Aa(e,`conversations/${encodeURIComponent(t)}`,{method:"DELETE",...n?.scope?{scope:n.scope}:{}});return{deleted:typeof o?.deleted=="number"?o.deleted:0}}async function OT(e,t){let n=await Aa(e,"conversations",{method:"DELETE",query:{...t?.targetId!==void 0?{targetId:t.targetId}:{}},...t?.scope?{scope:t.scope}:{}});return{deleted:typeof n?.deleted=="number"?n.deleted:0}}async function BT(e){vf(e),e.setHistoryIdentityStatus({state:"resetting"});try{await Aa(e,"visitor/reset",{method:"POST",scope:"browser",visitorTokenOptional:!0})}finally{await e.historyInternals.visitorStore?.clear(),e.setHistoryIdentityStatus(e.derivedBrowserOnly())}return{reset:!0}}var Uv,yf,Vv,jv,qv,zv,Kv,Cf=Ve(()=>{"use strict";Sa();Uv=32768,yf=49152,Vv=e=>{let t=e??{},n=typeof t.targetId=="string"?t.targetId:null;return{id:typeof t.id=="string"?t.id:"",title:typeof t.title=="string"?t.title:"",targetId:n,preview:typeof t.preview=="string"?t.preview:null,messageCount:typeof t.messageCount=="number"?t.messageCount:0,createdAt:typeof t.createdAt=="string"?t.createdAt:"",updatedAt:typeof t.updatedAt=="string"?t.updatedAt:""}},jv="The identity proof was not admitted; account history is unavailable",qv="The identity proof was rejected",zv="The request carried no visitor credential",Kv="The stored visitor belongs to a different signed-in user"});var Qv,Jv=Ve(()=>{"use strict";Rl();Qv=e=>{let{mount:t,overlay:n,sessionRef:o}=e,r=(d,g,f)=>{let h=g.trim();if(!h||!o.current)return;let y=d.getAttribute("data-tool-call-id")??"",v=f.source==="free-text";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:y,answer:h,answers:f.structured,values:f.values??(f.source==="multi"?h.split(", "):[h]),isFreeText:v,source:f.source},bubbles:!0,composed:!0})),Wr(n,y);let C=o.current.getMessages().find(A=>A.toolCall?.id===y);C?.agentMetadata?.awaitingLocalTool?o.current.resolveAskUserQuestion(C,f.structured??h):o.current.sendMessage(h)},s=d=>{let g=o.current;if(!g)return;let f=d.getAttribute("data-tool-call-id")??"",h=g.getMessages().find(y=>y.toolCall?.id===f);h&&g.persistAskUserQuestionProgress(h,{answers:Hd(d,h),currentIndex:Co(d)})},i=d=>Object.entries(d).map(([g,f])=>`${g}: ${Array.isArray(f)?f.join(", "):f}`).join(" | "),l=d=>{if(e.config().features?.askUserQuestion?.groupedAutoAdvance===!1)return;let g=Co(d),f=va(d);if(g>=f-1)return;let h=o.current?.getMessages().find(y=>y.toolCall?.id===d.getAttribute("data-tool-call-id"));h&&(Rd(d,h,e.config(),g+1),s(d))};return{click:d=>{let f=d.target.closest("[data-ask-user-action]");if(!f)return;let h=f.closest("[data-persona-ask-sheet-for]");if(!h)return;let y=f.getAttribute("data-ask-user-action");if(d.preventDefault(),d.stopPropagation(),y==="dismiss"){let v=h.getAttribute("data-tool-call-id")??"";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:v},bubbles:!0,composed:!0})),Wr(n,v);let C=o.current?.getMessages().find(A=>A.toolCall?.id===v);C?.agentMetadata?.awaitingLocalTool&&(o.current?.markAskUserQuestionResolved(C),o.current?.resolveAskUserQuestion(C,"(dismissed)"));return}if(y==="pick"){let v=f.getAttribute("data-option-label");if(!v)return;let C=h.getAttribute("data-multi-select")==="true",A=Ss(h);if(A&&C){let L=ui(h)[Co(h)],I=new Set(Array.isArray(L)?L:[]);I.has(v)?I.delete(v):I.add(v),As(h,Array.from(I)),s(h);return}if(A){As(h,v),s(h),l(h);return}if(C){let L=f.getAttribute("aria-pressed")==="true";f.setAttribute("aria-pressed",L?"false":"true"),f.classList.toggle("persona-ask-pill-selected",!L);let I=h.querySelector('[data-ask-user-action="submit-multi"]');I&&(I.disabled=pf(h).length===0);return}r(h,v,{source:"pick",values:[v]});return}if(y==="submit-multi"){let v=pf(h);if(v.length===0)return;r(h,v.join(", "),{source:"multi",values:v});return}if(y==="open-free-text"){let v=h.querySelector('[data-ask-free-text-row="true"]');v&&(v.classList.remove("persona-hidden"),v.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(y==="focus-free-text"){h.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(y==="submit-free-text"){let C=h.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!C.trim())return;if(Ss(h)){As(h,C.trim()),s(h),l(h);return}r(h,C,{source:"free-text"});return}if(y==="next"||y==="back"){if(!o.current)return;let v=h.getAttribute("data-tool-call-id")??"",C=o.current.getMessages().find(_=>_.toolCall?.id===v);if(!C)return;let L=h.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(L){let _=ui(h)[Co(h)];(typeof _!="string"||_!==L)&&As(h,L)}let I=y==="next"?1:-1,H=Co(h)+I;Rd(h,C,e.config(),H),s(h);return}if(y==="submit-all"){if(!o.current)return;let v=h.getAttribute("data-tool-call-id")??"",C=o.current.getMessages().find(_=>_.toolCall?.id===v);if(!C)return;let L=h.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";L&&As(h,L);let I=Hd(h,C);o.current.persistAskUserQuestionProgress(C,{answers:I,currentIndex:Co(h)});let H=i(I);r(h,H||"(submitted)",{source:"submit-all",structured:I});return}if(y==="skip"){if(!o.current)return;let v=h.getAttribute("data-tool-call-id")??"",C=o.current.getMessages().find(V=>V.toolCall?.id===v);if(!C)return;let A=Ss(h),L=Co(h),I=va(h),H=L>=I-1;if(!A){t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:v},bubbles:!0,composed:!0})),Wr(n,v),C.agentMetadata?.awaitingLocalTool&&(o.current.markAskUserQuestionResolved(C),o.current.resolveAskUserQuestion(C,"(dismissed)"));return}As(h,"");let _=h.querySelector('[data-ask-free-text-input="true"]');if(_&&(_.value=""),H){let V=Hd(h,C),oe=i(V);r(h,oe||"(skipped)",{source:"submit-all",structured:V});return}Rd(h,C,e.config(),L+1),s(h);return}},keydown:d=>{if(d.key!=="Enter")return;let f=d.target;if(!f.matches?.('[data-ask-free-text-input="true"]'))return;let h=f.closest("[data-persona-ask-sheet-for]");if(!h)return;d.preventDefault();let y=f.value;if(y.trim()){if(Ss(h)){As(h,y.trim()),s(h),l(h);return}r(h,y,{source:"free-text"})}}}}});function NT(e,t,n){if(n==="input-start")return t===0;let o=t>0?e[t-1]:"";return n==="line-start"?o===""||o===`
|
|
8
8
|
`:o===""||Zv.test(o)}function FT(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 NT(e,s,o)?{triggerIndex:s,query:e.slice(s+1,t)}:null;if(i===`
|
|
9
9
|
`||i==="\uFFFC"||!r&&Zv.test(i))return null;s--}return null}function eC(e,t,n){for(let o of n){let r=FT(e,t,o.trigger,o.position??"anywhere",o.allowSpaces??!1);if(r)return{channel:o,match:r}}return null}function tC(e){return e?e!=="insertFromPaste"&&e!=="insertFromDrop":!0}var Zv,nC=Ve(()=>{"use strict";Zv=/\s/});function oC(e){let t={trigger:e.trigger??"@",position:e.triggerPosition??"anywhere",allowSpaces:!1,sources:Array.isArray(e.sources)?e.sources:[],searchPlaceholder:e.searchPlaceholder,showButton:e.showButton!==!1,buttonIconName:e.buttonIconName,buttonTooltipText:e.buttonTooltipText},n=(e.triggers??[]).map(o=>({trigger:o.trigger,position:o.triggerPosition??"anywhere",allowSpaces:o.allowSpaces??!1,sources:Array.isArray(o.sources)?o.sources:[],searchPlaceholder:o.searchPlaceholder,showButton:o.showButton===!0,buttonIconName:o.buttonIconName,buttonTooltipText:o.buttonTooltipText}));return[t,...n]}var rC=Ve(()=>{"use strict"});var Fd=Ve(()=>{"use strict"});function lC(e){e.delayMs!==void 0&&(sC=Ud(e.delayMs)),e.skipDelayMs!==void 0&&(iC=Ud(e.skipDelayMs))}function cC(e){$d.get(e)?.hide()}function vn(e){$d.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:o,hint:r,enabled:s=!0,gap:i=$T,viewportPadding:l=UT}=e,c=()=>t.ownerDocument,p=()=>c().defaultView??window,d=null,g=null,f=null,h=null,y,v=!1,C=!1,A=!1,L=()=>(typeof o=="function"?o():o).trim(),I=()=>(typeof r=="function"?r():r??"").trim(),H=()=>Ud(e.delayMs??sC),_=()=>Ud(e.skipDelayMs??iC),V=()=>{y!==void 0&&(p().clearTimeout(y),y=void 0)},oe=()=>{V();let me=d!==null;h?.(),h=null,d?.remove(),d=null,g=null,f=null,me&&jT(_())},W=()=>{if(!d)return;let me=c(),He=p(),Ee=t.getBoundingClientRect(),Ie=d.getBoundingClientRect(),yt=me.documentElement.clientWidth||He.innerWidth,qe=me.documentElement.clientHeight||He.innerHeight,Oe=yt-l-Ie.width,$=Ee.left+Ee.width/2-Ie.width/2,Be=Sf($,l,Oe),ye=Ee.top-l,ut=qe-l-Ee.bottom,Zt=Ie.height+i,xt=ye>=Zt||ye>=ut?"top":"bottom",xe=xt==="top"?Ee.top-i-Ie.height:Ee.bottom+i,Wt=qe-l-Ie.height,vt=Sf(xe,l,Wt),Le=Ee.left+Ee.width/2,Ye=Math.max(wf,Ie.width-wf),D=Sf(Le-Be,wf,Ye);d.dataset.placement=xt,d.style.left=`${Be}px`,d.style.top=`${vt}px`,d.style.setProperty("--persona-tooltip-arrow-x",`${D}px`)},j=()=>{if(A||!s||d||!t.isConnected||qT(t))return;let me=L(),He=zT(t);if(!me||!He)return;let Ee=c(),Ie=p();d=Ee.createElement("div"),d.className="persona-control-tooltip",d.setAttribute("role","tooltip"),d.dataset.state="measuring",d.style.zIndex=String(wa);let yt=Ie.getComputedStyle?.(t);if(yt){for(let Zt of KT){let xt=yt.getPropertyValue(Zt).trim();xt&&d.style.setProperty(Zt,xt)}yt.fontFamily&&(d.style.fontFamily=yt.fontFamily)}g=Ee.createElement("span"),g.className="persona-control-tooltip__label",g.textContent=me,d.appendChild(g);let qe=I();qe&&(f=Ee.createElement("span"),f.className="persona-control-tooltip__hint",f.textContent=qe,d.appendChild(f));let Oe=Ee.createElement("span");Oe.className="persona-control-tooltip__arrow",d.appendChild(Oe),He.appendChild(d),W(),d.dataset.state="open";let $=()=>{if(!t.isConnected){oe();return}g&&(g.textContent=L()),f&&(f.textContent=I()),W()};Ie.addEventListener("scroll",$,!0),Ie.addEventListener("resize",$);let Be=t.getRootNode(),ye=dC(Be)?Be:Ee.documentElement,ut=typeof MutationObserver>"u"?null:new MutationObserver(()=>{t.isConnected||oe()});ut?.observe(ye,{childList:!0,subtree:!0}),h=()=>{Ie.removeEventListener("scroll",$,!0),Ie.removeEventListener("resize",$),ut?.disconnect()}},X=me=>{if(!(A||d)){if(V(),me||H()<=0||VT()){j();return}y=p().setTimeout(()=>{y=void 0,j()},H())}},E=()=>{v||C?X(C):oe()},T=()=>{let me=p();(!me.matchMedia||!me.matchMedia("(hover: none)").matches)&&(v=!0,E())},B=()=>{v=!1,E()},P=()=>{try{C=t.matches(":focus-visible")}catch{C=!0}E()},J=()=>{C=!1,E()},U=()=>{v=!1,C=!1,oe()},ue=me=>{me.key==="Escape"&&U()};n.addEventListener("mouseenter",T),n.addEventListener("mouseleave",B),t.addEventListener("focus",P),t.addEventListener("blur",J),t.addEventListener("keydown",ue),t.addEventListener("click",U);let fe={get isOpen(){return d!==null},show:j,hide:oe,reposition:W,destroy:()=>{A||(A=!0,oe(),n.removeEventListener("mouseenter",T),n.removeEventListener("mouseleave",B),t.removeEventListener("focus",P),t.removeEventListener("blur",J),t.removeEventListener("keydown",ue),t.removeEventListener("click",U),$d.delete(t))}};return $d.set(t,fe),fe}var $T,UT,wf,sC,iC,aC,Ud,VT,jT,$d,Af,qT,dC,zT,Sf,KT,xa=Ve(()=>{"use strict";Bo();Fd();$T=8,UT=8,wf=10,sC=200,iC=300,aC=0,Ud=e=>Math.max(0,e);VT=()=>Date.now()<aC,jT=e=>{aC=e>0?Date.now()+e:0},$d=new WeakMap,Af="data-persona-tooltip-suppressed",qT=e=>typeof e.closest=="function"&&e.closest(`[${Af}]`)!==null;dC=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,zT=e=>{let t=e.getRootNode?.();return dC(t)?t:e.ownerDocument.body},Sf=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n)),KT=[...["background","foreground","hint-fg","radius","font-size","padding","max-width","shadow","arrow-display"].map(e=>`--persona-tooltip-${e}`),"--persona-font-family","--persona-radius-sm"]});var GT,hi,xf,Mf=Ve(()=>{"use strict";GT=(e,t)=>e.visible!==!1&&(e.mode!=="transient"||t==="connecting"||t==="paused"||t==="resuming"||t==="error"),hi=(e,t,n)=>{let o=t.mode==="transient",r=e.hasAttribute("data-persona-composer-reason")||e.hasAttribute("data-persona-composer-notice");e.style.display=GT(t,n)||o&&r&&t.visible!==!1?"":"none",e.classList.toggle("persona-mt-2",!o),e.classList.toggle("persona-mb-2",o)},xf=(e,t,n)=>{!t.parentElement||e.parentElement!==t.parentElement||(n.mode==="transient"?e.nextElementSibling!==t&&t.before(e):t.nextElementSibling!==e&&t.after(e))}});function _o(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];pC(s)&&pC(r)?n[o]=_o(s,r):n[o]=r}return n}var pC,Vd=Ve(()=>{"use strict";pC=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});function jd(e,t=""){return Object.entries(e).flatMap(([n,o])=>{let r=t?`${t}.${n}`:n;return Tf(o)?jd(o,r):[r]})}function uC(e,t){for(let n of t.split(".")){if(!Tf(e)||!Object.prototype.hasOwnProperty.call(e,n))return"absent";if(e=e[n],e===void 0)return"clear"}return"explicit"}function gC(e,t){return e?.[Ef]??t.filter(n=>uC(e,n)==="explicit")}function Pf(e,t){return Object.defineProperty(e,Ef,{value:t,enumerable:!0,configurable:!0}),e}function kf(e,t,n){return Pf(e,gC(t,jd(n)))}function fC(e,t,n){let o=t[Ef];if(o)return o;let r=new Set(gC(e,n));for(let s of n){let i=uC(t,s);i==="clear"&&r.delete(s),i==="explicit"&&r.add(s)}return[...r]}function mC(e,t,n){let o={...e};for(let r of t){if(n.includes(r))continue;let s=r.split("."),i=o;for(let l of s.slice(0,-1)){let c=i[l];if(!Tf(c)){i=void 0;break}i[l]={...c},i=i[l]}i&&delete i[s[s.length-1]]}return o}var Ef,Tf,Lf=Ve(()=>{"use strict";Ef=Symbol("persona.defaultsProvenance"),Tf=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});var hC,Hf,yi,qd,YT,Br,If,Rf,yC,Ma=Ve(()=>{"use strict";hC="var(--persona-components-panel-width)",Hf=Symbol("persona.panelAliasProvenance"),yi=(e,t)=>e!=null&&Object.prototype.hasOwnProperty.call(e,t),qd=(e,t)=>yi(e,t)&&e[t]!==void 0,YT=e=>({launcherWidth:qd(e?.launcher,"width"),legacyLauncherWidth:qd(e,"launcherWidth"),sidebarWidth:qd(e?.launcher,"sidebarWidth"),dockWidth:qd(e?.launcher?.dock,"width")}),Br=e=>{let t=e?.[Hf];return t?{...t}:YT(e)},If=(e,t)=>(Object.defineProperty(e,Hf,{value:t,enumerable:!0,configurable:!0}),e),Rf=(e,t)=>If(e,Br(t)),yC=(e,t)=>{let n=t[Hf];if(n)return{...n};let o=Br(e);return yi(t,"launcherWidth")&&(o.legacyLauncherWidth=t.launcherWidth!==void 0),yi(t,"launcher")&&t.launcher===void 0?(o.launcherWidth=!1,o.sidebarWidth=!1,o.dockWidth=!1,o):(yi(t.launcher,"width")&&(o.launcherWidth=t.launcher?.width!==void 0),yi(t.launcher,"sidebarWidth")&&(o.sidebarWidth=t.launcher?.sidebarWidth!==void 0),yi(t.launcher,"dock")&&t.launcher?.dock===void 0?o.dockWidth=!1:yi(t.launcher?.dock,"width")&&(o.dockWidth=t.launcher?.dock?.width!==void 0),o)}});function Ms(e){return e?.future?.v5Defaults===!0?"v5":"v4"}function CC(e){let t=Ms(e)==="v5"?bi:JT;return _o(QT,t)}function bC(e,t){if(!(!e&&!t))return e?t?_o(e,t):e:t}function Ea(e){let t=CC(e);return e?kf(Rf({...t,...e,theme:bC(t.theme,e.theme),darkTheme:bC(t.darkTheme,e.darkTheme),launcher:{...t.launcher,...e.launcher,dock:{...t.launcher?.dock,...e.launcher?.dock},clearChat:{...t.launcher?.clearChat,...e.launcher?.clearChat}},...t.composer||e.composer?{composer:{...t.composer,...e.composer}}:{},tooltip:{...t.tooltip,...e.tooltip},copy:{...t.copy,...e.copy},sendButton:{...t.sendButton,...e.sendButton},statusIndicator:{...t.statusIndicator,...e.statusIndicator},voiceRecognition:{...t.voiceRecognition,...e.voiceRecognition},features:(()=>{let n=t.features?.artifacts,o=e.features?.artifacts,r=t.features?.scrollToBottom,s=e.features?.scrollToBottom,i=t.features?.scrollBehavior,l=e.features?.scrollBehavior,c=t.features?.streamAnimation,p=e.features?.streamAnimation,d=t.features?.askUserQuestion,g=e.features?.askUserQuestion,f=t.features?.history,h=e.features?.history,y=n===void 0&&o===void 0?void 0:{...n,...o,layout:{...n?.layout,...o?.layout}},v=r===void 0&&s===void 0?void 0:{...r,...s},C=i===void 0&&l===void 0?void 0:{...i,...l},A=c===void 0&&p===void 0?void 0:{...c,...p},L=d===void 0&&g===void 0?void 0:{...d,...g,styles:{...d?.styles,...g?.styles}},I=f===void 0&&h===void 0?void 0:{...f,...h,copy:{...f?.copy,...h?.copy}};return{...t.features,...e.features,toolCallDisplay:{...t.features?.toolCallDisplay,...e.features?.toolCallDisplay},reasoningDisplay:{...t.features?.reasoningDisplay,...e.features?.reasoningDisplay},...v!==void 0?{scrollToBottom:v}:{},...C!==void 0?{scrollBehavior:C}:{},...y!==void 0?{artifacts:y}:{},...A!==void 0?{streamAnimation:A}:{},...L!==void 0?{askUserQuestion:L}:{},...I!==void 0?{history:I}:{}}})(),suggestionChips:e.suggestionChips??t.suggestionChips,suggestionChipsConfig:{...t.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...t.layout,...e.layout,header:{...t.layout?.header,...e.layout?.header},messages:{...t.layout?.messages,...e.layout?.messages,...t.layout?.messages?.user||e.layout?.messages?.user?{user:{...t.layout?.messages?.user,...e.layout?.messages?.user}}:{},...t.layout?.messages?.assistant||e.layout?.messages?.assistant?{assistant:{...t.layout?.messages?.assistant,...e.layout?.messages?.assistant}}:{},avatar:{...t.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...t.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...t.layout?.slots,...e.layout?.slots}},markdown:{...t.markdown,...e.markdown,options:{...t.markdown?.options,...e.markdown?.options}},messageActions:{...t.messageActions,...e.messageActions}},e),e,bi):kf(Rf(t),void 0,bi)}var vi,vC,Bl,Wf,_r,Ci,XT,QT,JT,ZT,bi,wC,wo=Ve(()=>{"use strict";Vd();Lf();Ma();Fd();vi="min(440px, calc(100vw - 24px))",vC="440px",Bl="40px",Wf="How can I help...",_r={collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",previewMaxLines:3,expandable:!0,loadingAnimation:"none"},Ci={activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},XT={enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:vi,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:Bl,closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},QT={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",tooltip:{delayMs:200,skipDelayMs:300},launcher:XT,copy:{inputPlaceholder:Wf,sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",borderWidth:"0px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"anchor-top",anchorTopOffset:16,showActivityWhilePinned:!0},toolCallDisplay:_r,reasoningDisplay:Ci,streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"},history:{enabled:!1,presentation:"panel",showScopeStatus:!0,showDelete:!0,showDeleteAll:!0}},suggestionChips:["Show me what you can help with","Walk me through getting started","Answer a question about this page"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1},JT={},ZT={variant:"circle",width:"min(400px, calc(100vw - 24px))",headerIconSize:"20px"},bi={launcher:ZT,features:{toolCallDisplay:{variant:"row",iconVisibility:"active",autoExpand:!1,grouped:!0,groupedMode:"collapsible",loadingAnimation:"shimmer"},reasoningDisplay:{variant:"row",iconVisibility:"active",autoExpand:!1,loadingAnimation:"shimmer"}},composer:{layout:"single-row",placement:"overlay"},sendButton:{iconName:"arrow-up"},statusIndicator:{mode:"transient"},layout:{contentMaxWidth:"768px",topFade:!0,header:{showSubtitle:!1},messages:{assistant:{width:"full"}}}};wC=CC()});function SC(e){return typeof e=="string"?[{type:"text",text:e}]:e}function zd(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Pa(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function AC(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function So(e){return{type:"text",text:e}}function Kd(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function xC(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;t({type:"image",image:r,mimeType:e.type,alt:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function MC(e,t=["image/png","image/jpeg","image/gif","image/webp"],n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}function tP(e){return EC.includes(e)||e.startsWith("image/")}function Gd(e){return tP(e.type)}function TC(e,t,n){return{type:"file",data:e,mimeType:t,filename:n}}async function PC(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;Gd(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function kC(e,t=Dr,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function nP(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function LC(e,t){let n=nP(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||n||"FILE"}var Ta,EC,eP,Dr,Nr=Ve(()=>{"use strict";Ta="[Image]";EC=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],eP=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],Dr=[...EC,...eP]});function Of(e){let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return 20;let n=t.getComputedStyle(e).lineHeight;if(!n||!n.trim().endsWith("px"))return 20;let o=parseFloat(n);return Number.isFinite(o)&&o>0?o:20}function Yd(e,t){return typeof e!="number"||!Number.isFinite(e)?t:e>0?e:t}function HC(e,t){e.style.maxHeight=`${t*Of(e)}px`,e.style.overflowY="auto"}function _l(e){let t=e?.ownerDocument?.defaultView??(typeof window<"u"?window:null);if(!t||typeof t.matchMedia!="function")return!1;try{return t.matchMedia("(pointer: coarse)").matches===!0}catch{return!1}}function IC(e){return e.insertNewlineOnTouchEnter===!0&&e.coarsePointer===!0}function RC(e,t){if(e.key!=="Enter"||e.shiftKey||e.isComposing)return!1;let n=e.metaKey===!0||e.ctrlKey===!0,o=t.submitKey??"enter";return o==="none"?!1:o==="mod-enter"?n:n||!IC(t)}function oP(e){return(e.submitKey??"enter")!=="enter"||IC(e)?"enter":"send"}function Xd(e,t){e.setAttribute("enterkeyhint",oP(t))}function Qd(e,t){let n=t?.autocomplete;e.setAttribute("autocomplete",typeof n=="string"&&n?n:"off");let o=(r,s)=>{s===void 0?e.removeAttribute(r):e.setAttribute(r,s)};o("autocapitalize",typeof t?.autocapitalize=="string"?t.autocapitalize:void 0),o("spellcheck",typeof t?.spellcheck=="boolean"?String(t.spellcheck):void 0),o("inputmode",typeof t?.inputmode=="string"&&t.inputmode?t.inputmode:void 0),o("aria-label",typeof t?.ariaLabel=="string"&&t.ariaLabel?t.ariaLabel:void 0)}function Bf(e){return e===!0?{disabled:!0}:!e||typeof e!="object"?{disabled:!1}:{disabled:!0,reason:typeof e.reason=="string"&&e.reason?e.reason:void 0}}var Jd=Ve(()=>{"use strict"});var ro,Do,Df,Xn,Zd,ep,sP,Nf,tp,ka,np,op,rp,Es=Ve(()=>{"use strict";Mf();Je();kt();wo();Nr();xa();Jd();ro="persona-composer-control",Do="persona-composer-control--glyph",Df=40,Xn=24,Zd=(e,t,n)=>{let o=e.ownerDocument?.defaultView;if(!o)return;let r=o.getComputedStyle(e);for(let s of n){let i=r.getPropertyValue(s).trim();i?t.style.setProperty(s,i):t.style.removeProperty(s)}},ep=(e,t)=>{let n=x("textarea");n.setAttribute("data-persona-composer-input",""),n.placeholder=e?.copy?.inputPlaceholder??Wf,n.dir="auto",Xd(n,{submitKey:e?.composer?.submitKey,insertNewlineOnTouchEnter:e?.composer?.insertNewlineOnTouchEnter,coarsePointer:_l(n)}),Qd(n,e?.composer?.inputAttributes),n.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-text focus:persona-outline-none focus:persona-border-none persona-composer-textarea",n.rows=1,n.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',n.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let o=Yd(e?.composer?.maxLines,t?.defaultMaxLines??3),r=`${o*20}px`;n.style.maxHeight=r,n.style.overflowY="auto";let s=()=>{let l=n.style.maxHeight;if(l!==r){let p=parseFloat(l);if(Number.isFinite(p)&&p>0)return p}let c=o*Of(n);return r=`${c}px`,n.style.maxHeight=r,c},i=()=>{n.addEventListener("input",()=>{n.style.height="auto";let l=Math.min(n.scrollHeight,s());n.style.height=`${l}px`})};return n.style.border="none",n.style.outline="none",n.style.borderWidth="0",n.style.borderStyle="none",n.style.borderColor="transparent",n.addEventListener("focus",()=>{n.style.border="none",n.style.outline="none",n.style.borderWidth="0",n.style.borderStyle="none",n.style.borderColor="transparent",n.style.boxShadow="none"}),n.addEventListener("blur",()=>{n.style.border="none",n.style.outline="none"}),{textarea:n,attachAutoResize:i}},sP="[data-persona-glyph-stack]",Nf=(e,t,n="send")=>{let o=Q("span",{className:"persona-composer-glyph-stack",attrs:{"data-mode":n,"data-persona-glyph-stack":""}});return e.setAttribute("data-glyph","send"),t.setAttribute("data-glyph","stop"),o.append(e,t),o},tp=e=>{let t=e?.sendButton??{},n=t.useIcon??!1,o=t.iconText??"\u2191",r=t.iconName,s=t.stopIconName??"square",i=t.tooltipText??"Send message",l=t.stopTooltipText??"Stop generating",c=e?.copy?.sendButtonLabel??"Send",p=e?.copy?.stopButtonLabel??"Stop",d=t.showTooltip??!1,g=t.size,f=parseFloat(g??"")||Df,h=t.backgroundColor,y=t.textColor,v=x("div","persona-send-button-wrapper"),C=Q("button",{className:_n("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?`persona-flex persona-items-center persona-justify-center ${ro}`:"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!h&&"persona-bg-persona-primary",!n&&!y&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":"","data-persona-send-mode":"send"},style:{width:n?g:void 0,height:n?g:void 0,minWidth:n?g:void 0,minHeight:n?g:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?y||"var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))":y||void 0,backgroundColor:n&&h||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:n?"0":t.paddingX||void 0,paddingRight:n?"0":t.paddingX||void 0,paddingTop:n?"0":t.paddingY||void 0,paddingBottom:n?"0":t.paddingY||void 0}}),A=null,L=null,I=null;if(n){let V=parseFloat(t.iconSize??"")||Math.round(f*.5),oe=t.iconStrokeWidth??2,W=y?.trim()||"currentColor";if(r&&(A=ge(r,V,W,oe)),L=ge(s,V,W,oe),!t.iconSize)for(let j of[A,L])j&&(j.style.width=`var(--persona-components-composer-sendIconSize, ${V}px)`,j.style.height=`var(--persona-components-composer-sendIconSize, ${V}px)`);A&&L?(I=Nf(A,L),C.appendChild(I)):A?C.appendChild(A):(C.textContent=o,L=null)}else C.textContent=c;C.setAttribute("aria-label",i),v.appendChild(C),vn({anchor:C,trigger:v,text:()=>C.getAttribute("aria-label")??"",enabled:d});let H="send";return{button:C,wrapper:v,setMode:V=>{if(V===H)return;H=V;let oe=V==="stop"?l:i;C.setAttribute("aria-label",oe),C.setAttribute("data-persona-send-mode",V),n?(C.querySelector(sP)??I)?.setAttribute("data-mode",V):C.textContent=V==="stop"?p:c},glyphStack:I}},ka=e=>{let t=e?.voiceRecognition??{};if(!(t.enabled===!0))return null;let o=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),r=t.provider?.type==="runtype",s=t.provider?.type==="custom";if(!(o||r||s))return null;let l=t.iconName??"mic",c=t.iconSize,p=parseFloat(c??"")||Xn,d=t.backgroundColor??e?.sendButton?.backgroundColor,g=t.iconColor??e?.sendButton?.textColor,f=x("div","persona-send-button-wrapper"),h=Q("button",{className:_n("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",ro,!c&&Do),attrs:{type:"button","data-persona-composer-mic":"","data-state":"idle","aria-label":t.tooltipText??"Start voice recognition"},style:{width:c,height:c,minWidth:c,minHeight:c,fontSize:"18px",lineHeight:"1",color:g||"var(--persona-text, #111827)",backgroundColor:d||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),v=ge(l,p,g||"currentColor",1.5);v?h.appendChild(v):h.textContent="\u{1F3A4}",f.appendChild(h);let C=t.tooltipText??"Start voice recognition",A=t.showTooltip??!1;return vn({anchor:h,trigger:f,text:()=>h.getAttribute("aria-label")??C,enabled:A}),{button:h,wrapper:f}},np=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=x("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");n.setAttribute("data-persona-composer-attachment-previews",""),n.style.display="none";let o=x("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=(t.allowedTypes??Dr).join(","),o.multiple=(t.maxFiles??4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let r=t.buttonIconName??"paperclip",s=x("div","persona-send-button-wrapper"),i=Q("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${ro} ${Do}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),l=ge(r,Xn,"currentColor",1.5);l?i.appendChild(l):i.textContent="\u{1F4CE}",i.addEventListener("click",p=>{p.preventDefault(),o.click()}),s.appendChild(i);let c=t.buttonTooltipText??"Attach file";return vn({anchor:i,trigger:s,text:()=>i.getAttribute("aria-label")??c}),{button:i,wrapper:s,input:o,previewsContainer:n}},op=e=>{let t=e?.statusIndicator??{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=x("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status",""),hi(o,t,"idle");let r=t.idleText??"Online";if(t.idleLink){let s=x("a");s.href=t.idleLink,s.target="_blank",s.rel="noopener noreferrer",s.textContent=r,s.style.color="inherit",s.style.textDecoration="none",o.appendChild(s)}else o.textContent=r;return o},rp=()=>Q("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}})});function sp(e){let{config:t,onOpen:n}=e,o=t.buttonIconName??"plus",r=t.buttonTooltipText??"Add context",s=x("div","persona-send-button-wrapper"),i=Q("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${ro} ${Do}`,attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":r,"aria-haspopup":"listbox","aria-expanded":"false"},style:{fontSize:"18px",lineHeight:"1"}}),l=ge(o,Xn,"currentColor",1.5);return l?i.appendChild(l):i.textContent="+",i.addEventListener("click",c=>{c.preventDefault(),c.stopPropagation(),n()}),s.appendChild(i),vn({anchor:i,trigger:s,text:()=>i.getAttribute("aria-label")??r}),{button:i,wrapper:s}}var Ff=Ve(()=>{"use strict";Je();kt();xa();Es()});var iW,iP,ip,$f=Ve(()=>{"use strict";dn();({setLoader:iW,load:iP}=lt({fallbackImport:()=>import("@runtypelabs/persona/context-mentions")})),ip=iP});var cW,aP,ap,Uf=Ve(()=>{"use strict";dn();({setLoader:cW,load:aP}=lt({fallbackImport:()=>import("@runtypelabs/persona/context-mentions-inline"),resetOnSetLoader:!0})),ap=aP});function Dl(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=Q("span",{className:_n("persona-mention-token",t.readonly&&"persona-mention-token-readonly"),attrs:{"data-mention-source":e.sourceId,title:e.label,role:"img","aria-label":`${e.label} mention`}});e.color&&n.style.setProperty("--persona-mention-token-accent",e.color);let o=ge(e.iconName??"at-sign",13,"currentColor",2);if(o){let r=x("span","persona-mention-token-icon");r.appendChild(o),n.appendChild(r)}return n.appendChild(Q("span",{className:"persona-mention-token-label",text:`@${e.label}`})),n}var Vf=Ve(()=>{"use strict";Je();kt()});function WC(e){let{loadContextMentions:t,loadContextMentionsInline:n,renderLucideIcon:o,createMentionButton:r}=e.deps??lP,s=e.config.contextMentions;if(!s?.enabled)return null;let i=oC(s).filter(W=>W.sources.length>0);if(i.length===0)return typeof console<"u"&&console.warn("[Persona] contextMentions.enabled is true but no sources were provided; mentions are disabled."),null;let l=i.filter(W=>W.sources.some(j=>typeof j.matchCommand=="function")),c=W=>l.some(j=>j.trigger?j.position==="line-start"?W.split(`
|
|
10
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??Q("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),f=null,h=null,y=e.textarea,v=null,C=null,A=null,L=null,I=()=>{if(f)return Promise.resolve(f);if(h)return h;let W=t().then(j=>(j.setMentionIconRenderer(o),f=j.mountContextMentions({mentionConfig:s,textarea:e.textarea,composerInput:v??void 0,anchor:e.anchor,contextRow:g,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:oe,emit:p}),f)).catch(j=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",j),h===W&&(h=null),null));return h=W,W},H=()=>{n().then(W=>{let j=W.mountInlineComposer({textarea:e.textarea,renderToken:E=>Dl(E,{render:s.renderMentionToken}),onMentionRemoved:E=>f?.untrackMention(E)});v=j.input,C=j.destroy;let X=y;X.replaceWith(j.element),y=j.element,L={next:j.element,prev:X},A?.(j.element,X),f?f.rebindComposer(j.input):h&&h.then(E=>E?.rebindComposer(j.input))}).catch(W=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",W)})};s.display==="inline"&&H();let _=[],V=new Map;for(let W of i){if(!W.showButton)continue;let j=r({config:{...s,buttonIconName:W.buttonIconName,buttonTooltipText:W.buttonTooltipText},onOpen:()=>{I().then(X=>X?.openMenu(W.trigger))}});_.push(j),V.set(W.trigger,j.button)}let oe=(W,j,X)=>{let E=V.get(j);E&&(E.setAttribute("aria-expanded",W?"true":"false"),W?E.setAttribute("aria-controls",X):E.removeAttribute("aria-controls"))};return{affordanceButtons:_.map(W=>W.wrapper),contextRow:g,handleInput:W=>{if(f){f.handleInput();return}if(!tC(W))return;let j=y,X=j.selectionStart??0;eC(j.value,X,i)&&I().then(E=>E?.handleInput())},handleKeydown:W=>{if(f?.isMenuOpen())return f.handleKeydown(W);if(W.key==="Backspace"&&f?.hasMentions()&&!L){let j=y,X=j.selectionStart===0&&j.selectionEnd===0;if((j.value.length===0||X)&&f.removeLastChip())return W.preventDefault(),!0}return!1},isMenuOpen:()=>f?.isMenuOpen()??!1,hasMentions:()=>f?.hasMentions()??!1,getMentionRefs:()=>f?.getMentionRefs()??[],collectForSubmit:()=>f?.collectForSubmit()??null,takeInlineCommand:async W=>c(W)?(f??await I())?.dispatchInlineCommand(W)??null:null,clear:()=>f?.clear(),prefetch:()=>{t().catch(()=>{})},onComposerSwap:W=>{A=W,L&&W(L.next,L.prev)},destroy:()=>{f?.destroy(),C?.();for(let W of _)W.wrapper.remove();d&&g.remove()}}}var lP,OC=Ve(()=>{"use strict";Je();nC();rC();Ff();$f();kt();Uf();Vf();lP={loadContextMentions:()=>ip(),loadContextMentionsInline:()=>ap(),renderLucideIcon:(...e)=>ge(...e),createMentionButton:(...e)=>sp(...e)}});var lp={};ys(lp,{createAskUserSheetHandlers:()=>Qv,createContextMentionOrchestrator:()=>WC});var jf=Ve(()=>{"use strict";Jv();OC()});var pp={};ys(pp,{resolveApproval:()=>gP,resolveAskUserQuestion:()=>fP,resolveWebMcpToolCall:()=>yP,resolveWebMcpToolCallBatch:()=>DC});async function gP(e,t,n,o){let r=`approval-${t.id}`,s=`approval-error-${t.id}`,i={};e.s.approvalTokens.set(r,i);let l={...t,status:n,resolvedAt:Date.now()},c=e.s.messages.find(f=>f.id===r),p={id:r,role:"assistant",content:"",createdAt:c?.createdAt??new Date().toISOString(),...c?.sequence!==void 0?{sequence:c.sequence}:{},streaming:!1,variant:"approval",approval:l};e.s.upsertMessage(p),e.s.abortController?.abort(),e.s.abortController=new AbortController,e.setStreaming(!0);let d=e.s.config.approval,g=d&&typeof d=="object"?d.onDecision:void 0;try{let f;if(g?f=await g({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,o):f=await e.s.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),f){let h=null;if(f instanceof Response){if(!f.ok){let y=await f.json().catch(()=>null),v=y?.message??y?.error??`Approval request failed: ${f.status}`,C=y?.code==="APPROVAL_ALREADY_RESOLVED"||f.status===404&&/no paused execution/i.test(String(y?.error)),A=e.s.messages.find(L=>L.id===r);throw e.s.approvalTokens.get(r)===i&&A?.approval?.resolvedAt===l.resolvedAt&&(e.s.upsertMessage({...p,approval:C?{...l,status:"timeout"}:t}),C&&e.settleApprovalPausedToolCall(r),e.s.upsertMessage({id:s,role:"assistant",content:v,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()})),new Error(v)}h=f.body}else f instanceof ReadableStream&&(h=f);e.s.approvalTokens.get(r)===i&&e.s.messages.some(y=>y.id===s)&&(e.s.messages=e.s.messages.filter(y=>y.id!==s),e.s.callbacks.onMessagesChanged([...e.s.messages])),h?await e.s.connectStream(h,{allowReentry:!0}):(n==="denied"&&(e.settleApprovalPausedToolCall(r),e.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()})),e.setStreaming(!1),e.s.abortController=null)}else e.setStreaming(!1),e.s.abortController=null}catch(f){let h=f instanceof Error&&(f.name==="AbortError"||f.message.includes("aborted")||f.message.includes("abort"));e.setStreaming(!1),e.s.abortController=null,h||e.s.callbacks.onError?.(f instanceof Error?f:new Error(String(f)))}finally{e.s.approvalTokens.get(r)===i&&e.s.approvalTokens.delete(r)}}async function fP(e,t,n){if(e.s.messages.find(d=>d.id===t.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=t.agentMetadata?.executionId,s=t.toolCall?.name;if(!r||!s){e.s.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let i=typeof n=="string"?void 0:n;if(i===void 0&&typeof n=="string"){let d=t.toolCall?.args,g=Array.isArray(d?.questions)?d.questions:[];if(g.length===1){let f=typeof g[0]?.question=="string"?g[0].question:"";f&&(i={[f]:n})}}e.s.markAskUserQuestionResolved(t,i),e.s.abortController?.abort(),e.s.abortController=new AbortController,e.setStreaming(!0);let l=t.toolCall.id,c=t.toolCall?.args,p=Array.isArray(c?.questions)?c.questions:[];if(p.length===0){let d=typeof n=="string"?n:Object.entries(n).map(([g,f])=>`${g}: ${Array.isArray(f)?f.join(", "):f}`).join(" | ");e.appendMessage({id:`ask-user-answer-${l}`,role:"user",content:d,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()})}else{let d=i??{};p.forEach((g,f)=>{let h=typeof g?.question=="string"?g.question:"";if(!h)return;let y=d[h],v=Array.isArray(y)?y.join(", "):typeof y=="string"?y:"";e.appendMessage({id:`ask-user-q-${l}-${f}`,role:"assistant",content:h,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()}),e.appendMessage({id:`ask-user-a-${l}-${f}`,role:"user",content:v||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()})})}try{let d=await e.s.client.resumeFlow(r,{[s]:n},{after:e.resumeAfter(r)});if(!d.ok){let g=await d.json().catch(()=>null);throw new Error(g?.error??`Resume failed: ${d.status}`)}d.body?await e.s.connectStream(d.body,{allowReentry:!0}):(e.setStreaming(!1),e.s.abortController=null)}catch(d){let g=d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"));e.setStreaming(!1),e.s.abortController=null,g||e.s.callbacks.onError?.(d instanceof Error?d:new Error(String(d)))}}function mP(e,t){let o=[e.s.messages.find(r=>r.id===t.id)?.toolCall?.startedAt,t.toolCall?.startedAt];for(let r of o)if(typeof r=="number"&&Number.isFinite(r))return r;return Date.now()}function _C(e,t){return t.toolCall?.name!==Oo?!1:(e.s.messages.find(o=>o.id===t.id)??t).agentMetadata?.suggestRepliesResolved===!0}function hP(e,t){let n=mP(e,t);return e.s.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}function dp(e,t,n,o,r=Date.now(),s){e.s.messages.some(i=>i.id===t.id)&&e.s.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...s},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:o,completedAt:r,duration:void 0,durationMs:Math.max(0,r-o)}:t.toolCall})}async function DC(e,t,n){let o=[],r=new AbortController;e.s.webMcpResolveControllers.add(r),e.setStreaming(!0);let s=async c=>{let p=c.toolCall?.name,d=c.toolCall?.id;if(!p||!d)return null;let g=`${t}:${d}`;if(e.s.webMcpInflightKeys.has(g)||e.s.webMcpResolvedKeys.has(g)||_C(e,c))return null;e.s.webMcpInflightKeys.add(g),o.push(g);let f=hP(e,c),h=c.agentMetadata?.webMcpToolCallId??p;if(p===Oo)return{dedupeKey:g,resumeKey:h,output:Iv(),toolMessage:c,startedAt:f,completedAt:Date.now()};let y=e.s.client.executeWebMcpToolCall(p,c.toolCall?.args,r.signal),v;if(!y)v={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{v=await y}catch(C){let A=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));return A||e.s.callbacks.onError?.(C instanceof Error?C:new Error(String(C))),dp(e,c,zf(A?"Aborted by cancel()":uP(C)),f),e.s.webMcpInflightKeys.delete(g),null}return r.signal.aborted?(dp(e,c,zf("Aborted by cancel()"),f),e.s.webMcpInflightKeys.delete(g),null):{dedupeKey:g,resumeKey:h,output:v,toolMessage:c,startedAt:f,completedAt:Date.now()}},i;if(e.s.config.webmcp?.execution==="sequential"){i=[];for(let c of n)i.push(await s(c))}else i=await Promise.all(n.map(s));let l=[];try{if(l=i.filter(g=>g!==null),l.length===0)return;let c={};for(let g of l)c[g.resumeKey]=g.output;let p=await e.s.client.resumeFlow(t,c,{signal:r.signal,after:e.resumeAfter(t)});if(!p.ok){let g=await p.json().catch(()=>null);throw new Error(g?.error??`Resume failed: ${p.status}`)}let d=l[0].dedupeKey;for(let g of l){e.s.webMcpResolvedKeys.add(g.dedupeKey);let f=g.toolMessage.toolCall?.name,h=g.toolMessage.agentMetadata?.webMcpToolCallId;dp(e,g.toolMessage,g.output,g.startedAt,g.completedAt,{...f===Oo?{suggestRepliesResolved:!0}:{},...f&&h?{clientToolAnswer:{toolCallId:h,toolName:f,args:g.toolMessage.toolCall?.args,result:g.output,batch:d}}:{}})}p.body&&await e.s.connectStream(p.body,{allowReentry:!0})}catch(c){if(!(c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"))))e.s.callbacks.onError?.(c instanceof Error?c:new Error(String(c)));else for(let d of l)dp(e,d.toolMessage,zf("Aborted by cancel()"),d.startedAt)}finally{for(let c of o)e.s.webMcpInflightKeys.delete(c);e.s.webMcpResolveControllers.delete(r),e.s.webMcpResolveControllers.size===0&&!e.s.abortController&&e.setStreaming(!1)}}async function yP(e,t){let n=t.agentMetadata?.executionId,o=t.toolCall?.name,r=t.toolCall?.id;if(!n){e.s.callbacks.onError?.(new Error("WebMCP await missing executionId: dispatch left paused."));return}if(!o)return;if(!r){let i=`${n}:__no_tool_id__:${o}`;if(e.s.webMcpInflightKeys.has(i)||e.s.webMcpResolvedKeys.has(i))return;e.s.webMcpInflightKeys.add(i);try{await bP(e,n,o,{isError:!0,content:[{type:"text",text:"WebMCP await missing toolCall.id: cannot execute the page tool."}]}),e.s.webMcpResolvedKeys.add(i)}catch(l){e.s.callbacks.onError?.(l instanceof Error?l:new Error(String(l)))}finally{e.s.webMcpInflightKeys.delete(i)}return}let s=`${n}:${r}`;if(!(e.s.webMcpInflightKeys.has(s)||e.s.webMcpResolvedKeys.has(s)||_C(e,t)))return DC(e,n,[t])}async function bP(e,t,n,o,r){let s=await e.s.client.resumeFlow(t,{[n]:o},{signal:r?.signal,after:e.resumeAfter(t)});if(!s.ok){let i=await s.json().catch(()=>null);throw new Error(i?.error??`Resume failed: ${s.status}`)}r?.onHttpOk?.(),s.body?await e.s.connectStream(s.body,{allowReentry:!0}):e.s.webMcpResolveControllers.size===0&&(e.setStreaming(!1),e.s.abortController=null)}var zf,uP,Kf=Ve(()=>{"use strict";Ca();zf=e=>({isError:!0,content:[{type:"text",text:e}]}),uP=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t});function Yf(e){if(!e)return $C;let t={...$C};for(let n of SP){let o=e[n];typeof o=="string"&&o.length>0&&(t[n]=o)}return t}var SP,$C,UC=Ve(()=>{"use strict";SP=["viewTitle","openHistoryLabel","openHistoryBusyLabel","newConversationLabel","expandLabel","collapseLabel","resizeLabel","showEarlierMessagesLabel","openConversationLoadingLabel","openConversationErrorTitle","openConversationRetryLabel","openConversationBackLabel","confirmCancelLabel","deleteConversationConfirmTitle","deleteConversationConfirm","deleteConversationConfirmLabel","clearHistoryConfirmTitle","clearHistoryConfirm","clearHistoryVerifiedConfirm","clearHistoryConfirmLabel","resetIdentityConfirmTitle","resetIdentityConfirm","resetIdentityConfirmLabel","conversationDeletedNotice","identityResetNotice","identityResetUnconfirmedNotice"],$C={viewTitle:"Messages",openHistoryLabel:"Messages",openHistoryBusyLabel:"Messages, available once the reply finishes",newConversationLabel:"New conversation",expandLabel:"Expand conversation list",collapseLabel:"Collapse conversation list",resizeLabel:"Resize conversation list",showEarlierMessagesLabel:"Show earlier messages",openConversationLoadingLabel:"Loading conversation",openConversationErrorTitle:"Could not open the conversation.",openConversationRetryLabel:"Try again",openConversationBackLabel:"Back to messages",confirmCancelLabel:"Cancel",deleteConversationConfirmTitle:"Delete conversation",deleteConversationConfirm:"Delete this conversation? This cannot be undone.",deleteConversationConfirmLabel:"Delete",clearHistoryConfirmTitle:"Delete all conversations",clearHistoryConfirm:"Delete all conversations for this assistant on this browser? This cannot be undone.",clearHistoryVerifiedConfirm:"Delete all conversations for this assistant and signed-in user? This cannot be undone.",clearHistoryConfirmLabel:"Delete all",resetIdentityConfirmTitle:"Forget this device",resetIdentityConfirm:"Forget this device? All Persona data stored in this browser is cleared. Records are not deleted elsewhere.",resetIdentityConfirmLabel:"Forget this device",conversationDeletedNotice:"That conversation was deleted. You are now in a new conversation.",identityResetNotice:"This device was forgotten.",identityResetUnconfirmedNotice:"This device was cleared here, but the server could not confirm it."}});function qC(e){let{plugins:t,config:n}=e,o=!1,r=!1,s=!1,i=!1,l=null,c=[],p=()=>{for(let H of c.splice(0))try{H()}catch(_){Xf("renderHistoryView cleanup",_)}},d=(H,_)=>{for(let V of t){let oe=V[H];if(oe)try{let W=oe(_);if(W)return W}catch(W){Xf(H,W)}}return null},g=()=>({presentation:e.getPresentation(),config:n}),f={header:H=>i?d("renderHistoryHeader",Object.freeze({...g(),returnSurface:e.getReturnSurface(),identityStatus:Fr(H.identityStatus),pendingAction:jC(H.pendingAction),copy:Fr(H.copy),actions:Object.freeze({close:v.close,startNewConversation:v.startNewConversation}),defaultRenderer:H.defaultRenderer})):null,conversation:H=>i?d("renderHistoryConversation",Object.freeze({...g(),conversation:VC(H.conversation),active:H.active,pending:H.pending,open:H.open,requestDelete:H.requestDelete,defaultRenderer:H.defaultRenderer})):null,state:H=>i?d("renderHistoryState",Object.freeze({...g(),state:Fr(H.state),identityStatus:Fr(H.identityStatus),copy:Fr(H.copy),...H.retry?{retry:H.retry}:{},...H.startNewConversation?{startNewConversation:H.startNewConversation}:{},defaultRenderer:H.defaultRenderer})):null},h=t.flatMap(H=>(H.railSections??[]).map(_=>({..._,placement:_.placement??"above-conversations",items:[],render:V=>_.render(Object.freeze({collapsed:V,presentation:e.getPresentation(),actions:v}))}))),y=e.createView({slots:f,renderDom:!1,onModelChange:()=>I(),railSections:h}),v=Object.freeze({...y.operations,close:e.close}),C=()=>(i=!0,y.setDomRenderEnabled(!0),y.element),A=H=>Object.freeze({conversations:Object.freeze(H.conversations.map(VC)),activeConversationId:H.activeConversationId,state:Fr(H.state),pendingAction:jC(H.pendingAction),identityStatus:Fr(H.identityStatus),nextCursor:H.nextCursor,presentation:e.getPresentation(),returnSurface:e.getReturnSurface(),config:n,copy:Fr(y.copy),actions:v,defaultRenderer:C,requestRender:()=>I(),onCleanup:_=>{c.push(_)}}),L=()=>{i=!1;let H=null;for(let V of t)if(V.renderHistoryView){try{H=V.renderHistoryView(A(y.getModel()))}catch(oe){Xf("renderHistoryView",oe),H=null}if(H)break}let _=!H||H.contains(y.element);return i=_,y.setDomRenderEnabled(_),H??y.element};function I(){if(!(!s||o||r)){r=!0;try{p();let H=L();if(H===l)return;let _=l;l=H,e.onElementChanged(H,_)}finally{r=!1}}}return s=!0,I(),{view:y,get element(){return l??y.element},requestRender:I,dispose:()=>{o=!0,p()}}}var Xf,Fr,VC,jC,zC=Ve(()=>{"use strict";Xf=(e,t)=>{console.warn(`[persona] ${e} threw`,t)},Fr=e=>Object.freeze({...e}),VC=e=>Object.freeze({id:e.id,title:e.title,targetId:e.targetId,preview:e.preview,messageCount:e.messageCount,createdAt:e.createdAt,updatedAt:e.updatedAt}),jC=e=>e?Fr(e):null});var KC,Qf,AP,up,gp,xP,GC,fp,Nl,MP,EP,YC,mp=Ve(()=>{"use strict";KC=null,Qf=()=>{if(KC!==null)return KC;if(typeof navigator>"u")return!1;let t=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(t)},AP="ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space",up=(e,t)=>{console.warn(`[persona] ${e} shortcut: ${t}`)},gp=e=>{let t=e.toLowerCase().split("+").map(r=>r.trim()),n=t.pop(),o={key:n,mod:!1,shift:!1,alt:!1};for(let r of t)if(r==="mod"||r==="cmd"||r==="ctrl")o.mod=!0;else if(r==="shift")o.shift=!0;else if(r==="alt"||r==="option")o.alt=!0;else return up("unknown modifier in",e),null;return!o.mod||o.shift&&o.alt||/^(enter|esc(ape)?)$/.test(n)||!/^([^+\s]|[a-z]{2,12})$/.test(n)?(up("unsupported",e),null):(n==="space"&&(o.key=" "),o)},xP=e=>AP.split(" ").find(t=>t.toLowerCase()===e)??(e===" "?"Space":e.length===1?e.toUpperCase():e[0].toUpperCase()+e.slice(1)),GC=(e,t)=>{let n=gp(e);if(!n)return"";let o=Qf(),r=xP(n.key);if(!t&&o)return`${n.alt?"\u2325":""}${n.shift?"\u21E7":""}\u2318${r}`;let s=[t?o?"Meta":"Control":"Ctrl"];return n.alt&&s.push("Alt"),n.shift&&s.push("Shift"),s.push(r),s.join("+")},fp=e=>GC(e,!1),Nl=e=>GC(e,!0),MP=(e,t)=>t.key?.toLowerCase()===e.key&&(Qf()?t.metaKey:t.ctrlKey)===e.mod&&!(Qf()?t.ctrlKey:t.metaKey)&&t.shiftKey===e.shift&&t.altKey===e.alt,EP=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable},YC=e=>{let t=new Map,n=e?.ownerDocument??(typeof document<"u"?document:null),o=(s,i)=>{if((s.scope??"widget")==="page")return!0;if(!e)return!1;let l=i.composedPath?.();return l?.length?l.includes(e):e.contains(i.target)},r=s=>{if(s.isComposing||!t.size)return;let i=s.composedPath?.()[0]??s.target;for(let l of t.values())if(MP(l.parsed,s)&&l.when?.()!==!1&&o(l,s)&&!(!l.allowInInput&&EP(i))){s.preventDefault();try{l.run(s)}catch(c){up(`${l.id} threw on`,l.combo),console.warn(c)}return}};return n?.addEventListener("keydown",r),{register(s){let i=gp(s.combo);if(!i)return()=>{};let l=`${i.mod?"m":""}${i.shift?"s":""}${i.alt?"a":""}${i.key}`,c=t.get(l);return c?(up(`${c.id} already owns`,s.combo),()=>{}):(t.set(l,{...s,parsed:i}),s.element?.setAttribute("aria-keyshortcuts",Nl(s.combo)),()=>{t.get(l)?.id===s.id&&t.delete(l),s.element?.removeAttribute("aria-keyshortcuts")})},destroy(){t.clear(),n?.removeEventListener("keydown",r)}}}});function XC(e){if(typeof e!="string"||e==="")return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function hp(e){return typeof e=="string"?e:void 0}function kP(e){if(typeof e!="object"||e===null)return null;let t=e;switch(t.type){case"text":return typeof t.text=="string"?So(t.text):null;case"image":return typeof t.image=="string"?Kd(t.image,{mimeType:hp(t.mimeType),alt:hp(t.alt)}):null;case"file":return typeof t.data=="string"&&typeof t.mimeType=="string"&&typeof t.filename=="string"?TC(t.data,t.mimeType,t.filename):null;case"audio":return typeof t.audio=="string"?{type:"audio",audio:t.audio,...hp(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;case"video":return typeof t.video=="string"?{type:"video",video:t.video,...hp(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;default:return null}}function LP(e,t){let n=XC(t),o=e.map(i=>XC(i.timestamp)),r=new Array(e.length),s=0;for(;s<o.length;){let i=o[s];if(i!==null){r[s]=i,s+=1;continue}let l=s;for(;l+1<o.length&&o[l+1]===null;)l+=1;let c=l-s+1,p=s>0?r[s-1]:null,d=l+1<o.length?o[l+1]:null,g=d!==null&&n!==null?Math.min(d,n):d??n;for(let f=0;f<c;f+=1)r[s+f]=g!==null?g-(c-f):p!==null?p+f+1:PP+f;s=l+1}return r.map(i=>new Date(i).toISOString())}function QC(e,t){let n=LP(e,t?.beforeCreatedAt),o=[];return e.forEach((r,s)=>{if(typeof r?.id!="string"||r.id===""||!TP.includes(r.role))return;let i=r.role,l=n[s];if(r.displayAvailable===!1){let c={historyDisplayUnavailable:!0};o.push({id:r.id,role:i,content:"",createdAt:l,agentMetadata:c});return}if(typeof r.displayContent=="string"){o.push({id:r.id,role:i,content:r.displayContent,createdAt:l});return}if(typeof r.content=="string"){o.push({id:r.id,role:i,content:r.content,createdAt:l});return}if(Array.isArray(r.content)){let c=r.content.map(kP).filter(d=>d!==null),p=zd(c);o.push({id:r.id,role:i,content:p||(Pa(c)?Ta:""),createdAt:l,...c.length>0&&{contentParts:c}});return}o.push({id:r.id,role:i,content:"",createdAt:l})}),o}function Fl(e){let t=e.content;if(typeof t!="string"||t==="")return;let n=e.contentParts??e.llmContent??e.rawContent??t;if(!(typeof n=="string"&&n===t))return t}function $l(e,t){let n=new Map;for(let o of e)n.set(o.id,o);for(let o of t)n.set(o.id,o);return[...n.values()].sort((o,r)=>{let s=new Date(o.createdAt).getTime(),i=new Date(r.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(i)&&s!==i)return s-i;let l=o.sequence??0,c=r.sequence??0;return l!==c?l-c:o.id.localeCompare(r.id)})}var TP,PP,yp=Ve(()=>{"use strict";Nr();TP=["user","assistant","system"],PP=0});function RP(e,{HistoryClientError:t,HistoryProviderError:n}){if(e instanceof n)return e;if(e instanceof t){let o=HP.get(e.code)??"unavailable";return new n(o,Jf(o),{...e.retryAfterSeconds!==void 0?{retryAfterSeconds:e.retryAfterSeconds}:{}})}return new n("unavailable",Jf("unavailable"))}function JC(e){let{HistoryProviderError:t}=e.errors,n=()=>e.getClient?.()??e.client,o=e.getIdentityProofConfigured()?["browser","verified-user"]:["browser"],r={scopes:o},s=c=>{if(!o.includes(c))throw new t("unsupported_scope",Jf("unsupported_scope"))},i=async(c,p)=>{s(c);try{return await p()}catch(d){throw RP(d,e.errors)}},l=c=>{let p=!1;return{conversationId:c.session.conversationId??"",conversationRevision:c.session.conversationRevision??"",async commit(){p||(p=!0,c.commit(),await e.onActivationCommitted(c.session))},discard(){p||(p=!0,c.discard())}}};return{capabilities:r,getIdentityStatus(){return n().getHistoryIdentityStatus()},subscribeIdentityStatus(c){return n().subscribeHistoryIdentityStatus(c)},subscribeAvailability(c){return n().subscribeHistoryAvailability(c)},async list(c){return i(c.context.scope,async()=>{let p=await n().listConversations({...c.cursor?{cursor:c.cursor}:{},...c.limit!==void 0?{limit:c.limit}:{},...c.targetId?{targetId:c.targetId}:{},scope:c.context.scope});return{items:p.data,nextCursor:p.nextCursor}})},async getPage(c,p){return i(p.context.scope,async()=>{let d=await n().getConversation(c,{...p.cursor?{messageCursor:p.cursor}:{},scope:p.context.scope}),g=QC(d.messages,{...p.beforeCreatedAt?{beforeCreatedAt:p.beforeCreatedAt}:{}});return{summary:d.summary,messages:$l([],g),conversationRevision:d.conversationRevision??"",nextCursor:d.nextMessageCursor}})},async prepareOpen(c,p){return i(p.context.scope,async()=>l(await n().prepareConversationSession(c)))},async prepareStartNew(c){return i(c.context.scope,async()=>l(await n().prepareNewConversationSession()))},async delete(c,p){await i(p.context.scope,()=>n().deleteConversation(c,{scope:p.context.scope}))},async deleteAll(c){return i(c.context.scope,()=>n().deleteAllConversations({...c.targetId!==void 0?{targetId:c.targetId}:{},scope:c.context.scope}))},async resetDevice(){try{return await n().resetVisitor(),{remoteRevocationConfirmed:!0}}catch{return{remoteRevocationConfirmed:!1}}}}}var HP,IP,Jf,ZC=Ve(()=>{"use strict";yp();HP=new Map([["not_found","not_found"],["conversation_deleted","not_found"],["rate_limited","rate_limited"],["authentication_required","authentication_required"],["invalid_identity_proof","authentication_required"],["visitor_identity_mismatch","authentication_required"],["visitor_required","authentication_required"],["identity_provider_failed","identity_provider_failed"],["proof_not_admitted","proof_not_admitted"],["identity_contract_violation","proof_not_admitted"],["unauthorized","authentication_failed"],["visitor_token_missing","authentication_failed"],["conversation_credential_missing","authentication_failed"]]),IP=new Map([["not_found","That conversation is no longer available."],["rate_limited","Too many history requests."],["authentication_failed","History access was not authorized."],["authentication_required","Sign in again to view account history."],["identity_provider_failed","The identity provider did not respond."],["proof_not_admitted","Account history is not available for this configuration."],["unsupported_scope","This history scope is not supported."],["unavailable","Conversation history is unavailable right now."]]),Jf=e=>IP.get(e)??"Conversation history is unavailable right now."});var bp={};ys(bp,{createHistoryShell:()=>WP});var WP,Zf=Ve(()=>{"use strict";UC();zC();Je();mp();Bo();ZC();WP=e=>{let o=Yf(e.config.features?.history?.copy),r=null,s=!1,i=null,l=null,c="conversation",p=null,d=null,g=null,f=null,h=0,y=null,v=null,C=null,A=`persona-history-${Math.random().toString(36).slice(2,8)}`,L=()=>e.historyFeatureEnabled()&&!!r&&!s,I=()=>{let M=e.session.getStatus();return e.isStreaming||M==="paused"||M==="resuming"},H=()=>{let M=e.config.features?.history?.scope;if(M)return M;let N=e.config.getIdentityProof?"verified-user":"browser",ne=r?.capabilities.scopes;return!ne||ne.includes(N)?N:ne[0]??N},_=()=>l?.scope??H(),V=()=>e.session.getClientSession()?.targetId??null,oe=M=>`${M.state}:${"reason"in M?M.reason:""}`,W=M=>{let N=oe(M);N!==f&&(f=N,e.eventBus.emit("history:identityStatusChanged",{status:M,timestamp:Date.now()}))},j=null,X=null,E=()=>{if(!e.historyFeatureEnabled())return null;let M=e.getHistoryProviderFactory();if(M)return M();let N=e.config.features?.history?.provider;return N?typeof N!="function"?N:(j!==N&&(j=N,X=N()),X):e.session.isClientTokenMode()?JC({errors:e.historyErrors,client:e.session.getClient(),getIdentityProofConfigured:()=>typeof e.config.getIdentityProof=="function",onActivationCommitted:ne=>e.session.bindActivatedSession(ne),getClient:()=>e.session.getClient()}):null},T=()=>{v?.(),v=null,C?.(),C=null,s=!1,r=E();let M={...e.historyInternals};r?M.historyProvider=r:delete M.historyProvider,e.historyInternals=M,e.session.setHistoryInternals(e.historyInternals),r&&(v=r.subscribeAvailability?.(N=>{s=!N,N||xn({restoreFocus:!1}),jn()})??null,C=r.subscribeIdentityStatus(N=>W(N)),f=oe(r.getIdentityStatus()))},B=()=>{let M=e.config.features?.history?.presentation??"panel";if(M==="panel"||M==="auto"&&!(!e.launcherEnabled||e.isDockedMountMode(e.config)))return"panel";let N=e.artifactSplitRoot??e.container;return(N.getBoundingClientRect().width||N.clientWidth)>=720?"rail":"panel"},P=(M,N)=>{N?(M.setAttribute("aria-hidden","true"),M.setAttribute("inert","")):(M.removeAttribute("aria-hidden"),M.removeAttribute("inert"))},J="data-persona-history-suppressed",U=null,ue=null,fe=null,me=null,He=null,Ee="",Ie=()=>e.header===He?Ee:e.config.layout?.showHeader===!1?"none":"",yt=()=>e.historyPresentation==="panel"&&!!fe&&me===fe.element&&e.config.layout?.showHeader!==!1&&Ie()!=="none",qe=()=>{for(let M of Array.from(e.header.children))M!==U&&M.setAttribute(J,"")},Oe=()=>{for(let M of Array.from(e.container.querySelectorAll(`[${J}]`)))M.removeAttribute(J)},$=()=>{let M=fe;if(!M)return;if(Array.from(e.header.children).some(pe=>pe!==U&&!pe.hasAttribute(J))){ue&&ue!==e.header&&(ue.style.removeProperty("min-height"),ue=null);let pe=e.header.offsetHeight;pe>0&&(e.header.style.minHeight=`${pe}px`,ue=e.header)}U||(U=x("div","persona-history-header-host")),M.setHeaderPlacement("external");let ne=M.getHeaderElement();ne.parentNode!==U&&U.replaceChildren(ne),U.parentNode!==e.header&&e.header.appendChild(U),qe()},Be=()=>{ue&&(ue.style.removeProperty("min-height"),ue=null),U&&(fe?.setHeaderPlacement("inline"),U.remove(),U=null,Oe())},ye=null,ut=()=>{if(ye){if(e.body.style.display="none",P(e.body,!0),e.footer.hidden=!0,P(e.footer,!0),yt()){$(),e.header.style.display=Ie(),P(e.header,!1);return}Be(),e.header.style.display="none",P(e.header,!0)}};e.reapplyHistoryHostChrome=ut;let Zt=M=>{let N=e.body.style.display,ne=e.footer.hidden,pe=e.footer,Re=e.header,$t=e.header.style.display;He=Re,Ee=$t,ye=()=>{ye=null,Be(),He=null,e.body.style.display=N,P(e.body,!1),pe.hidden=ne,P(pe,!1),e.footer!==pe&&(e.footer.hidden=!1,P(e.footer,!1)),Re.style.display=$t,P(Re,!1),e.header!==Re&&(e.header.style.display=e.config.layout?.showHeader===!1?"none":"",P(e.header,!1))},e.footer.parentNode?.insertBefore(M,e.footer),ut()},xt=null,xe=null,Wt=null,vt=null,Le=()=>[e.header,e.panelElements.closeButtonWrapper,e.panelElements.clearChatButtonWrapper,e.body,e.footer],Ye=52,D=()=>e.config.features?.history?.rail?.collapsible!==!1,S=()=>e.config.features?.history?.rail?.side==="right"?"right":"left",F=200,z=400,K=M=>Math.min(z,Math.max(F,Math.round(M))),te=()=>e.config.features?.history?.rail?.resizable===!0,ve,Ce=()=>{if(ve===void 0&&(ve=null,e.config.persistState!==!1))try{let M=Number(window.localStorage.getItem(`${e.currentKeyPrefix()}rail-width`));M&&(ve=M)}catch{}return ve},Me=()=>K(Ce()??e.config.features?.history?.rail?.width??260),ot=M=>{if(ve=M,e.config.persistState!==!1)try{window.localStorage.setItem(`${e.currentKeyPrefix()}rail-width`,String(M))}catch{}},Ct=()=>D()&&e.config.features?.history?.rail?.collapsedBehavior==="overlay",De=!1,Xe=M=>{let N=x("img");return N.src=M,N.alt="",N.setAttribute("aria-hidden","true"),N},pn=()=>{let M=e.config.features?.history?.rail?.brand;if(!M)return;let N=!1,ne;return pe=>{if(M.render)try{return M.render({collapsed:pe})??null}catch(Re){return N||(N=!0,console.warn("[persona] history rail brand threw",Re)),null}return ne===void 0&&(M.iconUrl?ne=Xe(M.iconUrl):ne=M.icon?e.renderLucideIcon(M.icon,20):null),ne?ne.cloneNode(!0):null}},xo=()=>e.config.features?.history?.rail?.sections?.map(M=>{let N=!1,ne=pe=>{N||(N=!0,console.warn("[persona] history rail section threw",M.id,pe))};return{id:M.id,title:M.title,placement:M.placement??"above-conversations",items:M.items.map(pe=>{let Re;return{id:pe.id,label:pe.label,badge:pe.badge,iconNode:()=>{if(Re!==void 0)return Re;try{pe.renderIcon?Re=pe.renderIcon()??null:pe.iconUrl?Re=Xe(pe.iconUrl):Re=pe.icon?e.renderLucideIcon(pe.icon,20):null}catch($t){ne($t),Re=null}return Re},onSelect:()=>{try{pe.onSelect()}catch($t){ne($t)}}}})}})??[],ft=M=>{let N=xo();for(let ne of M)N.some(pe=>pe.id===ne.id)?console.warn("[persona] duplicate history rail section id",ne.id):N.push(ne);return N.length?N:void 0},bt=null,Ft=()=>`${e.currentKeyPrefix()}rail-collapsed`,Bi=()=>{if(bt===null&&(bt=e.config.features?.history?.rail?.defaultCollapsed===!0,e.config.persistState!==!1))try{let M=window.localStorage.getItem(Ft());M&&(bt=M==="1")}catch{}return bt},rn=M=>{if(bt=M,e.config.persistState!==!1)try{window.localStorage.setItem(Ft(),M?"1":"0")}catch{}},Sn=()=>e.historyPresentation==="rail"&&D()&&!Ct()&&Bi(),ao=()=>{},_i=()=>{if(Ct()){ao();return}rn(!Bi()),i?.view.setCollapsed(Sn()),e.applyRailChrome(),e.repinAnchoredMessage()},Di=()=>{let M=e.config.features?.history?.rail?.collapseShortcut;return!M||!gp(M)?null:{combo:M,hint:fp(M),aria:Nl(M)}},Qa=300,cr="var(--persona-history-overlay-margin,8px)",un=null,Un=null,dr=0,Vn=null,pr=null,Uo=!1,Yr=0,Cc=()=>window.matchMedia?.("(pointer: coarse)").matches===!0,eo=()=>L()&&Ct()&&(e.historyPresentation??B())==="rail",Dh=()=>e.historyVisible&&!De,ur=()=>{pr!==null&&clearTimeout(pr),pr=null},Bs=()=>{e.loadHistoryView().catch(()=>{})},Ln=()=>{ur(),De&&(pr=setTimeout(()=>{pr=null,!(Uo||!De)&&(Vn?.contains(document.activeElement)||xn({restoreFocus:!1}))},Qa))},Qe=(M,N)=>{let ne=Vn?.getBoundingClientRect();if(!ne)return!1;let pe=un?.getBoundingClientRect(),Re=pe?Math.min(pe.top,ne.top):ne.top;return M>=ne.left&&M<=ne.right&&N>=Re&&N<=ne.bottom||!!pe&&M>=pe.left&&M<=pe.right&&N>=pe.top&&N<=pe.bottom},Ae=M=>{De&&(Uo=Qe(M.clientX,M.clientY),Uo?ur():pr===null&&Ln())},Xt=M=>{e.historyVisible||!eo()||(De=!0,Ke({invoker:un,keyboard:M?.keyboard===!0}).then(()=>{e.historyVisible?!Uo&&document.activeElement!==un&&xn():De=!1}))},Ze=()=>{let M=me?.querySelector('[data-persona-history-focus="collapse"]');M&&(M.setAttribute("aria-label",De?o.expandLabel:o.collapseLabel),M.setAttribute("aria-expanded",De?"false":"true"))},we=()=>{rn(!1);let M=i;if(!De||!M){Ke({invoker:un});return}let N=document.activeElement===un;De=!1,Ni(),M.element.remove(),Ht(M.element),Ze(),N&&mt(),e.repinAnchoredMessage(),jn()},ae=()=>{rn(!0),xn()};ao=()=>{!e.historyVisible||De?we():ae()};let Te=()=>{let M=Di(),N=e.createHeaderIconButton({ariaLabel:o.expandLabel,iconName:"panel-left",wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center",extraClassName:"persona-rail-trigger",tooltip:!1,attrs:{"data-persona-rail-trigger":"","aria-controls":A,...M?{"aria-keyshortcuts":M.aria}:{}}}),ne=N.button;ne.addEventListener("mouseenter",()=>{Uo=!0,ur(),!(Cc()||Date.now()<Yr)&&Xt()}),ne.addEventListener("mouseleave",()=>{Uo=!1,Yr=0,Ln()}),ne.addEventListener("focus",()=>{e.historyVisible||Bs()}),ne.addEventListener("click",pe=>{L()&&(pe.detail!==0&&Cc()&&!e.historyVisible?Xt():we())}),un=ne,Un=N.wrapper},gr=()=>{if(Un&&!Un.isConnected&&(Un=null,un=null),!eo()){Un?.remove(),Un=null,un=null;return}un||Te();let M=Un,N=un;if(!M||!N)return;let ne=S()!=="right"?e.header.firstChild:null;(ne??e.header.lastChild)!==M&&e.header.insertBefore(M,ne),M.style.display=Dh()||dr>0?"none":"",N.setAttribute("aria-label",o.expandLabel),N.setAttribute("aria-expanded",e.historyVisible?"true":"false"),Vn&&e.applyRailChrome()},Xr=M=>{if(!De)return;let N=M.target;N instanceof Node&&(Vn?.contains(N)||Un?.contains(N)||N instanceof Element&&N.closest('.persona-dropdown-menu,[role="alertdialog"]')||xn({restoreFocus:!1}))};document.addEventListener("pointerdown",Xr,!0),e.destroyCallbacks.push(()=>{document.removeEventListener("pointerdown",Xr,!0),document.removeEventListener("pointermove",Ae),ce?.(),ur()});let lo=null,ce=null,Pe=16,An=M=>{ot(K(M)),e.applyRailChrome(),e.repinAnchoredMessage()},rt=()=>{let M=x("div","persona-rail-resizer");return M.tabIndex=0,M.setAttribute("role","separator"),M.setAttribute("aria-orientation","vertical"),M.setAttribute("aria-valuemin",String(F)),M.setAttribute("aria-valuemax",String(z)),M.addEventListener("pointerdown",N=>{let ne=xe;if(!ne||N.button!==0)return;N.preventDefault(),ce?.();let pe=N.clientX,Re=ne.getBoundingClientRect().width||Me(),$t=S()==="right"?-1:1,Ot=Re,Bt=e.mount.ownerDocument;ne.style.transition="none";let je=be=>{Ot=K(Re+$t*(be.clientX-pe)),ne.style.flex=`0 0 ${Ot}px`,M.setAttribute("aria-valuenow",String(Ot))},at=()=>{ce=null,Bt.removeEventListener("pointermove",je),Bt.removeEventListener("pointerup",at),Bt.removeEventListener("pointercancel",at),ne.style.removeProperty("transition");try{M.releasePointerCapture(N.pointerId)}catch{}An(Ot)};ce=at,Bt.addEventListener("pointermove",je),Bt.addEventListener("pointerup",at),Bt.addEventListener("pointercancel",at);try{M.setPointerCapture(N.pointerId)}catch{}}),M.addEventListener("keydown",N=>{let ne=S()==="right"?-Pe:Pe,pe=Me(),Re=N.key==="ArrowRight"?pe+ne:N.key==="ArrowLeft"?pe-ne:N.key==="Home"?F:N.key==="End"?z:null;Re!==null&&(N.preventDefault(),An(Re))}),M},en=(M,N)=>{if(!te()||Sn()){ce?.(),lo?.remove();return}let ne=lo??rt();lo=ne,ne.setAttribute("aria-label",o.resizeLabel),ne.setAttribute("aria-valuenow",String(Me())),ne.nextElementSibling!==N&&M.insertBefore(ne,N)};e.applyRailChrome=()=>{i?.view.setRailSide(S());let M=S()==="right",N=Vn;if(N){let Bt=un?un.getBoundingClientRect().bottom-e.container.getBoundingClientRect().top:0;N.style.top=`calc(${Math.max(0,Math.round(Bt))}px + ${cr})`,N.style.width=`${Me()}px`,N.style.left=M?"":cr,N.style.right=M?cr:""}let ne=xe,pe=xt,Re=Wt;if(!ne||!pe||!Re)return;ne.style.flex=`0 0 ${Sn()?Ye:Me()}px`;let $t="1px solid var(--persona-divider,#e5e7eb)";ne.style.borderRight=M?"":$t,ne.style.borderLeft=M?$t:"";let Ot=M?Re:ne;pe.firstElementChild!==Ot&&pe.append(Ot,M?ne:Re),en(pe,M?ne:Re)};let wc=M=>{if(vt&&xe){vt.replaceWith(M),vt=null,e.applyRailChrome();return}let N=x("div","persona-history-rail-shell");N.style.cssText="display:flex;flex-direction:row;flex:1 1 auto;min-height:0";let ne=x("div","persona-history-rail-conversation");ne.style.cssText="display:flex;flex-direction:column;flex:1 1 auto;min-width:0;min-height:0;position:relative";let pe=x("div","persona-history-rail-host");pe.style.cssText="display:flex;min-height:0;overflow:hidden",e.container.insertBefore(N,e.header.parentNode===e.container?e.header:e.body);for(let Re of Le())Re?.parentNode===e.container&&ne.appendChild(Re);N.append(pe,ne),pe.appendChild(M),xt=N,xe=pe,Wt=ne,e.applyRailChrome()},In=()=>{if(xt)return;let M=x("div","persona-history-rail-placeholder");M.style.cssText="flex:1 1 auto;min-height:0",vt=M,wc(M),e.repinAnchoredMessage()},Sc=()=>{vt&&(Ni(),e.repinAnchoredMessage())},Wu=M=>{let N=x("div","persona-history-rail-overlay");N.style.cssText=`position:absolute;bottom:${cr};display:flex;overflow:hidden;z-index:${wa-1};border-radius:var(--persona-history-overlay-radius,16px);background:var(--persona-history-overlay-bg,var(--persona-container,#f7f7f8));box-shadow:var(--persona-history-overlay-shadow,0 12px 40px rgba(0,0,0,0.25))`,e.container.style.position="relative",e.container.appendChild(N),N.appendChild(M),document.addEventListener("pointermove",Ae),Vn=N,e.applyRailChrome(),Ze()},Ni=()=>{ye?.(),Vn&&(Uo&&(Yr=Date.now()+150),document.removeEventListener("pointermove",Ae),Vn.remove(),Vn=null);let M=xt;if(M){ce?.();for(let N of Le())N&&M.contains(N)&&e.container.insertBefore(N,M);M.remove(),xt=null,xe=null,Wt=null,vt=null}},ze=M=>{me=M,M.id=A,M.style.flex="1 1 auto",M.style.minHeight="0"},Ht=M=>{ze(M),(e.historyPresentation!=="rail"||De)&&Sc(),e.historyPresentation!=="rail"?Zt(M):De?Wu(M):wc(M)},Vo=()=>{if(gr(),Jr(),!e.historyVisible||!i)return;let M=B();if(M===e.historyPresentation)return;let N=document.activeElement,ne=N instanceof HTMLElement&&(i.element.contains(N)||U?.contains(N)===!0)?N:null;Ni(),i.element.remove(),i.view.setHeaderPlacement("inline"),e.historyPresentation=M,i.view.setPresentation(M),i.view.setCollapsed(Sn()),i.requestRender(),i.element.isConnected||Ht(i.element),ne?.isConnected?ne.focus():mt(),e.syncScrollToBottomButton(),e.repinAnchoredMessage(),jn()},jo=(M,N)=>U?.querySelector(N)??M.querySelector(N),mt=()=>{let M=i?.element??me;if(!M)return;let N=jo(M,'[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]');if(N){N.focus();return}let ne=jo(M,".persona-history-title")??M;ne.tabIndex=-1,ne.focus()},Ke=async M=>{if(!L()||e.historyVisible)return;let N=r;if(!N)return;if(!De&&eo()&&Bi()){gr();return}Fi();let ne=++h;c=M?.returnSurface??"conversation",p=M?.invoker??d;let pe=eo()&&!De;pe&&(dr+=1,gr(),In());let Re;try{Re=await e.loadHistoryView()}catch{e.announceHistory(o.openHistoryLabel),pe&&(dr-=1,ne===h&&(Sc(),gr()));return}if(pe&&(dr-=1),ne!==h||e.historyVisible)return;l={scope:H()},e.historyPresentation=B(),e.historyVisible=!0;let $t=e.historyPresentation==="panel"&&e.config.layout?.showHeader!==!1&&e.header.style.display!=="none"?"external":"inline",Ot=e.config.features?.history?.rowAvatar,Bt=Di(),je=Bt?{hint:Bt.hint,aria:Bt.aria}:null,at={provider:N,context:l,targetId:V(),presentation:e.historyPresentation,collapsible:D(),collapsed:Sn(),railSide:S(),renderRailHeader:e.config.features?.history?.rail?.renderHeader,railBrand:pn(),onToggleCollapse:_i,...je?{collapseShortcut:je}:{},headerPlacement:$t,showScopeStatus:e.config.features?.history?.showScopeStatus!==!1,showDelete:e.config.features?.history?.showDelete!==!1,showDeleteAll:e.config.features?.history?.showDeleteAll!==!1,...e.config.features?.history?.listActions?.length?{listActions:e.config.features.history.listActions}:{},rowAvatar:Ot===!1?!1:typeof Ot=="string"?Ot:e.config.launcher?.iconUrl,activeConversationId:e.session.getActiveConversationId(),...e.config.features?.history?.grouping?{grouping:e.config.features.history.grouping}:{},...e.config.features?.history?.copy?{copy:e.config.features.history.copy}:{},...e.config.features?.history?.pageSize!==void 0?{pageSize:e.config.features.history.pageSize}:{},onSelect:be=>Mn(be,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:be=>e.setActiveConversationSummary(be),attachTooltip:e.attachTooltip,onStartNew:()=>Mo({focusComposer:!0}),onClose:()=>xn(),onRequestDeleteConversation:be=>Vt(be),onRequestClearHistory:()=>Fs(),...N.resetDevice?{onRequestResetIdentity:()=>el()}:{}};i=qC({plugins:e.plugins,config:e.config,getPresentation:()=>e.historyPresentation??"panel",getReturnSurface:()=>c,close:()=>xn(),createView:({slots:be,renderDom:Ui,onModelChange:co,railSections:mr})=>(fe=Re.createHistoryView({...at,railSections:ft(mr),slots:be,renderDom:Ui,onModelChange:co,onAnnounce:e.announceHistory}),fe),onElementChanged:(be,Ui)=>{if(!Ui?.isConnected)return Ht(be);ze(be),Ui.replaceWith(be),ut()}}),i.view.setNewConversationRequired(e.historySessionState.recovery==="new_conversation_required"),M?.focus!==!1&&(e.historyPresentation!=="rail"||M?.keyboard===!0)&&mt(),e.syncScrollToBottomButton(),e.repinAnchoredMessage(),jn(),e.eventBus.emit("history:opened",{presentation:e.historyPresentation,returnSurface:c,timestamp:Date.now()})},Fi=()=>{},xn=M=>{if(!e.historyVisible)return;h+=1;let N=c,ne=p,pe=i,Re=M?.restoreFocus!==!1;e.historyVisible=!1;let $t=!1,Ot=null,Bt=()=>{if(!$t){if($t=!0,Fi=()=>{},Ot!==null&&clearTimeout(Ot),De=!1,ur(),Ni(),pe?.dispose(),pe?.view.destroy(),pe?.element.remove(),i===pe&&(i=null,fe=null,me=null,e.historyPresentation=null,l=null,p=null),e.syncScrollToBottomButton(),e.repinAnchoredMessage(),jn(),Re){let at=ne??d;at?.isConnected?at.focus():e.maybeFocusInput()}e.eventBus.emit("history:closed",{returnSurface:N,timestamp:Date.now()})}},je=pe&&pe.element===pe.view.element?pe.view.playExit():null;if(!je){Bt();return}Fi=Bt,Ot=setTimeout(Bt,250),je.then(Bt)},_s=M=>{if(!(M.key!=="Escape"||!e.historyVisible||!i)){if(e.historyPresentation==="rail"){let N=M.target;if(!(N instanceof Node)||!(i.element.contains(N)||De&&Un?.contains(N)===!0))return}M.preventDefault(),M.stopPropagation(),xn()}};e.container.addEventListener("keydown",_s),e.destroyCallbacks.push(()=>e.container.removeEventListener("keydown",_s));let Rn=0,Ac=250,he=null,gn=()=>{he&&clearTimeout(he),he=null};e.destroyCallbacks.push(gn);let It=()=>{gn();let M=e.conversationOpenPendingEl;M&&(e.conversationOpenTakeover=!0,M.hidden=!1,e.messagesWrapper.style.display="none",e.updateWelcome())},sn=()=>{Rn+=1,gn(),e.conversationOpenPendingEl&&(e.conversationOpenPendingEl.remove(),e.conversationOpenPendingEl=null,e.conversationOpenTakeover=!1,e.messagesWrapper.style.removeProperty("display"),P(e.footer,!1),e.updateWelcome())},Mt=()=>{try{if(window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches)return;e.messagesWrapper.animate([{opacity:0},{opacity:1}],{duration:150,easing:"ease-out"})}catch{}},fn=(M,N)=>Q("div",{className:_n("persona-conversation-loading-bubble",N&&"persona-conversation-loading-bubble--trailing"),attrs:{"aria-hidden":"true"},style:{width:M}}),xc=()=>Q("div",{className:"persona-conversation-loading-body"},fn("58%",!1),fn("72%",!0),fn("44%",!1)),Qr=M=>{e.conversationOpenPendingEl?.remove(),e.conversationOpenPendingEl=M,M.hidden=!e.conversationOpenTakeover,e.body.insertBefore(M,e.messagesWrapper),gn(),e.conversationOpenTakeover||(he=setTimeout(It,Ac)),P(e.footer,!0)},Ou=()=>{let M={config:e.config,streaming:!1,location:"conversation-open",defaultRenderer:xc},N=null,ne=e.plugins.find(pe=>pe.renderLoadingIndicator);ne?.renderLoadingIndicator&&(N=ne.renderLoadingIndicator(M)),N===null&&e.config.loadingIndicator?.render&&(N=e.config.loadingIndicator.render(M)),Qr(Q("div",{className:"persona-conversation-loading",attrs:{role:"status","aria-label":o.openConversationLoadingLabel}},N??xc()))},Bu=M=>{let N=()=>{Mn(M,{focusComposer:!0}).catch(()=>{})},ne=L()?()=>{sn(),Ke()}:void 0,pe=(Bt,je)=>{let at=Q("button",{className:"persona-conversation-loading-error-action",attrs:{type:"button"},text:Bt});return at.addEventListener("click",je),at},Re=()=>Q("div",{className:"persona-conversation-loading-error-body"},Q("p",{className:"persona-conversation-loading-error-title",text:o.openConversationErrorTitle}),Q("div",{className:"persona-conversation-loading-error-actions"},pe(o.openConversationRetryLabel,N),ne?pe(o.openConversationBackLabel,ne):null)),$t=Object.freeze({conversationId:M,config:e.config,copy:Object.freeze({title:o.openConversationErrorTitle,retryLabel:o.openConversationRetryLabel,backLabel:o.openConversationBackLabel}),retry:N,...ne?{back:ne}:{},defaultRenderer:Re}),Ot=null;for(let Bt of e.plugins)if(Bt.renderHistoryOpenError){try{Ot=Bt.renderHistoryOpenError($t)}catch(je){console.warn("[persona] renderHistoryOpenError threw",je),Ot=null}if(Ot)break}Qr(Q("div",{className:"persona-conversation-loading-error",attrs:{role:"alert"}},Ot??Re())),It()};e.eventBus.on("history:closed",()=>{e.conversationOpenPendingEl&&P(e.footer,!0)});let Mn=async(M,{focusComposer:N=!1}={})=>{let ne=_(),pe=!!i;i?.view.setActiveConversationId(M),sn();let Re=Rn;Ou(),e.historyVisible&&(e.historyPresentation==="panel"||De)&&xn({restoreFocus:!1}),e.suppressScrollSend=!0;try{await e.session.openConversation(M,{scope:ne})}catch($t){throw Re===Rn&&Bu(M),$t}finally{e.suppressScrollSend=!1}Re===Rn&&(sn(),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),e.restoreScrollPosition()||e.jumpToBottomInstant(),Mt(),Qt(),pe||e.setActiveConversationSummary(null),e.eventBus.emit("history:conversationOpened",{conversationId:M,title:e.activeConversationTitle,scope:ne,timestamp:Date.now()}),N&&e.maybeFocusInput())},Mo=async({focusComposer:M=!1}={})=>{sn(),await e.session.startNewConversation({scope:_()}),e.setActiveConversationSummary(null),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),e.jumpToBottomInstant(),Qt();let N=e.session.getActiveConversationId();i?.view.setActiveConversationId(N),e.eventBus.emit("history:conversationStarted",{conversationId:N,timestamp:Date.now()}),e.historyVisible&&(e.historyPresentation==="panel"||De)&&xn({restoreFocus:!1}),M&&e.maybeFocusInput()},Ds=async(M,N)=>{let ne=await e.session.updateConversation(M,{...N,...N.title!==void 0?{title:N.title.trim()}:{}});return i?.view.applyConversationSummary(ne),!i&&M===e.session.getActiveConversationId()&&e.setActiveConversationSummary(ne),ne},Mc=async M=>{let N=_(),ne=e.session.getActiveConversationId()===M;await e.session.deleteConversation(M,{scope:N}),i?.view.removeConversationSummary(M),ne&&(e.setActiveConversationSummary(null),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),Qt()),e.eventBus.emit("history:conversationDeleted",{conversationId:M,scope:N,wasActive:ne,timestamp:Date.now()})},Ja=async M=>{let N=M?.scope??_(),ne=M?.allTargets?null:M?.targetId??V(),pe=await e.session.clearConversationHistory({...ne?{targetId:ne}:{},scope:N});return e.setActiveConversationSummary(null),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),Qt(),e.eventBus.emit("history:cleared",{deleted:pe.deleted,scope:N,targetId:ne,timestamp:Date.now()}),pe},Za=async()=>{if(!r?.resetDevice)throw new Error("[Persona] resetHistoryIdentity() requires a history provider that can reset this device");let M=!1;try{M=(await e.session.resetHistoryDevice()).remoteRevocationConfirmed}finally{e.setActiveConversationSummary(null),e.session.clearArtifacts(),e.messageCache.clear(),e.lastAppliedMessages=null,e.config.clearStoredSessionId?.(),e.config.clearStoredConversationId?.(),e.persistentMetadata={},e.actionManager.syncFromMetadata();let N=e.storageAdapter;N?.clear&&e.runStorageMutation(()=>N.clear(),"[AgentWidget] Failed to clear storage adapter:"),e.resetAnchorState(),e.resumeAutoScroll(),Qt(),xn({restoreFocus:!1}),e.maybeFocusInput(),e.open||e.launcherSurfaceInstance?.launcher.element.focus()}return e.announceHistory(M?o.identityResetNotice:o.identityResetUnconfirmedNotice),e.eventBus.emit("history:identityReset",{remoteRevocationConfirmed:M,timestamp:Date.now()}),{remoteRevocationConfirmed:M}},$i=()=>e.artifactSplitRoot?e.panel:e.container,Ns=async M=>{let N=await e.loadHistoryView().catch(()=>null);return typeof N?.showHistoryConfirm=="function"?N.showHistoryConfirm(M):window.confirm(`${M.title}
|
|
12
12
|
|
|
13
|
-
${M.description}`)},Vt=async M=>await Ns({host:$i(),title:o.deleteConversationConfirmTitle,description:o.deleteConversationConfirm,confirmLabel:o.deleteConversationConfirmLabel,cancelLabel:o.confirmCancelLabel})?(await Mc(M),"deleted"):"cancelled",Fs=async()=>{let M=_()==="verified-user";return await Ns({host:$i(),title:o.clearHistoryConfirmTitle,description:M?o.clearHistoryVerifiedConfirm:o.clearHistoryConfirm,confirmLabel:o.clearHistoryConfirmLabel,cancelLabel:o.confirmCancelLabel})?(await Ja(),"cleared"):"cancelled"},el=async()=>{if(!await Ns({host:$i(),title:o.resetIdentityConfirmTitle,description:o.resetIdentityConfirm,confirmLabel:o.resetIdentityConfirmLabel,cancelLabel:o.confirmCancelLabel}))return{outcome:"cancelled"};let{remoteRevocationConfirmed:N}=await Za();return{outcome:"reset",remoteRevocationConfirmed:N}},tn=x("button","persona-history-earlier");tn.type="button",tn.textContent=o.showEarlierMessagesLabel,tn.setAttribute("data-persona-history-earlier",""),Object.assign(tn.style,{alignSelf:"center",minHeight:"44px",padding:"0 16px",borderRadius:"999px",border:"1px solid var(--persona-border, rgba(0,0,0,0.12))",background:"transparent",color:"inherit",font:"inherit",cursor:"pointer",flexShrink:"0"});let Qt=()=>{if(!(L()&&!!e.historySessionState.nextMessageCursor&&!!e.session.getActiveConversationId())){tn.remove();return}tn.textContent=o.showEarlierMessagesLabel,tn.parentNode!==e.body&&e.body.insertBefore(tn,e.body.firstChild)};tn.addEventListener("click",()=>{let M=e.session.getActiveConversationId(),N=e.historySessionState.nextMessageCursor;if(!M||!N||tn.disabled)return;tn.disabled=!0;let ne=e.body.scrollHeight,pe=e.body.scrollTop;e.session.loadOlderMessages(M,N,{scope:_()}).then(()=>{e.body.scrollTop=pe+(e.body.scrollHeight-ne),e.repinAnchoredMessage()}).catch(()=>{}).finally(()=>{tn.disabled=!1,Qt()})});let Eo=()=>{let M=e.createHeaderIconButton({ariaLabel:o.openHistoryLabel,iconName:"history",wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center",extraClassName:"persona-history-toggle",attrs:{"data-persona-history-toggle":""}});return M.button.addEventListener("click",N=>{if(!(!L()||I())){if(e.historyVisible){xn();return}Ke({invoker:M.button,keyboard:N.detail===0})}}),M},Jr=()=>{if(!L()){g?.remove(),d=null,g=null;return}if(g&&!g.isConnected&&(d=null,g=null),!d&&e.header){let pe=Eo();d=pe.button,g=pe.wrapper;let Re=e.panelElements.clearChatButtonWrapper||e.panelElements.closeButtonWrapper;Re?.parentNode&&e.header.contains(Re)?Re.parentNode.insertBefore(g,Re):e.header.appendChild(g)}if(!d||!g)return;let M=eo()||e.historyVisible&&e.historyPresentation==="rail";if(g.style.display=M?"none":"",M){document.activeElement===d&&mt();return}let N=I();d.disabled=N,d.setAttribute("aria-disabled",N?"true":"false");let ne=N?o.openHistoryBusyLabel:o.openHistoryLabel;d.setAttribute("aria-label",ne),(e.config.features?.history?.presentation??"panel")==="panel"?(d.removeAttribute("aria-expanded"),d.removeAttribute("aria-controls")):(d.setAttribute("aria-expanded",e.historyVisible?"true":"false"),d.setAttribute("aria-controls",A))},fr=!1,$s=()=>{let M=e.panelElements.clearChatButton;if(M){if(L()){fr||(y=M.getAttribute("aria-label")??"",fr=!0),M.setAttribute("aria-label",o.newConversationLabel),M.removeAttribute("title");return}fr&&(fr=!1,y&&M.setAttribute("aria-label",y))}},jn=()=>{o=Yf(e.config.features?.history?.copy),Jr(),gr(),$s(),Qt()};return e.historyChromeSync=jn,T(),jn(),e.destroyCallbacks.push(()=>{v?.(),C?.(),h+=1,Fi(),i?.dispose(),i?.view.destroy(),i=null}),{historyAvailable:L,historyScope:H,installHistoryProvider:T,syncHistoryChromeImpl:jn,syncHistoryPresentation:Vo,syncEarlierMessagesPill:Qt,openHistory:Ke,closeHistory:xn,openHistoryConversation:Mn,startNewConversation:Mo,updateHistoryConversation:Ds,deleteHistoryConversation:Mc,requestDeleteConversation:Vt,clearConversationHistory:Ja,resetHistoryIdentity:Za,railCollapseShortcut:Di,railCollapsible:D,railTriggerApplies:eo,railOverlayMode:Ct,toggleRailCollapsed:_i,toggleRailPinned:()=>ao(),get historyProvider(){return r},get historySurface(){return i},get railShell(){return xt},get railHost(){return xe},get railColumn(){return Wt}}}});var Ra,dm=Ve(()=>{"use strict";Ra=class{#e=null;#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 pk(e){return e.replace(/\/+$/,"")}async function uk(e){try{let t=await e.json();return t.detail?`${t.error??`Runtype TTS ${e.status}`}: ${t.detail}`:t.error??`Runtype TTS request failed (${e.status})`}catch{return`Runtype TTS request failed (${e.status})`}}var Lp,Ww=Ve(()=>{"use strict";dm();Lp=class{constructor(t){this.id="runtype-tts";this.supportsPause=!0;this.#e=null;this.#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 Ra(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=`${pk(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 uk(i));let l=i.body.getReader();for(;;){let{done:c,value:p}=await l.read();if(t!==this.#o){await l.cancel().catch(()=>{});return}if(c)break;p&&p.byteLength>0&&r.enqueue(p)}r.markStreamEnd()}catch(r){if(t!==this.#o)return;let s=r instanceof Error?r:new Error(String(r));this.#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 Hp,Ow=Ve(()=>{"use strict";Hp=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 Bw={};ys(Bw,{FallbackSpeechEngine:()=>Hp,RuntypeSpeechEngine:()=>Lp});var _w=Ve(()=>{"use strict";Ww();Ow()});var LI={};ys(LI,{ASK_USER_QUESTION_CLIENT_TOOL:()=>mf,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>ff,ASK_USER_QUESTION_TOOL_NAME:()=>Hl,AgentWidgetClient:()=>wi,AgentWidgetSession:()=>Wa,AttachmentManager:()=>Ai,BrowserSpeechEngine:()=>ks,DEFAULT_COMPONENTS:()=>TS,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>vC,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>vi,DEFAULT_PALETTE:()=>xS,DEFAULT_SEMANTIC:()=>ES,DEFAULT_WIDGET_CONFIG:()=>wC,HistoryProviderError:()=>Vr,PRESETS:()=>Ih,PRESET_FULLSCREEN:()=>Hh,PRESET_MINIMAL:()=>Lh,PRESET_SHOP:()=>kh,ReadAloudController:()=>Si,SUGGEST_REPLIES_CLIENT_TOOL:()=>Wd,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>uf,SUGGEST_REPLIES_TOOL_NAME:()=>Oo,THEME_ZONES:()=>kS,VERSION:()=>Yn,WEBMCP_TOOL_PREFIX:()=>Ml,WebMcpBridge:()=>Iu,accessibilityPlugin:()=>kx,animationsPlugin:()=>Lx,applyFeaturePreferences:()=>fh,applyThemeVariables:()=>Mi,attachHeaderToContainer:()=>Ti,brandPlugin:()=>Hx,buildComposer:()=>ki,buildDefaultHeader:()=>_m,buildHeader:()=>jr,buildHeaderWithLayout:()=>Na,buildMinimalHeader:()=>Dm,builtInClientToolsForDispatch:()=>fi,canonicalArtifactDisplayMode:()=>Gn,collectEnrichedPageContext:()=>xx,componentRegistry:()=>Fo,createActionManager:()=>mc,createAgentExperience:()=>yu,createAskUserQuestionBubble:()=>Lv,createBestAvailableVoiceProvider:()=>Pu,createBubbleWithLayout:()=>pA,createCSATFeedback:()=>fu,createComboButton:()=>Qp,createComponentMiddleware:()=>ox,createComponentStreamParser:()=>pu,createDefaultSanitizer:()=>nm,createDemoCarousel:()=>Gx,createDirectivePostprocessor:()=>cw,createDropdownMenu:()=>Pi,createFlexibleJsonStreamParser:()=>yv,createIconButton:()=>Zn,createImagePart:()=>Kd,createJsonStreamParser:()=>Pd,createLabelButton:()=>Bm,createLocalStorageAdapter:()=>du,createMarkdownProcessor:()=>Vl,createMarkdownProcessorFromConfig:()=>jl,createMessageActions:()=>jm,createNPSFeedback:()=>mu,createPlainTextParser:()=>Ed,createPlugin:()=>Wx,createRegexJsonParser:()=>Td,createRovingTablist:()=>tM,createSlashCommandsSource:()=>eM,createSplitButton:()=>oA,createStandardBubble:()=>Fa,createStaticMentionSource:()=>Zx,createTextPart:()=>So,createTheme:()=>Gl,createThemeObserver:()=>Oa,createToggleGroup:()=>lc,createTypingIndicator:()=>Li,createVoiceProvider:()=>Xa,createWidgetHostLayout:()=>yc,createXmlParser:()=>kd,default:()=>Px,defaultActionHandlers:()=>Wi,defaultJsonActionParser:()=>fc,defaultMentionFilter:()=>Ru,defaultParseRules:()=>Th,detectColorScheme:()=>Xl,directivePostprocessor:()=>dw,ensureAskUserQuestionSheet:()=>Id,escapeHtml:()=>Ur,extractComponentDirectiveFromMessage:()=>gu,fileToImagePart:()=>xC,formatEnrichedContext:()=>Mx,generateAssistantMessageId:()=>Ps,generateCodeSnippet:()=>Fx,generateMessageId:()=>Sw,generateStableSelector:()=>Ph,generateUserMessageId:()=>Ha,getActiveTheme:()=>No,getAgentWidgetHandles:()=>gx,getColorScheme:()=>xi,getDisplayText:()=>zd,getHeaderLayout:()=>Nm,getImageParts:()=>AC,getPreset:()=>Tx,hasComponentDirective:()=>hc,hasImages:()=>Pa,headerLayouts:()=>Jp,highContrastPlugin:()=>Rx,initAgentWidget:()=>Ah,isAskUserQuestionMessage:()=>Ir,isComponentDirectiveType:()=>nx,isDockedMountMode:()=>Lt,isHistoryProviderError:()=>Tw,isSuggestRepliesMessage:()=>gi,isVoiceSupported:()=>_h,isWebMcpToolName:()=>bs,isWelcomeVisible:()=>Ws,latestAgentSuggestions:()=>Od,listRegisteredStreamAnimations:()=>QS,loadMarkdownParsers:()=>yd,markdownPostprocessor:()=>tm,mergeWithDefaults:()=>Ea,normalizeContent:()=>SC,normalizeMediaType:()=>vs,onMarkdownParsersReady:()=>ua,parseAskUserQuestionPayload:()=>Rr,parseSuggestRepliesPayload:()=>gf,parseWidgetPreferenceSlice:()=>gh,pickBestVoice:()=>Ia,pluginRegistry:()=>gc,reducedMotionPlugin:()=>Ix,registerIcons:()=>cv,registerStreamAnimationPlugin:()=>ec,removeAskUserQuestionSheet:()=>Wr,renderComponentDirective:()=>uu,renderLoadingIndicatorWithFallback:()=>Vm,renderLucideIcon:()=>ge,resolveArtifactDisplay:()=>rf,resolveArtifactDisplayMode:()=>or,resolveConfigPreferences:()=>uc,resolveDockConfig:()=>Jn,resolveSanitizer:()=>Pp,resolveTokens:()=>Vp,resolveWelcomeConfig:()=>Ua,stripWebMcpPrefix:()=>of,themeToCssVariables:()=>jp,unregisterStreamAnimationPlugin:()=>XS,validateImageFile:()=>MC,validateTheme:()=>Am});module.exports=BE(LI);var sv=require("marked"),iv=Bn(require("dompurify"),1);dn();var{setLoader:DI,load:_E,provide:DE,getSync:Qg}=lt({fallbackImport:()=>Promise.resolve().then(()=>(nv(),tv))}),hd=new Set,ov=()=>{let e=[...hd];hd.clear();for(let t of e)try{t()}catch{}};var yd=()=>{let e=Qg();return e?Promise.resolve(e):_E().then(t=>(ov(),t))},ua=e=>Qg()?()=>{}:(hd.add(e),()=>{hd.delete(e)}),rv=e=>{DE(e),ov()},nr=Qg;rv({Marked:sv.Marked,DOMPurify:iv.default});var G=require("lucide"),av={user:G.User,mail:G.Mail,phone:G.Phone,calendar:G.Calendar,clock:G.Clock,building:G.Building,"map-pin":G.MapPin,lock:G.Lock,key:G.Key,"credit-card":G.CreditCard,hash:G.Hash,globe:G.Globe,link:G.Link,"circle-check":G.CircleCheck,"circle-x":G.CircleX,"triangle-alert":G.TriangleAlert,info:G.Info,ban:G.Ban,shield:G.Shield,house:G.House,"pen-line":G.PenLine,save:G.Save,share:G.Share,funnel:G.Funnel,settings:G.Settings,"rotate-cw":G.RotateCw,"shopping-cart":G.ShoppingCart,"shopping-bag":G.ShoppingBag,package:G.Package,truck:G.Truck,tag:G.Tag,gift:G.Gift,receipt:G.Receipt,wallet:G.Wallet,store:G.Store,"dollar-sign":G.DollarSign,percent:G.Percent,play:G.Play,pause:G.Pause,"volume-x":G.VolumeX,camera:G.Camera,image:G.Image,film:G.Film,headphones:G.Headphones,"message-circle":G.MessageCircle,bell:G.Bell,heart:G.Heart,"eye-off":G.EyeOff,bookmark:G.Bookmark,"calendar-days":G.CalendarDays,timer:G.Timer,folder:G.Folder,"folder-open":G.FolderOpen,files:G.Files,"chart-column":G.ChartColumn,sparkles:G.Sparkles,zap:G.Zap,sun:G.Sun,moon:G.Moon,flag:G.Flag,lightbulb:G.Lightbulb,monitor:G.Monitor,smartphone:G.Smartphone};kt();dv(av);hf();dn();var{setLoader:hR,load:ST,provide:AT,getSync:xT}=lt({fallbackImport:()=>Promise.resolve().then(()=>(hf(),Dd))});var mi=ST,Dv=AT,Nv=xT;Dv(Dd);Cf();dn();var{setLoader:xR,load:_T,provide:DT}=lt({fallbackImport:()=>Promise.resolve().then(()=>(Cf(),Nd))});var Or=_T,Xv=DT;Xv(Nd);jf();dn();var{setLoader:EW,load:cP,provide:dP,getSync:pP}=lt({fallbackImport:()=>Promise.resolve().then(()=>(jf(),lp))});var cp=cP,BC=dP,qf=pP;BC(lp);Kf();dn();var{setLoader:HW,load:vP,provide:CP,getSync:wP}=lt({fallbackImport:()=>Promise.resolve().then(()=>(Kf(),pp))});var Gf=vP,NC=CP,FC=wP;NC(pp);Zf();dn();var{setLoader:GW,load:OP,provide:BP,getSync:_P}=lt({fallbackImport:()=>Promise.resolve().then(()=>(Zf(),bp))});var ew=OP,tw=BP,vp=_P;tw(bp);var Ep=require("lucide");Lr();wo();Je();kt();Je();var Cp=require("lucide");Lr();var DP=["persona-w-full","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"],NP="persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none",FP="persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none",$P=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),wp=(e,t)=>{let n=x("div",["persona-message-bubble",e,...DP].join(" "));return n.id=`bubble-${t}`,n.setAttribute("data-message-id",t),n},Sp=e=>{let t=x("button",e.expandable?NP:FP);return t.type="button",e.expandable&&(t.setAttribute("aria-expanded",e.expanded?"true":"false"),t.setAttribute("data-expand-header","true")),t.setAttribute("data-bubble-type",e.bubbleType),t},em=(e,t,n)=>{e.innerHTML="";let o=Nt(t?Cp.ChevronUp:Cp.ChevronDown,16,n,2);o?e.appendChild(o):e.textContent=t?"Hide":"Show"},La=(e,t,n)=>{if(!n.expandable)return e.append(t),null;let o=x("div","persona-flex persona-items-center");em(o,n.expanded,n.iconColor);let r=x("div",n.metaGap?"persona-flex persona-items-center persona-gap-2 persona-ml-auto":"persona-flex persona-items-center persona-ml-auto");return r.append(o),e.append(t,r),o},Ap=e=>{let t=x("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(t.setAttribute("data-persona-collapsed-preview",e.previewKind),t.style.display="none",t.style.whiteSpace="pre-wrap",!e.expanded&&e.isActive&&e.activePreview&&e.previewText){let n=e.renderPreview?.();$P(t,n)||(t.textContent=e.previewText),t.style.display=""}return!e.expanded&&e.isActive&&e.activeMinHeight&&(e.bubble.style.minHeight=e.activeMinHeight),t},xp=e=>{e.header.setAttribute("aria-expanded",e.expanded?"true":"false"),e.toggleIcon&&em(e.toggleIcon,e.expanded,e.iconColor),e.content.style.display=e.expanded?"":"none",e.collapsedPreview.style.display=e.expanded?"none":e.collapsedPreview.textContent||e.collapsedPreview.childNodes.length?"":"none"},Mp=(e,t,n)=>{let o=n.stateSet.has(e),r=t.querySelector('button[data-expand-header="true"]'),s=t.querySelector(".persona-border-t"),i=t.querySelector(`[data-persona-collapsed-preview="${n.previewKind}"]`);if(!r||!s)return;r.setAttribute("aria-expanded",o?"true":"false");let c=r.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");c&&em(c,o,n.iconColor),s.style.display=o?"":"none",i&&(i.style.display=o?"none":i.textContent||i.childNodes.length?"":"none")};function Tp(e,t){let n=t==="tool"?"toolCallDisplay":"reasoningDisplay";return{...e,features:{...e?.features,[n]:{...t==="tool"?_r:Ci,...e?.future?.v5Defaults===!0?bi.features?.[n]:{},...e?.features?.[n]}}}}function Ts(e,t){let n=t==="tool"?"toolCallDisplay":"reasoningDisplay";return e?.features?.[n]?.variant??(e?.future?.v5Defaults?"row":"card")}function Ul(e){let t=Math.max(0,Math.floor((e??0)/1e3));return t<1?"a moment":t<60?`${t}s`:`${Math.floor(t/60)}m ${t%60}s`}function $r(e,t,n,o){if(Ts(n,o)!=="row")return e;e.className=`persona-message-bubble persona-${o}-bubble persona-activity-row`,e.dataset.activityKind=o,o==="tool"&&n.toolCall?.shadow===void 0&&(e.style.boxShadow="var(--persona-tool-bubble-shadow, none)");let r=e.querySelector(":scope > button");if(!r)return e;r.className="persona-activity-header";let s=o==="tool"?t.toolCall:t.reasoning,i=s?.status!=="complete",l=t.approval?.status??t.toolCall?.approvalStatus,c=l==="denied"?"denied":l==="pending"?"awaiting-approval":t.toolCall?.success===!1?"error":i?s?.status==="pending"?"pending":"running":"done";e.dataset.activityState=c;let p=x("span","persona-activity-icon");p.dataset.activityIcon=c;let d={pending:"circle",running:"loader-circle",done:"check",error:"x",denied:"x","awaiting-approval":"clock"},g=o==="reasoning"?n.features?.reasoningDisplay?.iconName:void 0,f=g?ge(g,16,"currentColor",2):c==="pending"?Nt(Ep.Circle,16,"currentColor",2):c==="awaiting-approval"?Nt(Ep.Clock,16,"currentColor",2):ge(d[c],16,"currentColor",2);f&&p.appendChild(f),r.querySelector(".persona-reasoning-header-icon")?.remove();let h=o==="tool"?"toolCallDisplay":"reasoningDisplay",y=n.features?.[h]?.iconVisibility??(n.future?.v5Defaults?"active":"always");if((y==="always"||y==="active"&&c!=="done")&&r.prepend(p),o==="tool"&&s){let L=x("span","persona-activity-duration");i&&s.startedAt&&L.setAttribute("data-tool-elapsed",String(s.startedAt));let I=(o==="tool"?t.toolCall?.duration:void 0)??s.durationMs??(s.completedAt!==void 0&&s.startedAt!==void 0?s.completedAt-s.startedAt:void 0);L.textContent=I===void 0?"":Ul(I),r.appendChild(L)}r.querySelector(":scope > div:not(.persona-ml-auto)")?.classList.add("persona-activity-label"),r.querySelector(".persona-ml-auto")?.classList.add("persona-activity-chevron");let A=e.querySelector(":scope > .persona-border-t");return A?.classList.add("persona-activity-body"),A&&(A.id=`activity-details-${t.id}`,r.setAttribute("aria-controls",A.id)),e}function nw(e){let t=new Set,n=new Set,o=new Set,r=new Map,s=i=>{clearTimeout(r.get(i)),r.delete(i)};return{observe(i,l,c,p={}){let d=l==="tool"?i.toolCall:i.reasoning;if(!(!d||n.has(i.id))&&(!t.has(i.id)&&d.status!=="complete"&&d.chunks?.some(Boolean)&&(t.add(i.id),p.autoExpand!==!1&&c.add(i.id)),t.has(i.id)&&d.status==="complete"&&!o.has(i.id))){if(o.add(i.id),p.autoCollapseDelay===!1)return;r.set(i.id,setTimeout(()=>{r.delete(i.id),c.delete(i.id),e(i.id,l)},p.autoCollapseDelay??1e3))}},manual(i){n.add(i),s(i)},prune(i){for(let l of new Set([...t,...n,...o]))i.has(l)||(s(l),t.delete(l),n.delete(l),o.delete(l))},clear(){for(let i of r.keys())s(i);t.clear(),n.clear(),o.clear()}}}function ow(e,t,n,o){let r=x("div","");r.id=`bubble-${e.id}`,r.dataset.messageId=e.id;let s=x("button","");s.type="button",s.dataset.expandHeader="true",s.dataset.bubbleType="tool",s.setAttribute("aria-expanded",String(n));let i=x("div","");typeof o=="string"?i.textContent=o:i.appendChild(o),La(s,i,{expandable:!0,expanded:n,iconColor:t.toolCall?.toggleTextColor||t.toolCall?.headerTextColor||"currentColor",metaGap:!0});let l=x("div","persona-border-t");return l.id=`activity-details-${e.id}`,l.style.display=n?"":"none",s.setAttribute("aria-controls",l.id),r.append(s,l),$r(r,e,{...t,features:{...t.features,toolCallDisplay:{...t.features?.toolCallDisplay,variant:"row"}}},"tool"),r.dataset.personaToolGroup="true",t.features?.toolCallDisplay?.loadingAnimation==="shimmer"&&(r.dataset.activityGroupShimmer="true"),{bubble:r,body:l}}Mf();function rw(e,t){let n=e.voiceRecognition,o=t.voiceRecognition;return n?.enabled===!0!=(o?.enabled===!0)||n?.provider?.type!==o?.provider?.type||n?.provider?.custom!==o?.provider?.custom||n?.provider?.runtype?.createPlaybackEngine!==o?.provider?.runtype?.createPlaybackEngine||JSON.stringify(n?.provider?.runtype)!==JSON.stringify(o?.provider?.runtype)||e.agentId!==t.agentId||e.clientToken!==t.clientToken||e.apiUrl!==t.apiUrl}function Dn(e){return e?.type==="runtype"||e?.type==="custom"}var UP=()=>typeof window<"u"&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window);function sw(e){try{if(e?.type==="custom"&&e.custom){let t=e.custom,n=typeof t=="function"?t():t;return!!n&&typeof n.startListening=="function"}return e?.type==="runtype"&&e.runtype?!0:UP()}catch{return!1}}var VP=e=>{if(!e)return;let t={},n=e;if(n.heading){let o=n.heading;t.heading=(r,s,i)=>o({type:"heading",raw:i,depth:s,text:r,tokens:[]})}if(n.code){let o=n.code;t.code=(r,s,i)=>o({type:"code",raw:"",text:r,lang:s,escaped:i})}if(n.blockquote){let o=n.blockquote;t.blockquote=r=>o({type:"blockquote",raw:"",text:r,tokens:[]})}if(n.table){let o=n.table;t.table=(r,s)=>o({type:"table",raw:"",header:[],rows:[],align:[],headerHtml:r,bodyHtml:s})}if(n.link){let o=n.link;t.link=(r,s,i)=>o({type:"link",raw:"",href:r,title:s??null,text:i,tokens:[]})}if(n.image){let o=n.image;t.image=(r,s,i)=>o({type:"image",raw:"",href:r,title:s??null,text:i})}if(n.list){let o=n.list;t.list=(r,s,i)=>o({type:"list",raw:"",ordered:s,start:i,loose:!1,items:[],itemsHtml:r})}if(n.listitem){let o=n.listitem;t.listitem=(r,s,i)=>o({type:"list_item",raw:"",task:s,checked:i,loose:!1,text:r,tokens:[]})}if(n.paragraph){let o=n.paragraph;t.paragraph=r=>o({type:"paragraph",raw:"",text:r,tokens:[]})}if(n.codespan){let o=n.codespan;t.codespan=r=>o({type:"codespan",raw:"",text:r})}if(n.strong){let o=n.strong;t.strong=r=>o({type:"strong",raw:"",text:r,tokens:[]})}if(n.em){let o=n.em;t.em=r=>o({type:"em",raw:"",text:r,tokens:[]})}if(n.del){let o=n.del;t.del=r=>o({type:"del",raw:"",text:r,tokens:[]})}if(n.html){let o=n.html;t.html=r=>o({type:"html",raw:r,text:r})}if(n.text){let o=n.text;t.text=r=>o({type:"text",raw:r,text:r})}if(n.checkbox){let o=n.checkbox;t.checkbox=r=>o({checked:r})}return n.hr&&(t.hr=n.hr),n.br&&(t.br=n.br),t},Vl=e=>{let t=null;return n=>{let o=nr();if(!o)return Ur(n);if(!t){let{Marked:r}=o,s=e?.markedOptions;t=new r({gfm:s?.gfm??!0,breaks:s?.breaks??!0,pedantic:s?.pedantic,silent:s?.silent});let i=VP(e?.renderer);i&&t.use({renderer:i})}return t.parse(n)}},jl=e=>e?Vl({markedOptions:e.options,renderer:e.renderer}):Vl(),jP=Vl(),tm=e=>jP(e),Ur=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),aw=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),iw=e=>`%%FORM_PLACEHOLDER_${e}%%`,lw=(e,t)=>{let n=e;return n=n.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(o,r)=>{try{let s=JSON.parse(r.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let i=iw(t.length);return t.push({token:i,type:String(s.type)}),i}}catch{return o}return o}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(o,r)=>{let s=iw(t.length);return t.push({token:s,type:r}),s}),n},cw=e=>{let t=jl(e);return n=>{let o=[],r=lw(n,o),s=t(r);return o.forEach(({token:i,type:l})=>{let c=new RegExp(i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${aw(l)}"></div>`;s=s.replace(c,d)}),s}},dw=e=>{let t=[],n=lw(e,t),o=tm(n);return t.forEach(({token:r,type:s})=>{let i=new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),c=`<div class="persona-form-directive" data-tv-form="${aw(s)}"></div>`;o=o.replace(i,c)}),o};var qP={ALLOWED_TAGS:["h1","h2","h3","h4","h5","h6","p","br","hr","div","span","ul","ol","li","dl","dt","dd","strong","em","b","i","u","s","del","ins","mark","small","sub","sup","abbr","kbd","var","samp","code","a","img","blockquote","pre","details","summary","table","thead","tbody","tfoot","tr","th","td","caption","colgroup","col","input","label","select","option","textarea","button"],ALLOWED_ATTR:["href","src","alt","title","target","rel","loading","width","height","colspan","rowspan","scope","class","id","type","name","value","placeholder","disabled","checked","for","aria-label","aria-hidden","aria-expanded","role","tabindex","data-tv-form","data-message-id","data-persona-component-directive","data-preserve-animation","data-persona-instance"]},zP=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,nm=()=>{let e=null;return t=>{let n=nr();if(!n)return Ur(t);if(!e){let{DOMPurify:o}=n;e=o(typeof window<"u"?window:void 0),e.addHook("uponSanitizeAttribute",(r,s)=>{if(s.attrName==="src"||s.attrName==="href"){let i=s.attrValue;i.toLowerCase().startsWith("data:")&&!zP.test(i)&&(s.attrValue="",s.keepAttr=!1)}})}return e.sanitize(t,qP)}},Pp=e=>e===!1?null:typeof e=="function"?e:nm();var pw=/^\s*\|?[\s:|-]*-[\s:|-]*$/,uw=e=>e.includes("|"),gw=e=>{let t=e.trim();return t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1)),t.split("|").map(n=>n.trim())},KP=e=>`| ${e.join(" | ")} |`,GP=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,YP=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),fw=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
|
|
13
|
+
${M.description}`)},Vt=async M=>await Ns({host:$i(),title:o.deleteConversationConfirmTitle,description:o.deleteConversationConfirm,confirmLabel:o.deleteConversationConfirmLabel,cancelLabel:o.confirmCancelLabel})?(await Mc(M),"deleted"):"cancelled",Fs=async()=>{let M=_()==="verified-user";return await Ns({host:$i(),title:o.clearHistoryConfirmTitle,description:M?o.clearHistoryVerifiedConfirm:o.clearHistoryConfirm,confirmLabel:o.clearHistoryConfirmLabel,cancelLabel:o.confirmCancelLabel})?(await Ja(),"cleared"):"cancelled"},el=async()=>{if(!await Ns({host:$i(),title:o.resetIdentityConfirmTitle,description:o.resetIdentityConfirm,confirmLabel:o.resetIdentityConfirmLabel,cancelLabel:o.confirmCancelLabel}))return{outcome:"cancelled"};let{remoteRevocationConfirmed:N}=await Za();return{outcome:"reset",remoteRevocationConfirmed:N}},tn=x("button","persona-history-earlier");tn.type="button",tn.textContent=o.showEarlierMessagesLabel,tn.setAttribute("data-persona-history-earlier",""),Object.assign(tn.style,{alignSelf:"center",minHeight:"44px",padding:"0 16px",borderRadius:"999px",border:"1px solid var(--persona-border, rgba(0,0,0,0.12))",background:"transparent",color:"inherit",font:"inherit",cursor:"pointer",flexShrink:"0"});let Qt=()=>{if(!(L()&&!!e.historySessionState.nextMessageCursor&&!!e.session.getActiveConversationId())){tn.remove();return}tn.textContent=o.showEarlierMessagesLabel,tn.parentNode!==e.body&&e.body.insertBefore(tn,e.body.firstChild)};tn.addEventListener("click",()=>{let M=e.session.getActiveConversationId(),N=e.historySessionState.nextMessageCursor;if(!M||!N||tn.disabled)return;tn.disabled=!0;let ne=e.body.scrollHeight,pe=e.body.scrollTop;e.session.loadOlderMessages(M,N,{scope:_()}).then(()=>{e.body.scrollTop=pe+(e.body.scrollHeight-ne),e.repinAnchoredMessage()}).catch(()=>{}).finally(()=>{tn.disabled=!1,Qt()})});let Eo=()=>{let M=e.createHeaderIconButton({ariaLabel:o.openHistoryLabel,iconName:"history",wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center",extraClassName:"persona-history-toggle",attrs:{"data-persona-history-toggle":""}});return M.button.addEventListener("click",N=>{if(!(!L()||I())){if(e.historyVisible){xn();return}Ke({invoker:M.button,keyboard:N.detail===0})}}),M},Jr=()=>{if(!L()){g?.remove(),d=null,g=null;return}if(g&&!g.isConnected&&(d=null,g=null),!d&&e.header){let pe=Eo();d=pe.button,g=pe.wrapper;let Re=e.panelElements.clearChatButtonWrapper||e.panelElements.closeButtonWrapper;Re?.parentNode&&e.header.contains(Re)?Re.parentNode.insertBefore(g,Re):e.header.appendChild(g)}if(!d||!g)return;let M=eo()||e.historyVisible&&e.historyPresentation==="rail";if(g.style.display=M?"none":"",M){document.activeElement===d&&mt();return}let N=I();d.disabled=N,d.setAttribute("aria-disabled",N?"true":"false");let ne=N?o.openHistoryBusyLabel:o.openHistoryLabel;d.setAttribute("aria-label",ne),(e.config.features?.history?.presentation??"panel")==="panel"?(d.removeAttribute("aria-expanded"),d.removeAttribute("aria-controls")):(d.setAttribute("aria-expanded",e.historyVisible?"true":"false"),d.setAttribute("aria-controls",A))},fr=!1,$s=()=>{let M=e.panelElements.clearChatButton;if(M){if(L()){fr||(y=M.getAttribute("aria-label")??"",fr=!0),M.setAttribute("aria-label",o.newConversationLabel),M.removeAttribute("title");return}fr&&(fr=!1,y&&M.setAttribute("aria-label",y))}},jn=()=>{o=Yf(e.config.features?.history?.copy),Jr(),gr(),$s(),Qt()};return e.historyChromeSync=jn,T(),jn(),e.destroyCallbacks.push(()=>{v?.(),C?.(),h+=1,Fi(),i?.dispose(),i?.view.destroy(),i=null}),{historyAvailable:L,historyScope:H,installHistoryProvider:T,syncHistoryChromeImpl:jn,syncHistoryPresentation:Vo,syncEarlierMessagesPill:Qt,openHistory:Ke,closeHistory:xn,openHistoryConversation:Mn,startNewConversation:Mo,updateHistoryConversation:Ds,deleteHistoryConversation:Mc,requestDeleteConversation:Vt,clearConversationHistory:Ja,resetHistoryIdentity:Za,railCollapseShortcut:Di,railCollapsible:D,railTriggerApplies:eo,railOverlayMode:Ct,toggleRailCollapsed:_i,toggleRailPinned:()=>ao(),get historyProvider(){return r},get historySurface(){return i},get railShell(){return xt},get railHost(){return xe},get railColumn(){return Wt}}}});var Ra,dm=Ve(()=>{"use strict";Ra=class{#e=null;#n=0;#o=[];#t=[];#s=[];#r=!1;#p=!1;#f=0;#i=!1;#g=!1;#l;#c=[];#a=0;#E=!1;#h;#S;#v;#A=null;constructor(t=24e3,n={}){this.#S=t;let o=Math.max(0,n.prebufferMs??0);this.#v=Math.round(t*o/1e3),this.#l=this.#v>0}#d(){if(!this.#e){let n=typeof window<"u"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let o=n.AudioContext||n.webkitAudioContext;this.#e=new o({sampleRate:this.#S})}let t=this.#e;return t.state==="suspended"&&!this.#g&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.#A){let r=new Uint8Array(this.#A.length+t.length);r.set(this.#A),r.set(t,this.#A.length),n=r,this.#A=null}if(n.length%2!==0&&(this.#A=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let o=this.#x(n);o.length!==0&&(this.#l?(this.#c.push(o),this.#a+=o.length,clearTimeout(this.#h),this.#a>=this.#v?this.#u():this.#E&&(this.#h=setTimeout(()=>this.#u(),this.#v/this.#S*1e3))):this.#m(o))}markStreamEnd(){this.#c.length>0&&this.#u(),this.#p=!0,this.#C()}flush(){for(let t of this.#o){t.onended=null;try{t.stop(),t.disconnect()}catch{}}this.#o=[],this.#f=0,this.#n=0,this.#r=!1,this.#p=!1,this.#t=[],this.#s=[],this.#A=null,this.#c=[],this.#a=0,this.#l=this.#v>0,this.#i=!1,clearTimeout(this.#h)}setContinuousMode(t){this.#E=t}isPlaying(){return this.#r}onFinished(t){this.#t.push(t)}onStarted(t){this.#s.push(t)}pause(){this.#g=!0,this.#e&&this.#e.state==="running"&&this.#e.suspend()}resume(){this.#g=!1,this.#e&&this.#e.state==="suspended"&&this.#e.resume()}async destroy(){this.flush(),this.#e&&(await this.#e.close(),this.#e=null)}#u(){this.#l=!1;let t=this.#c;this.#c=[],this.#a=0;for(let n of t)this.#m(n)}#m(t){if(t.length===0)return;let n=this.#d(),o=n.createBuffer(1,t.length,this.#S);o.getChannelData(0).set(t);let r=n.createBufferSource();r.buffer=o,r.connect(n.destination);let s=n.currentTime;if(this.#n===0?this.#n=s:this.#n<s&&(this.#n=s,this.#v>0&&(this.#l=!0)),r.start(this.#n),this.#n+=o.duration,this.#o.push(r),this.#f++,this.#r=!0,!this.#i){this.#i=!0;let i=this.#s.slice();this.#s=[];for(let l of i)l()}r.onended=()=>{let i=this.#o.indexOf(r);i!==-1&&(this.#o.splice(i,1),this.#f--,this.#C())}}#C(){if(this.#p&&this.#f<=0&&this.#c.length===0){this.#r=!1,this.#p=!1;let t=this.#t.slice();this.#t=[];for(let n of t)n()}}#x(t){let n=Math.floor(t.length/2),o=new Float32Array(n),r=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let s=0;s<n;s++){let i=r.getInt16(s*2,!0);o[s]=i/32768}return o}}});function pk(e){return e.replace(/\/+$/,"")}async function uk(e){try{let t=await e.json();return t.detail?`${t.error??`Runtype TTS ${e.status}`}: ${t.detail}`:t.error??`Runtype TTS request failed (${e.status})`}catch{return`Runtype TTS request failed (${e.status})`}}var Lp,Ww=Ve(()=>{"use strict";dm();Lp=class{constructor(t){this.id="runtype-tts";this.supportsPause=!0;this.#e=null;this.#n=null;this.#o=0;this.#t=t}#e;#n;#o;#t;#s(){return this.#n??=Promise.resolve(this.#t.createPlaybackEngine?this.#t.createPlaybackEngine():new Ra(24e3,{prebufferMs:this.#t.prebufferMs??200})).then(t=>this.#e=t)}speak(t,n){let o=++this.#o;this.#r(o,t,n)}async#r(t,n,o){try{let r=await this.#s();if(t!==this.#o)return;r.flush(),r.resume(),r.onStarted(()=>{t===this.#o&&o.onStart?.()}),r.onFinished(()=>{t===this.#o&&o.onEnd?.()});let s=`${pk(this.#t.host)}/v1/agents/${encodeURIComponent(this.#t.agentId)}/speak`,i=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.#t.clientToken}`},body:JSON.stringify({text:n.text,voice:n.voice??this.#t.voice,format:"pcm"})});if(t!==this.#o)return;if(!i.ok||!i.body)throw new Error(await uk(i));let l=i.body.getReader();for(;;){let{done:c,value:p}=await l.read();if(t!==this.#o){await l.cancel().catch(()=>{});return}if(c)break;p&&p.byteLength>0&&r.enqueue(p)}r.markStreamEnd()}catch(r){if(t!==this.#o)return;let s=r instanceof Error?r:new Error(String(r));this.#t.onError?.(s),o.onError?.(s)}}pause(){this.#e?.pause()}resume(){this.#e?.resume()}stop(){this.#o++,this.#e?.flush()}destroy(){this.#o++,this.#e?.destroy(),this.#e=null,this.#n=null}}});var Hp,Ow=Ve(()=>{"use strict";Hp=class{constructor(t,n,o={}){this.id="fallback";this.#n=t,this.#o=n,this.#t=o,this.#e=t}#e;#n;#o;#t;get supportsPause(){return this.#e.supportsPause}speak(t,n){this.#e=this.#n;let o=!1;this.#n.speak(t,{onStart:()=>{o=!0,n.onStart?.()},onEnd:()=>n.onEnd?.(),onError:r=>{if(o){n.onError?.(r);return}this.#t.onFallback?.(r),this.#e=this.#o,this.#o.speak(t,n)}})}pause(){this.#e.pause()}resume(){this.#e.resume()}stop(){this.#e.stop()}destroy(){this.#n.destroy?.(),this.#o.destroy?.()}}});var Bw={};ys(Bw,{FallbackSpeechEngine:()=>Hp,RuntypeSpeechEngine:()=>Lp});var _w=Ve(()=>{"use strict";Ww();Ow()});var LI={};ys(LI,{ASK_USER_QUESTION_CLIENT_TOOL:()=>mf,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>ff,ASK_USER_QUESTION_TOOL_NAME:()=>Hl,AgentWidgetClient:()=>wi,AgentWidgetSession:()=>Wa,AttachmentManager:()=>Ai,BrowserSpeechEngine:()=>ks,DEFAULT_COMPONENTS:()=>TS,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>vC,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>vi,DEFAULT_PALETTE:()=>xS,DEFAULT_SEMANTIC:()=>ES,DEFAULT_WIDGET_CONFIG:()=>wC,HistoryProviderError:()=>Vr,PRESETS:()=>Ih,PRESET_FULLSCREEN:()=>Hh,PRESET_MINIMAL:()=>Lh,PRESET_SHOP:()=>kh,ReadAloudController:()=>Si,SUGGEST_REPLIES_CLIENT_TOOL:()=>Wd,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>uf,SUGGEST_REPLIES_TOOL_NAME:()=>Oo,THEME_ZONES:()=>kS,VERSION:()=>Yn,WEBMCP_TOOL_PREFIX:()=>Ml,WebMcpBridge:()=>Iu,accessibilityPlugin:()=>kx,animationsPlugin:()=>Lx,applyFeaturePreferences:()=>fh,applyThemeVariables:()=>Mi,attachHeaderToContainer:()=>Ti,brandPlugin:()=>Hx,buildComposer:()=>ki,buildDefaultHeader:()=>_m,buildHeader:()=>jr,buildHeaderWithLayout:()=>Na,buildMinimalHeader:()=>Dm,builtInClientToolsForDispatch:()=>fi,canonicalArtifactDisplayMode:()=>Gn,collectEnrichedPageContext:()=>xx,componentRegistry:()=>Fo,createActionManager:()=>mc,createAgentExperience:()=>yu,createAskUserQuestionBubble:()=>Lv,createBestAvailableVoiceProvider:()=>Pu,createBubbleWithLayout:()=>pA,createCSATFeedback:()=>fu,createComboButton:()=>Qp,createComponentMiddleware:()=>ox,createComponentStreamParser:()=>pu,createDefaultSanitizer:()=>nm,createDemoCarousel:()=>Gx,createDirectivePostprocessor:()=>cw,createDropdownMenu:()=>Pi,createFlexibleJsonStreamParser:()=>yv,createIconButton:()=>Zn,createImagePart:()=>Kd,createJsonStreamParser:()=>Pd,createLabelButton:()=>Bm,createLocalStorageAdapter:()=>du,createMarkdownProcessor:()=>Vl,createMarkdownProcessorFromConfig:()=>jl,createMessageActions:()=>jm,createNPSFeedback:()=>mu,createPlainTextParser:()=>Ed,createPlugin:()=>Wx,createRegexJsonParser:()=>Td,createRovingTablist:()=>tM,createSlashCommandsSource:()=>eM,createSplitButton:()=>oA,createStandardBubble:()=>Fa,createStaticMentionSource:()=>Zx,createTextPart:()=>So,createTheme:()=>Gl,createThemeObserver:()=>Oa,createToggleGroup:()=>lc,createTypingIndicator:()=>Li,createVoiceProvider:()=>Xa,createWidgetHostLayout:()=>yc,createXmlParser:()=>kd,default:()=>Px,defaultActionHandlers:()=>Wi,defaultJsonActionParser:()=>fc,defaultMentionFilter:()=>Ru,defaultParseRules:()=>Th,detectColorScheme:()=>Xl,directivePostprocessor:()=>dw,ensureAskUserQuestionSheet:()=>Id,escapeHtml:()=>Ur,extractComponentDirectiveFromMessage:()=>gu,fileToImagePart:()=>xC,formatEnrichedContext:()=>Mx,generateAssistantMessageId:()=>Ps,generateCodeSnippet:()=>Fx,generateMessageId:()=>Sw,generateStableSelector:()=>Ph,generateUserMessageId:()=>Ha,getActiveTheme:()=>No,getAgentWidgetHandles:()=>gx,getColorScheme:()=>xi,getDisplayText:()=>zd,getHeaderLayout:()=>Nm,getImageParts:()=>AC,getPreset:()=>Tx,hasComponentDirective:()=>hc,hasImages:()=>Pa,headerLayouts:()=>Jp,highContrastPlugin:()=>Rx,initAgentWidget:()=>Ah,isAskUserQuestionMessage:()=>Ir,isComponentDirectiveType:()=>nx,isDockedMountMode:()=>Lt,isHistoryProviderError:()=>Tw,isSuggestRepliesMessage:()=>gi,isVoiceSupported:()=>_h,isWebMcpToolName:()=>bs,isWelcomeVisible:()=>Ws,latestAgentSuggestions:()=>Od,listRegisteredStreamAnimations:()=>QS,loadMarkdownParsers:()=>yd,markdownPostprocessor:()=>tm,mergeWithDefaults:()=>Ea,normalizeContent:()=>SC,normalizeMediaType:()=>vs,onMarkdownParsersReady:()=>ua,parseAskUserQuestionPayload:()=>Rr,parseSuggestRepliesPayload:()=>gf,parseWidgetPreferenceSlice:()=>gh,pickBestVoice:()=>Ia,pluginRegistry:()=>gc,reducedMotionPlugin:()=>Ix,registerIcons:()=>cv,registerStreamAnimationPlugin:()=>ec,removeAskUserQuestionSheet:()=>Wr,renderComponentDirective:()=>uu,renderLoadingIndicatorWithFallback:()=>Vm,renderLucideIcon:()=>ge,resolveArtifactDisplay:()=>rf,resolveArtifactDisplayMode:()=>or,resolveConfigPreferences:()=>uc,resolveDockConfig:()=>Jn,resolveSanitizer:()=>Pp,resolveTokens:()=>Vp,resolveWelcomeConfig:()=>Ua,stripWebMcpPrefix:()=>of,themeToCssVariables:()=>jp,unregisterStreamAnimationPlugin:()=>XS,validateImageFile:()=>MC,validateTheme:()=>Am});module.exports=BE(LI);var sv=require("marked"),iv=Bn(require("dompurify"),1);dn();var{setLoader:DI,load:_E,provide:DE,getSync:Qg}=lt({fallbackImport:()=>Promise.resolve().then(()=>(nv(),tv))}),hd=new Set,ov=()=>{let e=[...hd];hd.clear();for(let t of e)try{t()}catch{}};var yd=()=>{let e=Qg();return e?Promise.resolve(e):_E().then(t=>(ov(),t))},ua=e=>Qg()?()=>{}:(hd.add(e),()=>{hd.delete(e)}),rv=e=>{DE(e),ov()},nr=Qg;rv({Marked:sv.Marked,DOMPurify:iv.default});var G=require("lucide"),av={user:G.User,mail:G.Mail,phone:G.Phone,calendar:G.Calendar,clock:G.Clock,building:G.Building,"map-pin":G.MapPin,lock:G.Lock,key:G.Key,"credit-card":G.CreditCard,hash:G.Hash,globe:G.Globe,link:G.Link,"circle-check":G.CircleCheck,"circle-x":G.CircleX,"triangle-alert":G.TriangleAlert,info:G.Info,ban:G.Ban,shield:G.Shield,house:G.House,"pen-line":G.PenLine,save:G.Save,share:G.Share,funnel:G.Funnel,settings:G.Settings,"rotate-cw":G.RotateCw,"shopping-cart":G.ShoppingCart,"shopping-bag":G.ShoppingBag,package:G.Package,truck:G.Truck,tag:G.Tag,gift:G.Gift,receipt:G.Receipt,wallet:G.Wallet,store:G.Store,"dollar-sign":G.DollarSign,percent:G.Percent,play:G.Play,pause:G.Pause,"volume-x":G.VolumeX,camera:G.Camera,image:G.Image,film:G.Film,headphones:G.Headphones,"message-circle":G.MessageCircle,bell:G.Bell,heart:G.Heart,"eye-off":G.EyeOff,bookmark:G.Bookmark,"calendar-days":G.CalendarDays,timer:G.Timer,folder:G.Folder,"folder-open":G.FolderOpen,files:G.Files,"chart-column":G.ChartColumn,sparkles:G.Sparkles,zap:G.Zap,sun:G.Sun,moon:G.Moon,flag:G.Flag,lightbulb:G.Lightbulb,monitor:G.Monitor,smartphone:G.Smartphone};kt();dv(av);hf();dn();var{setLoader:hR,load:ST,provide:AT,getSync:xT}=lt({fallbackImport:()=>Promise.resolve().then(()=>(hf(),Dd))});var mi=ST,Dv=AT,Nv=xT;Dv(Dd);Cf();dn();var{setLoader:xR,load:_T,provide:DT}=lt({fallbackImport:()=>Promise.resolve().then(()=>(Cf(),Nd))});var Or=_T,Xv=DT;Xv(Nd);jf();dn();var{setLoader:EW,load:cP,provide:dP,getSync:pP}=lt({fallbackImport:()=>Promise.resolve().then(()=>(jf(),lp))});var cp=cP,BC=dP,qf=pP;BC(lp);Kf();dn();var{setLoader:HW,load:vP,provide:CP,getSync:wP}=lt({fallbackImport:()=>Promise.resolve().then(()=>(Kf(),pp))});var Gf=vP,NC=CP,FC=wP;NC(pp);Zf();dn();var{setLoader:GW,load:OP,provide:BP,getSync:_P}=lt({fallbackImport:()=>Promise.resolve().then(()=>(Zf(),bp))});var ew=OP,tw=BP,vp=_P;tw(bp);var Ep=require("lucide");Lr();wo();Je();kt();Je();var Cp=require("lucide");Lr();var DP=["persona-w-full","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"],NP="persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none",FP="persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none",$P=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),wp=(e,t)=>{let n=x("div",["persona-message-bubble",e,...DP].join(" "));return n.id=`bubble-${t}`,n.setAttribute("data-message-id",t),n},Sp=e=>{let t=x("button",e.expandable?NP:FP);return t.type="button",e.expandable&&(t.setAttribute("aria-expanded",e.expanded?"true":"false"),t.setAttribute("data-expand-header","true")),t.setAttribute("data-bubble-type",e.bubbleType),t},em=(e,t,n)=>{e.innerHTML="";let o=Nt(t?Cp.ChevronUp:Cp.ChevronDown,16,n,2);o?e.appendChild(o):e.textContent=t?"Hide":"Show"},La=(e,t,n)=>{if(!n.expandable)return e.append(t),null;let o=x("div","persona-flex persona-items-center");em(o,n.expanded,n.iconColor);let r=x("div",n.metaGap?"persona-flex persona-items-center persona-gap-2 persona-ml-auto":"persona-flex persona-items-center persona-ml-auto");return r.append(o),e.append(t,r),o},Ap=e=>{let t=x("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(t.setAttribute("data-persona-collapsed-preview",e.previewKind),t.style.display="none",t.style.whiteSpace="pre-wrap",!e.expanded&&e.isActive&&e.activePreview&&e.previewText){let n=e.renderPreview?.();$P(t,n)||(t.textContent=e.previewText),t.style.display=""}return!e.expanded&&e.isActive&&e.activeMinHeight&&(e.bubble.style.minHeight=e.activeMinHeight),t},xp=e=>{e.header.setAttribute("aria-expanded",e.expanded?"true":"false"),e.toggleIcon&&em(e.toggleIcon,e.expanded,e.iconColor),e.content.style.display=e.expanded?"":"none",e.collapsedPreview.style.display=e.expanded?"none":e.collapsedPreview.textContent||e.collapsedPreview.childNodes.length?"":"none"},Mp=(e,t,n)=>{let o=n.stateSet.has(e),r=t.querySelector('button[data-expand-header="true"]'),s=t.querySelector(".persona-border-t"),i=t.querySelector(`[data-persona-collapsed-preview="${n.previewKind}"]`);if(!r||!s)return;r.setAttribute("aria-expanded",o?"true":"false");let c=r.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");c&&em(c,o,n.iconColor),s.style.display=o?"":"none",i&&(i.style.display=o?"none":i.textContent||i.childNodes.length?"":"none")};function Tp(e,t){let n=t==="tool"?"toolCallDisplay":"reasoningDisplay";return{...e,features:{...e?.features,[n]:{...t==="tool"?_r:Ci,...e?.future?.v5Defaults===!0?bi.features?.[n]:{},...e?.features?.[n]}}}}function Ts(e,t){let n=t==="tool"?"toolCallDisplay":"reasoningDisplay";return e?.features?.[n]?.variant??(e?.future?.v5Defaults?"row":"card")}function Ul(e){let t=Math.max(0,Math.floor((e??0)/1e3));return t<1?"a moment":t<60?`${t}s`:`${Math.floor(t/60)}m ${t%60}s`}function $r(e,t,n,o){if(Ts(n,o)!=="row")return e;e.className=`persona-message-bubble persona-${o}-bubble persona-activity-row`,e.dataset.activityKind=o,o==="tool"&&n.toolCall?.shadow===void 0&&(e.style.boxShadow="var(--persona-tool-bubble-shadow, none)");let r=e.querySelector(":scope > button");if(!r)return e;r.className="persona-activity-header";let s=o==="tool"?t.toolCall:t.reasoning,i=s?.status!=="complete",l=t.approval?.status??t.toolCall?.approvalStatus,c=l==="denied"?"denied":l==="pending"?"awaiting-approval":t.toolCall?.success===!1?"error":i?s?.status==="pending"?"pending":"running":"done";e.dataset.activityState=c;let p=x("span","persona-activity-icon");p.dataset.activityIcon=c;let d={pending:"circle",running:"loader-circle",done:"check",error:"x",denied:"x","awaiting-approval":"clock"},g=o==="reasoning"?n.features?.reasoningDisplay?.iconName:void 0,f=g?ge(g,16,"currentColor",2):c==="pending"?Nt(Ep.Circle,16,"currentColor",2):c==="awaiting-approval"?Nt(Ep.Clock,16,"currentColor",2):ge(d[c],16,"currentColor",2);f&&p.appendChild(f),r.querySelector(".persona-reasoning-header-icon")?.remove();let h=o==="tool"?"toolCallDisplay":"reasoningDisplay",y=n.features?.[h]?.iconVisibility??(n.future?.v5Defaults?"active":"always");if((y==="always"||y==="active"&&c!=="done")&&r.prepend(p),o==="tool"&&s){let L=x("span","persona-activity-duration");i&&s.startedAt&&L.setAttribute("data-tool-elapsed",String(s.startedAt));let I=(o==="tool"?t.toolCall?.duration:void 0)??s.durationMs??(s.completedAt!==void 0&&s.startedAt!==void 0?s.completedAt-s.startedAt:void 0);L.textContent=I===void 0?"":Ul(I),r.appendChild(L)}r.querySelector(":scope > div:not(.persona-ml-auto)")?.classList.add("persona-activity-label"),r.querySelector(".persona-ml-auto")?.classList.add("persona-activity-chevron");let A=e.querySelector(":scope > .persona-border-t");return A?.classList.add("persona-activity-body"),A&&(A.id=`activity-details-${t.id}`,r.setAttribute("aria-controls",A.id)),e}function nw(e){let t=new Set,n=new Set,o=new Set,r=new Map,s=i=>{clearTimeout(r.get(i)),r.delete(i)};return{observe(i,l,c,p={}){let d=l==="tool"?i.toolCall:i.reasoning;if(!(!d||n.has(i.id))&&(!t.has(i.id)&&d.status!=="complete"&&d.chunks?.some(Boolean)&&(t.add(i.id),p.autoExpand!==!1&&c.add(i.id)),t.has(i.id)&&d.status==="complete"&&!o.has(i.id))){if(o.add(i.id),p.autoCollapseDelay===!1)return;r.set(i.id,setTimeout(()=>{r.delete(i.id),c.delete(i.id),e(i.id,l)},p.autoCollapseDelay??1e3))}},manual(i){n.add(i),s(i)},prune(i){for(let l of new Set([...t,...n,...o]))i.has(l)||(s(l),t.delete(l),n.delete(l),o.delete(l))},clear(){for(let i of r.keys())s(i);t.clear(),n.clear(),o.clear()}}}function ow(e,t,n,o){let r=x("div","");r.id=`bubble-${e.id}`,r.dataset.messageId=e.id;let s=x("button","");s.type="button",s.dataset.expandHeader="true",s.dataset.bubbleType="tool",s.setAttribute("aria-expanded",String(n));let i=x("div","");typeof o=="string"?i.textContent=o:i.appendChild(o),La(s,i,{expandable:!0,expanded:n,iconColor:t.toolCall?.toggleTextColor||t.toolCall?.headerTextColor||"currentColor",metaGap:!0});let l=x("div","persona-border-t");return l.id=`activity-details-${e.id}`,l.style.display=n?"":"none",s.setAttribute("aria-controls",l.id),r.append(s,l),$r(r,e,{...t,features:{...t.features,toolCallDisplay:{...t.features?.toolCallDisplay,variant:"row"}}},"tool"),r.dataset.personaToolGroup="true",t.features?.toolCallDisplay?.loadingAnimation==="shimmer"&&(r.dataset.activityGroupShimmer="true"),{bubble:r,body:l}}Mf();function rw(e,t){let n=e.voiceRecognition,o=t.voiceRecognition;return n?.enabled===!0!=(o?.enabled===!0)||n?.provider?.type!==o?.provider?.type||n?.provider?.custom!==o?.provider?.custom||n?.provider?.runtype?.createPlaybackEngine!==o?.provider?.runtype?.createPlaybackEngine||JSON.stringify(n?.provider?.runtype)!==JSON.stringify(o?.provider?.runtype)||e.agentId!==t.agentId||e.clientToken!==t.clientToken||e.apiUrl!==t.apiUrl}function Dn(e){return e?.type==="runtype"||e?.type==="custom"}var UP=()=>typeof window<"u"&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window);function sw(e){try{if(e?.type==="custom"&&e.custom){let t=e.custom,n=typeof t=="function"?t():t;return!!n&&typeof n.startListening=="function"}return e?.type==="runtype"&&e.runtype?!0:UP()}catch{return!1}}var VP=e=>{if(!e)return;let t={},n=e;if(n.heading){let o=n.heading;t.heading=(r,s,i)=>o({type:"heading",raw:i,depth:s,text:r,tokens:[]})}if(n.code){let o=n.code;t.code=(r,s,i)=>o({type:"code",raw:"",text:r,lang:s,escaped:i})}if(n.blockquote){let o=n.blockquote;t.blockquote=r=>o({type:"blockquote",raw:"",text:r,tokens:[]})}if(n.table){let o=n.table;t.table=(r,s)=>o({type:"table",raw:"",header:[],rows:[],align:[],headerHtml:r,bodyHtml:s})}if(n.link){let o=n.link;t.link=(r,s,i)=>o({type:"link",raw:"",href:r,title:s??null,text:i,tokens:[]})}if(n.image){let o=n.image;t.image=(r,s,i)=>o({type:"image",raw:"",href:r,title:s??null,text:i})}if(n.list){let o=n.list;t.list=(r,s,i)=>o({type:"list",raw:"",ordered:s,start:i,loose:!1,items:[],itemsHtml:r})}if(n.listitem){let o=n.listitem;t.listitem=(r,s,i)=>o({type:"list_item",raw:"",task:s,checked:i,loose:!1,text:r,tokens:[]})}if(n.paragraph){let o=n.paragraph;t.paragraph=r=>o({type:"paragraph",raw:"",text:r,tokens:[]})}if(n.codespan){let o=n.codespan;t.codespan=r=>o({type:"codespan",raw:"",text:r})}if(n.strong){let o=n.strong;t.strong=r=>o({type:"strong",raw:"",text:r,tokens:[]})}if(n.em){let o=n.em;t.em=r=>o({type:"em",raw:"",text:r,tokens:[]})}if(n.del){let o=n.del;t.del=r=>o({type:"del",raw:"",text:r,tokens:[]})}if(n.html){let o=n.html;t.html=r=>o({type:"html",raw:r,text:r})}if(n.text){let o=n.text;t.text=r=>o({type:"text",raw:r,text:r})}if(n.checkbox){let o=n.checkbox;t.checkbox=r=>o({checked:r})}return n.hr&&(t.hr=n.hr),n.br&&(t.br=n.br),t},Vl=e=>{let t=null;return n=>{let o=nr();if(!o)return Ur(n);if(!t){let{Marked:r}=o,s=e?.markedOptions;t=new r({gfm:s?.gfm??!0,breaks:s?.breaks??!0,pedantic:s?.pedantic,silent:s?.silent});let i=VP(e?.renderer);i&&t.use({renderer:i})}return t.parse(n)}},jl=e=>e?Vl({markedOptions:e.options,renderer:e.renderer}):Vl(),jP=Vl(),tm=e=>jP(e),Ur=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),aw=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),iw=e=>`%%FORM_PLACEHOLDER_${e}%%`,lw=(e,t)=>{let n=e;return n=n.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(o,r)=>{try{let s=JSON.parse(r.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let i=iw(t.length);return t.push({token:i,type:String(s.type)}),i}}catch{return o}return o}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(o,r)=>{let s=iw(t.length);return t.push({token:s,type:r}),s}),n},cw=e=>{let t=jl(e);return n=>{let o=[],r=lw(n,o),s=t(r);return o.forEach(({token:i,type:l})=>{let c=new RegExp(i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${aw(l)}"></div>`;s=s.replace(c,d)}),s}},dw=e=>{let t=[],n=lw(e,t),o=tm(n);return t.forEach(({token:r,type:s})=>{let i=new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),c=`<div class="persona-form-directive" data-tv-form="${aw(s)}"></div>`;o=o.replace(i,c)}),o};var qP={ALLOWED_TAGS:["h1","h2","h3","h4","h5","h6","p","br","hr","div","span","ul","ol","li","dl","dt","dd","strong","em","b","i","u","s","del","ins","mark","small","sub","sup","abbr","kbd","var","samp","code","a","img","blockquote","pre","details","summary","table","thead","tbody","tfoot","tr","th","td","caption","colgroup","col","input","label","select","option","textarea","button"],ALLOWED_ATTR:["href","src","alt","title","target","rel","loading","width","height","colspan","rowspan","scope","class","id","type","name","value","placeholder","disabled","checked","for","aria-label","aria-hidden","aria-expanded","role","tabindex","data-tv-form","data-message-id","data-persona-component-directive","data-preserve-animation","data-persona-instance"]},zP=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,nm=()=>{let e=null;return t=>{let n=nr();if(!n)return Ur(t);if(!e){let{DOMPurify:o}=n;e=o(typeof window<"u"?window:void 0),e.addHook("uponSanitizeAttribute",(r,s)=>{if(s.attrName==="src"||s.attrName==="href"){let i=s.attrValue;i.toLowerCase().startsWith("data:")&&!zP.test(i)&&(s.attrValue="",s.keepAttr=!1)}})}return e.sanitize(t,qP)}},Pp=e=>e===!1?null:typeof e=="function"?e:nm();var pw=/^\s*\|?[\s:|-]*-[\s:|-]*$/,uw=e=>e.includes("|"),gw=e=>{let t=e.trim();return t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1)),t.split("|").map(n=>n.trim())},KP=e=>`| ${e.join(" | ")} |`,GP=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,YP=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),fw=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
|
|
14
14
|
`),n=!1;for(let o=0;o<t.length-1;o++){let r=t[o],s=t[o+1];if(!uw(r)||pw.test(r)||!pw.test(s))continue;let i=gw(r).length;if(i<1)continue;let l=GP(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()===""||!uw(p))break;let d=KP(YP(gw(p),i));t[c]!==d&&(t[c]=d,n=!0)}o=c-1}return n?t.join(`
|
|
15
|
-
`):e};var mw="var(--persona-md-table-scroll-fade, 24px)",hw=new WeakSet;function bw(e){e.querySelectorAll("table").forEach(n=>{if(n.parentElement?.classList.contains("persona-table-scroll"))return;let r=document.createElement("div");r.className="persona-table-scroll",n.replaceWith(r),r.appendChild(n)})}function yw(e){let t=e.scrollWidth-e.clientWidth;if(t<=1){e.removeAttribute("data-persona-scroll-x");return}e.setAttribute("data-persona-scroll-x","");let o=getComputedStyle(e).direction==="rtl"?t+e.scrollLeft:e.scrollLeft,r=t-o;e.style.setProperty("--persona-fade-l",o<=1?"0px":mw),e.style.setProperty("--persona-fade-r",r<=1?"0px":mw)}function om(e){hw.has(e)||(hw.add(e),e.addEventListener("scroll",t=>{let n=t.target;n?.classList?.contains("persona-table-scroll")&&yw(n)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(yw)}pi();dn();var{setLoader:mO,load:XP}=lt({fallbackImport:()=>import("@runtypelabs/persona/webmcp-runtime")});var vw=XP;var QP="agent_",JP="flow_";function Cw(e){return e.startsWith(QP)?{kind:"agentId",agentId:e}:e.startsWith(JP)?{kind:"flowId",flowId:e}:null}function ww(e,t){let n=e.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let i=n.slice(0,o),l=n.slice(o+1);if(i==="runtype"){let p=Cw(l);if(p)return p;throw new Error(`[Persona] target "runtype:${l}" is not a valid Runtype agent_/flow_ id.`)}let c=t?.[i];if(!c)throw new Error(`[Persona] No target provider registered for "${i}". Add a \`targetProviders.${i}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:c(l).payload}}let r=Cw(n);if(r)return r;let s=t?.default;if(s)return{kind:"payload",payload:s(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}function Sw(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Ha(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Ps(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}function Aw(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`turn_${e}_${t}`}Bd();var ZP=e=>e.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase().replace(/_+/g,"_").replace(/^_|_$/g,""),ek=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),tk=e=>{if(e.variant!=="tool")return null;let t=e.agentMetadata?.clientToolAnswer;if(!t||!t.toolCallId||t.result===void 0)return null;let n=ZP(t.toolName);return n?{call:{toolCallId:t.toolCallId,toolName:n,args:ek(t.args)?t.args:{}},result:{toolCallId:t.toolCallId,toolName:n,result:t.result}}:null},rm=(e,t)=>{let n=[],o=[],r=[],s="",i,l=()=>{o.length!==0&&(n.push({role:"assistant",content:"",createdAt:s,toolCalls:o},{role:"tool",content:"",createdAt:s,toolResults:r}),o=[],r=[])};for(let c of e){let p=tk(c);if(p){let g=c.agentMetadata?.clientToolAnswer?.batch;o.length>0&&(g===void 0||g!==i)&&l(),o.length===0&&(s=c.createdAt,i=g),o.some(f=>f.toolCallId===p.call.toolCallId)||(o.push(p.call),r.push(p.result));continue}let d=t(c);d&&(l(),n.push(d))}return l(),n};Cs();Sa();yp();Bo();var nk="https://api.runtype.com/v1/dispatch",on=class extends Error{constructor(t,n,o){super(n),this.name="HistoryClientError",this.code=t,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}},xw=e=>"reason"in e?e.reason:void 0,ok="The identity proof was rejected",sm=(e,t)=>e instanceof on&&e.code===t,im=e=>e.voiceCaption?!1:!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0),Mw=e=>e.slice().sort((t,n)=>new Date(t.createdAt).getTime()-new Date(n.createdAt).getTime()),Ew=e=>({role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,createdAt:e.createdAt});function rk(e){switch(e){case"json":return Pd;case"regex-json":return Td;case"xml":return kd;default:return Ed}}var wi=class{constructor(t={},n={}){this.config=t;this.historyInternals=n;this.#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??nk,this.#t={"Content-Type":"application/json","X-Persona-Version":Yn,...t.headers},this.debug=!!t.debug,this.#o=t.streamParser??rk(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 vw().then(n=>{let o=new n.WebMcpBridge(t,{recordToolDisplayTitles:Cd,getToolDisplayTitle:ma,loadPolyfill:wd});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=ww(o,r);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.#M().agentId)}#k(){return this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||_d}#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 on("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":Yn,"X-Visitor-Token":s},signal:t.signal});if(c.status===401&&!o){o=!0;let p=await Or();n=await p.recoverFromUnauthorized(this.#I(),await p.readErrorCode(this.#I(),c),null,!0);continue}if(!c.ok)throw await(await Or()).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&&xw(n)===xw(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":Yn},body:JSON.stringify(c),signal:t.signal});if(!p.ok){let g=await p.json().catch(()=>({error:"Session initialization failed"}));if(n&&p.status===403&&g.error==="visitor_history_disabled"){if(this.#G(),l)throw new on("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 on("history_disabled","Durable recovery is disabled for this surface"):(n||t.durableResume)&&p.status===401&&g.error==="visitor_required"?new on("visitor_required","Visitor credential no longer resolves"):l&&p.status===404?new on("not_found","Conversation not found"):p.status===401?new Error(`Invalid client token: ${g.hint||g.error}`):p.status===403?new Error(`Origin not allowed: ${g.hint||g.error}`):new Error(g.error||"Failed to initialize session")}let d=await p.json();return d.visitor?.token&&await this.historyInternals.visitorStore?.set(d.visitor.token),{sessionId:d.sessionId,expiresAt:new Date(d.expiresAt),flow:d.flow,...d.conversationId?{conversationId:d.conversationId}:{},...d.targetId?{targetId:d.targetId}:{},...d.conversationRevision?{conversationRevision:d.conversationRevision}:{},...d.durableRecovery?{durableRecovery:d.durableRecovery}:{},...d.visitor?{visitor:d.visitor}:{},config:{welcomeMessage:d.config.welcomeMessage,placeholder:d.config.placeholder,theme:d.config.theme}}}async#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(!sm(r,"not_found")&&!sm(r,"visitor_required")&&!sm(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 on("history_disabled","Visitor history is disabled for this surface");await this.historyInternals.historyBootstrapReady;let o=n?.proof??null;if(!await this.readVisitorToken()&&!o)throw new on("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let s=await this.#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":Yn},body:JSON.stringify(r)});if(!s.ok){let i=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,this.#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:on,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 Or()).listConversations(this.#I(),t)}async getConversation(t,n){return(await Or()).getConversation(this.#I(),t,n)}async finalizeDisplayProjections(t,n){return(await Or()).finalizeDisplayProjections(this.#I(),t,n)}async deleteConversation(t,n){return(await Or()).deleteConversation(this.#I(),t,n)}async deleteAllConversations(t){return(await Or()).deleteAllConversations(this.#I(),t)}async resetVisitor(){return(await Or()).resetVisitor(this.#I())}async dispatch(t,n){return t.signal?.throwIfAborted(),mi().catch(()=>{}),this.isClientTokenMode()?this.#de(t,n):this.isAgentMode()?this.#pe(t,n):this.#ne(t,n)}async#de(t,n){let o=Aw();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(im).map(A=>{let L=g?Fl(A):void 0;return{id:A.id,role:A.role,content:A.contentParts??A.llmContent??A.rawContent??A.content,...L!==void 0&&{displayContent:L}}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...d&&Object.keys(d).length>0&&{metadata:d},...p.inputs&&Object.keys(p.inputs).length>0&&{inputs:p.inputs},...p.context&&{context:p.context},turnId:o,...t.interrupt&&{submitMode:"interrupt"}},h=async()=>{i();let A=l.durableRecovery?.enabled===!0?await this.readVisitorToken():null;return i(),this.#$(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":Yn,...A?{"X-Visitor-Token":A}:{}},body:JSON.stringify(H),signal:t.signal})})},y=await h();if(i(),y.response.status===401){let A=await y.response.clone().json().catch(()=>null);i(),A?.error==="Session not found or expired"&&(await c(),y=await h(),i())}let{response:v,commit:C}=y;if(!v.ok){let A=await v.json().catch(()=>({error:"Chat request failed"}));if(v.status===401&&A.error==="invalid_identity_proof"){let I=new on("invalid_identity_proof",ok);throw s({type:"error",error:I}),I}if(v.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let I=new Error("Session expired. Please refresh to continue.");throw s({type:"error",error:I}),I}if(v.status===429){let I=new Error(A.hint||"Message limit reached for this session.");throw s({type:"error",error:I}),I}if(v.status===410&&A.error==="conversation_deleted"){let I=new on("conversation_deleted","This conversation was deleted");throw s({type:"error",error:I}),I}let L=new Error(A.error||"Failed to send message");throw s({type:"error",error:L}),L}if(!v.body){let A=new Error("No response body received");throw s({type:"error",error:A}),A}C(),s({type:"status",status:"connected"});try{await this.#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 on)&&!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 mi()).resolveApproval(this.#le(),t,n)}async#$(t,n,o,r){let s=!!(n&&n.length>0),i=s?gv(n):void 0,l=this.clientToolsFingerprintSessionId===t,c=s&&l&&this.lastSentClientToolsFingerprint===i,p=!s&&r?.emptyMeansReplace===!0&&this.#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 mi()).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=rm(Mw(t),p=>im(p)&&(p.role==="user"||p.role==="assistant"||p.role==="system")&&(!p.variant||p.variant==="assistant")?Ew(p):null),s=this.#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=[...fi(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=rm(Mw(t),p=>im(p)?Ew(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=[...fi(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}=Nv()??await mi();return s({config:()=>this.config,createStreamParser:this.#o,parseSSEEvent:this.#c,onSSEEvent:(i,l)=>this.#d?.(i,l)},t,n,o,r)}};var Vr=class extends Error{constructor(t,n,o){super(n),this.name="HistoryProviderError",this.code=t,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}};function Tw(e){return e instanceof Vr}pi();Ca();Nr();ha();Nr();function sk(e){let t=0;for(let n of e.split(`
|
|
15
|
+
`):e};var mw="var(--persona-md-table-scroll-fade, 24px)",hw=new WeakSet;function bw(e){e.querySelectorAll("table").forEach(n=>{if(n.parentElement?.classList.contains("persona-table-scroll"))return;let r=document.createElement("div");r.className="persona-table-scroll",n.replaceWith(r),r.appendChild(n)})}function yw(e){let t=e.scrollWidth-e.clientWidth;if(t<=1){e.removeAttribute("data-persona-scroll-x");return}e.setAttribute("data-persona-scroll-x","");let o=getComputedStyle(e).direction==="rtl"?t+e.scrollLeft:e.scrollLeft,r=t-o;e.style.setProperty("--persona-fade-l",o<=1?"0px":mw),e.style.setProperty("--persona-fade-r",r<=1?"0px":mw)}function om(e){hw.has(e)||(hw.add(e),e.addEventListener("scroll",t=>{let n=t.target;n?.classList?.contains("persona-table-scroll")&&yw(n)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(yw)}pi();dn();var{setLoader:mO,load:XP}=lt({fallbackImport:()=>import("@runtypelabs/persona/webmcp-runtime")});var vw=XP;var QP="agent_",JP="flow_";function Cw(e){return e.startsWith(QP)?{kind:"agentId",agentId:e}:e.startsWith(JP)?{kind:"flowId",flowId:e}:null}function ww(e,t){let n=e.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let i=n.slice(0,o),l=n.slice(o+1);if(i==="runtype"){let p=Cw(l);if(p)return p;throw new Error(`[Persona] target "runtype:${l}" is not a valid Runtype agent_/flow_ id.`)}let c=t?.[i];if(!c)throw new Error(`[Persona] No target provider registered for "${i}". Add a \`targetProviders.${i}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:c(l).payload}}let r=Cw(n);if(r)return r;let s=t?.default;if(s)return{kind:"payload",payload:s(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}function Sw(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Ha(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Ps(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}function Aw(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`turn_${e}_${t}`}Bd();var ZP=e=>e.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase().replace(/_+/g,"_").replace(/^_|_$/g,""),ek=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),tk=e=>{if(e.variant!=="tool")return null;let t=e.agentMetadata?.clientToolAnswer;if(!t||!t.toolCallId||t.result===void 0)return null;let n=ZP(t.toolName);return n?{call:{toolCallId:t.toolCallId,toolName:n,args:ek(t.args)?t.args:{}},result:{toolCallId:t.toolCallId,toolName:n,result:t.result}}:null},rm=(e,t)=>{let n=[],o=[],r=[],s="",i,l=()=>{o.length!==0&&(n.push({role:"assistant",content:"",createdAt:s,toolCalls:o},{role:"tool",content:"",createdAt:s,toolResults:r}),o=[],r=[])};for(let c of e){let p=tk(c);if(p){let g=c.agentMetadata?.clientToolAnswer?.batch;o.length>0&&(g===void 0||g!==i)&&l(),o.length===0&&(s=c.createdAt,i=g),o.some(f=>f.toolCallId===p.call.toolCallId)||(o.push(p.call),r.push(p.result));continue}let d=t(c);d&&(l(),n.push(d))}return l(),n};Cs();Sa();yp();Bo();var nk="https://api.runtype.com/v1/dispatch",on=class extends Error{constructor(t,n,o){super(n),this.name="HistoryClientError",this.code=t,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}},xw=e=>"reason"in e?e.reason:void 0,ok="The identity proof was rejected",sm=(e,t)=>e instanceof on&&e.code===t,im=e=>e.voiceCaption?!1:!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0),Mw=e=>e.slice().sort((t,n)=>new Date(t.createdAt).getTime()-new Date(n.createdAt).getTime()),Ew=e=>({role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,createdAt:e.createdAt});function rk(e){switch(e){case"json":return Pd;case"regex-json":return Td;case"xml":return kd;default:return Ed}}var wi=class{constructor(t={},n={}){this.config=t;this.historyInternals=n;this.#g=null;this.clientSession=null;this.#l=null;this.#c=!1;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.#a=null;this.#E=!1;this.#h=!1;this.#S=!1;this.#v=null;this.#A=new Set;this.#d=new Set;this.webMcpBridge=null;this.#u=null;this.#$=null;this.#de=null;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.#e=t.apiUrl??nk,this.#n={"Content-Type":"application/json","X-Persona-Version":Yn,...t.headers},this.debug=!!t.debug,this.#o=t.streamParser??rk(t.parserType),this.#t=t.contextProviders??[],this.#s=t.requestMiddleware,this.#r=t.customFetch,this.#p=t.parseSSEEvent,this.#f=t.getHeaders,t.webmcp?.enabled===!0&&(this.#u=this.#C(t.webmcp))}#e;#n;#o;#t;#s;#r;#p;#f;#i;#g;#l;#c;#a;#E;#h;#S;#v;#A;#d;#u;#m;#C(t){return vw().then(n=>{let o=new n.WebMcpBridge(t,{recordToolDisplayTitles:Cd,getToolDisplayTitle:ma,loadPolyfill:wd});return this.#m!==void 0&&o.setConfirmHandler(this.#m),this.webMcpBridge=o,o}).catch(n=>(this.#u=null,console.warn("[Persona] Failed to load the WebMCP runtime chunk",n),null))}#x(){return this.webMcpBridge?Promise.resolve(this.webMcpBridge):this.config.webmcp?.enabled!==!0?Promise.resolve(null):(this.#u||(this.#u=this.#C(this.config.webmcp)),this.#u)}updateConfig(t){this.config=t}setHistoryInternals(t){this.historyInternals=t}setSSEEventCallback(t){this.#i=t}setWebMcpConfirmHandler(t){this.#m=t,this.webMcpBridge?.setConfirmHandler(t)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(t,n,o){return this.config.webmcp?.enabled!==!0?null:this.#x().then(r=>r?r.executeToolCall(t,n,o):{isError:!0,content:[{type:"text",text:"WebMCP runtime failed to load."}]})}getSSEEventCallback(){return this.#i}isClientTokenMode(){return!!this.config.clientToken}#y(){let{agentId:t,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:t,flowId:n};let s=ww(o,r);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.#y().agentId)}#b(){return this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||_d}#H(t){return`${this.#b()}/v1/client/${t}`}getClientSession(){return this.clientSession}async reconnectClientTokenStream(t){let n=await this.initSession(),o=!1;for(;;){let r=n.conversationId,s=await this.readVisitorToken();if(n.durableRecovery?.enabled!==!0||!r||!s)throw new on("visitor_token_missing","Durable recovery is not enabled for this client session");let i=`${this.#b()}/v1/client/conversations/${encodeURIComponent(r)}/executions/${encodeURIComponent(t.executionId)}/events`,l=new URLSearchParams({sessionId:n.sessionId,after:t.after}),c=await fetch(`${i}?${l}`,{method:"GET",headers:{"X-Persona-Version":Yn,"X-Visitor-Token":s},signal:t.signal});if(c.status===401&&!o){o=!0;let p=await Or();n=await p.recoverFromUnauthorized(this.#W(),await p.readErrorCode(this.#W(),c),null,!0);continue}if(!c.ok)throw await(await Or()).historyErrorFor(this.#W(),c,!0);return c}}async warmSession(){let t=this.clientSession;return!this.isClientTokenMode()||this.#l||t&&new Date<t.expiresAt||this.#c===t?null:(this.#c=t,this.initSession().catch(()=>null))}async initSession(){if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.#l)return this.#l;let t=this.#l=this.#K().then(n=>this.#l!==t?this.initSession():(this.clientSession=n,this.#c=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(n),n)).finally(()=>{this.#l===t&&(this.#l=null)});return t}#k(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()&&!this.#E}async readVisitorToken(){let t=this.historyInternals.visitorStore;return t?(await t.ready,await t.get()??null):null}#M(){if(!this.#E){this.#B({state:"unavailable",reason:"history_disabled"}),this.#E=!0,!this.#h&&typeof console<"u"&&(this.#h=!0,console.warn("[Persona] Visitor history is disabled for this surface; continuing without it.")),this.historyInternals.onHistoryAvailabilityChanged?.(!1);for(let t of[...this.#d])t(!1)}}getHistoryIdentityStatus(){return this.#v??this.#I()}subscribeHistoryIdentityStatus(t){return this.#A.add(t),()=>{this.#A.delete(t)}}subscribeHistoryAvailability(t){return this.#d.add(t),this.#E&&t(!1),()=>{this.#d.delete(t)}}#I(){return this.isClientTokenMode()?this.config.features?.history?.enabled!==!0||this.#E?{state:"unavailable",reason:"history_disabled"}:this.#Y():{state:"unavailable",reason:"ineligible_mode"}}#Y(){let t=this.#v;return t?.state==="browser_only"?t:this.#j()}#j(){return this.config.features?.history?.scope==="browser"?{state:"browser_only",reason:"configured_browser_scope"}:this.config.getIdentityProof?{state:"browser_only",reason:"proof_unavailable_before_binding"}:{state:"browser_only",reason:"no_identity_provider"}}#B(t){let n=this.getHistoryIdentityStatus(),o=n.state===t.state&&xw(n)===xw(t);if(this.#v=t,!o){this.historyInternals.onHistoryIdentityStatusChanged?.(t);for(let r of[...this.#A])r(t)}}async#T(t){let n=this.#k()&&!t.omitVisitorFields,o=!t.omitVisitorFields,r=null;(n||o)&&(await this.historyInternals.historyBootstrapReady,r=await this.readVisitorToken());let s=this.#y(),i=s.agentId??s.flowId,l=n||t.durableResume?t.conversationId:void 0,c={token:this.config.clientToken,...i&&{flowId:i},...n&&{visitorHistory:!0},...o&&{durableRecovery:!0},...(n||o)&&r?{visitorToken:r}:{},...n&&t.identityProof?{identityProof:t.identityProof}:{},...l?{conversationId:l}:t.storedSessionId?{sessionId:t.storedSessionId}:{}};t.signal?.throwIfAborted();let p=await fetch(this.#H("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Yn},body:JSON.stringify(c),signal:t.signal});if(!p.ok){let g=await p.json().catch(()=>({error:"Session initialization failed"}));if(n&&p.status===403&&g.error==="visitor_history_disabled"){if(this.#M(),l)throw new on("history_disabled","Visitor history is disabled for this surface");return this.#T({...t,omitVisitorFields:!0})}throw p.status===403&&g.error==="durable_recovery_disabled"?new on("history_disabled","Durable recovery is disabled for this surface"):(n||t.durableResume)&&p.status===401&&g.error==="visitor_required"?new on("visitor_required","Visitor credential no longer resolves"):l&&p.status===404?new on("not_found","Conversation not found"):p.status===401?new Error(`Invalid client token: ${g.hint||g.error}`):p.status===403?new Error(`Origin not allowed: ${g.hint||g.error}`):new Error(g.error||"Failed to initialize session")}let d=await p.json();return d.visitor?.token&&await this.historyInternals.visitorStore?.set(d.visitor.token),{sessionId:d.sessionId,expiresAt:new Date(d.expiresAt),flow:d.flow,...d.conversationId?{conversationId:d.conversationId}:{},...d.targetId?{targetId:d.targetId}:{},...d.conversationRevision?{conversationRevision:d.conversationRevision}:{},...d.durableRecovery?{durableRecovery:d.durableRecovery}:{},...d.visitor?{visitor:d.visitor}:{},config:{welcomeMessage:d.config.welcomeMessage,placeholder:d.config.placeholder,theme:d.config.theme}}}async#K(){await this.historyInternals.historyBootstrapReady;let t=this.config.getStoredConversationId?.()||null,n=this.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.#k()&&!n)return this.#_(t,!1);let o=await this.readVisitorToken();if(t&&o)try{let r=await this.#T({conversationId:t,durableResume:n});return n&&r.durableRecovery?.enabled!==!0&&this.historyInternals.setStoredResumableHandle?.(null),this.#D(r,t,!1)}catch(r){if(!sm(r,"not_found")&&!sm(r,"visitor_required")&&!sm(r,"history_disabled"))throw r;return n&&this.historyInternals.setStoredResumableHandle?.(null),this.#_(t,!0)}return this.#_(t,!1)}async#_(t,n){let o=this.historyInternals.visitorStore;return o&&!await this.readVisitorToken()?o.withFirstInitLock(()=>this.#F(t,n)):this.#F(t,n)}async#F(t,n){let o=this.config.getStoredSessionId?.()||null,r=await this.#T({storedSessionId:o}),s=await this.#te(r);return this.#D(s,t,n)}async#ee(t){let n=this.config.getStoredSessionId?.()||null,o=this.config.getStoredConversationId?.()||null,r=await this.#T({storedSessionId:n,identityProof:t}),s=this.#D(r,o,!1);return this.clientSession=s,this.#l=null,this.#c=!1,this.resetClientToolsFingerprint(),s}async#te(t){if(!t.visitor?.token||this.#S||!this.#k()&&t.durableRecovery?.enabled!==!0)return t;this.#S=!0;try{return await this.#T({storedSessionId:t.sessionId})}catch{return t}finally{this.#S=!1}}#D(t,n,o){let r=t.conversationId;return r&&n&&(o||r!==n)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:n,conversationId:r}),this.config.setStoredSessionId?.(t.sessionId),r&&(this.config.setStoredConversationId?.(r),this.historyInternals.setStoredConversationRevision?.(t.conversationRevision??null)),t}#X(t){let n=!1;return{session:t,commit:()=>{n||(n=!0,this.clientSession=t,this.#c=!1,this.resetClientToolsFingerprint())},discard:()=>{n=!0}}}async prepareConversationSession(t,n){if(!this.isClientTokenMode())throw new Error("prepareConversationSession() only available in client token mode");if(!this.#k())throw new on("history_disabled","Visitor history is disabled for this surface");await this.historyInternals.historyBootstrapReady;let o=n?.proof??null;if(!await this.readVisitorToken()&&!o)throw new on("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let s=await this.#T({conversationId:t,identityProof:o});return this.#X(s)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw new Error("prepareNewConversationSession() only available in client token mode");await this.historyInternals.historyBootstrapReady;let t=await this.#T({});return this.#X(t)}handleExternalCredentialChange(){this.clearClientSession(),this.#k()&&this.#B(this.#j())}clearClientSession(){this.clientSession=null,this.#l=null,this.#c=!1,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.#a=null}#Z(){return`${this.#b()}/v1/client/feedback`}async sendFeedback(t){if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.#Z(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Yn},body:JSON.stringify(r)});if(!s.ok){let i=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,this.#c=!1,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:n})}async#ne(t){t?.throwIfAborted();let n=this.config.identityProvider;if(n===void 0)return;let o=this.config.getIdentityProof;if(!n.trim()||!o)throw new Error("Chat identity requires identityProvider and getIdentityProof.");let r,s;try{let i=Promise.resolve().then(()=>o());r=t?await Promise.race([i,new Promise((l,c)=>{s=()=>c(t.reason),t.addEventListener("abort",s,{once:!0}),t.aborted&&s()})]):await i}catch{throw t?.throwIfAborted(),new Error("The identity proof provider failed.")}finally{s&&t?.removeEventListener("abort",s)}if(typeof r!="string"||!r.trim())throw new Error("A fresh identity proof is required to send this message.");return{provider:n,token:r}}#$;#U(){let t=this;return this.#$??={get config(){return t.config},headers:this.#n,getHeaders:this.#f,debug:this.debug,clientApiBase:()=>t.#b(),getClientApiUrl:n=>t.#H(n),getWebMcpBridge:()=>t.#x(),sendWithClientToolsDiff:(n,o,r,s)=>t.#re(n,o,r,s),initSession:()=>t.initSession(),readVisitorToken:()=>t.readVisitorToken(),isClientTokenMode:()=>t.isClientTokenMode()}}#de;#W(){let t=this;return this.#de??={HistoryClientError:on,get config(){return t.config},get historyInternals(){return t.historyInternals},get clientSession(){return t.clientSession},clientApiBase:()=>t.#b(),setHistoryIdentityStatus:n=>t.#B(n),browserOnlyStatus:()=>t.#Y(),derivedBrowserOnly:()=>t.#j(),reinitWithProof:n=>t.#ee(n),isHistoryCapable:()=>t.#k(),clearClientSession:()=>t.clearClientSession(),initSession:()=>t.initSession(),readVisitorToken:()=>t.readVisitorToken(),isClientTokenMode:()=>t.isClientTokenMode()}}async listConversations(t){return(await Or()).listConversations(this.#W(),t)}async getConversation(t,n){return(await Or()).getConversation(this.#W(),t,n)}async finalizeDisplayProjections(t,n){return(await Or()).finalizeDisplayProjections(this.#W(),t,n)}async deleteConversation(t,n){return(await Or()).deleteConversation(this.#W(),t,n)}async deleteAllConversations(t){return(await Or()).deleteAllConversations(this.#W(),t)}async resetVisitor(){return(await Or()).resetVisitor(this.#W())}async dispatch(t,n){return t.signal?.throwIfAborted(),mi().catch(()=>{}),this.isClientTokenMode()?this.#be(t,n):this.isAgentMode()?this.#pe(t,n):this.#oe(t,n)}async#be(t,n){let o=Aw();this.#g=o;let r=()=>this.#g===o,s=i=>{r()&&n(i)};n({type:"status",status:"connecting"});try{let i=()=>{if(t.signal?.throwIfAborted(),!r())throw new DOMException("Turn superseded","AbortError")},l=this.clientSession??await this.initSession();i();let c=async()=>{i();let A=l,L=A.durableRecovery?.enabled===!0;if(L&&(!A.conversationId||!await this.readVisitorToken()))throw new Error("Renewing this conversation requires its visitor credential.");i();let I=await this.#T({...L||this.#k()?{conversationId:A.conversationId,durableResume:L}:{storedSessionId:A.sessionId},signal:t.signal});if(i(),A.conversationId&&I.conversationId!==A.conversationId||L&&I.durableRecovery?.enabled!==!0)throw new Error("Session renewal did not preserve this conversation.");l=this.#D(I,A.conversationId??null,!1),this.clientSession=l,this.#c=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(l)};Date.now()>=l.expiresAt.getTime()-6e4&&await c();let p=await this.#N(t.messages),d=p.metadata?Object.fromEntries(Object.entries(p.metadata).filter(([A])=>A!=="sessionId"&&A!=="session_id")):void 0,g=this.#k(),f={sessionId:l.sessionId,messages:t.messages.filter(im).map(A=>{let L=g?Fl(A):void 0;return{id:A.id,role:A.role,content:A.contentParts??A.llmContent??A.rawContent??A.content,...L!==void 0&&{displayContent:L}}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...d&&Object.keys(d).length>0&&{metadata:d},...p.inputs&&Object.keys(p.inputs).length>0&&{inputs:p.inputs},...p.context&&{context:p.context},turnId:o,...t.interrupt&&{submitMode:"interrupt"}},h=async()=>{i();let A=l.durableRecovery?.enabled===!0?await this.readVisitorToken():null;return i(),this.#re(l.sessionId,p.clientTools,async L=>{i();let I=await this.#ne(t.signal);i();let H={...f,sessionId:l.sessionId,...L,...I&&{identityProof:I}};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",{...H,...I&&{identityProof:{provider:I.provider,token:"[REDACTED]"}}}),fetch(this.#H("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Yn,...A?{"X-Visitor-Token":A}:{}},body:JSON.stringify(H),signal:t.signal})})},y=await h();if(i(),y.response.status===401){let A=await y.response.clone().json().catch(()=>null);i(),A?.error==="Session not found or expired"&&(await c(),y=await h(),i())}let{response:v,commit:C}=y;if(!v.ok){let A=await v.json().catch(()=>({error:"Chat request failed"}));if(v.status===401&&A.error==="invalid_identity_proof"){let I=new on("invalid_identity_proof",ok);throw s({type:"error",error:I}),I}if(v.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let I=new Error("Session expired. Please refresh to continue.");throw s({type:"error",error:I}),I}if(v.status===429){let I=new Error(A.hint||"Message limit reached for this session.");throw s({type:"error",error:I}),I}if(v.status===410&&A.error==="conversation_deleted"){let I=new on("conversation_deleted","This conversation was deleted");throw s({type:"error",error:I}),I}let L=new Error(A.error||"Failed to send message");throw s({type:"error",error:L}),L}if(!v.body){let A=new Error("No response body received");throw s({type:"error",error:A}),A}C(),s({type:"status",status:"connected"});try{await this.#G(v.body,s,t.assistantMessageId)}finally{s({type:"status",status:"idle"})}}catch(i){let l=i instanceof Error?i:new Error(String(i));throw!(l instanceof on)&&!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&s({type:"error",error:l}),l}}async#oe(t,n){n({type:"status",status:"connecting"});let o=await this.#N(t.messages,t.composerOptions);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.#n};if(this.#f)try{let i=await this.#f();r={...r,...i}}catch(i){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.#r)try{s=await this.#r(this.#e,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(i){let l=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:l}),l}else s=await fetch(this.#e,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let i=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.#G(s.body,n)}finally{n({type:"status",status:"idle"})}}async#pe(t,n){n({type:"status",status:"connecting"});let o=await this.#L(t.messages,t.composerOptions);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.#n};if(this.#f)try{let i=await this.#f();r={...r,...i}}catch(i){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.#r)try{s=await this.#r(this.#e,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(i){let l=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:l}),l}else s=await fetch(this.#e,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let i=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.#G(s.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o,r){n({type:"status",status:"connected"});try{await this.#G(t,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){return(await mi()).resolveApproval(this.#U(),t,n)}async#re(t,n,o,r){let s=!!(n&&n.length>0),i=s?gv(n):void 0,l=this.clientToolsFingerprintSessionId===t,c=s&&l&&this.lastSentClientToolsFingerprint===i,p=!s&&r?.emptyMeansReplace===!0&&this.#a===t,d=!1,g;for(let f=0;;f++){if(g=await o({...s&&(d||!c)&&n?{clientTools:n}:{},...p?{clientTools:[]}:{},...i?{clientToolsFingerprint:i}:{}}),g.status===409&&f===0&&s&&(await g.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){d=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:g,commit:()=>{this.lastSentClientToolsFingerprint=i??null,this.clientToolsFingerprintSessionId=t,s?this.#a=t:p&&(this.#a=null)}}}async resumeFlow(t,n,o){return(await mi()).resumeFlow(this.#U(),t,n,o)}#se(t){for(let n=t.length-1;n>=0;n--){let o=t[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async#q(t){let n={};this.#t.length&&await Promise.all(this.#t.map(async r=>{try{let s=await r({messages:t,config:this.config});s&&typeof s=="object"&&Object.assign(n,s)}catch(s){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",s)}}));let o=this.#se(t);return o&&Object.assign(n,o),Object.keys(n).length?n:null}#R(t){if(!t)return;let n={};return t.selectedModelId&&(n.selectedModelId=t.selectedModelId),t.activeModeIds?.length&&(n.activeModeIds=[...t.activeModeIds]),Object.keys(n).length>0?n:void 0}#O(t,n){let o=n?.selectedModelId;return!o||!("model"in t)?t:this.config.composer?.models?.some(s=>s.id===o)?{...t,model:o}:t}async#L(t,n){let o=this.#y().agentId;if(!this.config.agent&&!o)throw new Error("Agent configuration required for agent mode");let r=rm(Mw(t),p=>im(p)&&(p.role==="user"||p.role==="assistant"||p.role==="system")&&(!p.variant||p.variant==="assistant")?Ew(p):null),s=this.#R(n),i={agent:this.#O(this.config.agent??{agentId:o},s),messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};s&&(i.composerOptions=s);let l=[...fi(this.config),...await(await this.#x())?.snapshotForDispatch()??[]];l.length>0&&(i.clientTools=l);let c=await this.#q(t);return c&&(i.context=c),i}async#N(t,n){let o=rm(Mw(t),p=>im(p)?Ew(p):null),r=this.#y(),s={messages:o,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[p,d]of Object.entries(r.targetPayload))p!=="messages"&&(s[p]=d);let i=[...fi(this.config),...await(await this.#x())?.snapshotForDispatch()??[]];i.length>0&&(s.clientTools=i);let l=await this.#q(t);l&&(s.context=l);let c=this.#R(n);if(c&&(s.composerOptions=c),this.#s)try{let p=await this.#s({payload:{...s},config:this.config});if(p&&typeof p=="object"){let d=p;return s.clientTools!==void 0&&!("clientTools"in d)&&(d.clientTools=s.clientTools),d}}catch(p){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",p)}return s}async#G(t,n,o,r){let{streamResponse:s}=Nv()??await mi();return s({config:()=>this.config,createStreamParser:this.#o,parseSSEEvent:this.#p,onSSEEvent:(i,l)=>this.#i?.(i,l)},t,n,o,r)}};var Vr=class extends Error{constructor(t,n,o){super(n),this.name="HistoryProviderError",this.code=t,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}};function Tw(e){return e instanceof Vr}pi();Ca();Nr();ha();Nr();function sk(e){let t=0;for(let n of e.split(`
|
|
16
16
|
`)){let o=/^ {0,3}(`+)/.exec(n);o&&o[1].length>t&&(t=o[1].length)}return t}function Pw(e,t){let n="`".repeat(Math.max(3,sk(t)+1));return`${n}${e}
|
|
17
17
|
${t}
|
|
18
18
|
${n}`}var ik=e=>e.sourceLabel?`quoted-text source=${e.sourceLabel}`:"quoted-text";function ak(e){let t=e?.text?.trim()??"";return t?Pw(ik(e),t):""}function kw(e){let t=ak(e.quote);return t?e.contentParts&&e.contentParts.length>0?{contentParts:[So(t),...e.contentParts]}:{llmContent:[t,e.text].filter(Boolean).join(`
|
|
19
19
|
|
|
20
|
-
`)}:{}}function kp(e,t=140){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function Lw(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 am(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 Hw(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 am(e,n.id)?n.id:null}return null}function lm(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}yp();function Ia(e){let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let n of t){let o=e.find(r=>r.name===n);if(o)return o}return e.find(n=>n.lang.startsWith("en"))??e[0]}var ks=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(t,n){if(!e.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(t.text),s=o.getVoices();if(t.voice){let i=s.find(l=>l.name===t.voice);i&&(r.voice=i)}else s.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(s):Ia(s));t.rate!==void 0&&(r.rate=t.rate),t.pitch!==void 0&&(r.pitch=t.pitch),r.onend=()=>n.onEnd?.(),r.onerror=i=>{let l=i.error;l==="canceled"||l==="interrupted"?n.onEnd?.():n.onError?.(new Error(l||"Speech synthesis failed"))},setTimeout(()=>{o.speak(r),n.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var Si=class{#e=null;#
|
|
20
|
+
`)}:{}}function kp(e,t=140){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function Lw(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 am(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 Hw(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 am(e,n.id)?n.id:null}return null}function lm(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}yp();function Ia(e){let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let n of t){let o=e.find(r=>r.name===n);if(o)return o}return e.find(n=>n.lang.startsWith("en"))??e[0]}var ks=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(t,n){if(!e.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(t.text),s=o.getVoices();if(t.voice){let i=s.find(l=>l.name===t.voice);i&&(r.voice=i)}else s.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(s):Ia(s));t.rate!==void 0&&(r.rate=t.rate),t.pitch!==void 0&&(r.pitch=t.pitch),r.onend=()=>n.onEnd?.(),r.onerror=i=>{let l=i.error;l==="canceled"||l==="interrupted"?n.onEnd?.():n.onError?.(new Error(l||"Speech synthesis failed"))},setTimeout(()=>{o.speak(r),n.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var Si=class{#e=null;#n=null;#o="idle";#t=new Set;#s=0;#r;constructor(t){this.#r=t}get supportsPause(){return this.#e?.supportsPause??!0}stateFor(t){return this.#n===t?this.#o:"idle"}activeMessageId(){return this.#n}onChange(t){return this.#t.add(t),()=>this.#t.delete(t)}toggle(t,n){if(this.#n===t){if(this.#o==="playing"){this.#e?.supportsPause?(this.#e.pause(),this.#p(t,"paused")):this.stop();return}if(this.#o==="paused"){this.#e?.resume(),this.#p(t,"playing");return}if(this.#o==="loading"){this.stop();return}}this.play(t,n)}async play(t,n){let o=++this.#s;this.#e?.stop(),this.#p(t,"loading");try{if(!this.#e){let r=await this.#r();if(o!==this.#s)return;if(!r){this.#p(null,"idle");return}this.#e=r}this.#e.speak(n,{onStart:()=>{o===this.#s&&this.#p(t,"playing")},onEnd:()=>{o===this.#s&&this.#p(null,"idle")},onError:()=>{o===this.#s&&this.#p(null,"idle")}})}catch{o===this.#s&&this.#p(null,"idle")}}stop(){this.#s++,this.#e?.stop(),this.#p(null,"idle")}destroy(){this.stop(),this.#e?.destroy?.(),this.#e=null,this.#t.clear()}#p(t,n){this.#n=n==="idle"?null:t,this.#o=n;for(let o of this.#t)o(this.#n,this.#o)}};var ql=class{#e;#n=!1;start(t){this.#e=t,this.#n=!1}cancel(){this.#n=!0}accepts(t){return!this.#n&&(!t||!this.#e||t===this.#e)}};dn();var{setLoader:VO,load:lk,getSync:ck}=lt({fallbackImport:()=>import("@runtypelabs/persona/voice-runtime")});var zl=lk,Iw=ck;function cm(e){if(!e)return"";let t=dk(e);return Rw(t!==null?t:e)}function dk(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 Rw(e){if(!e)return"";let t=e;return t=t.replace(/```[\s\S]*?```/g," "),t=t.replace(/~~~[\s\S]*?~~~/g," "),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),t=t.replace(/<\/?[a-zA-Z][^>]*>/g," "),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),t=t.replace(/^[ \t]*>[ \t]?/gm,""),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,""),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,""),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),t=t.replace(/(\*\*|__)(.*?)\1/g,"$2"),t=t.replace(/(\*|_)(.*?)\1/g,"$2"),t=t.replace(/~~(.*?)~~/g,"$1"),t=t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
|
|
21
21
|
`),t=t.replace(/\n{2,}/g,`
|
|
22
22
|
`),t.trim()}var Dw=null;var pm=()=>Dw?Dw():Promise.resolve().then(()=>(_w(),Bw));dn();var{setLoader:eB,load:gk}=lt({fallbackImport:()=>import("@runtypelabs/persona/session-reconnect")});var Nw=gk;var fk=["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 mk(e,t){return fk.some(n=>e[n]!==t[n])}var rr=class extends Error{constructor(t,n){super(n),this.name="SessionHistoryError",this.code=t}};function um(e,t){let n=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(n);let o="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${o}
|
|
23
23
|
|
|
24
|
-
_Details: ${n.message}_`:o}var Fw=e=>bs(e)||e===Oo,Wa=class e{constructor(t={},n,o={}){this.config=t;this.callbacks=n;this.historyInternals=o;this.status="idle";this.streaming=!1;this.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 ql;this.#re=Promise.resolve();this.#Y=null;this.#_=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new Si(()=>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)&&Gf().catch(()=>{});let o=t.message.toolCall,r=!!o?.name&&(bs(o.name)||o.name===Oo&&xs(this.config).enabled);t.message.agentMetadata?.awaitingLocalTool===!0&&r&&this.#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 wi(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&&zl().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||pm().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return sw(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.#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=ks.isSupported()?new ks({pickVoice:t?.pickVoice}):null;if(t?.provider==="runtype"){let o=t.host??this.config.apiUrl,r=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,s=this.config.clientToken,i=t.browserFallback!==!1;if(o&&r&&s)return pm().then(({RuntypeSpeechEngine:l,FallbackSpeechEngine:c})=>{let p=new l({host:o,agentId:r,clientToken:s,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return i&&n?new c(p,n,{onFallback:d=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${d.message}`)}):p});if(i&&n)return s&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(t){try{let n=t||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.cleanupVoice();let o=this.#re,r=++this.#g;this.#s=zl().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(!Dn(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 ql,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 rr("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 Vr("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 rr("conversation_busy","Finish or stop the current turn before switching conversations")}listConversations(t){return this.#R().list({...t?.cursor?{cursor:t.cursor}:{},...t?.limit!==void 0?{limit:t.limit}:{},...t?.targetId!==void 0?{targetId:t.targetId}:{},context:this.#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 rr("superseded","A later selection won");let l=await o.prepareOpen(t,{context:r});if(s!==this.#h)throw l.discard(),new rr("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=$l(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 rr("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 rr("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 rr("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 rr("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=$l(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=Fl(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=Fl(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 on&&(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 on?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 on&&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=rw(this.config,o),s=mk(this.config,o);this.config=o,r&&(this.cleanupVoice(),o.voiceRecognition?.enabled===!0&&Dn(o.voiceRecognition.provider)&&this.setupVoice());let i=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!s){this.client.updateConfig(o),i&&this.#Oe();return}this.#ge(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let l=this.client.getSSEEventCallback();this.client=new wi(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"?Ha():n==="assistant"?Ps():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:l??new Date().toISOString(),sequence:c??this.#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"?Ha():r==="assistant"?Ps():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:s,createdAt:p??new Date().toISOString(),sequence:d??this.#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 Fw=e=>bs(e)||e===Oo,Wa=class e{constructor(t={},n,o={}){this.config=t;this.callbacks=n;this.historyInternals=o;this.status="idle";this.streaming=!1;this.#e=new Map;this.abortController=null;this.#o=Date.now();this.clientSession=null;this.agentExecution=null;this.#t=null;this.#s=null;this.#r=!1;this.#p=null;this.#f=null;this.#i=null;this.artifacts=new Map;this.#g=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.#l=0;this.webMcpApprovalResolvers=new Map;this.#c=0;this.approvalTokens=new Map;this.webMcpAwaitBatches=new Map;this.#a=null;this.#E=null;this.#h=0;this.#S=0;this.#v=!1;this.#A="disconnected";this.#d=null;this.#u=null;this.#m=null;this.#C=0;this.#x=!1;this.#y=null;this.#b=!1;this.#H=null;this.#k=new Map;this.#M=null;this.#I=new Map;this.#Y=null;this.#j=null;this.#B=!1;this.#T=null;this.#K=null;this.#_=!1;this.#F=null;this.#D=null;this.#X=null;this.#Z=new ql;this.#ne=Promise.resolve();this.#$=null;this.#U=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new Si(()=>this.#de());this.#Ze=null;this.#le=0;this.handleEvent=t=>{let n=this.#U;if(n&&(t.type==="error"||t.type==="status"&&t.status==="error"?n.failed=!0:t.type==="message"&&t.message.role==="assistant"&&(n.dropped||this.ttsSpokenMessageIds.add(t.message.id),n.ids.includes(t.message.id)||n.ids.push(t.message.id))),t.type==="message"){this.upsertMessage(t.message),t.message.variant==="approval"&&t.message.approval&&t.message.approval.status!=="pending"&&this.#e.set(t.message.id,this.#n),t.message.role==="assistant"&&!t.message.variant&&t.message.streaming&&(this.#s=t.message.id),(t.message.variant==="approval"||t.message.agentMetadata?.awaitingLocalTool===!0)&&Gf().catch(()=>{});let o=t.message.toolCall,r=!!o?.name&&(bs(o.name)||o.name===Oo&&xs(this.config).enabled);t.message.agentMetadata?.awaitingLocalTool===!0&&r&&this.#et(t.message),t.message.agentMetadata?.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:t.message.agentMetadata.agentName??"",status:"running",currentIteration:t.message.agentMetadata.iteration??0,maxTurns:0})}else if(t.type==="cursor")this.#st(t.id);else if(t.type==="status"){if(t.status==="idle"&&!t.terminal&&this.#it()){this.#Pe();return}if(this.#z(t.status),t.status==="connecting")this.#P(!0);else if(t.status==="idle"||t.status==="error"){this.#De()||this.#Ae(),this.webMcpResolveControllers.size===0&&(this.#P(!1),this.abortController=null,this.#Ke(),this.#qe());let o=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(t.status==="error"?this.agentExecution.status="error":o||(this.agentExecution.status="complete")),this.#tt()}}else t.type==="error"?(this.#z("error"),this.#Ae(),this.webMcpResolveControllers.size===0&&(this.#P(!1),this.abortController=null),this.agentExecution?.status==="running"&&(this.agentExecution.status="error"),this.callbacks.onError?.(t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.#rt(t)};this.historyInternals=this.#se(o),this.messages=[...t.initialMessages??[]].map(r=>({...r,sequence:r.sequence??this.#V()})),this.messages=this.#ce(this.messages),this.client=new wi(t,this.historyInternals),this.#Le(),this.#Be();for(let r of t.initialArtifacts??[])this.artifacts.set(r.id,{...r,status:"complete"});t.initialSelectedArtifactId!=null&&(this.#g=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.#he(),this.callbacks.onStatusChanged(this.status),this.#te(),this.#ee()}#e;#n;#o;#t;#s;#r;#p;#f;#i;#g;#l;#c;#a;#E;#h;#S;#v;#A;#d;#u;#m;#C;#x;#y;#b;#H;#k;#M;#I;#Y;#j;#B;#T;#K;#_;#F;#ee(){this.config.voiceRecognition?.provider&&zl().catch(()=>{})}#te(){let t=this.config.textToSpeech;if(t?.provider!=="runtype"||t.createEngine)return;let n=t.host??this.config.apiUrl,o=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!n||!o||!this.config.clientToken||pm().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return sw(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.#v}getVoiceStatus(){return this.#A}getVoiceDisclosure(){return this.#a?.getDisclosure?.()??null}getVoiceLevel(){return this.#a?.onLevel?this.#S:null}getVoiceInterruptionMode(){return this.#a?.getInterruptionMode?this.#a.getInterruptionMode():"none"}stopVoicePlayback(){this.#a?.stopPlayback&&(this.#Z.cancel(),this.#$?.cancel(),this.#a.stopPlayback())}isBargeInActive(){return this.#a?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.#a?.deactivateBargeIn&&await this.#a.deactivateBargeIn()}#D;#X;#Z;#ne;#$;#U;#de(){let t=this.config.textToSpeech;if(t?.createEngine)return t.createEngine();let n=ks.isSupported()?new ks({pickVoice:t?.pickVoice}):null;if(t?.provider==="runtype"){let o=t.host??this.config.apiUrl,r=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,s=this.config.clientToken,i=t.browserFallback!==!1;if(o&&r&&s)return pm().then(({RuntypeSpeechEngine:l,FallbackSpeechEngine:c})=>{let p=new l({host:o,agentId:r,clientToken:s,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return i&&n?new c(p,n,{onFallback:d=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${d.message}`)}):p});if(i&&n)return s&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(t){try{let n=t||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.cleanupVoice();let o=this.#ne,r=++this.#h;this.#E=zl().then(async s=>{await o,r===this.#h&&this.#W(s,s.createVoiceProvider(n))}).catch(s=>{console.error("Failed to setup voice:",s)}).finally(()=>{r===this.#h&&(this.#E=null)})}catch(n){console.error("Failed to setup voice:",n)}}#W(t,n){this.#a=n;let o=this;t.wireSessionVoice({session:this,provider:()=>o.#a,generation:()=>o.#h,get keyed(){return o.#$},set keyed(r){o.#$=r},get pendingUser(){return o.#D},set pendingUser(r){o.#D=r},get pendingAssistant(){return o.#X},set pendingAssistant(r){o.#X=r},turns:()=>o.#Z,busy:()=>o.#be(),setStreaming:r=>o.#P(r),setDelegation:r=>{o.#U=r},setLevel:r=>{o.#S=r},setStatus:r=>{o.#A=r,o.#v=r==="listening"},settlePending:r=>o.#pe(r)},n,t.KeyedVoiceTranscript,t.createVoiceSessionBridge)}async toggleVoice(){if(!this.#a&&this.#E&&await this.#E,!this.#a){console.error("Voice not configured");return}if(this.#v)await this.#a.stopListening();else{this.stopSpeaking();try{await this.#a.startListening()}catch(t){console.error("Failed to start voice:",t)}}}prewarmVoice(){if(!Dn(this.config.voiceRecognition?.provider)){this.warmClientSession();return}let t=this.#h,n=()=>{let o=this.#a;!o?.prewarm||t!==this.#h||this.#v||this.isBargeInActive()||Promise.resolve().then(()=>o.prewarm?.()).catch(()=>{})};if(!this.#a&&this.#E){this.#E.then(n,()=>{});return}n()}#be(){return!!this.abortController||this.webMcpResolveControllers.size>0||this.webMcpAwaitBatches.size>0||this.#r||this.status==="resuming"}cleanupVoice(){let t=this.#a!==null;if(this.#h++,this.#E=null,this.#a){let n=this.#a;this.#a=null,this.#ne=this.#oe(n)}this.#v=!1,this.#A="disconnected",this.#pe(!0),this.#$?.settle(),this.#$=null,this.#Z=new ql,t&&this.callbacks.onVoiceStatusChanged?.("disconnected")}async#oe(t){try{await t.disconnect()}catch(n){console.error("Failed to disconnect voice:",n)}}#pe(t){let n=t?this.#D:null,o=this.#X;!n&&!o||(o&&this.#Z.cancel(),t&&(this.#D=null),this.#X=null,o&&this.ttsSpokenMessageIds.add(o),this.messages=this.messages.flatMap(r=>r.id!==n&&r.id!==o?[r]:r.id===o&&!r.content.trim()?[]:[{...r,streaming:!1,voiceProcessing:!1}]),this.callbacks.onMessagesChanged([...this.messages]),o&&this.#P(!1))}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:t.runtype?.agentId??this.config.agentId??"",clientToken:t.runtype?.clientToken??this.config.clientToken,host:t.runtype?.host??this.config.apiUrl,voiceId:t.runtype?.voiceId,createPlaybackEngine:t.runtype?.createPlaybackEngine,prewarmMode:t.runtype?.prewarmMode,attachIdleMs:t.runtype?.attachIdleMs,clientDelegation:t.runtype?.clientDelegation,callContext:t.runtype?.callContext,approvalTimeoutMs:t.runtype?.approvalTimeoutMs,disclosureText:t.runtype?.disclosureText}};case"browser":return{type:"browser",browser:{language:t.browser?.language||"en-US",continuous:t.browser?.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;this.config.features?.history?.enabled&&(await this.historyInternals.historyBootstrapReady,this.#j=this.historyInternals.getStoredConversationRevision?.()??null,this.#B=!0);try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return this.callbacks.onError?.(t instanceof Error?t:new Error(String(t))),null}}warmClientSession(){let t=!this.messages.length;this.client.warmSession().then(n=>{n&&this.client.getClientSession()===n&&this.setClientSession(n,t)})}setClientSession(t,n){this.clientSession=t,this.#re(t,n)}#re(t,n=!this.messages.length){if(this.#x||!t.config.welcomeMessage||!n)return;let o=this.messages[0],r={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:o?.createdAt??new Date().toISOString(),sequence:o?(o.sequence??0)-1:this.#V()};this.#J(r)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}setHistoryInternals(t){this.historyInternals=this.#se(t),this.client.setHistoryInternals(this.historyInternals),this.#Le()}destroy(){this.cleanupVoice(),this.#T?.(),this.#T=null,this.#K=null}#se(t){let n=t.onHistoryContinuityChanged;return{...t,onHistoryContinuityChanged:o=>{this.#Fe(o),n?.(o)}}}get#q(){return this.historyInternals.historyProvider??null}#R(){let t=this.#q;if(!t)throw new rr("history_unavailable","No conversation history provider is installed");return t}#O(t){let n=this.#R(),o=t??this.config.features?.history?.scope,r=this.config.getIdentityProof?"verified-user":"browser",s=o??(n.capabilities.scopes.includes(r)?r:n.capabilities.scopes[0]??r);if(!n.capabilities.scopes.includes(s))throw new Vr("unsupported_scope","This history scope is not supported.");return{scope:s}}getHistoryState(){return{activeConversationId:this.#d,conversationRevision:this.#u,nextMessageCursor:this.#m,recovery:this.#y,sendBlocked:this.#b}}getActiveConversationId(){return this.#d}#L(){this.callbacks.onHistoryStateChanged?.(this.getHistoryState())}#N(t,n){this.callbacks.onHistoryNotice?.({code:t,message:n})}async awaitHistorySettled(){let t=this.#H;t&&await t.catch(()=>{});let n=this.#M;n&&await n.catch(()=>{})}#G(){if(this.streaming||this.status==="paused"||this.status==="resuming")throw new rr("conversation_busy","Finish or stop the current turn before switching conversations")}listConversations(t){return this.#R().list({...t?.cursor?{cursor:t.cursor}:{},...t?.limit!==void 0?{limit:t.limit}:{},...t?.targetId!==void 0?{targetId:t.targetId}:{},context:this.#O(t?.scope)})}async openConversation(t,n){let o=this.#R();this.#G();let r=this.#O(n?.scope);await this.awaitHistorySettled();let s=++this.#C,i=await o.getPage(t,{context:r});if(s!==this.#C)throw new rr("superseded","A later selection won");let l=await o.prepareOpen(t,{context:r});if(s!==this.#C)throw l.discard(),new rr("superseded","A later selection won");this.#x=!0;try{await this.#ie(l)}finally{this.#x=!1}this.#d=l.conversationId||t,this.#u=l.conversationRevision||i.conversationRevision||null,this.#m=i.nextCursor,this.#y=null,this.#b=!1,this.#we();for(let c of i.messages)this.#I.set(c.id,c.content);return this.#ae(),this.hydrateMessages(i.messages),this.#L(),{summary:i.summary,nextMessageCursor:i.nextCursor}}loadOlderMessages(t,n,o){let r=this.#R(),s=this.#O(o?.scope),i=n??this.#m;if(!i)return Promise.resolve({messages:[],nextMessageCursor:null});let l=`${t} ${i}`,c=this.#k.get(l);if(c)return c;let p=this.#xe(r,t,i,s).finally(()=>{this.#k.delete(l)});return this.#k.set(l,p),p}async#xe(t,n,o,r){let s=this.messages[0]?.createdAt,i=await t.getPage(n,{cursor:o,...s?{beforeCreatedAt:s}:{},context:r});if(this.#d&&this.#d!==n)return{messages:[],nextMessageCursor:i.nextCursor};let l=$l(this.messages,i.messages);this.messages=this.#ce(l.map(c=>this.#Ce(c))),this.#m=i.nextCursor;for(let c of i.messages)this.#I.set(c.id,c.content);return this.historyInternals.setStoredMessageCursor?.(i.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.#L(),{messages:i.messages,nextMessageCursor:i.nextCursor}}async startNewConversation(t){let n=this.#R(),o=this.#O(t?.scope);await this.awaitHistorySettled();let r=++this.#C,s=await n.prepareStartNew({context:o});if(r!==this.#C)throw s.discard(),new rr("superseded","A later action won");await this.#ue(s)}async#ue(t){this.#ge(),await this.#ie(t),this.#d=t.conversationId||null,this.#u=t.conversationRevision||null,this.#m=null,this.#y=null,this.#b=!1,this.#ae(),this.#L()}async deleteConversation(t,n){let o=this.#R(),r=this.#O(n?.scope);await this.awaitHistorySettled(),await o.delete(t,{context:r}),t===this.#d&&await this.#ve(r)}async updateConversation(t,n,o){let r=this.#R();if(!r.update)throw new rr("history_unavailable","This history provider cannot update conversations");let s=this.#O(o?.scope);return await this.awaitHistorySettled(),r.update(t,n,{context:s})}canUpdateConversations(){return typeof this.#q?.update=="function"}async clearConversationHistory(t){let n=this.#R(),o=this.#O(t?.scope);await this.awaitHistorySettled();let r=await n.deleteAll({...t?.targetId!==void 0?{targetId:t.targetId}:{},context:o});return await this.#ve(o),r}async resetHistoryDevice(){let t=this.#R();if(!t.resetDevice)throw new rr("history_unavailable","This history provider cannot reset the device");this.#C+=1,this.#M=null;try{return await t.resetDevice()}finally{this.#ge(),this.#d=null,this.#u=null,this.#m=null,this.#y=null,this.#b=!1,this.#L()}}async#ve(t){this.#C+=1,this.#M=null,this.#ge(),this.#d=null,this.#u=null,this.#m=null,this.#b=!0,this.#y=null,this.#L(),await this.#Q(t)}async#Q(t){let n=this.#q;if(!n){this.#b=!1,this.#L();return}try{let o=await n.prepareStartNew({context:t});await this.#ue(o)}catch{this.#b=!0,this.#y="new_conversation_required",this.#L(),this.#N("new_conversation_required","That conversation was deleted. Start a new conversation to continue.")}}async#w(){if(!(this.#y!=="new_conversation_required"||!this.#q)&&(this.#y=null,await this.#Q(this.#O()),this.#y==="new_conversation_required"))throw new rr("new_conversation_required","A new conversation is required before sending")}async#ie(t){await t.commit();let n=this.client.getClientSession();n&&n.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(n)}bindActivatedSession(t){this.clientSession=t,this.config.setStoredSessionId?.(t.sessionId),t.conversationId&&(this.#d=t.conversationId,this.#u=t.conversationRevision??null,this.config.setStoredConversationId?.(t.conversationId),this.historyInternals.setStoredConversationRevision?.(t.conversationRevision??null)),this.#x||this.#re(t)}#ae(){this.#d?this.config.setStoredConversationId?.(this.#d):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.#u),this.historyInternals.setStoredMessageCursor?.(this.#m)}#we(){this.historyInternals.setStoredResumableHandle?.(null),this.agentExecution=null,this.#Te(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#I.clear(),this.#fe(null)}#ge(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#ye(),this.#me(),this.#le++,this.messages=[],this.#we(),this.#k.clear(),this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),this.#P(!1),this.#z("idle"),this.callbacks.onMessagesChanged([...this.messages])}#Fe(t){this.#C+=1,this.#M=null,this.#b=!0,this.#ge(),this.#d=t.conversationId,this.#u=null,this.#m=null,this.#y=null,this.#L(),this.#N("history_continuity_reset","This browser was reconnected to a different conversation, so the previous messages were cleared."),this.#H=Promise.resolve().then(()=>{this.#b=!1,this.#H=null,this.#L()})}#Le(){let t=this.historyInternals.visitorStore??null;t!==this.#K&&(this.#T?.(),this.#T=null,this.#K=t,t&&(this.#T=t.subscribe(n=>this.#$e(n))))}#$e(t){if(t.source!=="external"||t.previousToken===null)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.#C+=1,this.#M=null,this.#_=!0,this.#F=null;let n=this.messages.length>0;n||this.#d!==null||(this.config.getStoredConversationId?.()??null)!==null?this.#ge():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.#k.clear(),this.#fe(null)),this.#d=null,this.#u=null,this.#m=null,this.#y=null,this.#L(),n&&this.#N("history_continuity_reset","This browser's conversation history was reset in another tab, so the previous messages were cleared.")}#Ue(){return this.#_?(this.#F||(this.#F=this.#Ve().finally(()=>{this.#F=null})),this.#F):Promise.resolve()}async#Ve(){if(!this.isClientTokenMode()){this.#_=!1;return}try{this.bindActivatedSession(await this.client.initSession()),this.#_=!1}catch{}}reconcileBootConversation(t){let n=this.#q,o=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.#d;if(!n||!o)return Promise.resolve();let r=this.#O(t?.scope);this.#b=!0,this.#L();let s=this.#je(n,o,r).finally(()=>{this.#b=this.#y!==null,this.#H===s&&(this.#H=null),this.#L()});return this.#H=s,s}async#je(t,n,o){this.#d=n;let r=this.clientSession?.conversationRevision??this.#u??null,s=this.#B?this.#j:this.historyInternals.getStoredConversationRevision?.()??null;if(this.#B=!1,this.#m=this.historyInternals.getStoredMessageCursor?.()??this.#m,await this.replayPendingProjections(),r&&s&&r===s){this.#u=r;return}let i=await t.getPage(n,{context:o}),l=new Set(i.messages.map(g=>g.id)),c=this.messages.some(g=>l.has(g.id)),p=i.messages[0]?.createdAt,d;if(!c)d=i.messages.map(g=>this.#Ce(g));else{let g=this.#t?this.#s:null,f=this.messages.filter(h=>l.has(h.id)||h.id===g?!0:p!==void 0&&h.createdAt<p);d=$l(f,i.messages).map(h=>this.#Ce(h))}this.#m=i.nextCursor,this.#u=i.conversationRevision||r||null,this.#I.clear();for(let g of i.messages)this.#I.set(g.id,g.content);this.#ae(),this.messages=this.#ce(d),this.callbacks.onMessagesChanged([...this.messages])}#Me(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}#fe(t){this.#Y=t,this.historyInternals.setPendingDisplayProjections?.(t)}#He(){return this.historyInternals.getPendingDisplayProjections?.()??this.#Y}#Ie(t){if(this.#Me())for(let n of t){let o=Fl(n);o!==void 0&&this.#I.set(n.id,o)}}#qe(){if(!this.#Me())return;let t=this.#d;if(!t)return;let n=[];for(let o of this.messages){if(o.role!=="assistant"||o.streaming)continue;let r=Fl(o);r!==void 0&&this.#I.get(o.id)!==r&&n.push({id:o.id,displayContent:r})}n.length!==0&&(this.#fe({conversationId:t,messageIds:n.map(o=>o.id)}),this.#Re(t,n))}#Re(t,n){let r=(this.#M??Promise.resolve()).catch(()=>{}).then(()=>this.#We(t,n,!1)).finally(()=>{this.#M===r&&(this.#M=null)});this.#M=r}async#We(t,n,o){if(this.#d!==t)return;let r=n.filter(s=>this.#I.get(s.id)!==s.displayContent);if(r.length===0){this.#Ee(t,n);return}try{let{conversationRevision:s}=await this.client.finalizeDisplayProjections(t,r);for(let i of r)this.#I.set(i.id,i.displayContent);this.#d===t&&s&&(this.#u=s),this.#Ee(t,n)}catch(s){if(!o&&this.#ze(s)){await this.#We(t,r,!0);return}if(s instanceof on&&(s.code==="not_found"||s.code==="conversation_deleted")){this.#Ee(t,n);return}this.#N("projection_finalization_failed","Some message formatting could not be saved for history; it will be retried.")}}#ze(t){return t instanceof on?t.code==="request_failed":t instanceof Error}#Ee(t,n){let o=this.#He();if(!o||o.conversationId!==t)return;let r=new Set(n.map(i=>i.id)),s=o.messageIds.filter(i=>!r.has(i));this.#fe(s.length?{conversationId:t,messageIds:s}:null)}async replayPendingProjections(){if(!this.#Me())return;let t=this.#He();if(!t)return;if(this.#d&&t.conversationId!==this.#d){this.#fe(null);return}let n=[];for(let o of t.messageIds){let r=this.messages.find(s=>s.id===o);!r||typeof r.content!="string"||n.push({id:o,displayContent:r.content})}if(n.length===0){this.#fe(null);return}this.#Re(t.conversationId,n),await this.#M?.catch(()=>{})}#Ke(){this.#d&&(this.#u=null,this.historyInternals.setStoredConversationRevision?.(null))}async#Oe(){await this.awaitHistorySettled(),await this.#Ue(),this.#y==="new_conversation_required"&&await this.#w()}static#Ge(t){return t instanceof on&&t.code==="conversation_deleted"}async#Ye(t,n,o,r,s){this.#Ie(t);try{await this.client.dispatch({messages:t,signal:n.signal,assistantMessageId:o,composerOptions:s?.composerOptions,interrupt:s?.interrupt},this.handleEvent);return}catch(i){if(!e.#Ge(i))throw i;let l=await this.#Xe(r);if(!l)throw i;this.#Ie([l]),await this.client.dispatch({messages:[l],signal:n.signal,assistantMessageId:o,composerOptions:s?.composerOptions},this.handleEvent)}}async#Xe(t){let n=this.messages.find(r=>r.id===t);if(!n)return null;let o={...n};this.#C+=1,this.#M=null,this.#ge(),this.#d=null,this.#u=null,this.#m=null,this.#x=!0;try{let r=this.#q;if(r){let s=await r.prepareStartNew({context:this.#O()});await this.#ue(s)}else{this.client.clearClientSession();let s=await this.client.initSession();this.bindActivatedSession(s)}}catch{return this.#b=!0,this.#y="new_conversation_required",this.#L(),this.#N("new_conversation_required","That conversation was deleted. Start a new conversation to continue."),null}finally{this.#x=!1}return this.#J(o),this.#P(!0),this.#N("conversation_deleted_recovered","That conversation was deleted. Started a new conversation."),this.messages.find(r=>r.id===o.id)??o}updateConfig(t){let n=this.config.features?.artifacts?.display,o={...this.config,...t},r=rw(this.config,o),s=mk(this.config,o);this.config=o,r&&(this.cleanupVoice(),o.voiceRecognition?.enabled===!0&&Dn(o.voiceRecognition.provider)&&this.setupVoice());let i=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!s){this.client.updateConfig(o),i&&this.#_e();return}this.#me(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let l=this.client.getSSEEventCallback();this.client=new wi(this.config,this.historyInternals),i&&this.#_e(),this.#Be(),l&&this.client.setSSEEventCallback(l)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:o,llmContent:r,contentParts:s,id:i,createdAt:l,sequence:c,streaming:p=!1,voiceProcessing:d,voiceCaption:g,rawContent:f}=t,y={id:i??(n==="user"?Ha():n==="assistant"?Ps():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:l??new Date().toISOString(),sequence:c??this.#V(),streaming:p,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...d!==void 0&&{voiceProcessing:d},...g&&{voiceCaption:g},...f!==void 0&&{rawContent:f}};return this.upsertMessage(y),y}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:r,content:s,llmContent:i,contentParts:l,id:c,createdAt:p,sequence:d,streaming:g=!1,voiceProcessing:f,rawContent:h}=o,v={id:c??(r==="user"?Ha():r==="assistant"?Ps():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:s,createdAt:p??new Date().toISOString(),sequence:d??this.#V(),streaming:g,...i!==void 0&&{llmContent:i},...l!==void 0&&{contentParts:l},...f!==void 0&&{voiceProcessing:f},...h!==void 0&&{rawContent:h}};n.push(v)}return this.messages=this.#ce([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:o={},text:r="",llmContent:s,id:i,createdAt:l,sequence:c}=t,p={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(p),...s!==void 0&&{llmContent:s},...i!==void 0&&{id:i},...l!==void 0&&{createdAt:l},...c!==void 0&&{sequence:c}})}async#Qe(t,n,o){let r;try{r=await o()}catch{return}let s=r.blocks.join(`
|
|
25
25
|
|
|
26
26
|
`),i=[s,n].filter(Boolean).join(`
|
|
27
27
|
|
|
28
|
-
`),l=Array.isArray(t.contentParts)&&t.contentParts.length>0,c=r.contentParts.length>0;if(l){let p=[];s&&p.push(So(s)),p.push(...r.contentParts),p.push(...t.contentParts),t.contentParts=p}else if(c){let p=[];i&&p.push(So(i)),p.push(...r.contentParts),t.contentParts=p}else s&&(t.llmContent=i);Object.keys(r.context).length>0&&(t.mentionContext=r.context)}async sendMessage(t,n){let o=t.trim(),r=!!n?.replayFields&&(n.replayFields.llmContent!==void 0||n.replayFields.rawContent!==void 0||(n.replayFields.contextMentions?.length??0)>0);if(!o&&(!n?.contentParts||n.contentParts.length===0)&&(!n?.mentions||n.mentions.refs.length===0)&&!r)return;this.#_&&!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??Ha(),c=Ps();this.#o=null;let p=n?.contentParts&&Pa(n.contentParts)?Ta:"",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=kw({quote:n.quote,text:h.llmContent??h.content,contentParts:h.contentParts});y.contentParts&&(h.contentParts=y.contentParts),y.llmContent!==void 0&&(h.llmContent=y.llmContent),(y.contentParts||y.llmContent!==void 0)&&(h.quote={...n.quote},this.callbacks.onMessagesChanged([...this.messages]))}let f=i?[...this.messages.filter(h=>h!==i),{...i,createdAt:new Date().toISOString()}]:[...this.messages];try{await this.#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=um(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=Lw(this.messages,t);if(!o)return!1;let r=this.messages[o.start],s=n.replacement,i=s?s.text:r.content,l=s?s.contentParts:r.contentParts;if(!(!!i?.trim()||(l?.length??0)>0||!s&&(r.llmContent?.trim()?.length??0)>0))return!1;let p=s?void 0:{...r.llmContent!==void 0&&{llmContent:r.llmContent},...r.rawContent!==void 0&&{rawContent:r.rawContent},...r.mentionContext&&{mentionContext:r.mentionContext},...r.contextMentions&&{contextMentions:r.contextMentions},...r.quote&&{quote:r.quote}},d=s?this.#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=Ps();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=um(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=FC();if(o)return t(o,n);let r=this.#ie;return Gf().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=or(this.config.features?.artifacts,t),r=El(o,{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:"complete",...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...t.component?{component:t.component}:{},...t.props?{componentProps:t.props}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}),s=this.messages.find(i=>i.id===n);if(s){s.rawContent=r,s.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:n,content:"",rawContent:r})}#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=or(this.config.features?.artifacts,n),s=El(r,{artifactId:n.id,title:n.title,artifactType:n.artifactType,status:n.status,...n.file?{file:n.file}:{},...n.presentation?{presentation:n.presentation}:{},...n.component?{component:n.component}:{},...n.props?{componentProps:n.props}:{},...n.markdown!==void 0?{markdown:n.markdown}:{}});o.rawContent!==s&&(o.rawContent=s,o.streaming=n.status==="streaming",t=!0)}t&&this.callbacks.onMessagesChanged([...this.messages])}#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=Nw().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=>um(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=Ps(),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=cm(r.content);s.trim()&&this.readAloud.play(r.id,{text:s,voice:n.voice,rate:n.rate,pitch:n.pitch})}static pickBestVoice(t){return Ia(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let o=cm(n.content||"");if(!o.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(t,{text:o,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}#_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&&Fw(c)&&p&&d&&n.agentMetadata?.awaitingLocalTool===!0){let g=`${p}:${d}`,f=this.webMcpInflightKeys.has(g),h=this.webMcpResolvedKeys.has(g),y=r.toolCall?.name,v=r.agentMetadata?.executionId===p&&r.toolCall?.id===d&&y!==void 0&&Fw(y)&&r.toolCall?.status==="complete";(f||h||v)&&(i.agentMetadata={...i.agentMetadata??{},awaitingLocalTool:!1},i.toolCall=r.toolCall,i.streaming=r.streaming)}return i}),this.messages=this.#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)})}};Je();var Ao=require("lucide");Lr();kt();Nr();var hk={add:e=>PC(e)},yk=e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0,Ip={allowedTypes:Dr,maxFileSize:10*1024*1024,maxFiles:4};function bk(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function vk(e){return e==="application/pdf"?Ao.FileText:e.startsWith("text/")?Ao.FileText:e.includes("word")?Ao.FileText:e.includes("excel")||e.includes("spreadsheet")?Ao.FileSpreadsheet:e==="application/json"?Ao.FileCode:Ao.File}var Ai=class e{constructor(t={}){this.attachments=[];this.#e=null;this.#t=new Map;this.#o=!1;this.config={allowedTypes:t.allowedTypes??Ip.allowedTypes,maxFileSize:t.maxFileSize??Ip.maxFileSize,maxFiles:t.maxFiles??Ip.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange,adapter:t.adapter}}#e;#t;#o;#n(){return typeof this.config.adapter?.add=="function"}#l(){return this.#n()?this.config.adapter:hk}setPreviewsContainer(t){this.#e=t}remountPreviews(t){if(this.#e=t,t){t.innerHTML="";for(let n of this.attachments)this.#A(n)}this.#g()}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:Ip.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange),t.adapter!==void 0&&(this.config.adapter=t.adapter)}isReady(){return this.attachments.every(t=>t.status==="ready")}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart).filter(t=>t!==null)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){if(!t.length||this.#o)return;let n=[];for(let o of t){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(o,"count");continue}let r=kC(o,this.config.allowedTypes,this.config.maxFileSize);if(!r.valid){let i=r.error?.includes("type")?"type":"size";this.config.onFileRejected?.(o,i);continue}let s={id:bk(),file:o,previewUrl:Gd(o)?URL.createObjectURL(o):null,contentPart:null,status:this.#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=yk(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=Gd(t.file),o=x("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",t.id),o.style.width="48px",o.style.height="48px",n&&t.previewUrl){let d=x("img");d.src=t.previewUrl,d.alt=t.file.name,d.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",d.style.width="48px",d.style.height="48px",d.style.objectFit="cover",d.style.borderRadius="8px",o.appendChild(d)}else{let d=x("div");d.style.width="48px",d.style.height="48px",d.style.borderRadius="8px",d.style.backgroundColor="var(--persona-container, #f3f4f6)",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.display="flex",d.style.flexDirection="column",d.style.alignItems="center",d.style.justifyContent="center",d.style.gap="2px",d.style.overflow="hidden";let g=vk(t.file.type),f=Nt(g,20,"var(--persona-muted, #6b7280)",1.5);f&&d.appendChild(f);let h=x("span");h.textContent=LC(t.file.type,t.file.name),h.style.fontSize="8px",h.style.fontWeight="600",h.style.color="var(--persona-muted, #6b7280)",h.style.textTransform="uppercase",h.style.lineHeight="1",d.appendChild(h),o.appendChild(d)}let r=Q("div",{className:"persona-attachment-status",attrs:{"data-persona-attachment-status":""}}),s=x("div","persona-attachment-progress");s.appendChild(x("div","persona-attachment-progress__bar"));let i=Q("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),l=ge("rotate-cw",12,"var(--persona-text-inverse, #ffffff)",2);l?i.appendChild(l):i.textContent="\u21BB",i.addEventListener("click",d=>{d.preventDefault(),d.stopPropagation(),this.retryAttachment(t.id)}),r.append(s,i),o.appendChild(r);let c=x("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");c.type="button",c.setAttribute("aria-label","Remove attachment"),c.style.position="absolute",c.style.top="-4px",c.style.insetInlineEnd="-4px",c.style.width="18px",c.style.height="18px",c.style.borderRadius="50%",c.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",c.style.border="none",c.style.cursor="pointer",c.style.display="flex",c.style.alignItems="center",c.style.justifyContent="center",c.style.padding="0";let p=Nt(Ao.X,10,"var(--persona-text-inverse, #ffffff)",2);p?c.appendChild(p):(c.textContent="\xD7",c.style.color="var(--persona-text-inverse, #ffffff)",c.style.fontSize="14px",c.style.lineHeight="1"),c.addEventListener("click",d=>{d.preventDefault(),d.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(c),this.#e.appendChild(o),this.#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 $w=(e,t)=>e.length===t.length&&e.every((n,o)=>n===t[o]),Ck=(e,t)=>e.length===t.length&&e.every((n,o)=>{let r=t[o];return n.id===r.id&&n.name===r.name&&n.mimeType===r.mimeType&&n.size===r.size&&n.status===r.status&&n.progress===r.progress&&n.error===r.error});function Uw(){let e={text:"",attachments:[],mentionRefs:[],selectedModelId:void 0,activeModeIds:[],quote:void 0,pendingSubmission:void 0,preparing:!1,streaming:!1,inputDisabled:!1,sendDisabled:!1},t=new Set,n=null,o=!1,r=!1,s=()=>e.preparing?"preparing":e.streaming?"streaming":"idle",i=()=>{let d=s();return Object.freeze({text:e.text,attachments:Object.freeze(e.attachments.map(g=>Object.freeze({...g}))),mentionRefs:Object.freeze([...e.mentionRefs]),selectedModelId:e.selectedModelId,activeModeIds:Object.freeze([...e.activeModeIds]),quote:e.quote?Object.freeze({...e.quote}):void 0,pendingSubmission:e.pendingSubmission,phase:d,inputDisabled:e.inputDisabled,sendDisabled:d!=="idle"||e.sendDisabled||e.inputDisabled})},l=()=>(n||(n=i()),n),c=()=>{if(o=!1,r||t.size===0)return;let d=l();for(let g of[...t])try{g(d)}catch(f){typeof console<"u"&&console.error("[AgentWidget] composer state listener failed:",f)}},p=()=>{n=null,!(r||o)&&(o=!0,queueMicrotask(c))};return{getState:l,subscribe:d=>(t.add(d),()=>t.delete(d)),setText:d=>{e.text!==d&&(e.text=d,p())},setAttachments:d=>{Ck(e.attachments,d)||(e.attachments=[...d],p())},setMentionRefs:d=>{$w(e.mentionRefs,d)||(e.mentionRefs=[...d],p())},setSelectedModelId:d=>{e.selectedModelId!==d&&(e.selectedModelId=d,p())},setActiveModeIds:d=>{$w(e.activeModeIds,d)||(e.activeModeIds=[...d],p())},setQuote:d=>{let g=e.quote;g?.text===d?.text&&g?.messageId===d?.messageId&&g?.sourceLabel===d?.sourceLabel||(e.quote=d?{...d}:void 0,p())},setPendingSubmission:d=>{e.pendingSubmission!==d&&(e.pendingSubmission=d,p())},setPreparing:d=>{e.preparing!==d&&(e.preparing=d,p())},setStreaming:d=>{e.streaming!==d&&(e.streaming=d,p())},setInputDisabled:d=>{e.inputDisabled!==d&&(e.inputDisabled=d,p())},setSendDisabled:d=>{e.sendDisabled!==d&&(e.sendDisabled=d,p())},flush:()=>{o&&c()},destroy:()=>{r=!0,o=!1,t.clear()}}}Je();var Qn=(e,...t)=>{for(let n of t){let o=e.querySelector(n);if(o)return o}return null},Vw=(e,t)=>{let n=x("div",e);return n.setAttribute(t,""),n.setAttribute("data-persona-composer-synthesized",""),n.style.display="contents",n};function jw(e,t={}){let n=Qn(e,"[data-persona-composer-form]"),o=Qn(e,"[data-persona-composer-input]");if(!n||!o){let A=`[Persona] composer surface is missing required element(s): ${[!n&&"form",!o&&"input"].filter(Boolean).join(", ")}. Mark them with data-persona-composer-form / data-persona-composer-input.`;if(t.debug&&(n||o))throw new Error(A);return typeof console<"u"&&console.warn(A),null}let r={header:Qn(e,"[data-persona-composer-header]"),body:Qn(e,"[data-persona-composer-body]"),actionsStart:Qn(e,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:Qn(e,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:Qn(e,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:Qn(e,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:Qn(e,"[data-persona-composer-status]")},s=new Set,i=r.header;i||(s.add("header"),i=Vw("persona-widget-composer__header","data-persona-composer-header"),n.parentNode?n.parentNode.insertBefore(i,n):e.appendChild(i));let l=r.body??o.parentElement??n,c=(C,A,L,I,H)=>{if(A)return A;s.add(C);let _=Vw(L,I);return H.appendChild(_),_},p=c("actionsStart",r.actionsStart,"persona-widget-composer__left-actions","data-persona-composer-actions-start",n),d=c("actionsEnd",r.actionsEnd,"persona-widget-composer__right-actions","data-persona-composer-actions-end",n),g=c("suggestions",r.suggestions,"persona-widget-composer__suggestions","data-persona-composer-suggestions",e),f=c("status",r.status,"persona-widget-composer__status","data-persona-composer-status",e),h=[],y=(C,A)=>C.target===A.target&&C.type===A.type&&C.handler===A.handler,v=Qn(e,"[data-persona-composer-attachment-input]",'input[type="file"]')??void 0;return{footer:e,form:n,input:o,header:i,body:l,actionsStart:p,actionsEnd:d,suggestions:g,status:f,attachmentInput:v,attachmentPreviews:Qn(e,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:Qn(e,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:Qn(e,"[data-persona-composer-submit]")??void 0,micButton:Qn(e,"[data-persona-composer-mic]")??void 0,synthesized:s,found:r,addListener:(C,A,L,I)=>{C.addEventListener(A,L,I),h.push({target:C,type:A,handler:L,options:I})},removeListener:(C,A,L,I)=>{C.removeEventListener(A,L,I),h=h.filter(H=>!y(H,{target:C,type:A,handler:L}))},destroy:()=>{for(let C of h)C.target.removeEventListener(C.type,C.handler,C.options);h=[]}}}Je();kt();xa();Es();function wk(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function Rp(e){let{anchor:t,content:n,placement:o="bottom-start",offset:r=6,matchAnchorWidth:s=!1,horizontalOffset:i,verticalOffset:l,zIndex:c=2147483e3,onOpen:p,onDismiss:d}=e,g=e.container??wk(t),f=!1,h=null,y=()=>{if(!f)return;let A=t.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${A.width}px`),i&&(n.style.maxWidth=`${A.width}px`);let L=n.getBoundingClientRect(),I=l?.()??null,H=I!=null?A.top+I:A.top,_=o==="top-start"||o==="top-end"?H-r-L.height:A.bottom+r,oe=o==="bottom-end"||o==="top-end"?A.right-L.width:A.left,W=i?.()??null;if(W!=null){let j=Math.max(A.left,A.right-L.width);oe=Math.min(Math.max(A.left+W,A.left),j)}n.style.top=`${_}px`,n.style.left=`${oe}px`},v=()=>{f&&(f=!1,h&&(h(),h=null),n.remove())},C=()=>{if(f)return;f=!0,c!=null&&(n.style.zIndex=String(c)),g.appendChild(n),y();let A=(t.ownerDocument??document).defaultView??window,L=t.ownerDocument??document,I=()=>{if(!t.isConnected){v(),d?.("anchor-removed");return}y()},H=V=>{let oe=typeof V.composedPath=="function"?V.composedPath():[];oe.includes(n)||oe.includes(t)||(v(),d?.("outside"))},_=A.setTimeout(()=>{L.addEventListener("pointerdown",H,!0)},0);A.addEventListener("scroll",I,!0),A.addEventListener("resize",I),h=()=>{A.clearTimeout(_),L.removeEventListener("pointerdown",H,!0),A.removeEventListener("scroll",I,!0),A.removeEventListener("resize",I)},p?.()};return{get isOpen(){return f},open:C,close:v,toggle:()=>f?v():C(),reposition:y,destroy:v}}Je();kt();Es();var Sk='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',Ak=["--persona-components-composer-overflowMenu-background","--persona-components-composer-overflowMenu-borderColor","--persona-components-composer-overflowMenu-borderRadius","--persona-components-composer-overflowMenu-foreground","--persona-components-composer-overflowMenu-shadow"],gm="data-persona-menu-focus",xk=new Set(["ArrowDown","ArrowUp","Home","End"]);function qw(e){return e.getAttribute("role")==="menuitem"?e:e.querySelector(Sk)??e}var Mk=e=>e.disabled===!0||e.getAttribute("aria-disabled")==="true";function zw(e){let t=e.label,n=!1,o=x("div","persona-send-button-wrapper"),r=Q("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${ro} ${Do}`,attrs:{type:"button","aria-haspopup":"menu","aria-expanded":"false","data-persona-composer-overflow-trigger":""}});o.appendChild(r);let s=Q("div",{className:"persona-composer-overflow-menu",attrs:{role:"menu",tabindex:"-1","data-persona-composer-overflow-menu":""}}),i=()=>{let P=e.getButtonSize?.()??"";r.style.width=P,r.style.height=P,r.style.minWidth=P,r.style.minHeight=P,r.style.lineHeight="1",r.replaceChildren();let J=ge("plus",Xn,"currentColor",1.5);J?r.appendChild(J):r.textContent="+"},l=()=>{r.setAttribute("aria-label",t),r.setAttribute("title",t),s.setAttribute("aria-label",t)};l(),i();let c=[],p=-1,d=!1,g=()=>{let J=s.getRootNode().activeElement;return J instanceof HTMLElement?J:null},f=()=>{let P=g();for(let J of c){let U=!!P&&qw(J)===P;J.toggleAttribute(gm,U&&d)}},h=()=>c.filter(P=>P.isConnected||s.contains(P)).map(qw).filter(P=>!Mk(P)),y=(P,J)=>{P.forEach((U,ue)=>{U.setAttribute("tabindex",ue===J?"0":"-1")})},v=P=>{let J=h();if(J.length===0)return;let U=(P%J.length+J.length)%J.length;p=U,y(J,U),J[U].focus(),f()},C=()=>o.ownerDocument??document,A=null,L=null,I=null,H=()=>{A&&(C().removeEventListener("focusin",A,!0),A=null)},_=()=>{L&&(s.removeEventListener("focusin",L),L=null),I&&(s.removeEventListener("pointerdown",I,!0),I=null)},V=null,oe=()=>(V||(V=Rp({anchor:r,content:s,placement:"top-start",offset:6,onDismiss:()=>{r.setAttribute("aria-expanded","false"),H()}})),V),W=()=>V?.isOpen===!0,j=(P=!1)=>{if(W()){V?.close(),r.setAttribute("aria-expanded","false"),H(),_(),p=-1,d=!1;for(let J of c)J.removeAttribute(gm);P&&r.focus()}},X=(P=0,J=!1)=>{if(n||W())return;d=J,Zd(r,s,Ak),oe().open(),r.setAttribute("aria-expanded","true");let U=h();y(U,-1),v(P<0?U.length-1:P),A=ue=>{let fe=typeof ue.composedPath=="function"?ue.composedPath():[];fe.includes(s)||fe.includes(o)||j()},C().addEventListener("focusin",A,!0),L=()=>f(),s.addEventListener("focusin",L),I=()=>{d=!1},s.addEventListener("pointerdown",I,!0)},E=P=>{P.preventDefault(),P.stopPropagation(),W()?j(!0):X(0)},T=P=>{if(P.key==="ArrowDown"||P.key==="Enter"||P.key===" "){P.preventDefault(),d=!0,W()?v(0):X(0,!0);return}P.key==="ArrowUp"&&(P.preventDefault(),d=!0,W()?v(-1):X(-1,!0))},B=P=>{switch(xk.has(P.key)&&(d=!0),P.key){case"ArrowDown":P.preventDefault(),v(p+1);return;case"ArrowUp":P.preventDefault(),v(p-1);return;case"Home":P.preventDefault(),v(0);return;case"End":P.preventDefault(),v(h().length-1);return;case"Escape":P.preventDefault(),P.stopPropagation(),j(!0);return;case"Tab":j(!0);return;default:}};return r.addEventListener("click",E),r.addEventListener("keydown",T),s.addEventListener("keydown",B),{trigger:o,triggerButton:r,panel:s,setItems:P=>{for(let U of c)P.includes(U)||U.removeAttribute(gm);if(c=[...P],!W())return;let J=h();y(J,Math.min(p,J.length-1)),f()},isOpen:W,open:()=>X(0),close:j,setLabel:P=>{P!==t&&(t=P,l())},applyButtonSize:i,destroy:()=>{n=!0,H(),_(),r.removeEventListener("click",E),r.removeEventListener("keydown",T),s.removeEventListener("keydown",B),V?.destroy(),V=null,o.remove(),s.remove(),c=[]}}}var sr={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},Kw="data-persona-composer-action",fm="data-persona-composer-disable-when-streaming",Ek="core:overflow",Tk=e=>e==="core:attachment"?"attachments":e.startsWith("core:mention")?"mentions":null;function Pk(e,t){if(e===void 0)return null;if(typeof e=="number")return Number.isFinite(e)?e:null;let n=Number.parseFloat(e);if(/^\s*-?\d*\.?\d+(px)?\s*$/.test(e)&&Number.isFinite(n))return n;let o=x("div");o.style.position="absolute",o.style.visibility="hidden",o.style.pointerEvents="none",o.style.height="0",o.style.width=e,t.appendChild(o);let r=o.getBoundingClientRect().width;return o.remove(),Number.isFinite(r)&&r>0?r:Number.isFinite(n)?n:null}function mm(e){let t=e.clientWidth;if(!t)return 0;let n=e.ownerDocument?.defaultView;if(!n?.getComputedStyle)return t;let o=n.getComputedStyle(e),r=(Number.parseFloat(o.paddingLeft)||0)+(Number.parseFloat(o.paddingRight)||0);return Math.max(0,t-r)}var Gw=(e,t)=>{!e||typeof console>"u"||console.warn(t)},kk=(e,t)=>t.includes(":")?t:`${e}:${t}`;function Lk(e){let{debug:t}=e,n=[],o=new Map,r=0,s=l=>{let c=o.get(l.id);if(c){Gw(t,`[Persona] composer action "${l.id}" is already contributed by ${Yw(c)}; the ${Yw(l)} copy is ignored.`);return}o.set(l.id,l),n.push(l)};for(let l of e.builtIns)s({id:l.id,placement:l.placement,presentation:"bar",order:l.order,sequence:r++,source:"core",builtIn:l});let i=(l,c,p)=>{let d=p?kk(p,l.id):l.id,g=l.order??sr.custom;l.placement==="end"&&g>=sr.send&&(Gw(t,`[Persona] composer action "${d}" ordered at ${g} would render after send; clamped to ${sr.send-1}.`),g=sr.send-1),s({id:d,placement:l.placement,presentation:l.presentation??"bar",order:g,sequence:r++,source:c,pluginId:p,action:l})};for(let l of e.configActions??[])i(l,"config");for(let l of e.plugins){if(!l.contributeComposerActions)continue;let c;try{c=l.contributeComposerActions(e.contributionContext)}catch(p){typeof console<"u"&&console.error(`[Persona] plugin "${l.id}" contributeComposerActions failed:`,p);continue}for(let p of c??[])i(p,"plugin",l.id)}return n.sort((l,c)=>l.order===c.order?l.sequence-c.sequence:l.order-c.order)}var Yw=e=>e.source==="plugin"?`plugin "${e.pluginId}"`:e.source==="config"?"composer.actions":"a core built-in",Xw=(e,t,n)=>e===void 0?n:typeof e=="function"?e(t)===!0:e===!0,Hk=e=>e.phase==="streaming"||e.text.trim().length>0||e.attachments.length>0;function Ik(e,t){if(!e||e==="always")return!0;let n=Hk(t);return e==="when-text"?n:!n}var Ls=e=>e.kind==="custom",hm=e=>e instanceof HTMLButtonElement?e:e.querySelector("button")??e,Rk=e=>{let t=hm(e);return t.getAttribute("aria-label")?.trim()||t.getAttribute("title")?.trim()||""},Wk='.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]';function Ok(e){let t="",n=o=>{if(o.nodeType===Node.TEXT_NODE){t+=o.nodeValue??"";return}if(o.nodeType!==Node.ELEMENT_NODE)return;let r=o;typeof r.matches=="function"&&r.matches(Wk)||o.childNodes.forEach(n)};return n(e),t.trim()}var Bk=e=>Ok(e).length===0;function Qw(e){let t=new Map,n=[],o=!1,r=()=>e.getButtonSize?.(),s=(E,T)=>{let B=E.button;if(!B)return;B.setAttribute("role","menuitem"),B.setAttribute("tabindex","-1"),B.className="persona-composer-overflow-menu__item";for(let U of["width","height","minWidth","minHeight","fontSize","color","backgroundColor"])B.style[U]="";B.style.lineHeight="1",T.tooltipText?B.setAttribute("title",T.tooltipText):B.removeAttribute("title"),B.replaceChildren();let P=x("span","persona-composer-overflow-menu__icon");if(T.iconName){let U=ge(T.iconName,16,"currentColor",1.5);U&&P.appendChild(U)}let J=x("span","persona-composer-overflow-menu__label");J.textContent=T.shortLabel??T.label,B.append(P,J)},i=(E,T)=>{let B=E.button;if(!B)return;if(B.setAttribute("aria-label",T.label),T.pressed===void 0?B.removeAttribute("aria-pressed"):B.setAttribute("aria-pressed",T.pressed?"true":"false"),B.toggleAttribute(fm,T.disableWhenStreaming===!0),E.mode==="menu"){E.tooltip?.destroy(),E.tooltip=void 0,s(E,T);return}B.removeAttribute("role"),B.removeAttribute("tabindex"),B.removeAttribute("title");let P=r(),J=!!T.shortLabel;if(B.className=_n("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",ro,Do,J&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),B.style.width=P&&!J?P:"",B.style.height=P??"",B.style.minWidth=P&&!J?P:"",B.style.minHeight=P??"",B.style.fontSize=J?"":"18px",B.style.lineHeight="1",B.style.color=T.iconColor??"",B.style.backgroundColor=T.backgroundColor??"",B.replaceChildren(),T.iconName){let U=ge(T.iconName,Xn,"currentColor",1.5);U&&B.appendChild(U)}if(J){let U=x("span","persona-composer-action-button__label");U.textContent=T.shortLabel,B.appendChild(U)}else B.firstChild||(B.textContent=T.label);E.tooltip?.destroy(),E.tooltip=vn({anchor:B,trigger:E.element,text:()=>T.tooltipText??T.label,enabled:!!T.tooltipText})},l=(E,T)=>{let B=E.action,P=Q("button",{attrs:{type:"button"}}),J=P;if(T==="bar"){let fe=x("div","persona-send-button-wrapper");fe.appendChild(P),J=fe}J.setAttribute(Kw,E.id);let U={resolved:E,element:J,button:P,owned:!0,managed:!0,busy:!1,visible:!0,mode:T},ue=fe=>{if(fe.preventDefault(),fe.stopPropagation(),U.busy||P.disabled)return;let me=U.resolved.action;U.mode==="menu"&&h?.close(!0);let He;try{He=me.onSelect(e.actionContext,fe)}catch(Ee){e.reportError(Ee,{actionId:U.resolved.id});return}!He||typeof He.then!="function"||(U.busy=!0,P.setAttribute("aria-busy","true"),He.catch(Ee=>{e.reportError(Ee,{actionId:U.resolved.id})}).finally(()=>{U.busy=!1,P.removeAttribute("aria-busy")}))};return P.addEventListener("click",ue),U.detach=()=>P.removeEventListener("click",ue),i(U,B),U},c=E=>{let T=E.action,B;try{B=T.render({...e.actionContext,id:E.id,action:T})}catch(P){return e.reportError(P,{actionId:E.id}),null}return B?.element?(B.element.setAttribute(Kw,E.id),B.element.toggleAttribute(fm,T.disableWhenStreaming===!0),{resolved:E,element:B.element,owned:!0,managed:!0,destroy:B.destroy,busy:!1,visible:!0,mode:"bar"}):null},p=(E,T)=>{if(E.builtIn){let P=E.builtIn.element;return P?{resolved:E,element:P,owned:!1,managed:E.builtIn.managed===!0,busy:!1,visible:!0,mode:"bar"}:null}let B=E.action;return B?Ls(B)?c(E):l(E,T):null},d=E=>{if(E.detach?.(),E.tooltip?.destroy(),E.detachMenuSlot?.(),E.detachMenuSlot=void 0,E.menuLabel?.remove(),E.menuLabel=void 0,E.menuSlot?.remove(),E.menuSlot=void 0,E.owned){try{E.destroy?.()}catch(T){e.reportError(T,{actionId:E.resolved.id})}E.element.remove()}},g=(E,T)=>{for(let B=0;B<T.length;B++){let P=T[B];if(!P.managed)continue;let J=null;for(let U=B+1;U<T.length;U++){let ue=T[U];if(!ue.managed&&ue.element.parentElement===E){J=ue.element;break}}J?(P.element.parentElement!==E||P.element.nextSibling!==J)&&E.insertBefore(P.element,J):E.lastChild!==P.element&&E.appendChild(P.element)}},f=(E,T)=>{if(E.button){E.button.disabled=T;return}if(!E.owned)return;let B=E.element;B.toggleAttribute("data-disabled",T),B.setAttribute("aria-disabled",T?"true":"false");let P=B instanceof HTMLButtonElement||B instanceof HTMLSelectElement||B instanceof HTMLInputElement||B instanceof HTMLTextAreaElement?B:B.querySelector("button, select, input, textarea");P&&(P.disabled=T)},h=null,y=null,v=null,C=0,A=()=>{let E=e.getOverflow?.();return E?.enabled===!0?E:void 0},L=()=>(h?h.setLabel(e.getOverflowLabel?.()??"More actions"):h=zw({label:e.getOverflowLabel?.()??"More actions",getButtonSize:r}),h),I=E=>{y!==E&&(v?.disconnect(),y=E,C=mm(E),!(typeof ResizeObserver>"u")&&(v=new ResizeObserver(T=>{let P=T[T.length-1]?.contentRect?.width??mm(E);P!==C&&(C=P,j())}),v.observe(E)))},H=(E,T)=>{let B=Pk(E.collapseAutoActionsBelow,T);if(B===null)return!1;let P=C||mm(T);return P>0&&P<B},_=(E,T,B)=>{if(!T)return"bar";if(E.resolved.builtIn){let J=Tk(E.resolved.id);return J&&T.includeBuiltIns?.includes(J)?"menu":"bar"}let P=E.resolved.presentation;return P==="overflow"||P==="auto"&&B?"menu":"bar"},V=E=>{let T=E.menuSlot;if(!T)return;if(!Bk(E.element)){E.menuLabel?.remove(),E.menuLabel=void 0;return}let B=Rk(E.element);if(!B){E.menuLabel?.remove(),E.menuLabel=void 0;return}E.menuLabel||(E.menuLabel=x("span","persona-composer-overflow-menu__label")),E.menuLabel.textContent!==B&&(E.menuLabel.textContent=B),E.menuLabel.parentElement!==T&&T.appendChild(E.menuLabel)},oe=(E,T)=>{if(E.mode===T)return E;let B=E.resolved.action;if(B&&!Ls(B)){d(E),t.delete(E.resolved.id);let P=l(E.resolved,T);return t.set(E.resolved.id,P),P}if(T==="menu"){let P=Q("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none",[Af]:""}});P.appendChild(E.element),cC(hm(E.element)),E.menuSlot=P;let J=U=>{let ue=hm(E.element);if(ue.disabled)return;let fe=U.target===ue||ue.contains(U.target);h?.close(!0),fe||ue.click()};P.addEventListener("click",J,!0),E.detachMenuSlot=()=>P.removeEventListener("click",J,!0),E.managed=!0,V(E)}else E.detachMenuSlot?.(),E.detachMenuSlot=void 0,E.menuLabel?.remove(),E.menuLabel=void 0,E.menuSlot?.remove(),E.menuSlot=void 0;return E.mode=T,E},W=(E,T)=>{let B=T.map(P=>P.menuSlot??P.element);for(B.forEach((P,J)=>{let U=E.children[J];U!==P&&(U?E.insertBefore(P,U):E.appendChild(P))});E.children.length>B.length;)E.lastElementChild?.remove()},j=()=>{if(o)return;let E=e.getBindings();if(!E)return;let T=e.getState(),B=T.phase==="streaming",P=A();P&&I(E.footer);let J=P?H(P,E.footer):!1,U={start:[],end:[]},ue=[];for(let fe of n){let me=t.get(fe.id);if(!me)continue;let He=fe.action,Ee=He?Xw(He.visible,T,!0)&&Ik(He.visibility,T):!0;if(me.visible!==Ee&&(me.visible=Ee,!Ee&&me.managed&&(me.menuSlot??me.element).remove()),!!Ee){if(me=oe(me,_(me,P,J)),He){let Ie=Xw(He.disabled,T,!1)||He.disableWhenStreaming===!0&&B;f(me,Ie),!Ls(He)&&He.pressed!==void 0&&me.button?.setAttribute("aria-pressed",He.pressed?"true":"false")}me.mode==="menu"?(V(me),ue.push(me)):U[fe.placement].push(me)}}if(ue.length>0){let fe=L();W(fe.panel,ue),fe.setItems(ue.map(Ie=>Ie.menuSlot??Ie.element)),fe.applyButtonSize();let me=Number.isFinite(P?.order)?P?.order:sr.overflow,He=U.start.findIndex(Ie=>Ie.resolved.order>me),Ee={resolved:{id:Ek,placement:"start",presentation:"bar",order:me,sequence:-1,source:"core"},element:fe.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};U.start.splice(He<0?U.start.length:He,0,Ee)}else h&&(h.close(),h.trigger.remove(),h.setItems([]));g(E.actionsStart,U.start),g(E.actionsEnd,U.end)};return{resolve:()=>{if(o)return;let E=Lk(e.collect()),T=new Set(E.map(B=>B.id));for(let[B,P]of t)T.has(B)||(d(P),t.delete(B));for(let B of E){let P=t.get(B.id);if(!P){let fe=p(B,"bar");fe&&t.set(B.id,fe);continue}let J=P.resolved.action,U=B.action;if(!!J!=!!U||J&&U&&Ls(J)!==Ls(U)||J&&U&&Ls(J)&&Ls(U)&&J.render!==U.render){d(P),t.delete(B.id);let fe=p(B,P.mode);fe&&t.set(B.id,fe);continue}P.resolved=B,B.builtIn?(P.managed=B.builtIn.managed===!0||P.mode==="menu",B.builtIn.element&&P.mode==="bar"&&(P.element=B.builtIn.element)):U&&!Ls(U)?i(P,U):U&&P.element.toggleAttribute(fm,U.disableWhenStreaming===!0)}n=E,j()},sync:j,getResolved:()=>n,getOverflowMenu:()=>h,destroy:()=>{if(!o){o=!0,v?.disconnect(),v=null,y=null;for(let E of t.values())d(E);t.clear(),h?.destroy(),h=null,n=[]}}}}Je();kt();Es();var _k="core:model",Dk=700,Jw=16,Nk=["--persona-components-composer-modelPicker-menuBackground","--persona-components-composer-modelPicker-menuBorderRadius","--persona-components-composer-modelPicker-rowHoverBackground","--persona-components-composer-modelPicker-labelColor","--persona-components-composer-modelPicker-descriptionColor"],Zw=()=>{let e=Q("span",{className:"persona-composer-model-picker-wrapper",attrs:{"data-persona-composer-model-picker-wrapper":""}}),t=Q("span",{className:"persona-composer-model-picker-chevron",attrs:{"aria-hidden":"true"}});return{wrapper:e,chevron:t}};function eS(e){let t=e.label??"Model",n=e.presentation??"native",o=null,r=c=>{let p=e.getSelectedModelId();return c.find(d=>d.id===p)??c[0]},s=()=>{let c=Q("select",{className:"persona-composer-model-picker",attrs:{"aria-label":t,"data-persona-composer-model-picker":""}}),p="",d=()=>{let v=e.getModels(),C=v.map(A=>`${A.id}:${A.label}`).join("|");C!==p&&(p=C,c.replaceChildren(...v.map(A=>{let L=Q("option",{attrs:{value:A.id}});return L.textContent=A.label,L}))),c.value=r(v)?.id??""};d(),o=d;let g=()=>{c.value&&e.onSelect(c.value)};c.addEventListener("change",g);let f=v=>v.stopPropagation();c.addEventListener("click",f);let{wrapper:h,chevron:y}=Zw();return h.append(c,y),{element:h,destroy:()=>{o===d&&(o=null),c.removeEventListener("change",g),c.removeEventListener("click",f)}}},i=()=>{let c=Q("button",{className:"persona-composer-model-picker persona-composer-model-picker-trigger",attrs:{type:"button","aria-haspopup":"listbox","aria-expanded":"false","data-persona-composer-model-picker":"popover"}}),p=x("span","persona-composer-model-picker-label"),d=x("span","persona-composer-model-picker-suffix");c.append(p,d);let g=Q("div",{className:"persona-composer-model-menu",attrs:{role:"listbox",tabindex:"-1","aria-label":t,"data-persona-composer-model-menu":""}}),f=new Map,h="",y=null,v=()=>y?.isOpen===!0,C=(T=!1)=>{v()&&(y?.close(),c.setAttribute("aria-expanded","false"),T&&c.focus())},A=T=>{let B=[...f.values()];if(B.length===0)return;let P=(T%B.length+B.length)%B.length;B[P].focus()},L=T=>{if(v())return;y||(y=Rp({anchor:c,content:g,placement:"top-start",offset:6,onDismiss:()=>c.setAttribute("aria-expanded","false")})),Zd(c,g,Nk),y.open(),c.setAttribute("aria-expanded","true");let P=[...f.keys()].indexOf(r(e.getModels())?.id??"");A(T??(P>=0?P:0))},I=T=>{C(!0),e.onSelect(T)},H=T=>{T.preventDefault(),T.stopPropagation();let B=T.currentTarget.getAttribute("data-persona-model-option");B&&I(B)},_=T=>{let B=Q("button",{className:"persona-composer-model-option",attrs:{type:"button",role:"option",tabindex:"-1","aria-selected":"false","data-persona-model-option":T.id}});if(T.icon){let fe=ge(T.icon,Jw,"currentColor",1.5);if(fe){let me=x("span","persona-composer-model-option-icon");me.appendChild(fe),B.appendChild(me)}}let P=x("span","persona-composer-model-option-body"),J=x("span","persona-composer-model-option-label");if(J.textContent=T.label,P.appendChild(J),T.description){let fe=x("span","persona-composer-model-option-description");fe.textContent=T.description,P.appendChild(fe)}B.appendChild(P);let U=x("span","persona-composer-model-option-check");U.setAttribute("aria-hidden","true");let ue=ge("check",Jw,"currentColor",2);return ue&&U.appendChild(ue),B.appendChild(U),B.addEventListener("click",H),B},V=()=>{let T=e.getModels(),B=T.map(U=>`${U.id}:${U.label}:${U.icon??""}:${U.description??""}`).join("|");if(B!==h){h=B;for(let U of f.values())U.removeEventListener("click",H);f.clear(),g.replaceChildren(...T.map(U=>{let ue=_(U);return f.set(U.id,ue),ue}))}let P=r(T);for(let[U,ue]of f)ue.setAttribute("aria-selected",String(U===P?.id));p.textContent=P?.label??"";let J=e.getSuffix?.()??"";d.textContent=J,c.setAttribute("aria-label",[t,[P?.label,J].filter(Boolean).join(" ")].filter(Boolean).join(": "))};V(),o=V;let oe=T=>{T.preventDefault(),T.stopPropagation(),v()?C(!0):L()},W=T=>{if(T.key==="ArrowDown"){T.preventDefault(),v()?A(0):L(0);return}T.key==="ArrowUp"&&(T.preventDefault(),v()?A(-1):L(-1))},j=T=>{let B=[...f.values()],P=B.indexOf(T.target?.closest?.(".persona-composer-model-option"));switch(T.key){case"ArrowDown":T.preventDefault(),A(P+1);return;case"ArrowUp":T.preventDefault(),A(P-1);return;case"Home":T.preventDefault(),A(0);return;case"End":T.preventDefault(),A(B.length-1);return;case"Escape":T.preventDefault(),T.stopPropagation(),C(!0);return;case"Tab":C(!0);return;default:}};c.addEventListener("click",oe),c.addEventListener("keydown",W),g.addEventListener("keydown",j);let{wrapper:X,chevron:E}=Zw();return X.append(c,E),{element:X,destroy:()=>{o===V&&(o=null),c.removeEventListener("click",oe),c.removeEventListener("keydown",W),g.removeEventListener("keydown",j);for(let T of f.values())T.removeEventListener("click",H);f.clear(),y?.destroy(),y=null,g.remove()}}};return{action:{id:_k,kind:"custom",placement:"end",order:Dk,presentation:n==="popover"?"bar":"auto",label:t,render:()=>n==="popover"?i():s()},repaint:()=>o?.()}}Je();kt();Je();var ym="[data-persona-composer-chip-row]";function Wp(e){e.style.display=e.childElementCount>0?"flex":"none"}function bm(e){let t=e.querySelector(ym);if(t)return t;let n=Q("div",{className:"persona-composer-chip-row",attrs:{"data-persona-composer-chip-row":""}});n.style.display="none";let o=e.querySelector("[data-persona-composer-quote], [data-persona-composer-pending]");return o?.parentElement===e?e.insertBefore(n,o):e.appendChild(n),n}var Fk=":scope > [data-persona-composer-mode]";function tS(e){let t=e.row,n="",o=!1,r=new Set(e.initialIds??[]),s=p=>{let d=Q("span",{className:"persona-mention-chip persona-composer-mode-chip",attrs:{"data-persona-composer-mode":p.id}});if(p.iconName){let y=x("span","persona-mention-chip-icon"),v=ge(p.iconName,12,"currentColor",1.5);v&&y.appendChild(v),d.appendChild(y)}let g=x("span","persona-mention-chip-label");g.textContent=p.shortLabel??p.label,d.appendChild(g);let f=Q("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${p.label}`}}),h=ge("x",12,"currentColor",2);return h?f.appendChild(h):f.textContent="\xD7",f.addEventListener("click",y=>{y.preventDefault(),y.stopPropagation(),e.onRemove(p.id)}),d.appendChild(f),d},i=()=>Array.from(t.querySelectorAll(Fk)),l=p=>{p.setAttribute("data-persona-chip-exit",""),p.setAttribute("aria-hidden","true"),p.style.pointerEvents="none";let d=()=>{p.remove(),Wp(t)},g=t.ownerDocument.defaultView,f=typeof g?.getComputedStyle=="function"?g.getComputedStyle(p).animationName:"";if(!f||f==="none"){d();return}p.addEventListener("animationend",d,{once:!0}),p.addEventListener("animationcancel",d,{once:!0})},c=()=>{for(let p of i())p.remove()};return{element:t,render:(p,d)=>{if(o)return;let g=d.filter(v=>p.includes(v.id)),f=g.map(v=>`${v.id}:${v.shortLabel??v.label}`).join("|");if(f===n)return;n=f;let h=new Map;for(let v of i()){let C=v.getAttribute("data-persona-composer-mode");C&&g.some(L=>L.id===C)&&!v.hasAttribute("data-persona-chip-exit")?h.set(C,v):v.hasAttribute("data-persona-chip-exit")||l(v)}let y=t.firstChild;for(let v of g){let C=h.get(v.id);C||(C=s(v),r.has(v.id)||(C.setAttribute("data-persona-chip-enter",""),C.addEventListener("animationend",()=>C?.removeAttribute("data-persona-chip-enter"),{once:!0}))),r.delete(v.id),C!==y&&t.insertBefore(C,y),y=C.nextSibling}Wp(t)},destroy:()=>{o=!0,c(),Wp(t)}}}Je();kt();var nS=e=>`core:mode:${e}`;var vm=e=>Math.min(300+e,499),oS=e=>`core:mode-group:${e}`;function Op(e,t){return e?t?.find(n=>n.id===e)?.presentation==="segmented":!1}function $k(e,t){return e?t?.find(n=>n.id===e)?.chipVisibility==="hidden":!1}function rS(e,t){return e?.length?e.filter(n=>!Op(n.groupId,t)&&!$k(n.groupId,t)):[]}var Uk=(e,t)=>e.groupId?t?.find(n=>n.id===e.groupId)?.selection??null:null;function sS(e,t,n,o){let r=n.find(l=>l.id===t);if(!r)return[...e];let s=e.includes(t),i=new Set(e);if(s)i.delete(t);else{if(Uk(r,o)==="single"){let l=n.filter(c=>c.groupId===r.groupId).map(c=>c.id);i=new Set([...i].filter(c=>!l.includes(c)))}i.add(t)}return n.filter(l=>i.has(l.id)).map(l=>l.id)}function Bp(e,t){return t?.length?t.filter(n=>e.includes(n.id)).map(n=>n.id):[]}function iS(e,t){return t?.length?t.filter(n=>e.includes(n.id)&&(n.persistence??"sticky")!=="once").map(n=>n.id):[]}function aS(e,t){if(!(!t?.length||e.length===0))return t.find(n=>e.includes(n.id)&&n.placeholder)?.placeholder}var Vk=16;function lS(e){let t=null;return{action:{id:oS(e.groupId),kind:"custom",placement:"start",presentation:"bar",label:e.getGroup()?.label??e.groupId,render:()=>{let o=Q("div",{className:"persona-composer-segmented",attrs:{"data-persona-composer-mode-group":e.groupId}}),r=new Map,s="",i=p=>{p.preventDefault(),p.stopPropagation();let g=p.currentTarget.getAttribute("data-persona-composer-mode");!g||e.getActiveIds().includes(g)&&e.getGroup()?.selection==="single"||e.onSelect(g)},l=p=>{let d=Q("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":p.id,"aria-label":p.label}});if(p.iconName){let f=ge(p.iconName,Vk,"currentColor",1.5);f&&d.appendChild(f)}let g=x("span","persona-composer-segmented-label");return g.textContent=p.shortLabel??p.label,d.appendChild(g),d.addEventListener("click",i),d},c=()=>{let p=e.getGroup();p?.label?(o.setAttribute("role","group"),o.setAttribute("aria-label",p.label)):(o.removeAttribute("role"),o.removeAttribute("aria-label"));let d=e.getModes(),g=d.map(h=>`${h.id}:${h.shortLabel??h.label}:${h.iconName??""}`).join("|");if(g!==s){s=g;for(let y of r.values())y.removeEventListener("click",i);r.clear();let h=d.map(y=>{let v=l(y);return r.set(y.id,v),v});o.replaceChildren(...h)}let f=e.getActiveIds();for(let[h,y]of r)y.setAttribute("aria-pressed",String(f.includes(h)))};return c(),t=c,{element:o,destroy:()=>{t===c&&(t=null);for(let p of r.values())p.removeEventListener("click",i);r.clear()}}}},repaint:()=>t?.()}}Je();kt();function cS(e){let t=Q("div",{className:"persona-composer-quote",attrs:{"data-persona-composer-quote":""}});t.style.display="none";let n="",o=!1,r=s=>{let i=x("span","persona-composer-quote-bar"),l=x("div","persona-composer-quote-content");if(s.sourceLabel){let g=x("div","persona-composer-quote-source");g.textContent=s.sourceLabel,l.appendChild(g)}let c=Q("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});c.textContent=kp(s.text),l.appendChild(c);let p=Q("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":e.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),d=ge("x",12,"currentColor",2);d?p.appendChild(d):p.textContent="\xD7",p.addEventListener("click",g=>{g.preventDefault(),g.stopPropagation(),e.onDismiss()}),t.replaceChildren(i,l,p)};return{element:t,render:s=>{if(o)return;let i=s?`${s.sourceLabel??""}\0${s.text}`:"";if(i!==n){if(n=i,!s){t.replaceChildren(),t.style.display="none";return}r(s),t.style.display="flex"}},destroy:()=>{o=!0,t.replaceChildren(),t.remove()}}}Je();kt();function dS(e){let t=Q("div",{className:"persona-composer-pending",attrs:{"data-persona-composer-pending":""}});t.style.display="none";let n,o=!1,r=(i,l,c,p)=>{let d=Q("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":l,[c]:""}}),g=ge(i,12,"currentColor",2);return g?d.appendChild(g):d.textContent=l,d.addEventListener("click",f=>{f.preventDefault(),f.stopPropagation(),p()}),d},s=i=>{let l=kp(i.text??"",90);if(l)return l;let c=i.contentParts?.length??0;return c>0?c===1?"1 attachment":`${c} attachments`:(i.mentionRefs?.length??0)>0?i.mentionRefs.map(d=>d.label).join(", "):"Queued message"};return{element:t,render:i=>{if(o||i===n)return;if(n=i,!i){t.replaceChildren(),t.style.display="none";return}let l=x("span","persona-composer-pending-badge");l.textContent=e.label??"Sends next";let c=Q("div",{className:"persona-composer-pending-text",attrs:{"data-persona-composer-pending-text":""}});c.textContent=s(i),t.replaceChildren(l,c,r("pencil",e.editLabel??"Edit queued message","data-persona-composer-pending-edit",e.onEdit),r("x",e.removeLabel??"Remove queued message","data-persona-composer-pending-remove",e.onRemove)),t.style.display="flex"},destroy:()=>{o=!0,t.replaceChildren(),t.remove()}}}Je();function pS(e){let t=Q("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":e.messageId,"data-preserve-runtime":""}}),n=Q("textarea",{className:"persona-message-edit-input",attrs:{rows:"1",dir:"auto","aria-label":"Edit message","data-persona-message-edit-input":""}});n.value=e.initialText;let o=()=>{n.style.height="auto",n.style.height=`${n.scrollHeight}px`};n.addEventListener("input",o);let r=x("div","persona-message-edit-actions"),s=(l,c,p,d)=>{let g=Q("button",{className:`persona-message-edit-button ${c}`,attrs:{type:"button",[p]:""},text:l});return g.addEventListener("click",f=>{f.preventDefault(),f.stopPropagation(),d()}),g},i=()=>{let l=n.value.trim();l&&e.onSave(l)};return r.append(s(e.cancelLabel??"Cancel","persona-message-edit-cancel","data-persona-message-edit-cancel",e.onCancel),s(e.saveLabel??"Send","persona-message-edit-save","data-persona-message-edit-save",i)),n.addEventListener("keydown",l=>{if(l.key==="Escape"){l.preventDefault(),l.stopPropagation(),e.onCancel();return}l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),i())}),t.append(n,r),{element:t,getValue:()=>n.value,focus:()=>{n.focus();let l=n.value.length;n.setSelectionRange(l,l),o()},destroy:()=>{t.replaceChildren(),t.remove()}}}function uS(e){let t=e.text??"";if(t.trim().length>0||(e.mentionRefs?.length??0)>0||(e.activeModeIds?.length??0)>0||e.quote||e.selectedModelId)return{text:t,...e.mentionRefs?.length?{mentionRefs:[...e.mentionRefs]}:{},...e.contentSegments?.length?{contentSegments:[...e.contentSegments]}:{},...e.selectedModelId?{selectedModelId:e.selectedModelId}:{},...e.activeModeIds?.length?{activeModeIds:[...e.activeModeIds]}:{},...e.quote?{quote:{...e.quote}}:{}}}function gS(e,t){if(!e||typeof e.text!="string")return;let n=new Set(t.mentionSourceIds),o=(e.mentionRefs??[]).filter(c=>n.has(c.sourceId)),r=o.length===(e.mentionRefs?.length??0)&&o.length>0,s=new Set(t.modes.map(c=>c.id)),i=(e.activeModeIds??[]).filter(c=>s.has(c)),l=e.selectedModelId&&t.modelIds.includes(e.selectedModelId)?e.selectedModelId:void 0;return{text:e.text,...r?{mentionRefs:o}:{},...r&&e.contentSegments?.length?{contentSegments:e.contentSegments}:{},...l?{selectedModelId:l}:{},...i.length?{activeModeIds:i}:{},...e.quote?.text?{quote:e.quote}:{}}}function fS(e){let t=e.delay??500,n=null,o=!1,r=()=>{n!==null&&(clearTimeout(n),n=null)};return{schedule:()=>{o||(r(),n=setTimeout(()=>{n=null,e.write()},t))},flush:()=>{o||n===null||(r(),e.write())},cancel:r,destroy:()=>{o=!0,r()}}}function mS(e){return e.wrapped||e.text.includes(`
|
|
28
|
+
`),l=Array.isArray(t.contentParts)&&t.contentParts.length>0,c=r.contentParts.length>0;if(l){let p=[];s&&p.push(So(s)),p.push(...r.contentParts),p.push(...t.contentParts),t.contentParts=p}else if(c){let p=[];i&&p.push(So(i)),p.push(...r.contentParts),t.contentParts=p}else s&&(t.llmContent=i);Object.keys(r.context).length>0&&(t.mentionContext=r.context)}async sendMessage(t,n){let o=t.trim(),r=!!n?.replayFields&&(n.replayFields.llmContent!==void 0||n.replayFields.rawContent!==void 0||(n.replayFields.contextMentions?.length??0)>0);if(!o&&(!n?.contentParts||n.contentParts.length===0)&&(!n?.mentions||n.mentions.refs.length===0)&&!r)return;this.#U&&!n?.voiceTurn&&(this.#U.failed=!0,this.#U=null),(this.#H||this.#M||this.#b||this.#_)&&await this.#Oe(),this.stopSpeaking(),this.abortController?.abort(),this.#me(),this.#le++,this.#ye();let s=n?.voiceTurn?.userMessageId,i=s?this.messages.find(h=>h.id===s&&h.role==="user"):void 0,l=i?.id??Ha(),c=Ps();this.#s=null;let p=n?.contentParts&&Pa(n.contentParts)?Ta:"",d={id:l,role:"user",content:o||p,createdAt:new Date().toISOString(),sequence:this.#V(),viaVoice:n?.viaVoice||!1,...n?.contentParts&&n.contentParts.length>0&&{contentParts:n.contentParts},...n?.mentions&&n.mentions.refs.length>0&&{contextMentions:n.mentions.refs},...n?.contentSegments&&n.contentSegments.length>0&&{contentSegments:n.contentSegments},...n?.composerOptions&&{composerOptions:n.composerOptions},...n?.replayFields??{}};i?(i.viaVoice=!0,delete i.voiceCaption,i.content.trim()!==o&&(i.llmContent=o),this.callbacks.onMessagesChanged([...this.messages])):this.#J(d),this.#P(!0);let g=new AbortController;if(this.abortController=g,n?.mentions){let h=this.messages.find(y=>y.id===l)??d;if(await this.#Qe(h,o,n.mentions.finalize),g.signal.aborted||this.abortController!==g)return;this.callbacks.onMessagesChanged([...this.messages])}if(n?.quote&&!n.replayFields){let h=this.messages.find(v=>v.id===l)??d,y=kw({quote:n.quote,text:h.llmContent??h.content,contentParts:h.contentParts});y.contentParts&&(h.contentParts=y.contentParts),y.llmContent!==void 0&&(h.llmContent=y.llmContent),(y.contentParts||y.llmContent!==void 0)&&(h.quote={...n.quote},this.callbacks.onMessagesChanged([...this.messages]))}let f=i?[...this.messages.filter(h=>h!==i),{...i,createdAt:new Date().toISOString()}]:[...this.messages];try{await this.#Ye(f,g,c,l,{composerOptions:n?.composerOptions,interrupt:n?.interrupt})}catch(h){if(this.status==="resuming"||this.#r)return;this.#U&&(this.#U.failed=!0);let y=h instanceof Error&&(h.name==="AbortError"||h.message.includes("aborted")||h.message.includes("abort"));if(!y){let v=um(h,this.config.errorMessage);if(v){let C={id:c,role:"assistant",createdAt:new Date().toISOString(),content:v,sequence:this.#V()};this.#J(C)}}this.#z("idle"),this.#P(!1),this.abortController=null,y||(h instanceof Error?this.callbacks.onError?.(h):this.callbacks.onError?.(new Error(String(h))))}}resubmitFrom(t,n){let o=Lw(this.messages,t);if(!o)return!1;let r=this.messages[o.start],s=n.replacement,i=s?s.text:r.content,l=s?s.contentParts:r.contentParts;if(!(!!i?.trim()||(l?.length??0)>0||!s&&(r.llmContent?.trim()?.length??0)>0))return!1;let p=s?void 0:{...r.llmContent!==void 0&&{llmContent:r.llmContent},...r.rawContent!==void 0&&{rawContent:r.rawContent},...r.mentionContext&&{mentionContext:r.mentionContext},...r.contextMentions&&{contextMentions:r.contextMentions},...r.quote&&{quote:r.quote}},d=s?this.#Je(s.options):r.composerOptions,g=s?s.contentSegments:r.contentSegments,f=s?s.options?.quote:void 0,h=s?s.viaVoice:r.viaVoice;return this.cancel(),this.messages=this.messages.slice(0,o.start),this.sendMessage(i??"",{...l?.length?{contentParts:[...l]}:{},...g?.length?{contentSegments:[...g]}:{},...d?{composerOptions:d}:{},...f?{quote:f}:{},...p&&Object.keys(p).length>0?{replayFields:p}:{},viaVoice:h===!0}),!0}#Je(t){if(!t)return;let n={};return t.selectedModelId&&(n.selectedModelId=t.selectedModelId),t.activeModeIds?.length&&(n.activeModeIds=[...t.activeModeIds]),Object.keys(n).length>0?n:void 0}async continueConversation(){if(this.streaming)return;(this.#H||this.#M||this.#b||this.#_)&&await this.#Oe(),this.abortController?.abort(),this.#ye();let t=Ps();this.#s=null,this.#P(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(r){if(this.status==="resuming"||this.#r)return;let s=r instanceof Error&&(r.name==="AbortError"||r.message.includes("aborted")||r.message.includes("abort"));if(!s){let i=um(r,this.config.errorMessage);if(i){let l={id:t,role:"assistant",createdAt:new Date().toISOString(),content:i,sequence:this.#V()};this.#J(l)}}this.#z("idle"),this.#P(!1),this.abortController=null,s||(r instanceof Error?this.callbacks.onError?.(r):this.callbacks.onError?.(new Error(String(r))))}}async connectStream(t,n){if(this.streaming&&!n?.allowReentry)return;n?.allowReentry||this.abortController?.abort(),n?.preserveAssistantId&&n.assistantMessageId&&(this.#s=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,r=!1;for(let i of this.messages)i.streaming&&i.id!==o&&(i.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.#P(!0);let s={};try{await this.client.processStream(t,i=>{let l=this.#n;this.#n=s;try{this.handleEvent(i)}finally{this.#n=l}},n?.assistantMessageId,n?.seedContent),this.#ke(s)}catch(i){if(this.status==="resuming"||this.#r){this.#pt(s);return}this.#ke(s),this.#z("error"),this.webMcpResolveControllers.size===0&&(this.#P(!1),this.abortController=null),this.callbacks.onError?.(i instanceof Error?i:new Error(String(i)))}}#Be(){let t=this.config.webmcp;t?.enabled===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){try{if(this.config.webmcp?.autoApprove?.(t)===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.#c}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:t.description??`Allow the assistant to run ${t.toolName}?`,parameters:t.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(r=>{this.webMcpApprovalResolvers.set(o,r)})}resolveWebMcpApproval(t,n){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let r=this.messages.find(s=>s.id===t);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}#Ze;#le;#Se(t){let n=this.#Ze??={s:this,setStreaming:s=>this.#P(s),appendMessage:s=>this.#J(s),nextSequence:()=>this.#V(),settleApprovalPausedToolCall:s=>this.#Ne(s),resumeAfter:s=>this.#t?.executionId===s?this.#t.lastEventId:void 0},o=FC();if(o)return t(o,n);let r=this.#le;return Gf().then(s=>r===this.#le?t(s,n):void 0,s=>{this.callbacks.onError?.(s instanceof Error?s:new Error(String(s)))})}resolveApproval(t,n,o){return this.#Se((r,s)=>r.resolveApproval(s,t,n,o))}resolveAskUserQuestion(t,n){return this.#Se((o,r)=>o.resolveAskUserQuestion(r,t,n))}resolveWebMcpToolCall(t){return this.#Se((n,o)=>n.resolveWebMcpToolCall(o,t))}persistAskUserQuestionProgress(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}#et(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.id;if(!n||!o){let s=this.#l;queueMicrotask(()=>{s===this.#l&&this.resolveWebMcpToolCall(t)});return}let r=this.webMcpAwaitBatches.get(n);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,r)),!r.seen.has(o)&&(r.seen.add(o),r.snapshots.push(t))}#tt(){if(this.webMcpAwaitBatches.size===0)return;let t=this.#l;queueMicrotask(()=>{if(t===this.#l)for(let n of[...this.webMcpAwaitBatches.keys()])this.#nt(n)})}#nt(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.#Se((r,s)=>r.resolveWebMcpToolCallBatch(s,t,o))}#me(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.#l++}cancel(){this.abortController?.abort(),this.abortController=null,this.#ye(),this.#me(),this.#le++,this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.#P(!1),this.#z("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#ye(),this.#me(),this.#le++,this.messages=[],this.agentExecution=null,this.#Te(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#P(!1),this.#z("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.#g}selectArtifact(t){this.#g=t,this.#he()}clearArtifacts(){this.#Te()}upsertArtifact(t){let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=t.artifactType==="markdown"?{id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{}}:{id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:t.props??{},...t.presentation?{presentation:t.presentation}:{}};return this.artifacts.set(n,o),this.#g=n,this.#he(),t.transcript!==!1&&this.#ot(o),o}#ot(t){let n=`artifact-ref-${t.id}`,o=or(this.config.features?.artifacts,t),r=El(o,{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:"complete",...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...t.component?{component:t.component}:{},...t.props?{componentProps:t.props}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}),s=this.messages.find(i=>i.id===n);if(s){s.rawContent=r,s.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:n,content:"",rawContent:r})}#_e(){let t=!1;for(let n of this.artifacts.values()){let o=this.messages.find(i=>i.id===`artifact-ref-${n.id}`);if(!o)continue;let r=or(this.config.features?.artifacts,n),s=El(r,{artifactId:n.id,title:n.title,artifactType:n.artifactType,status:n.status,...n.file?{file:n.file}:{},...n.presentation?{presentation:n.presentation}:{},...n.component?{component:n.component}:{},...n.props?{componentProps:n.props}:{},...n.markdown!==void 0?{markdown:n.markdown}:{}});o.rawContent!==s&&(o.rawContent=s,o.streaming=n.status==="streaming",t=!0)}t&&this.callbacks.onMessagesChanged([...this.messages])}#Te(){this.artifacts.size===0&&this.#g===null||(this.artifacts.clear(),this.#g=null,this.#he())}#he(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.#g})}#rt(t){switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:"",...t.file?{file:t.file}:{}}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:t.component??"",props:{}}),this.#g=t.id;break}case"artifact_delta":{let n=this.artifacts.get(t.id);n?.artifactType==="markdown"&&(n.markdown=(n.markdown??"")+t.artDelta);break}case"artifact_update":{let n=this.artifacts.get(t.id);n?.artifactType==="component"&&(n.props={...n.props,...t.props},t.component&&(n.component=t.component));break}case"artifact_complete":{let n=this.artifacts.get(t.id);n&&(n.status="complete");break}default:return}this.#he()}hydrateMessages(t){this.abortController?.abort(),this.abortController=null,this.#ye(),this.#me(),this.#le++,this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.#ce(t.map(n=>({...n,streaming:!1,sequence:n.sequence??this.#V()}))),this.#P(!1),this.#z("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let o of t)this.artifacts.set(o.id,{...o,status:"complete"});this.#g=n,this.#he()}#st(t){let n=this.agentExecution?.executionId;if(!n||!this.#s||this.agentExecution?.status!=="running")return;let o=this.#t===null;this.#t={executionId:n,lastEventId:t,assistantMessageId:this.#s,status:"running"},this.#dt(o)}#it(){return this.#t!==null&&typeof this.config.reconnectStream=="function"&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.#De()}#De(){return this.messages.some(t=>t.agentMetadata?.awaitingLocalTool===!0&&t.agentMetadata?.askUserQuestionAnswered!==!0||t.variant==="approval"&&t.approval?.status==="pending")}#Pe(){this.#r||!this.#t||typeof this.config.reconnectStream!="function"||(this.#r=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.#t}),this.#P(!0),this.#z("resuming"),this.#at().then(t=>{this.#r&&this.#t&&t.begin()}))}#at(){return this.#p?Promise.resolve(this.#p):(this.#f||(this.#f=Nw().then(({createReconnectController:t})=>{let n=t(this.#lt());return this.#p=n,n}),this.#f.catch(()=>{this.#f=null})),this.#f)}#lt(){let t=this;return{get config(){return t.config},getResumable:()=>t.#t,clearResumable:()=>t.#Ae(),getStatus:()=>t.status,setStatus:n=>t.#z(n),setStreaming:n=>t.#P(n),setReconnecting:n=>{t.#r=n},setAbortController:n=>{t.abortController=n},getMessages:()=>t.messages,notifyMessagesChanged:()=>t.callbacks.onMessagesChanged([...t.messages]),resumeConnect:(n,o,r)=>t.connectStream(n,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:n=>t.#J(n),nextSequence:()=>t.#V(),emitReconnect:n=>t.callbacks.onReconnect?.(n),buildErrorContent:n=>um(new Error(n),t.config.errorMessage),onError:n=>t.callbacks.onError?.(n)}}reconnectNow(){if(this.#r){this.#p?.wake();return}this.#Pe()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.#r)return;let n=this.#ct();n||(n=Ps(),this.#J({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.#V()})),this.#s=n,this.agentExecution||(this.agentExecution={executionId:t.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.#t={executionId:t.executionId,lastEventId:t.after,assistantMessageId:n,status:"running"},this.#Pe()}#ct(){for(let t=this.messages.length-1;t>=0;t--){let n=this.messages[t];if(n.role==="assistant"&&!n.variant)return n.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),n.id;if(n.role==="user")break}return null}#ye(){this.#r=!1,this.#p?.teardown(),this.#Ae()}#Ae(){this.#i&&(clearTimeout(this.#i),this.#i=null);let t=this.#t!==null;this.#t=null,t&&this.config.onExecutionState?.(null)}#dt(t){let n=this.config.onExecutionState;if(n){if(t){this.#i&&(clearTimeout(this.#i),this.#i=null),n(this.#t);return}this.#i||(this.#i=setTimeout(()=>{this.#i=null,this.config.onExecutionState?.(this.#t)},500))}}getResumableHandle(){return this.#t}#z(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}#P(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&(this.#ke(void 0),this.speakLatestAssistantMessage())}speakLatestAssistantMessage(t){let n=this.config.textToSpeech;if(!n?.enabled||!(!n.provider||n.provider==="browser"||n.provider==="runtype"&&n.browserFallback))return;let r=[...this.messages].reverse().find(i=>i.role==="assistant"&&i.content&&!i.voiceProcessing);if(!r||t&&!t.includes(r.id))return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let s=cm(r.content);s.trim()&&this.readAloud.play(r.id,{text:s,voice:n.voice,rate:n.rate,pitch:n.pitch})}static pickBestVoice(t){return Ia(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let o=cm(n.content||"");if(!o.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(t,{text:o,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}#ke(t){for(let[n,o]of[...this.#e])o===t&&(this.#e.delete(n),this.#Ne(n))}#pt(t){for(let[n,o]of this.#e)o===t&&this.#e.set(n,void 0)}#Ne(t){let n=this.messages.find(l=>l.id===t)?.approval,o=n?.toolCallId,r=o&&this.messages.find(l=>l.toolCall?.id===o),s=r&&r.toolCall;if(!s||s.status==="complete"||n.status==="pending")return;let i={...s,status:"complete",approvalStatus:n.status,completedAt:Date.now(),...n.status==="approved"?{superseded:!0}:{success:!1,error:n.status==="denied"?"Denied":"Approval timed out"}};this.upsertMessage({...r,streaming:!1,toolCall:i})}#J(t){let n=this.#Ce(t);this.messages=this.#ce([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.#Ce(t),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.#J(n);return}this.messages=this.messages.map((r,s)=>{if(s!==o)return r;let i={...r,...n};r.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(i.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(i.agentMetadata={...i.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1});let l=r.agentMetadata?.clientToolAnswer;if(l&&i.agentMetadata&&!i.agentMetadata.clientToolAnswer&&(i.agentMetadata={...i.agentMetadata,clientToolAnswer:l}),r.approval&&n.approval&&r.approval.id===n.approval.id){let g=r.approval,f=n.approval;i.approval={...g,...f,executionId:f.executionId||g.executionId,toolName:f.toolName||g.toolName,description:f.description||g.description,toolType:f.toolType??g.toolType,reason:f.reason??g.reason,parameters:f.parameters??g.parameters,toolCallId:f.toolCallId??g.toolCallId}}let c=n.toolCall?.name,p=n.agentMetadata?.executionId,d=n.toolCall?.id;if(c&&Fw(c)&&p&&d&&n.agentMetadata?.awaitingLocalTool===!0){let g=`${p}:${d}`,f=this.webMcpInflightKeys.has(g),h=this.webMcpResolvedKeys.has(g),y=r.toolCall?.name,v=r.agentMetadata?.executionId===p&&r.toolCall?.id===d&&y!==void 0&&Fw(y)&&r.toolCall?.status==="complete";(f||h||v)&&(i.agentMetadata={...i.agentMetadata??{},awaitingLocalTool:!1},i.toolCall=r.toolCall,i.streaming=r.streaming)}return i}),this.messages=this.#ce(this.messages),this.callbacks.onMessagesChanged([...this.messages])}#Ce(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.#V()}}#V(){return this.#o++}#ce(t){return[...t].sort((n,o)=>{let r=new Date(n.createdAt).getTime(),s=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let i=n.sequence??0,l=o.sequence??0;return i!==l?i-l:n.id.localeCompare(o.id)})}};Je();var Ao=require("lucide");Lr();kt();Nr();var hk={add:e=>PC(e)},yk=e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0,Ip={allowedTypes:Dr,maxFileSize:10*1024*1024,maxFiles:4};function bk(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function vk(e){return e==="application/pdf"?Ao.FileText:e.startsWith("text/")?Ao.FileText:e.includes("word")?Ao.FileText:e.includes("excel")||e.includes("spreadsheet")?Ao.FileSpreadsheet:e==="application/json"?Ao.FileCode:Ao.File}var Ai=class e{constructor(t={}){this.attachments=[];this.#e=null;this.#n=new Map;this.#o=!1;this.config={allowedTypes:t.allowedTypes??Ip.allowedTypes,maxFileSize:t.maxFileSize??Ip.maxFileSize,maxFiles:t.maxFiles??Ip.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange,adapter:t.adapter}}#e;#n;#o;#t(){return typeof this.config.adapter?.add=="function"}#s(){return this.#t()?this.config.adapter:hk}setPreviewsContainer(t){this.#e=t}remountPreviews(t){if(this.#e=t,t){t.innerHTML="";for(let n of this.attachments)this.#g(n)}this.#a()}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:Ip.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange),t.adapter!==void 0&&(this.config.adapter=t.adapter)}isReady(){return this.attachments.every(t=>t.status==="ready")}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart).filter(t=>t!==null)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){if(!t.length||this.#o)return;let n=[];for(let o of t){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(o,"count");continue}let r=kC(o,this.config.allowedTypes,this.config.maxFileSize);if(!r.valid){let i=r.error?.includes("type")?"type":"size";this.config.onFileRejected?.(o,i);continue}let s={id:bk(),file:o,previewUrl:Gd(o)?URL.createObjectURL(o):null,contentPart:null,status:this.#t()?"uploading":"processing",progress:this.#t()?0:void 0};this.attachments.push(s),this.#g(s),n.push(s)}this.#a(),this.#i(),await Promise.all(n.map(o=>this.#r(o)))}async#r(t){let n=new AbortController;this.#n.set(t.id,n);let o=()=>this.#o||n.signal.aborted||this.#n.get(t.id)!==n||!this.attachments.includes(t);try{let r=await this.#s().add(t.file,{signal:n.signal,onProgress:s=>{o()||t.status!=="uploading"||(t.progress=yk(s),this.#l(t),this.#i())}});if(o())return;t.contentPart=r,t.status="ready",t.progress=void 0,t.error=void 0}catch(r){if(o())return;t.status="error",t.progress=void 0,t.error=r instanceof Error?r.message:String(r??"Upload failed")}finally{this.#n.get(t.id)===n&&this.#n.delete(t.id)}this.#l(t),this.#i()}retryAttachment(t){let n=this.attachments.find(o=>o.id===t);!n||n.status!=="error"||this.#o||(n.status=this.#t()?"uploading":"processing",n.progress=this.#t()?0:void 0,n.error=void 0,this.#l(n),this.#i(),this.#r(n))}#p(t){let n=this.#n.get(t);n&&(this.#n.delete(t),n.abort())}removeAttachment(t){let n=this.attachments.findIndex(s=>s.id===t);if(n===-1)return;let o=this.attachments[n];this.#p(t),o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let r=this.#e?.querySelector(`[data-attachment-id="${t}"]`);r&&r.remove(),o.status==="ready"&&o.contentPart&&this.#f(o.contentPart),this.#a(),this.#i()}#f(t){let n=this.config.adapter?.remove;if(n)try{let o=n(t,{signal:new AbortController().signal});o&&typeof o.catch=="function"&&o.catch(r=>{console.error("[AttachmentManager] adapter.remove failed:",r)})}catch(o){console.error("[AttachmentManager] adapter.remove failed:",o)}}clearAttachments(){for(let t of this.attachments)this.#p(t.id),t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.#n.clear(),this.#e&&(this.#e.innerHTML=""),this.#a(),this.#i()}destroy(){if(!this.#o){this.#o=!0;for(let t of this.#n.values())t.abort();this.#n.clear();for(let t of this.attachments)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.#e=null}}#i(){this.#o||this.config.onAttachmentsChange?.(this.getAttachments())}#g(t){if(!this.#e)return;let n=Gd(t.file),o=x("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",t.id),o.style.width="48px",o.style.height="48px",n&&t.previewUrl){let d=x("img");d.src=t.previewUrl,d.alt=t.file.name,d.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",d.style.width="48px",d.style.height="48px",d.style.objectFit="cover",d.style.borderRadius="8px",o.appendChild(d)}else{let d=x("div");d.style.width="48px",d.style.height="48px",d.style.borderRadius="8px",d.style.backgroundColor="var(--persona-container, #f3f4f6)",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.display="flex",d.style.flexDirection="column",d.style.alignItems="center",d.style.justifyContent="center",d.style.gap="2px",d.style.overflow="hidden";let g=vk(t.file.type),f=Nt(g,20,"var(--persona-muted, #6b7280)",1.5);f&&d.appendChild(f);let h=x("span");h.textContent=LC(t.file.type,t.file.name),h.style.fontSize="8px",h.style.fontWeight="600",h.style.color="var(--persona-muted, #6b7280)",h.style.textTransform="uppercase",h.style.lineHeight="1",d.appendChild(h),o.appendChild(d)}let r=Q("div",{className:"persona-attachment-status",attrs:{"data-persona-attachment-status":""}}),s=x("div","persona-attachment-progress");s.appendChild(x("div","persona-attachment-progress__bar"));let i=Q("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),l=ge("rotate-cw",12,"var(--persona-text-inverse, #ffffff)",2);l?i.appendChild(l):i.textContent="\u21BB",i.addEventListener("click",d=>{d.preventDefault(),d.stopPropagation(),this.retryAttachment(t.id)}),r.append(s,i),o.appendChild(r);let c=x("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");c.type="button",c.setAttribute("aria-label","Remove attachment"),c.style.position="absolute",c.style.top="-4px",c.style.insetInlineEnd="-4px",c.style.width="18px",c.style.height="18px",c.style.borderRadius="50%",c.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",c.style.border="none",c.style.cursor="pointer",c.style.display="flex",c.style.alignItems="center",c.style.justifyContent="center",c.style.padding="0";let p=Nt(Ao.X,10,"var(--persona-text-inverse, #ffffff)",2);p?c.appendChild(p):(c.textContent="\xD7",c.style.color="var(--persona-text-inverse, #ffffff)",c.style.fontSize="14px",c.style.lineHeight="1"),c.addEventListener("click",d=>{d.preventDefault(),d.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(c),this.#e.appendChild(o),this.#c(o,t)}#l(t){let n=this.#e?.querySelector(`[data-attachment-id="${t.id}"]`);n&&this.#c(n,t)}#c(t,n){t.dataset.status=n.status;let o=n.status!=="ready"&&n.status!=="error";t.setAttribute("aria-busy",o?"true":"false"),t.title=n.status==="error"?`${n.file.name}: ${n.error??"Upload failed"}`:n.file.name;let r=t.querySelector(".persona-attachment-progress__bar");if(r){let s=n.progress;r.style.width=typeof s=="number"?`${Math.round(s*100)}%`:""}}#a(){this.#e&&(this.#e.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t?.allowedTypes,maxFileSize:t?.maxFileSize,maxFiles:t?.maxFiles,onFileRejected:t?.onFileRejected,onAttachmentsChange:n,adapter:t?.adapter})}};var $w=(e,t)=>e.length===t.length&&e.every((n,o)=>n===t[o]),Ck=(e,t)=>e.length===t.length&&e.every((n,o)=>{let r=t[o];return n.id===r.id&&n.name===r.name&&n.mimeType===r.mimeType&&n.size===r.size&&n.status===r.status&&n.progress===r.progress&&n.error===r.error});function Uw(){let e={text:"",attachments:[],mentionRefs:[],selectedModelId:void 0,activeModeIds:[],quote:void 0,pendingSubmission:void 0,preparing:!1,streaming:!1,inputDisabled:!1,sendDisabled:!1},t=new Set,n=null,o=!1,r=!1,s=()=>e.preparing?"preparing":e.streaming?"streaming":"idle",i=()=>{let d=s();return Object.freeze({text:e.text,attachments:Object.freeze(e.attachments.map(g=>Object.freeze({...g}))),mentionRefs:Object.freeze([...e.mentionRefs]),selectedModelId:e.selectedModelId,activeModeIds:Object.freeze([...e.activeModeIds]),quote:e.quote?Object.freeze({...e.quote}):void 0,pendingSubmission:e.pendingSubmission,phase:d,inputDisabled:e.inputDisabled,sendDisabled:d!=="idle"||e.sendDisabled||e.inputDisabled})},l=()=>(n||(n=i()),n),c=()=>{if(o=!1,r||t.size===0)return;let d=l();for(let g of[...t])try{g(d)}catch(f){typeof console<"u"&&console.error("[AgentWidget] composer state listener failed:",f)}},p=()=>{n=null,!(r||o)&&(o=!0,queueMicrotask(c))};return{getState:l,subscribe:d=>(t.add(d),()=>t.delete(d)),setText:d=>{e.text!==d&&(e.text=d,p())},setAttachments:d=>{Ck(e.attachments,d)||(e.attachments=[...d],p())},setMentionRefs:d=>{$w(e.mentionRefs,d)||(e.mentionRefs=[...d],p())},setSelectedModelId:d=>{e.selectedModelId!==d&&(e.selectedModelId=d,p())},setActiveModeIds:d=>{$w(e.activeModeIds,d)||(e.activeModeIds=[...d],p())},setQuote:d=>{let g=e.quote;g?.text===d?.text&&g?.messageId===d?.messageId&&g?.sourceLabel===d?.sourceLabel||(e.quote=d?{...d}:void 0,p())},setPendingSubmission:d=>{e.pendingSubmission!==d&&(e.pendingSubmission=d,p())},setPreparing:d=>{e.preparing!==d&&(e.preparing=d,p())},setStreaming:d=>{e.streaming!==d&&(e.streaming=d,p())},setInputDisabled:d=>{e.inputDisabled!==d&&(e.inputDisabled=d,p())},setSendDisabled:d=>{e.sendDisabled!==d&&(e.sendDisabled=d,p())},flush:()=>{o&&c()},destroy:()=>{r=!0,o=!1,t.clear()}}}Je();var Qn=(e,...t)=>{for(let n of t){let o=e.querySelector(n);if(o)return o}return null},Vw=(e,t)=>{let n=x("div",e);return n.setAttribute(t,""),n.setAttribute("data-persona-composer-synthesized",""),n.style.display="contents",n};function jw(e,t={}){let n=Qn(e,"[data-persona-composer-form]"),o=Qn(e,"[data-persona-composer-input]");if(!n||!o){let A=`[Persona] composer surface is missing required element(s): ${[!n&&"form",!o&&"input"].filter(Boolean).join(", ")}. Mark them with data-persona-composer-form / data-persona-composer-input.`;if(t.debug&&(n||o))throw new Error(A);return typeof console<"u"&&console.warn(A),null}let r={header:Qn(e,"[data-persona-composer-header]"),body:Qn(e,"[data-persona-composer-body]"),actionsStart:Qn(e,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:Qn(e,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:Qn(e,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:Qn(e,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:Qn(e,"[data-persona-composer-status]")},s=new Set,i=r.header;i||(s.add("header"),i=Vw("persona-widget-composer__header","data-persona-composer-header"),n.parentNode?n.parentNode.insertBefore(i,n):e.appendChild(i));let l=r.body??o.parentElement??n,c=(C,A,L,I,H)=>{if(A)return A;s.add(C);let _=Vw(L,I);return H.appendChild(_),_},p=c("actionsStart",r.actionsStart,"persona-widget-composer__left-actions","data-persona-composer-actions-start",n),d=c("actionsEnd",r.actionsEnd,"persona-widget-composer__right-actions","data-persona-composer-actions-end",n),g=c("suggestions",r.suggestions,"persona-widget-composer__suggestions","data-persona-composer-suggestions",e),f=c("status",r.status,"persona-widget-composer__status","data-persona-composer-status",e),h=[],y=(C,A)=>C.target===A.target&&C.type===A.type&&C.handler===A.handler,v=Qn(e,"[data-persona-composer-attachment-input]",'input[type="file"]')??void 0;return{footer:e,form:n,input:o,header:i,body:l,actionsStart:p,actionsEnd:d,suggestions:g,status:f,attachmentInput:v,attachmentPreviews:Qn(e,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:Qn(e,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:Qn(e,"[data-persona-composer-submit]")??void 0,micButton:Qn(e,"[data-persona-composer-mic]")??void 0,synthesized:s,found:r,addListener:(C,A,L,I)=>{C.addEventListener(A,L,I),h.push({target:C,type:A,handler:L,options:I})},removeListener:(C,A,L,I)=>{C.removeEventListener(A,L,I),h=h.filter(H=>!y(H,{target:C,type:A,handler:L}))},destroy:()=>{for(let C of h)C.target.removeEventListener(C.type,C.handler,C.options);h=[]}}}Je();kt();xa();Es();function wk(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function Rp(e){let{anchor:t,content:n,placement:o="bottom-start",offset:r=6,matchAnchorWidth:s=!1,horizontalOffset:i,verticalOffset:l,zIndex:c=2147483e3,onOpen:p,onDismiss:d}=e,g=e.container??wk(t),f=!1,h=null,y=()=>{if(!f)return;let A=t.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${A.width}px`),i&&(n.style.maxWidth=`${A.width}px`);let L=n.getBoundingClientRect(),I=l?.()??null,H=I!=null?A.top+I:A.top,_=o==="top-start"||o==="top-end"?H-r-L.height:A.bottom+r,oe=o==="bottom-end"||o==="top-end"?A.right-L.width:A.left,W=i?.()??null;if(W!=null){let j=Math.max(A.left,A.right-L.width);oe=Math.min(Math.max(A.left+W,A.left),j)}n.style.top=`${_}px`,n.style.left=`${oe}px`},v=()=>{f&&(f=!1,h&&(h(),h=null),n.remove())},C=()=>{if(f)return;f=!0,c!=null&&(n.style.zIndex=String(c)),g.appendChild(n),y();let A=(t.ownerDocument??document).defaultView??window,L=t.ownerDocument??document,I=()=>{if(!t.isConnected){v(),d?.("anchor-removed");return}y()},H=V=>{let oe=typeof V.composedPath=="function"?V.composedPath():[];oe.includes(n)||oe.includes(t)||(v(),d?.("outside"))},_=A.setTimeout(()=>{L.addEventListener("pointerdown",H,!0)},0);A.addEventListener("scroll",I,!0),A.addEventListener("resize",I),h=()=>{A.clearTimeout(_),L.removeEventListener("pointerdown",H,!0),A.removeEventListener("scroll",I,!0),A.removeEventListener("resize",I)},p?.()};return{get isOpen(){return f},open:C,close:v,toggle:()=>f?v():C(),reposition:y,destroy:v}}Je();kt();Es();var Sk='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',Ak=["--persona-components-composer-overflowMenu-background","--persona-components-composer-overflowMenu-borderColor","--persona-components-composer-overflowMenu-borderRadius","--persona-components-composer-overflowMenu-foreground","--persona-components-composer-overflowMenu-shadow"],gm="data-persona-menu-focus",xk=new Set(["ArrowDown","ArrowUp","Home","End"]);function qw(e){return e.getAttribute("role")==="menuitem"?e:e.querySelector(Sk)??e}var Mk=e=>e.disabled===!0||e.getAttribute("aria-disabled")==="true";function zw(e){let t=e.label,n=!1,o=x("div","persona-send-button-wrapper"),r=Q("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${ro} ${Do}`,attrs:{type:"button","aria-haspopup":"menu","aria-expanded":"false","data-persona-composer-overflow-trigger":""}});o.appendChild(r);let s=Q("div",{className:"persona-composer-overflow-menu",attrs:{role:"menu",tabindex:"-1","data-persona-composer-overflow-menu":""}}),i=()=>{let P=e.getButtonSize?.()??"";r.style.width=P,r.style.height=P,r.style.minWidth=P,r.style.minHeight=P,r.style.lineHeight="1",r.replaceChildren();let J=ge("plus",Xn,"currentColor",1.5);J?r.appendChild(J):r.textContent="+"},l=()=>{r.setAttribute("aria-label",t),r.setAttribute("title",t),s.setAttribute("aria-label",t)};l(),i();let c=[],p=-1,d=!1,g=()=>{let J=s.getRootNode().activeElement;return J instanceof HTMLElement?J:null},f=()=>{let P=g();for(let J of c){let U=!!P&&qw(J)===P;J.toggleAttribute(gm,U&&d)}},h=()=>c.filter(P=>P.isConnected||s.contains(P)).map(qw).filter(P=>!Mk(P)),y=(P,J)=>{P.forEach((U,ue)=>{U.setAttribute("tabindex",ue===J?"0":"-1")})},v=P=>{let J=h();if(J.length===0)return;let U=(P%J.length+J.length)%J.length;p=U,y(J,U),J[U].focus(),f()},C=()=>o.ownerDocument??document,A=null,L=null,I=null,H=()=>{A&&(C().removeEventListener("focusin",A,!0),A=null)},_=()=>{L&&(s.removeEventListener("focusin",L),L=null),I&&(s.removeEventListener("pointerdown",I,!0),I=null)},V=null,oe=()=>(V||(V=Rp({anchor:r,content:s,placement:"top-start",offset:6,onDismiss:()=>{r.setAttribute("aria-expanded","false"),H()}})),V),W=()=>V?.isOpen===!0,j=(P=!1)=>{if(W()){V?.close(),r.setAttribute("aria-expanded","false"),H(),_(),p=-1,d=!1;for(let J of c)J.removeAttribute(gm);P&&r.focus()}},X=(P=0,J=!1)=>{if(n||W())return;d=J,Zd(r,s,Ak),oe().open(),r.setAttribute("aria-expanded","true");let U=h();y(U,-1),v(P<0?U.length-1:P),A=ue=>{let fe=typeof ue.composedPath=="function"?ue.composedPath():[];fe.includes(s)||fe.includes(o)||j()},C().addEventListener("focusin",A,!0),L=()=>f(),s.addEventListener("focusin",L),I=()=>{d=!1},s.addEventListener("pointerdown",I,!0)},E=P=>{P.preventDefault(),P.stopPropagation(),W()?j(!0):X(0)},T=P=>{if(P.key==="ArrowDown"||P.key==="Enter"||P.key===" "){P.preventDefault(),d=!0,W()?v(0):X(0,!0);return}P.key==="ArrowUp"&&(P.preventDefault(),d=!0,W()?v(-1):X(-1,!0))},B=P=>{switch(xk.has(P.key)&&(d=!0),P.key){case"ArrowDown":P.preventDefault(),v(p+1);return;case"ArrowUp":P.preventDefault(),v(p-1);return;case"Home":P.preventDefault(),v(0);return;case"End":P.preventDefault(),v(h().length-1);return;case"Escape":P.preventDefault(),P.stopPropagation(),j(!0);return;case"Tab":j(!0);return;default:}};return r.addEventListener("click",E),r.addEventListener("keydown",T),s.addEventListener("keydown",B),{trigger:o,triggerButton:r,panel:s,setItems:P=>{for(let U of c)P.includes(U)||U.removeAttribute(gm);if(c=[...P],!W())return;let J=h();y(J,Math.min(p,J.length-1)),f()},isOpen:W,open:()=>X(0),close:j,setLabel:P=>{P!==t&&(t=P,l())},applyButtonSize:i,destroy:()=>{n=!0,H(),_(),r.removeEventListener("click",E),r.removeEventListener("keydown",T),s.removeEventListener("keydown",B),V?.destroy(),V=null,o.remove(),s.remove(),c=[]}}}var sr={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},Kw="data-persona-composer-action",fm="data-persona-composer-disable-when-streaming",Ek="core:overflow",Tk=e=>e==="core:attachment"?"attachments":e.startsWith("core:mention")?"mentions":null;function Pk(e,t){if(e===void 0)return null;if(typeof e=="number")return Number.isFinite(e)?e:null;let n=Number.parseFloat(e);if(/^\s*-?\d*\.?\d+(px)?\s*$/.test(e)&&Number.isFinite(n))return n;let o=x("div");o.style.position="absolute",o.style.visibility="hidden",o.style.pointerEvents="none",o.style.height="0",o.style.width=e,t.appendChild(o);let r=o.getBoundingClientRect().width;return o.remove(),Number.isFinite(r)&&r>0?r:Number.isFinite(n)?n:null}function mm(e){let t=e.clientWidth;if(!t)return 0;let n=e.ownerDocument?.defaultView;if(!n?.getComputedStyle)return t;let o=n.getComputedStyle(e),r=(Number.parseFloat(o.paddingLeft)||0)+(Number.parseFloat(o.paddingRight)||0);return Math.max(0,t-r)}var Gw=(e,t)=>{!e||typeof console>"u"||console.warn(t)},kk=(e,t)=>t.includes(":")?t:`${e}:${t}`;function Lk(e){let{debug:t}=e,n=[],o=new Map,r=0,s=l=>{let c=o.get(l.id);if(c){Gw(t,`[Persona] composer action "${l.id}" is already contributed by ${Yw(c)}; the ${Yw(l)} copy is ignored.`);return}o.set(l.id,l),n.push(l)};for(let l of e.builtIns)s({id:l.id,placement:l.placement,presentation:"bar",order:l.order,sequence:r++,source:"core",builtIn:l});let i=(l,c,p)=>{let d=p?kk(p,l.id):l.id,g=l.order??sr.custom;l.placement==="end"&&g>=sr.send&&(Gw(t,`[Persona] composer action "${d}" ordered at ${g} would render after send; clamped to ${sr.send-1}.`),g=sr.send-1),s({id:d,placement:l.placement,presentation:l.presentation??"bar",order:g,sequence:r++,source:c,pluginId:p,action:l})};for(let l of e.configActions??[])i(l,"config");for(let l of e.plugins){if(!l.contributeComposerActions)continue;let c;try{c=l.contributeComposerActions(e.contributionContext)}catch(p){typeof console<"u"&&console.error(`[Persona] plugin "${l.id}" contributeComposerActions failed:`,p);continue}for(let p of c??[])i(p,"plugin",l.id)}return n.sort((l,c)=>l.order===c.order?l.sequence-c.sequence:l.order-c.order)}var Yw=e=>e.source==="plugin"?`plugin "${e.pluginId}"`:e.source==="config"?"composer.actions":"a core built-in",Xw=(e,t,n)=>e===void 0?n:typeof e=="function"?e(t)===!0:e===!0,Hk=e=>e.phase==="streaming"||e.text.trim().length>0||e.attachments.length>0;function Ik(e,t){if(!e||e==="always")return!0;let n=Hk(t);return e==="when-text"?n:!n}var Ls=e=>e.kind==="custom",hm=e=>e instanceof HTMLButtonElement?e:e.querySelector("button")??e,Rk=e=>{let t=hm(e);return t.getAttribute("aria-label")?.trim()||t.getAttribute("title")?.trim()||""},Wk='.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]';function Ok(e){let t="",n=o=>{if(o.nodeType===Node.TEXT_NODE){t+=o.nodeValue??"";return}if(o.nodeType!==Node.ELEMENT_NODE)return;let r=o;typeof r.matches=="function"&&r.matches(Wk)||o.childNodes.forEach(n)};return n(e),t.trim()}var Bk=e=>Ok(e).length===0;function Qw(e){let t=new Map,n=[],o=!1,r=()=>e.getButtonSize?.(),s=(E,T)=>{let B=E.button;if(!B)return;B.setAttribute("role","menuitem"),B.setAttribute("tabindex","-1"),B.className="persona-composer-overflow-menu__item";for(let U of["width","height","minWidth","minHeight","fontSize","color","backgroundColor"])B.style[U]="";B.style.lineHeight="1",T.tooltipText?B.setAttribute("title",T.tooltipText):B.removeAttribute("title"),B.replaceChildren();let P=x("span","persona-composer-overflow-menu__icon");if(T.iconName){let U=ge(T.iconName,16,"currentColor",1.5);U&&P.appendChild(U)}let J=x("span","persona-composer-overflow-menu__label");J.textContent=T.shortLabel??T.label,B.append(P,J)},i=(E,T)=>{let B=E.button;if(!B)return;if(B.setAttribute("aria-label",T.label),T.pressed===void 0?B.removeAttribute("aria-pressed"):B.setAttribute("aria-pressed",T.pressed?"true":"false"),B.toggleAttribute(fm,T.disableWhenStreaming===!0),E.mode==="menu"){E.tooltip?.destroy(),E.tooltip=void 0,s(E,T);return}B.removeAttribute("role"),B.removeAttribute("tabindex"),B.removeAttribute("title");let P=r(),J=!!T.shortLabel;if(B.className=_n("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",ro,Do,J&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),B.style.width=P&&!J?P:"",B.style.height=P??"",B.style.minWidth=P&&!J?P:"",B.style.minHeight=P??"",B.style.fontSize=J?"":"18px",B.style.lineHeight="1",B.style.color=T.iconColor??"",B.style.backgroundColor=T.backgroundColor??"",B.replaceChildren(),T.iconName){let U=ge(T.iconName,Xn,"currentColor",1.5);U&&B.appendChild(U)}if(J){let U=x("span","persona-composer-action-button__label");U.textContent=T.shortLabel,B.appendChild(U)}else B.firstChild||(B.textContent=T.label);E.tooltip?.destroy(),E.tooltip=vn({anchor:B,trigger:E.element,text:()=>T.tooltipText??T.label,enabled:!!T.tooltipText})},l=(E,T)=>{let B=E.action,P=Q("button",{attrs:{type:"button"}}),J=P;if(T==="bar"){let fe=x("div","persona-send-button-wrapper");fe.appendChild(P),J=fe}J.setAttribute(Kw,E.id);let U={resolved:E,element:J,button:P,owned:!0,managed:!0,busy:!1,visible:!0,mode:T},ue=fe=>{if(fe.preventDefault(),fe.stopPropagation(),U.busy||P.disabled)return;let me=U.resolved.action;U.mode==="menu"&&h?.close(!0);let He;try{He=me.onSelect(e.actionContext,fe)}catch(Ee){e.reportError(Ee,{actionId:U.resolved.id});return}!He||typeof He.then!="function"||(U.busy=!0,P.setAttribute("aria-busy","true"),He.catch(Ee=>{e.reportError(Ee,{actionId:U.resolved.id})}).finally(()=>{U.busy=!1,P.removeAttribute("aria-busy")}))};return P.addEventListener("click",ue),U.detach=()=>P.removeEventListener("click",ue),i(U,B),U},c=E=>{let T=E.action,B;try{B=T.render({...e.actionContext,id:E.id,action:T})}catch(P){return e.reportError(P,{actionId:E.id}),null}return B?.element?(B.element.setAttribute(Kw,E.id),B.element.toggleAttribute(fm,T.disableWhenStreaming===!0),{resolved:E,element:B.element,owned:!0,managed:!0,destroy:B.destroy,busy:!1,visible:!0,mode:"bar"}):null},p=(E,T)=>{if(E.builtIn){let P=E.builtIn.element;return P?{resolved:E,element:P,owned:!1,managed:E.builtIn.managed===!0,busy:!1,visible:!0,mode:"bar"}:null}let B=E.action;return B?Ls(B)?c(E):l(E,T):null},d=E=>{if(E.detach?.(),E.tooltip?.destroy(),E.detachMenuSlot?.(),E.detachMenuSlot=void 0,E.menuLabel?.remove(),E.menuLabel=void 0,E.menuSlot?.remove(),E.menuSlot=void 0,E.owned){try{E.destroy?.()}catch(T){e.reportError(T,{actionId:E.resolved.id})}E.element.remove()}},g=(E,T)=>{for(let B=0;B<T.length;B++){let P=T[B];if(!P.managed)continue;let J=null;for(let U=B+1;U<T.length;U++){let ue=T[U];if(!ue.managed&&ue.element.parentElement===E){J=ue.element;break}}J?(P.element.parentElement!==E||P.element.nextSibling!==J)&&E.insertBefore(P.element,J):E.lastChild!==P.element&&E.appendChild(P.element)}},f=(E,T)=>{if(E.button){E.button.disabled=T;return}if(!E.owned)return;let B=E.element;B.toggleAttribute("data-disabled",T),B.setAttribute("aria-disabled",T?"true":"false");let P=B instanceof HTMLButtonElement||B instanceof HTMLSelectElement||B instanceof HTMLInputElement||B instanceof HTMLTextAreaElement?B:B.querySelector("button, select, input, textarea");P&&(P.disabled=T)},h=null,y=null,v=null,C=0,A=()=>{let E=e.getOverflow?.();return E?.enabled===!0?E:void 0},L=()=>(h?h.setLabel(e.getOverflowLabel?.()??"More actions"):h=zw({label:e.getOverflowLabel?.()??"More actions",getButtonSize:r}),h),I=E=>{y!==E&&(v?.disconnect(),y=E,C=mm(E),!(typeof ResizeObserver>"u")&&(v=new ResizeObserver(T=>{let P=T[T.length-1]?.contentRect?.width??mm(E);P!==C&&(C=P,j())}),v.observe(E)))},H=(E,T)=>{let B=Pk(E.collapseAutoActionsBelow,T);if(B===null)return!1;let P=C||mm(T);return P>0&&P<B},_=(E,T,B)=>{if(!T)return"bar";if(E.resolved.builtIn){let J=Tk(E.resolved.id);return J&&T.includeBuiltIns?.includes(J)?"menu":"bar"}let P=E.resolved.presentation;return P==="overflow"||P==="auto"&&B?"menu":"bar"},V=E=>{let T=E.menuSlot;if(!T)return;if(!Bk(E.element)){E.menuLabel?.remove(),E.menuLabel=void 0;return}let B=Rk(E.element);if(!B){E.menuLabel?.remove(),E.menuLabel=void 0;return}E.menuLabel||(E.menuLabel=x("span","persona-composer-overflow-menu__label")),E.menuLabel.textContent!==B&&(E.menuLabel.textContent=B),E.menuLabel.parentElement!==T&&T.appendChild(E.menuLabel)},oe=(E,T)=>{if(E.mode===T)return E;let B=E.resolved.action;if(B&&!Ls(B)){d(E),t.delete(E.resolved.id);let P=l(E.resolved,T);return t.set(E.resolved.id,P),P}if(T==="menu"){let P=Q("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none",[Af]:""}});P.appendChild(E.element),cC(hm(E.element)),E.menuSlot=P;let J=U=>{let ue=hm(E.element);if(ue.disabled)return;let fe=U.target===ue||ue.contains(U.target);h?.close(!0),fe||ue.click()};P.addEventListener("click",J,!0),E.detachMenuSlot=()=>P.removeEventListener("click",J,!0),E.managed=!0,V(E)}else E.detachMenuSlot?.(),E.detachMenuSlot=void 0,E.menuLabel?.remove(),E.menuLabel=void 0,E.menuSlot?.remove(),E.menuSlot=void 0;return E.mode=T,E},W=(E,T)=>{let B=T.map(P=>P.menuSlot??P.element);for(B.forEach((P,J)=>{let U=E.children[J];U!==P&&(U?E.insertBefore(P,U):E.appendChild(P))});E.children.length>B.length;)E.lastElementChild?.remove()},j=()=>{if(o)return;let E=e.getBindings();if(!E)return;let T=e.getState(),B=T.phase==="streaming",P=A();P&&I(E.footer);let J=P?H(P,E.footer):!1,U={start:[],end:[]},ue=[];for(let fe of n){let me=t.get(fe.id);if(!me)continue;let He=fe.action,Ee=He?Xw(He.visible,T,!0)&&Ik(He.visibility,T):!0;if(me.visible!==Ee&&(me.visible=Ee,!Ee&&me.managed&&(me.menuSlot??me.element).remove()),!!Ee){if(me=oe(me,_(me,P,J)),He){let Ie=Xw(He.disabled,T,!1)||He.disableWhenStreaming===!0&&B;f(me,Ie),!Ls(He)&&He.pressed!==void 0&&me.button?.setAttribute("aria-pressed",He.pressed?"true":"false")}me.mode==="menu"?(V(me),ue.push(me)):U[fe.placement].push(me)}}if(ue.length>0){let fe=L();W(fe.panel,ue),fe.setItems(ue.map(Ie=>Ie.menuSlot??Ie.element)),fe.applyButtonSize();let me=Number.isFinite(P?.order)?P?.order:sr.overflow,He=U.start.findIndex(Ie=>Ie.resolved.order>me),Ee={resolved:{id:Ek,placement:"start",presentation:"bar",order:me,sequence:-1,source:"core"},element:fe.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};U.start.splice(He<0?U.start.length:He,0,Ee)}else h&&(h.close(),h.trigger.remove(),h.setItems([]));g(E.actionsStart,U.start),g(E.actionsEnd,U.end)};return{resolve:()=>{if(o)return;let E=Lk(e.collect()),T=new Set(E.map(B=>B.id));for(let[B,P]of t)T.has(B)||(d(P),t.delete(B));for(let B of E){let P=t.get(B.id);if(!P){let fe=p(B,"bar");fe&&t.set(B.id,fe);continue}let J=P.resolved.action,U=B.action;if(!!J!=!!U||J&&U&&Ls(J)!==Ls(U)||J&&U&&Ls(J)&&Ls(U)&&J.render!==U.render){d(P),t.delete(B.id);let fe=p(B,P.mode);fe&&t.set(B.id,fe);continue}P.resolved=B,B.builtIn?(P.managed=B.builtIn.managed===!0||P.mode==="menu",B.builtIn.element&&P.mode==="bar"&&(P.element=B.builtIn.element)):U&&!Ls(U)?i(P,U):U&&P.element.toggleAttribute(fm,U.disableWhenStreaming===!0)}n=E,j()},sync:j,getResolved:()=>n,getOverflowMenu:()=>h,destroy:()=>{if(!o){o=!0,v?.disconnect(),v=null,y=null;for(let E of t.values())d(E);t.clear(),h?.destroy(),h=null,n=[]}}}}Je();kt();Es();var _k="core:model",Dk=700,Jw=16,Nk=["--persona-components-composer-modelPicker-menuBackground","--persona-components-composer-modelPicker-menuBorderRadius","--persona-components-composer-modelPicker-rowHoverBackground","--persona-components-composer-modelPicker-labelColor","--persona-components-composer-modelPicker-descriptionColor"],Zw=()=>{let e=Q("span",{className:"persona-composer-model-picker-wrapper",attrs:{"data-persona-composer-model-picker-wrapper":""}}),t=Q("span",{className:"persona-composer-model-picker-chevron",attrs:{"aria-hidden":"true"}});return{wrapper:e,chevron:t}};function eS(e){let t=e.label??"Model",n=e.presentation??"native",o=null,r=c=>{let p=e.getSelectedModelId();return c.find(d=>d.id===p)??c[0]},s=()=>{let c=Q("select",{className:"persona-composer-model-picker",attrs:{"aria-label":t,"data-persona-composer-model-picker":""}}),p="",d=()=>{let v=e.getModels(),C=v.map(A=>`${A.id}:${A.label}`).join("|");C!==p&&(p=C,c.replaceChildren(...v.map(A=>{let L=Q("option",{attrs:{value:A.id}});return L.textContent=A.label,L}))),c.value=r(v)?.id??""};d(),o=d;let g=()=>{c.value&&e.onSelect(c.value)};c.addEventListener("change",g);let f=v=>v.stopPropagation();c.addEventListener("click",f);let{wrapper:h,chevron:y}=Zw();return h.append(c,y),{element:h,destroy:()=>{o===d&&(o=null),c.removeEventListener("change",g),c.removeEventListener("click",f)}}},i=()=>{let c=Q("button",{className:"persona-composer-model-picker persona-composer-model-picker-trigger",attrs:{type:"button","aria-haspopup":"listbox","aria-expanded":"false","data-persona-composer-model-picker":"popover"}}),p=x("span","persona-composer-model-picker-label"),d=x("span","persona-composer-model-picker-suffix");c.append(p,d);let g=Q("div",{className:"persona-composer-model-menu",attrs:{role:"listbox",tabindex:"-1","aria-label":t,"data-persona-composer-model-menu":""}}),f=new Map,h="",y=null,v=()=>y?.isOpen===!0,C=(T=!1)=>{v()&&(y?.close(),c.setAttribute("aria-expanded","false"),T&&c.focus())},A=T=>{let B=[...f.values()];if(B.length===0)return;let P=(T%B.length+B.length)%B.length;B[P].focus()},L=T=>{if(v())return;y||(y=Rp({anchor:c,content:g,placement:"top-start",offset:6,onDismiss:()=>c.setAttribute("aria-expanded","false")})),Zd(c,g,Nk),y.open(),c.setAttribute("aria-expanded","true");let P=[...f.keys()].indexOf(r(e.getModels())?.id??"");A(T??(P>=0?P:0))},I=T=>{C(!0),e.onSelect(T)},H=T=>{T.preventDefault(),T.stopPropagation();let B=T.currentTarget.getAttribute("data-persona-model-option");B&&I(B)},_=T=>{let B=Q("button",{className:"persona-composer-model-option",attrs:{type:"button",role:"option",tabindex:"-1","aria-selected":"false","data-persona-model-option":T.id}});if(T.icon){let fe=ge(T.icon,Jw,"currentColor",1.5);if(fe){let me=x("span","persona-composer-model-option-icon");me.appendChild(fe),B.appendChild(me)}}let P=x("span","persona-composer-model-option-body"),J=x("span","persona-composer-model-option-label");if(J.textContent=T.label,P.appendChild(J),T.description){let fe=x("span","persona-composer-model-option-description");fe.textContent=T.description,P.appendChild(fe)}B.appendChild(P);let U=x("span","persona-composer-model-option-check");U.setAttribute("aria-hidden","true");let ue=ge("check",Jw,"currentColor",2);return ue&&U.appendChild(ue),B.appendChild(U),B.addEventListener("click",H),B},V=()=>{let T=e.getModels(),B=T.map(U=>`${U.id}:${U.label}:${U.icon??""}:${U.description??""}`).join("|");if(B!==h){h=B;for(let U of f.values())U.removeEventListener("click",H);f.clear(),g.replaceChildren(...T.map(U=>{let ue=_(U);return f.set(U.id,ue),ue}))}let P=r(T);for(let[U,ue]of f)ue.setAttribute("aria-selected",String(U===P?.id));p.textContent=P?.label??"";let J=e.getSuffix?.()??"";d.textContent=J,c.setAttribute("aria-label",[t,[P?.label,J].filter(Boolean).join(" ")].filter(Boolean).join(": "))};V(),o=V;let oe=T=>{T.preventDefault(),T.stopPropagation(),v()?C(!0):L()},W=T=>{if(T.key==="ArrowDown"){T.preventDefault(),v()?A(0):L(0);return}T.key==="ArrowUp"&&(T.preventDefault(),v()?A(-1):L(-1))},j=T=>{let B=[...f.values()],P=B.indexOf(T.target?.closest?.(".persona-composer-model-option"));switch(T.key){case"ArrowDown":T.preventDefault(),A(P+1);return;case"ArrowUp":T.preventDefault(),A(P-1);return;case"Home":T.preventDefault(),A(0);return;case"End":T.preventDefault(),A(B.length-1);return;case"Escape":T.preventDefault(),T.stopPropagation(),C(!0);return;case"Tab":C(!0);return;default:}};c.addEventListener("click",oe),c.addEventListener("keydown",W),g.addEventListener("keydown",j);let{wrapper:X,chevron:E}=Zw();return X.append(c,E),{element:X,destroy:()=>{o===V&&(o=null),c.removeEventListener("click",oe),c.removeEventListener("keydown",W),g.removeEventListener("keydown",j);for(let T of f.values())T.removeEventListener("click",H);f.clear(),y?.destroy(),y=null,g.remove()}}};return{action:{id:_k,kind:"custom",placement:"end",order:Dk,presentation:n==="popover"?"bar":"auto",label:t,render:()=>n==="popover"?i():s()},repaint:()=>o?.()}}Je();kt();Je();var ym="[data-persona-composer-chip-row]";function Wp(e){e.style.display=e.childElementCount>0?"flex":"none"}function bm(e){let t=e.querySelector(ym);if(t)return t;let n=Q("div",{className:"persona-composer-chip-row",attrs:{"data-persona-composer-chip-row":""}});n.style.display="none";let o=e.querySelector("[data-persona-composer-quote], [data-persona-composer-pending]");return o?.parentElement===e?e.insertBefore(n,o):e.appendChild(n),n}var Fk=":scope > [data-persona-composer-mode]";function tS(e){let t=e.row,n="",o=!1,r=new Set(e.initialIds??[]),s=p=>{let d=Q("span",{className:"persona-mention-chip persona-composer-mode-chip",attrs:{"data-persona-composer-mode":p.id}});if(p.iconName){let y=x("span","persona-mention-chip-icon"),v=ge(p.iconName,12,"currentColor",1.5);v&&y.appendChild(v),d.appendChild(y)}let g=x("span","persona-mention-chip-label");g.textContent=p.shortLabel??p.label,d.appendChild(g);let f=Q("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${p.label}`}}),h=ge("x",12,"currentColor",2);return h?f.appendChild(h):f.textContent="\xD7",f.addEventListener("click",y=>{y.preventDefault(),y.stopPropagation(),e.onRemove(p.id)}),d.appendChild(f),d},i=()=>Array.from(t.querySelectorAll(Fk)),l=p=>{p.setAttribute("data-persona-chip-exit",""),p.setAttribute("aria-hidden","true"),p.style.pointerEvents="none";let d=()=>{p.remove(),Wp(t)},g=t.ownerDocument.defaultView,f=typeof g?.getComputedStyle=="function"?g.getComputedStyle(p).animationName:"";if(!f||f==="none"){d();return}p.addEventListener("animationend",d,{once:!0}),p.addEventListener("animationcancel",d,{once:!0})},c=()=>{for(let p of i())p.remove()};return{element:t,render:(p,d)=>{if(o)return;let g=d.filter(v=>p.includes(v.id)),f=g.map(v=>`${v.id}:${v.shortLabel??v.label}`).join("|");if(f===n)return;n=f;let h=new Map;for(let v of i()){let C=v.getAttribute("data-persona-composer-mode");C&&g.some(L=>L.id===C)&&!v.hasAttribute("data-persona-chip-exit")?h.set(C,v):v.hasAttribute("data-persona-chip-exit")||l(v)}let y=t.firstChild;for(let v of g){let C=h.get(v.id);C||(C=s(v),r.has(v.id)||(C.setAttribute("data-persona-chip-enter",""),C.addEventListener("animationend",()=>C?.removeAttribute("data-persona-chip-enter"),{once:!0}))),r.delete(v.id),C!==y&&t.insertBefore(C,y),y=C.nextSibling}Wp(t)},destroy:()=>{o=!0,c(),Wp(t)}}}Je();kt();var nS=e=>`core:mode:${e}`;var vm=e=>Math.min(300+e,499),oS=e=>`core:mode-group:${e}`;function Op(e,t){return e?t?.find(n=>n.id===e)?.presentation==="segmented":!1}function $k(e,t){return e?t?.find(n=>n.id===e)?.chipVisibility==="hidden":!1}function rS(e,t){return e?.length?e.filter(n=>!Op(n.groupId,t)&&!$k(n.groupId,t)):[]}var Uk=(e,t)=>e.groupId?t?.find(n=>n.id===e.groupId)?.selection??null:null;function sS(e,t,n,o){let r=n.find(l=>l.id===t);if(!r)return[...e];let s=e.includes(t),i=new Set(e);if(s)i.delete(t);else{if(Uk(r,o)==="single"){let l=n.filter(c=>c.groupId===r.groupId).map(c=>c.id);i=new Set([...i].filter(c=>!l.includes(c)))}i.add(t)}return n.filter(l=>i.has(l.id)).map(l=>l.id)}function Bp(e,t){return t?.length?t.filter(n=>e.includes(n.id)).map(n=>n.id):[]}function iS(e,t){return t?.length?t.filter(n=>e.includes(n.id)&&(n.persistence??"sticky")!=="once").map(n=>n.id):[]}function aS(e,t){if(!(!t?.length||e.length===0))return t.find(n=>e.includes(n.id)&&n.placeholder)?.placeholder}var Vk=16;function lS(e){let t=null;return{action:{id:oS(e.groupId),kind:"custom",placement:"start",presentation:"bar",label:e.getGroup()?.label??e.groupId,render:()=>{let o=Q("div",{className:"persona-composer-segmented",attrs:{"data-persona-composer-mode-group":e.groupId}}),r=new Map,s="",i=p=>{p.preventDefault(),p.stopPropagation();let g=p.currentTarget.getAttribute("data-persona-composer-mode");!g||e.getActiveIds().includes(g)&&e.getGroup()?.selection==="single"||e.onSelect(g)},l=p=>{let d=Q("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":p.id,"aria-label":p.label}});if(p.iconName){let f=ge(p.iconName,Vk,"currentColor",1.5);f&&d.appendChild(f)}let g=x("span","persona-composer-segmented-label");return g.textContent=p.shortLabel??p.label,d.appendChild(g),d.addEventListener("click",i),d},c=()=>{let p=e.getGroup();p?.label?(o.setAttribute("role","group"),o.setAttribute("aria-label",p.label)):(o.removeAttribute("role"),o.removeAttribute("aria-label"));let d=e.getModes(),g=d.map(h=>`${h.id}:${h.shortLabel??h.label}:${h.iconName??""}`).join("|");if(g!==s){s=g;for(let y of r.values())y.removeEventListener("click",i);r.clear();let h=d.map(y=>{let v=l(y);return r.set(y.id,v),v});o.replaceChildren(...h)}let f=e.getActiveIds();for(let[h,y]of r)y.setAttribute("aria-pressed",String(f.includes(h)))};return c(),t=c,{element:o,destroy:()=>{t===c&&(t=null);for(let p of r.values())p.removeEventListener("click",i);r.clear()}}}},repaint:()=>t?.()}}Je();kt();function cS(e){let t=Q("div",{className:"persona-composer-quote",attrs:{"data-persona-composer-quote":""}});t.style.display="none";let n="",o=!1,r=s=>{let i=x("span","persona-composer-quote-bar"),l=x("div","persona-composer-quote-content");if(s.sourceLabel){let g=x("div","persona-composer-quote-source");g.textContent=s.sourceLabel,l.appendChild(g)}let c=Q("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});c.textContent=kp(s.text),l.appendChild(c);let p=Q("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":e.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),d=ge("x",12,"currentColor",2);d?p.appendChild(d):p.textContent="\xD7",p.addEventListener("click",g=>{g.preventDefault(),g.stopPropagation(),e.onDismiss()}),t.replaceChildren(i,l,p)};return{element:t,render:s=>{if(o)return;let i=s?`${s.sourceLabel??""}\0${s.text}`:"";if(i!==n){if(n=i,!s){t.replaceChildren(),t.style.display="none";return}r(s),t.style.display="flex"}},destroy:()=>{o=!0,t.replaceChildren(),t.remove()}}}Je();kt();function dS(e){let t=Q("div",{className:"persona-composer-pending",attrs:{"data-persona-composer-pending":""}});t.style.display="none";let n,o=!1,r=(i,l,c,p)=>{let d=Q("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":l,[c]:""}}),g=ge(i,12,"currentColor",2);return g?d.appendChild(g):d.textContent=l,d.addEventListener("click",f=>{f.preventDefault(),f.stopPropagation(),p()}),d},s=i=>{let l=kp(i.text??"",90);if(l)return l;let c=i.contentParts?.length??0;return c>0?c===1?"1 attachment":`${c} attachments`:(i.mentionRefs?.length??0)>0?i.mentionRefs.map(d=>d.label).join(", "):"Queued message"};return{element:t,render:i=>{if(o||i===n)return;if(n=i,!i){t.replaceChildren(),t.style.display="none";return}let l=x("span","persona-composer-pending-badge");l.textContent=e.label??"Sends next";let c=Q("div",{className:"persona-composer-pending-text",attrs:{"data-persona-composer-pending-text":""}});c.textContent=s(i),t.replaceChildren(l,c,r("pencil",e.editLabel??"Edit queued message","data-persona-composer-pending-edit",e.onEdit),r("x",e.removeLabel??"Remove queued message","data-persona-composer-pending-remove",e.onRemove)),t.style.display="flex"},destroy:()=>{o=!0,t.replaceChildren(),t.remove()}}}Je();function pS(e){let t=Q("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":e.messageId,"data-preserve-runtime":""}}),n=Q("textarea",{className:"persona-message-edit-input",attrs:{rows:"1",dir:"auto","aria-label":"Edit message","data-persona-message-edit-input":""}});n.value=e.initialText;let o=()=>{n.style.height="auto",n.style.height=`${n.scrollHeight}px`};n.addEventListener("input",o);let r=x("div","persona-message-edit-actions"),s=(l,c,p,d)=>{let g=Q("button",{className:`persona-message-edit-button ${c}`,attrs:{type:"button",[p]:""},text:l});return g.addEventListener("click",f=>{f.preventDefault(),f.stopPropagation(),d()}),g},i=()=>{let l=n.value.trim();l&&e.onSave(l)};return r.append(s(e.cancelLabel??"Cancel","persona-message-edit-cancel","data-persona-message-edit-cancel",e.onCancel),s(e.saveLabel??"Send","persona-message-edit-save","data-persona-message-edit-save",i)),n.addEventListener("keydown",l=>{if(l.key==="Escape"){l.preventDefault(),l.stopPropagation(),e.onCancel();return}l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),i())}),t.append(n,r),{element:t,getValue:()=>n.value,focus:()=>{n.focus();let l=n.value.length;n.setSelectionRange(l,l),o()},destroy:()=>{t.replaceChildren(),t.remove()}}}function uS(e){let t=e.text??"";if(t.trim().length>0||(e.mentionRefs?.length??0)>0||(e.activeModeIds?.length??0)>0||e.quote||e.selectedModelId)return{text:t,...e.mentionRefs?.length?{mentionRefs:[...e.mentionRefs]}:{},...e.contentSegments?.length?{contentSegments:[...e.contentSegments]}:{},...e.selectedModelId?{selectedModelId:e.selectedModelId}:{},...e.activeModeIds?.length?{activeModeIds:[...e.activeModeIds]}:{},...e.quote?{quote:{...e.quote}}:{}}}function gS(e,t){if(!e||typeof e.text!="string")return;let n=new Set(t.mentionSourceIds),o=(e.mentionRefs??[]).filter(c=>n.has(c.sourceId)),r=o.length===(e.mentionRefs?.length??0)&&o.length>0,s=new Set(t.modes.map(c=>c.id)),i=(e.activeModeIds??[]).filter(c=>s.has(c)),l=e.selectedModelId&&t.modelIds.includes(e.selectedModelId)?e.selectedModelId:void 0;return{text:e.text,...r?{mentionRefs:o}:{},...r&&e.contentSegments?.length?{contentSegments:e.contentSegments}:{},...l?{selectedModelId:l}:{},...i.length?{activeModeIds:i}:{},...e.quote?.text?{quote:e.quote}:{}}}function fS(e){let t=e.delay??500,n=null,o=!1,r=()=>{n!==null&&(clearTimeout(n),n=null)};return{schedule:()=>{o||(r(),n=setTimeout(()=>{n=null,e.write()},t))},flush:()=>{o||n===null||(r(),e.write())},cancel:r,destroy:()=>{o=!0,r()}}}function mS(e){return e.wrapped||e.text.includes(`
|
|
29
29
|
`)?!1:!(e.hasAttachments||e.hasChips||e.hasQuote||e.hasPendingSubmission)}function hS(){let e=!1;return{observe:(t,n)=>n?(t&&(e=!0),e):(e=!1,!1),release:()=>{e=!1}}}function yS(e){if(!e)return!1;let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return!1;let n=t.getComputedStyle(e),o=Number.parseFloat(n.lineHeight),r=Number.parseFloat(n.fontSize),s=Number.isFinite(o)&&o>0?o:Number.isFinite(r)&&r>0?r*1.4:0;if(!s)return!1;let i=(Number.parseFloat(n.paddingTop)||0)+(Number.parseFloat(n.paddingBottom)||0);return e.scrollHeight-i>s*1.5}function bS(e){e&&(typeof e.requestSubmit=="function"?e.requestSubmit():e.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})))}Jd();function Cm(e){return Object.freeze({text:e.text,contentParts:e.contentParts?Object.freeze([...e.contentParts]):void 0,mentionRefs:Object.freeze([...e.mentionRefs]),contentSegments:e.contentSegments?Object.freeze([...e.contentSegments]):void 0,options:Object.freeze({...e.options}),viaVoice:e.viaVoice})}function CS(e){return e.inputDisabled===!0||e.sendDisabled===!0||e.hasAttachments&&!e.attachmentsReady?!1:!!e.text||e.hasAttachments||e.hasMentions||e.hasServerMentions}var jk=e=>typeof e?.then=="function";function vS(e,t){return t===!1?{status:"canceled"}:!t||typeof t!="object"?{status:"proceed"}:(typeof t.text=="string"&&(e.text=t.text),t.options&&(e.options={...e.options,...t.options}),{status:"proceed"})}function wS(e,t,n){let o;try{o=e(Cm(t),{signal:n})}catch(r){return{status:"error",error:r}}return jk(o)?Promise.resolve(o).then(r=>n.aborted?{status:"aborted"}:vS(t,r),r=>n.aborted?{status:"aborted"}:{status:"error",error:r}):vS(t,o)}$f();Uf();Ff();Nr();var _p=e=>e?.launcher?.variant??(e?.future?.v5Defaults===!0?"circle":"pill"),Dp={background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",border:"transparent",size:"48px",iconSize:"24px",borderRadius:"palette.radius.full",shadow:"0 8px 24px rgba(0,0,0,.16)",offset:"20px"};wo();wo();var Fp="16px",$p="transparent",qk=(()=>{let e={};for(let t of[0,1,2,3,4,5,6,8,10,12,16,20,24,32,40,48,56,64])e[t]=t===0?"0px":`${t/4}rem`;return e})(),Kl={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"},purple:{50:"#faf5ff",100:"#f3e8ff",200:"#e9d5ff",300:"#d8b4fe",400:"#c084fc",500:"#a855f7",600:"#9333ea",700:"#7e22ce",800:"#6b21a8",900:"#581c87",950:"#3b0764"},teal:{50:"#f0fdfa",100:"#ccfbf1",200:"#99f6e4",300:"#5eead4",400:"#2dd4bf",500:"#14b8a6",600:"#0d9488",700:"#0f766e",800:"#115e59",900:"#134e4a",950:"#042f2e"}},spacing:qk,typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},Np={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.50",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.info.500"}},spacing:{xs:"palette.spacing.1",sm:"palette.spacing.2",md:"palette.spacing.4",lg:"palette.spacing.6",xl:"palette.spacing.8","2xl":"palette.spacing.10"},typography:{fontFamily:"palette.typography.fontFamily.sans",fontSize:"palette.typography.fontSize.base",fontWeight:"palette.typography.fontWeight.normal",lineHeight:"palette.typography.lineHeight.normal"}},so={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm",hoverBackground:"rgba(0, 0, 0, 0.05)"}},input:{background:"semantic.colors.surface",placeholder:"semantic.colors.textMuted",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"semantic.colors.surface",foreground:"semantic.colors.primary",border:"semantic.colors.border",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:vi,maxWidth:"none",height:"min(640px, max(200px, calc(100vh - 64px)))",maxHeight:"none",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:Fp,canvasBackground:$p,modes:{floating:{border:"1px solid var(--persona-border)",shadow:"palette.shadows.xl",borderRadius:"palette.radius.xl"},inline:{border:"1px solid var(--persona-border)",shadow:"none",borderRadius:"palette.radius.xl"},docked:{border:"none",shadow:"none",borderRadius:"palette.radius.xl"},sidebar:{border:"none",borderRadius:"0"},mobile:{border:"none",shadow:"none",borderRadius:"0"}}},header:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"20px 24px",minimalPadding:"16px 24px",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50"},message:{gap:"12px",user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"semantic.colors.container",text:"semantic.colors.text",borderRadius:"palette.radius.lg",border:"semantic.colors.border",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"transparent",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"palette.shadows.none"},suggestion:{chip:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.full",padding:"0.5rem 0.875rem",gap:"0.5rem",itemGap:"8px",minHeight:"36px",fontSize:"0.8125rem",lineHeight:"1.25",iconSize:"16px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},card:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.xl",padding:"1rem",shadow:"palette.shadows.sm",gap:"0.625rem",itemGap:"8px",minHeight:"72px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"18px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},list:{background:"transparent",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.md",padding:"0.75rem",gap:"0.625rem",itemGap:"8px",minHeight:"44px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"17px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"}},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},scrollbar:{thumb:"semantic.colors.border",track:"transparent"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit",borderRadius:"palette.radius.md"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},eventStream:{badge:{flow:{background:"palette.colors.success.100",foreground:"palette.colors.success.700"},step:{background:"palette.colors.primary.100",foreground:"palette.colors.primary.700"},reasoning:{background:"palette.colors.warning.100",foreground:"palette.colors.warning.700"},tool:{background:"palette.colors.purple.100",foreground:"palette.colors.purple.800"},agent:{background:"palette.colors.teal.100",foreground:"palette.colors.teal.800"},error:{background:"palette.colors.error.100",foreground:"palette.colors.error.700"},default:{background:"palette.colors.gray.100",foreground:"palette.colors.gray.600"}}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}},zk=Kl.colors.gray,Kk={50:"#fafafa",100:"#f5f5f5",200:"#e5e5e5",300:"#d4d4d4",400:"#a3a3a3",500:"#737373",600:"#525252",700:"#404040",800:"#262626",900:"#171717",950:"#0a0a0a"},AS={...Kl,colors:{...Kl.colors,gray:zk}},Gk={...Kl,colors:{...Kl.colors,gray:Kk},radius:{none:"0px",sm:"4px",md:"8px",lg:"12px",xl:"16px","2xl":"24px",full:"9999px"}},xS=AS,MS=Np,Yk={...Np,colors:{...Np.colors,surface:"#ffffff",background:"#ffffff",container:"semantic.colors.surface",textInverse:"#ffffff"},typography:{...Np.typography,fontSize:"14px",lineHeight:"1.5"}},ES=MS,Up=so,Xk={...so,launcher:Dp,activity:{rowHeight:"32px",labelSize:"13px",iconSize:"16px",indent:"0px",groupIndent:"0px",groupGap:"0px",groupPadding:"0px",transcriptGap:"0px",responseGap:"12px",bodyPadding:"4px 0",bodySize:"13px",bodyLineHeight:"1.5",bodyFontWeight:"400",sectionGap:"8px",bodySurface:"transparent"},toolBubble:{shadow:"none"},reasoningBubble:{shadow:"none"},input:{...so.input,borderRadius:"palette.radius.full"},introCard:{...so.introCard,title:{fontSize:"22px",fontWeight:"500"}},suggestion:{chip:{...so.suggestion.chip,fontWeight:"400"},card:{...so.suggestion.card,fontWeight:"400"},list:{...so.suggestion.list,fontWeight:"400"}},panel:{...so.panel,width:"min(400px, calc(100vw - 24px))",height:"min(704px, calc(100dvh - 104px))",borderRadius:"palette.radius.xl"},header:{...so.header,background:"semantic.colors.container",foreground:"semantic.colors.text",padding:"8px 8px 8px 16px",minimalPadding:"8px 8px 8px 16px",minHeight:"48px",borderBottom:"none",iconBackground:"transparent",iconForeground:"semantic.colors.text",iconScale:"1",controlSize:"28px",controlIconSize:"18px",controlStrokeWidth:"1.5",actionIconForeground:"semantic.colors.textMuted",controlBorderRadius:"8px",controlHoverBackground:"color-mix(in srgb, var(--persona-text) 8%, transparent)",controlHoverForeground:"semantic.colors.text",controlFocusOutline:"2px solid color-mix(in srgb, var(--persona-text) 50%, transparent)",title:{fontSize:"14px",fontWeight:"500",lineHeight:"1.5"}},message:{...so.message,gap:"20px",fullscreenGap:"28px",topFadeHeight:"18px",user:{...so.message.user,background:"palette.colors.gray.100",text:"semantic.colors.text",borderRadius:"palette.radius.xl",shadow:"none",padding:"8px 14px",fontSize:"14px",lineHeight:"1.5"},assistant:{...so.message.assistant,background:"transparent",border:"transparent",borderWidth:"0px",borderRadius:"0px",shadow:"none",padding:"0px",fontSize:"14px",lineHeight:"1.55"}},composer:{...so.composer,padding:"8px",fontSize:"15px",lineHeight:"1.5",controlSize:"32px",controlIconSize:"20px",sendIconSize:"18px",sendButtonRadius:"9999px",footerBorder:"none",overlayBand:"linear-gradient(to bottom, transparent, var(--persona-container) 24px)",focusBorderColor:"color-mix(in srgb, var(--persona-text) 28%, var(--persona-border))",focusRing:"1px solid color-mix(in srgb, var(--persona-text) 12%, transparent)"}},TS=Up,Qk=e=>Ms({future:e}),Sm=e=>Qk(e)==="v5"?{palette:Gk,semantic:Yk,components:Xk}:{palette:AS,semantic:MS,components:Up};function wn(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?wn(e,o):o}function Vp(e){let t={};function n(o,r){for(let[s,i]of Object.entries(o)){let l=`${r}.${s}`;if(typeof i=="string"){let c=wn(e,i);c!==void 0&&(t[l]={path:l,value:c,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof i=="object"&&i!==null&&n(i,l)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function Am(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function PS(e,t){let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];s&&typeof s=="object"&&!Array.isArray(s)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=PS(s,r):n[o]=r}return n}function Jk(e,t){return t?PS(e,t):e}function Gl(e,t={}){let n=Sm(t.future),o={palette:n.palette,semantic:n.semantic,components:n.components},r={palette:{...o.palette,...e?.palette,colors:{...o.palette.colors,...e?.palette?.colors},spacing:{...o.palette.spacing,...e?.palette?.spacing},typography:{...o.palette.typography,...e?.palette?.typography},shadows:{...o.palette.shadows,...e?.palette?.shadows},borders:{...o.palette.borders,...e?.palette?.borders},radius:{...o.palette.radius,...e?.palette?.radius}},semantic:{...o.semantic,...e?.semantic,colors:{...o.semantic.colors,...e?.semantic?.colors,interactive:{...o.semantic.colors.interactive,...e?.semantic?.colors?.interactive},feedback:{...o.semantic.colors.feedback,...e?.semantic?.colors?.feedback}},spacing:{...o.semantic.spacing,...e?.semantic?.spacing},typography:{...o.semantic.typography,...e?.semantic?.typography}},components:Jk(o.components,e?.components)},s=e?.components?.activity;for(let p of["toolBubble","reasoningBubble"])for(let d of["rowHeight","labelSize","iconSize","indent","bodySurface"])s?.[d]!==void 0&&(r.components[p][d]=s[d]);let i=e?.components?.collapsibleWidget?.surface;i!==void 0&&s?.bodySurface===void 0&&(r.components.activity={...r.components.activity,bodySurface:i});let l=e?.components?.header;l?.padding!==void 0&&l.minimalPadding===void 0&&(r.components.header.minimalPadding=r.components.header.padding);let c=e?.components?.message;if(c?.gap!==void 0&&c.fullscreenGap===void 0&&(r.components.message.fullscreenGap=r.components.message.gap),t.validate!==!1){let p=Am(r);if(!p.valid)throw new Error(`Theme validation failed: ${p.errors.map(d=>d.message).join(", ")}`)}if(t.plugins)for(let p of t.plugins)r=p.transform(r);return r}var wm=e=>e.trim()==="0"?"0px":e,SS="--persona-",Zk=e=>{if(!e)return;let t=e.trim().toLowerCase(),n;if(t.charCodeAt(0)===35){let i=t.slice(1);if(!/^[0-9a-f]+$/.test(i))return;i.length===3||i.length===4?n=[0,1,2].map(l=>parseInt(i[l]+i[l],16)):(i.length===6||i.length===8)&&(n=[0,2,4].map(l=>parseInt(i.slice(l,l+2),16)))}else{let i=t.match(/^rgba?\(([^)]+)\)$/);if(i){let l=i[1].split(/[,/\s]+/).filter(Boolean);l.length>=3&&(n=l.slice(0,3).map(c=>{let p=c.endsWith("%"),d=parseFloat(p?c.slice(0,-1):c);return p?d/100*255:d}))}}if(!n||n.some(i=>!Number.isFinite(i)))return;let[o,r,s]=n.map(i=>{let l=Math.max(0,Math.min(255,i))/255;return l<=.03928?l/12.92:Math.pow((l+.055)/1.055,2.4)});return .2126*o+.7152*r+.0722*s},e0=.179,Cn=(e,t)=>{for(let[n,...o]of t){let r;for(let s of o)if(r=s.charCodeAt(0)===61?s.slice(1):e[SS+s],r!==void 0)break;r!==void 0&&(e[SS+n]=r)}};function jp(e){let t=Vp(e),n={};for(let[$,Be]of Object.entries(t)){let ye=$.replace(/\./g,"-");n[`--persona-${ye}`]=Be.value}Cn(n,[["primary","semantic-colors-primary","palette-colors-primary-500"],["secondary","semantic-colors-secondary","palette-colors-secondary-500"],["accent","semantic-colors-accent","palette-colors-accent-500"],["surface","semantic-colors-surface","palette-colors-gray-50"],["background","semantic-colors-background","palette-colors-gray-50"],["container","semantic-colors-container","palette-colors-gray-100"],["text","semantic-colors-text","palette-colors-gray-900"],["text-muted","semantic-colors-text-muted","palette-colors-gray-500"],["text-inverse","semantic-colors-text-inverse","palette-colors-gray-50"],["border","semantic-colors-border","palette-colors-gray-200"],["divider","semantic-colors-divider","palette-colors-gray-200"],["muted","text-muted"],["voice-recording-indicator","components-voice-recording-indicator","palette-colors-error-500"],["voice-recording-bg","components-voice-recording-background","palette-colors-error-50"],["voice-processing-icon","components-voice-processing-icon","palette-colors-primary-500"],["voice-speaking-icon","components-voice-speaking-icon","palette-colors-success-500"],["approval-bg","components-approval-requested-background","surface"],["approval-border","components-approval-requested-border","border"],["approval-text","components-approval-requested-text","palette-colors-gray-900"],["approval-shadow","components-approval-requested-shadow","=0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"],["approval-approve-bg","components-approval-approve-background","button-primary-bg"],["approval-deny-bg","components-approval-deny-background","container"],["attachment-image-bg","components-attachment-image-background","palette-colors-gray-100"],["attachment-image-border","components-attachment-image-border","palette-colors-gray-200"],["font-family","semantic-typography-fontFamily","palette-typography-fontFamily-sans"],["font-size","semantic-typography-fontSize","palette-typography-fontSize-base"],["font-weight","semantic-typography-fontWeight","palette-typography-fontWeight-normal"],["line-height","semantic-typography-lineHeight","palette-typography-lineHeight-normal"],["input-font-family","font-family"],["input-font-weight","font-weight"],["radius-sm","palette-radius-sm","=0.125rem"],["radius-md","palette-radius-md","=0.375rem"],["radius-lg","palette-radius-lg","=0.5rem"],["radius-xl","palette-radius-xl","=0.75rem"],["radius-full","palette-radius-full","=9999px"],["launcher-radius","components-launcher-borderRadius","palette-radius-full","=9999px"],["launcher-bg","components-launcher-background","surface"],["launcher-fg","components-launcher-foreground","primary"]]);let o=n["--persona-components-launcher-foreground"];n["--persona-launcher-fg-muted"]=o&&o!==n["--persona-primary"]?`color-mix(in srgb, ${o} 70%, transparent)`:n["--persona-muted"],Cn(n,[["launcher-border","components-launcher-border","border"],["button-primary-bg","components-button-primary-background","primary"],["button-primary-fg","components-button-primary-foreground","text-inverse"],["button-radius","components-button-primary-borderRadius","palette-radius-full","=9999px"],["button-stop-bg","components-button-stop-background"],["button-stop-fg","components-button-stop-foreground"]]),Cn(n,[["button-ghost-bg","components-button-ghost-background","=transparent"],["button-ghost-fg","components-button-ghost-foreground","text"],["button-ghost-radius","components-button-ghost-borderRadius","radius-md","=0.375rem"],["button-ghost-hover-bg","components-button-ghost-hoverBackground","=rgba(0, 0, 0, 0.05)"],["panel-radius","components-panel-borderRadius","radius-xl","=0.75rem"]]),n["--persona-panel-border"]=n["--persona-components-panel-border"]??`1px solid ${n["--persona-border"]}`,Cn(n,[["panel-shadow","components-panel-shadow","palette-shadows-xl","=0 25px 50px -12px rgba(0, 0, 0, 0.25)"]]),n["--persona-panel-inset"]=n["--persona-components-panel-inset"]??Fp,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??$p,Cn(n,[["launcher-shadow","components-launcher-shadow","=0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"],["input-radius","components-input-borderRadius","radius-lg","=0.5rem"],["message-user-radius","components-message-user-borderRadius","radius-lg","=0.5rem"],["message-assistant-radius","components-message-assistant-borderRadius","radius-lg","=0.5rem"]]),Cn(n,[["header-bg","components-header-background","surface"]]);let r=n["--persona-header-bg"],s=n["--persona-components-header-foreground"],i=s?`color-mix(in srgb, ${s} 72%, ${r})`:void 0;n["--persona-header-border"]=n["--persona-components-header-border"]??(s?`color-mix(in srgb, ${s} 14%, ${r})`:void 0)??n["--persona-divider"],Cn(n,[["header-icon-bg","components-header-iconBackground","primary"],["header-icon-fg","components-header-iconForeground","text-inverse"]]),n["--persona-header-title-fg"]=n["--persona-components-header-title-color"]??n["--persona-components-header-titleForeground"]??s??n["--persona-primary"],n["--persona-header-subtitle-fg"]=n["--persona-components-header-subtitle-color"]??n["--persona-components-header-subtitleForeground"]??i??n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=n["--persona-components-header-actionIconForeground"]??i??n["--persona-muted"],Cn(n,[["header-control-size","components-header-controlSize","=32px"],["header-control-icon-size","components-header-controlIconSize","=20px"]]);let l=e.components?.header;l?.shadow&&(n["--persona-header-shadow"]=l.shadow),l?.borderBottom&&(n["--persona-header-border-bottom"]=l.borderBottom),l?.minHeight&&(n["--persona-header-min-height"]=l.minHeight);let c=n["--persona-components-history-railHeader-background"];c&&(n["--persona-history-rail-header-bg"]=c);let p=n["--persona-components-history-railHeader-border"];p&&(n["--persona-history-rail-header-border"]=p);let d=n["--persona-components-history-railHeader-minHeight"];d&&(n["--persona-history-rail-header-min-height"]=d);for(let[$,Be]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let ye=n[`--persona-components-history-overlay-${$}`];ye&&(n[`--persona-history-overlay-${Be}`]=ye)}for(let[$,Be]of[["background","bg"],["borderRadius","radius"]]){let ye=n[`--persona-components-history-menu-${$}`];ye&&(n[`--persona-history-menu-${Be}`]=ye)}let g=e.components?.history?.motion;if(g){let $=ut=>{if(ut===void 0)return;let Zt=String(ut).trim();return/^\d+(\.\d+)?$/.test(Zt)?`${Zt}ms`:Zt},Be=$(g.enterDurationMs);Be!==void 0&&(n["--persona-history-enter-ms"]=Be);let ye=$(g.exitDurationMs);ye!==void 0&&(n["--persona-history-exit-ms"]=ye),g.enterEasing&&(n["--persona-history-enter-easing"]=g.enterEasing),g.exitEasing&&(n["--persona-history-exit-easing"]=g.exitEasing)}let f=n["--persona-components-history-dangerForeground"];f&&(n["--persona-history-danger-fg"]=f),n["--persona-danger"]=n["--persona-components-history-confirm-dangerBackground"]??n["--persona-palette-colors-error-700"]??"#b42318",n["--persona-danger-fg"]=n["--persona-components-history-confirm-dangerForeground"]??"#ffffff";for(let $ of["scrim","shadow"]){let Be=n[`--persona-components-history-confirm-${$}`];Be&&(n[`--persona-history-confirm-${$}`]=Be)}for(let[$,Be]of[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]]){let ye=n[`--persona-components-tooltip-${$}`];ye&&(n[`--persona-tooltip-${Be}`]=ye)}e.components?.tooltip?.arrow===!1&&(n["--persona-tooltip-arrow-display"]="none");for(let[$,Be]of[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let ye=n[`--persona-components-messageActions-${$}`];ye&&(n[`--persona-message-action-${Be}`]=ye)}Cn(n,[["intro-card-bg","components-introCard-background","=transparent"],["intro-card-radius","components-introCard-borderRadius","=1rem"]]);let h=n["--persona-components-introCard-background"],y=n["--persona-components-introCard-shadow"],v=(!h||h==="transparent"||h==="none")&&(!y||y==="none"),C=n["--persona-components-introCard-padding"]??"1.5rem";n["--persona-intro-card-padding"]=v&&C==="1.5rem"?"1.5rem 0":C,Cn(n,[["intro-card-shadow","components-introCard-shadow","=none"],["intro-card-border","components-introCard-border","=none"],["input-background","components-input-background","surface"],["input-placeholder","components-input-placeholder","text-muted"],["input-backdrop-filter","components-input-backdropFilter","=none"],["message-user-bg","components-message-user-background","accent"],["message-user-text","components-message-user-text","text-inverse"],["message-user-shadow","components-message-user-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["message-assistant-bg","components-message-assistant-background","surface"],["message-assistant-text","components-message-assistant-text","text"],["message-assistant-border","components-message-assistant-border","border"],["message-assistant-shadow","components-message-assistant-shadow","=0 1px 2px 0 rgb(0 0 0 / 0.05)"],["scroll-to-bottom-bg","components-scrollToBottom-background","button-primary-bg","accent"],["scroll-to-bottom-fg","components-scrollToBottom-foreground","button-primary-fg","text-inverse"],["scroll-to-bottom-border","components-scrollToBottom-border","primary"],["scroll-to-bottom-size","components-scrollToBottom-size","=40px"],["scroll-to-bottom-radius","components-scrollToBottom-borderRadius","button-radius","radius-full","=9999px"],["scroll-to-bottom-shadow","components-scrollToBottom-shadow","palette-shadows-sm","=0 1px 2px 0 rgb(0 0 0 / 0.05)"],["scroll-to-bottom-padding","components-scrollToBottom-padding","=0.5rem 0.875rem"],["scroll-to-bottom-gap","components-scrollToBottom-gap","=0.5rem"],["scroll-to-bottom-font-size","components-scrollToBottom-fontSize","palette-typography-fontSize-sm","=0.875rem"],["scroll-to-bottom-icon-size","components-scrollToBottom-iconSize","=14px"],["event-badge-flow-bg","components-eventStream-badge-flow-background","=#dcfce7"],["event-badge-flow-fg","components-eventStream-badge-flow-foreground","=#15803d"],["event-badge-step-bg","components-eventStream-badge-step-background","=#f5f5f5"],["event-badge-step-fg","components-eventStream-badge-step-foreground","=#0a0a0a"],["event-badge-reasoning-bg","components-eventStream-badge-reasoning-background","=#fef9c3"],["event-badge-reasoning-fg","components-eventStream-badge-reasoning-foreground","=#a16207"],["event-badge-tool-bg","components-eventStream-badge-tool-background","=#f3e8ff"],["event-badge-tool-fg","components-eventStream-badge-tool-foreground","=#6b21a8"],["event-badge-agent-bg","components-eventStream-badge-agent-background","=#ccfbf1"],["event-badge-agent-fg","components-eventStream-badge-agent-foreground","=#115e59"],["event-badge-error-bg","components-eventStream-badge-error-background","=#fee2e2"],["event-badge-error-fg","components-eventStream-badge-error-foreground","=#b91c1c"],["event-badge-default-bg","components-eventStream-badge-default-background","=#f3f4f6"],["event-badge-default-fg","components-eventStream-badge-default-foreground","=#4b5563"],["tool-bubble-shadow","components-toolBubble-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["reasoning-bubble-shadow","components-reasoningBubble-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["composer-shadow","components-composer-shadow","=none"]]),Cn(n,[["composer-padding","components-composer-padding","=0.75rem 1rem"],["composer-gap","components-composer-gap","=0.5rem"],["composer-font-size","components-composer-fontSize","=0.875rem"],["composer-line-height","components-composer-lineHeight","=1.25rem"],["composer-control-size","components-composer-controlSize","=40px"],["composer-control-icon-size","components-composer-controlIconSize","=24px"],["motion-duration-fast","components-motion-durationFast","=120ms"],["motion-duration-base","components-motion-durationBase","=200ms"],["motion-easing","components-motion-easing","=cubic-bezier(0.2, 0, 0, 1)"],["composer-border-color","components-composer-borderColor","border","=#e5e7eb"],["composer-overlay-band","components-composer-overlayBand","=transparent"],["scrollbar-thumb","components-scrollbar-thumb","border","=#e5e7eb"],["scrollbar-track","components-scrollbar-track","=transparent"],["md-inline-code-bg","components-markdown-inlineCode-background","container"],["md-inline-code-color","components-markdown-inlineCode-foreground","text"],["md-link-color","components-markdown-link-foreground","accent","=#0f0f0f"]]);let A=n["--persona-components-markdown-heading-h1-fontSize"];A&&(n["--persona-md-h1-size"]=A);let L=n["--persona-components-markdown-heading-h1-fontWeight"];L&&(n["--persona-md-h1-weight"]=L);let I=n["--persona-components-markdown-heading-h2-fontSize"];I&&(n["--persona-md-h2-size"]=I);let H=n["--persona-components-markdown-heading-h2-fontWeight"];H&&(n["--persona-md-h2-weight"]=H);let _=n["--persona-components-markdown-prose-fontFamily"];_&&_!=="inherit"&&(n["--persona-md-prose-font-family"]=_),Cn(n,[["md-code-block-bg","components-markdown-codeBlock-background","container"],["md-code-block-border-color","components-markdown-codeBlock-borderColor","border"],["md-code-block-text-color","components-markdown-codeBlock-textColor","=inherit"]]),Cn(n,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),Cn(n,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),Cn(n,[["md-hr-color","components-markdown-hr-color","divider"]]),Cn(n,[["md-blockquote-border-color","components-markdown-blockquote-borderColor","palette-colors-gray-900"],["md-blockquote-bg","components-markdown-blockquote-background","=transparent"],["md-blockquote-text-color","components-markdown-blockquote-textColor","palette-colors-gray-500"]]);let V=[["container","surface"],["surface","surface"],["border","border"]];for(let[$,Be]of V){let ye=n[`--persona-components-collapsibleWidget-${$}`]??n[`--persona-${Be}`];ye!==void 0&&(n[`--persona-cw-${$}`]=ye,n[`--cw-${$}`]=ye)}Cn(n,[["message-border","components-message-border","border"]]),Cn(n,[["message-user-padding","components-message-user-padding"],["message-user-max-width","components-message-user-maxWidth"],["message-user-font-size","components-message-user-fontSize"],["message-user-font-family","components-message-user-fontFamily"],["message-user-line-height","components-message-user-lineHeight"],["message-assistant-padding","components-message-assistant-padding"],["message-assistant-border-width","components-message-assistant-borderWidth"],["message-assistant-max-width","components-message-assistant-maxWidth"],["message-assistant-font-size","components-message-assistant-fontSize"],["message-assistant-font-family","components-message-assistant-fontFamily"],["message-assistant-line-height","components-message-assistant-lineHeight"]]);let oe=e.components,W=oe?.iconButton;W&&(W.background&&(n["--persona-icon-btn-bg"]=W.background),W.border&&(n["--persona-icon-btn-border"]=W.border),W.color&&(n["--persona-icon-btn-color"]=W.color),W.padding&&(n["--persona-icon-btn-padding"]=W.padding),W.borderRadius&&(n["--persona-icon-btn-radius"]=W.borderRadius),W.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=W.hoverBackground),W.hoverColor&&(n["--persona-icon-btn-hover-color"]=W.hoverColor),W.activeBackground&&(n["--persona-icon-btn-active-bg"]=W.activeBackground),W.activeBorder&&(n["--persona-icon-btn-active-border"]=W.activeBorder));let j=oe?.labelButton;j&&(j.background&&(n["--persona-label-btn-bg"]=j.background),j.border&&(n["--persona-label-btn-border"]=j.border),j.color&&(n["--persona-label-btn-color"]=j.color),j.padding&&(n["--persona-label-btn-padding"]=j.padding),j.borderRadius&&(n["--persona-label-btn-radius"]=j.borderRadius),j.hoverBackground&&(n["--persona-label-btn-hover-bg"]=j.hoverBackground),j.fontSize&&(n["--persona-label-btn-font-size"]=j.fontSize),j.gap&&(n["--persona-label-btn-gap"]=j.gap));let X=oe?.toggleGroup;X&&(X.gap&&(n["--persona-toggle-group-gap"]=X.gap),X.borderRadius&&(n["--persona-toggle-group-radius"]=X.borderRadius));let E=oe?.artifact;if(E?.toolbar){let $=E.toolbar;$.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=$.iconHoverColor),$.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=$.iconHoverBackground),$.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=$.iconPadding),$.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=$.iconBorderRadius),$.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=$.iconBorder),$.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=wm($.toggleGroupGap)),$.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=$.toggleBorderRadius),$.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=wm($.toggleGroupPadding)),$.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=$.toggleGroupBorder),$.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=$.toggleGroupBorderRadius),$.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=wn(e,$.toggleGroupBackground)??$.toggleGroupBackground),$.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=$.copyBackground),$.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=$.copyBorder),$.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=$.copyColor),$.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=wm($.copyBorderRadius)),$.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=$.copyPadding),$.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=$.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??$.copyMenuBackground),$.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=$.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??$.copyMenuBorder),$.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=$.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??$.copyMenuShadow),$.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=$.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??$.copyMenuBorderRadius),$.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=$.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??$.copyMenuItemHoverBackground),$.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=$.iconBackground),$.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=$.toolbarBorder)}if(E?.tab){let $=E.tab;$.background&&(n["--persona-artifact-tab-bg"]=$.background),$.activeBackground&&(n["--persona-artifact-tab-active-bg"]=$.activeBackground),$.activeBorder&&(n["--persona-artifact-tab-active-border"]=$.activeBorder),$.borderRadius&&(n["--persona-artifact-tab-radius"]=$.borderRadius),$.textColor&&(n["--persona-artifact-tab-color"]=$.textColor),$.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=$.hoverBackground),$.listBackground&&(n["--persona-artifact-tab-list-bg"]=$.listBackground),$.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=$.listBorderColor),$.listPadding&&(n["--persona-artifact-tab-list-padding"]=$.listPadding)}if(E?.pane){let $=E.pane;if($.toolbarBackground){let Be=wn(e,$.toolbarBackground)??$.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Be}}if(E?.card){let $=E.card;$.background&&(n["--persona-artifact-card-bg"]=$.background),$.border&&(n["--persona-artifact-card-border"]=$.border),$.borderRadius&&(n["--persona-artifact-card-radius"]=$.borderRadius),$.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=$.hoverBackground),$.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=$.hoverBorderColor)}if(E?.inline){let $=E.inline;$.background&&(n["--persona-artifact-inline-bg"]=wn(e,$.background)??$.background),$.border&&(n["--persona-artifact-inline-border"]=$.border),$.borderRadius&&(n["--persona-artifact-inline-radius"]=$.borderRadius),$.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=wn(e,$.chromeBackground)??$.chromeBackground),$.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=wn(e,$.chromeBorder)??$.chromeBorder),$.titleColor&&(n["--persona-artifact-inline-title-color"]=wn(e,$.titleColor)??$.titleColor),$.mutedColor&&(n["--persona-artifact-inline-muted-color"]=wn(e,$.mutedColor)??$.mutedColor),$.frameHeight&&(n["--persona-artifact-inline-frame-height"]=$.frameHeight)}let T=oe?.code;T&&(T.keywordColor&&(n["--persona-code-keyword-color"]=T.keywordColor),T.stringColor&&(n["--persona-code-string-color"]=T.stringColor),T.commentColor&&(n["--persona-code-comment-color"]=T.commentColor),T.numberColor&&(n["--persona-code-number-color"]=T.numberColor),T.tagColor&&(n["--persona-code-tag-color"]=T.tagColor),T.attrColor&&(n["--persona-code-attr-color"]=T.attrColor),T.propertyColor&&(n["--persona-code-property-color"]=T.propertyColor),T.lineNumberColor&&(n["--persona-code-line-number-color"]=T.lineNumberColor),T.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=T.gutterBorderColor),T.background&&(n["--persona-code-bg"]=wn(e,T.background)??T.background));let B=n["--persona-surface"],P=n["--persona-container"],J=n["--persona-palette-colors-gray-100"]??"#f3f4f6",U=n["--persona-palette-colors-gray-200"]??"#e5e7eb",ue=n["--persona-palette-colors-gray-300"]??"#d1d5db",fe=!P||P===B,me=Zk(B??n["--persona-background"]),He=fe&&me!==void 0&&me<e0,Ee=He?"rgba(255, 255, 255, 0.08)":J,Ie=He?"rgba(255, 255, 255, 0.12)":U,yt=He?"rgba(255, 255, 255, 0.16)":ue,qe=fe?Ee:P,Oe=fe?Ie:P;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??qe,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??Oe,fe&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??yt),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??qe,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??qe,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??qe,n}var kS={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar","artifact-inline":"Inline artifact block","artifact-inline-chrome":"Inline artifact title bar"};Vd();var t0=e=>!!e&&"launcher"in e&&(e.launcher?.sidebarMode===!0||e.launcher?.mountMode==="docked"),LS=(e,t)=>{if(!t||!t0(t))return e;let n=t.theme?.components?.panel?.width,o=t.darkTheme?.components?.panel?.width;return(xi(t)==="dark"?o??n:n)!=null?e:{...e,components:{...e.components,panel:{...e.components.panel,width:Ms(t)==="v5"?"400px":"420px"}}}},n0={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},Yl={components:{button:{ghost:{hoverBackground:"rgba(255, 255, 255, 0.08)"}},markdown:{link:{foreground:"palette.colors.primary.300"}},eventStream:{badge:{flow:{background:"palette.colors.success.900",foreground:"palette.colors.success.300"},step:{background:"palette.colors.primary.800",foreground:"palette.colors.primary.200"},reasoning:{background:"palette.colors.warning.900",foreground:"palette.colors.warning.300"},tool:{background:"palette.colors.purple.900",foreground:"palette.colors.purple.300"},agent:{background:"palette.colors.teal.900",foreground:"palette.colors.teal.300"},error:{background:"palette.colors.error.900",foreground:"palette.colors.error.300"},default:{background:"palette.colors.gray.800",foreground:"palette.colors.gray.300"}}},history:{dangerForeground:"#f87171",confirm:{dangerBackground:"palette.colors.error.600",scrim:"rgba(0, 0, 0, 0.6)"}}}},xm=n0,o0={...xm,colors:{...xm.colors,primary:{50:"#0f0f10",100:"#27272a",200:"#3f3f46",300:"#52525b",400:"#71717a",500:"#f4f4f5",600:"#e4e4e7",700:"#d4d4d8",800:"#a1a1aa",900:"#fafafa",950:"#ffffff"},gray:{50:"#1a1a1b",100:"#27272a",200:"#2a2a2d",300:"#52525b",400:"#71717a",500:"#a1a1aa",600:"#b4b4bd",700:"#d4d4d8",800:"#e4e4e7",900:"#f4f4f5",950:"#fafafa"}}},r0=Yl,s0={semantic:{colors:{primary:"palette.colors.primary.500",accent:"palette.colors.primary.600",background:"#0f0f10",surface:"palette.colors.gray.50",container:"#1c1c20",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"#0f0f10",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600"}}},components:{...Yl.components,button:{...Yl.components?.button,primary:{background:"semantic.colors.primary",foreground:"palette.colors.primary.50"}},markdown:{inlineCode:{background:"palette.colors.gray.100",foreground:"semantic.colors.text"},link:{foreground:"semantic.colors.accent"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"semantic.colors.text"},table:{headerBackground:"palette.colors.gray.100",borderColor:"semantic.colors.border"},blockquote:{background:"semantic.colors.container",borderColor:"palette.colors.gray.300",textColor:"semantic.colors.textMuted"}},eventStream:{...Yl.components?.eventStream,badge:{...Yl.components?.eventStream?.badge,step:{background:"palette.colors.gray.100",foreground:"palette.colors.gray.700"},default:{background:"palette.colors.gray.100",foreground:"palette.colors.gray.700"}}}}},i0=e=>Ms({future:e})==="v5"?{palette:o0,components:s0}:{palette:xm,components:r0},HS=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Xl=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",a0=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":Xl()},xi=e=>a0(e),l0=(e,t={})=>Gl(e,t),c0=(e,t={})=>{let n=i0(t.future),o=_o(n.components,e??{})??{};return Gl({...o,palette:{...o.palette,colors:Ms(t)==="v5"?_o(n.palette.colors,o.palette?.colors):{...n.palette.colors,...o.palette?.colors}}},{validate:!1,future:t.future})},No=e=>{let t=xi(e),n=HS(e?.theme),o=_p(e)==="circle"?Dp:{...Up.launcher,...e?.future?.v5Defaults?{offset:"1.5rem"}:{}},r=_o({components:{launcher:o}},n),s=HS(e?.darkTheme);return LS(t==="dark"?c0(_o(r??{},s??{}),{future:e?.future}):l0(r,{future:e?.future}),e)},d0=e=>jp(e),Mi=(e,t)=>{let n=No(t),o=d0(n);for(let[r,s]of Object.entries(o))e.style.setProperty(r,s);e.setAttribute("data-persona-color-scheme",xi(t)),e.setAttribute("data-persona-defaults",Ms(t))},Oa=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e(Xl())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window<"u"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>e(Xl());n.addEventListener?(n.addEventListener("change",o),t.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),t.push(()=>n.removeListener(o)))}return()=>{t.forEach(n=>n())}};Vd();var Kr=require("lucide");kt();Lr();Je();var Hs=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");var qp="24px",Mm=(e,t)=>t||e?.composer?.placement!=="overlay"?"block":"overlay",Ql=e=>{if(typeof e!="string")return null;let t=/^\s*(\d+(?:\.\d+)?)\s*%\s*$/.exec(e);if(!t)return null;let n=Number(t[1])/100;return n>0&&n<1?n:null},IS=e=>Math.max(0,Math.round(e.columnHeight*(1-e.fraction))-e.footerHeight);xa();Fd();mp();var RS=require("idiomorph"),zp=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;RS.Idiomorph.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,s){if(r instanceof HTMLElement&&o){if(r.classList.contains("persona-animate-typing")||r.hasAttribute("data-preserve-runtime"))return!1;if(r.hasAttribute("data-tool-elapsed"))return s instanceof HTMLElement&&s.getAttribute("data-tool-elapsed")===r.getAttribute("data-tool-elapsed")?!1:void 0;if(r.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let i=r.textContent??"",l=s.textContent??"";if(i!==l)return}return!1}}}}})};var WS=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var Em={index:-1,draft:""};function OS(e){let{direction:t,history:n,currentValue:o,atStart:r,state:s}=e,i=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="up"){if(!i&&!r)return{handled:!1,state:s};if(!i){let l=n.length-1;return{handled:!0,value:n[l],state:{index:l,draft:o}}}if(s.index>0){let l=s.index-1;return{handled:!0,value:n[l],state:{index:l,draft:s.draft}}}return{handled:!0,state:s}}if(!i)return{handled:!1,state:s};if(s.index<n.length-1){let l=s.index+1;return{handled:!0,value:n[l],state:{index:l,draft:s.draft}}}return{handled:!0,value:s.draft,state:{index:-1,draft:s.draft}}}function BS(e,t){return[e.id,e.role,e.content?.length??0,e.content?.slice(-32)??"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",e.variant??"",e.rawContent?.length??0,e.llmContent?.length??0,e.approval?.status??"",e.toolCall?.status??"",e.toolCall?.name??"",e.toolCall?.chunks?.length??0,e.toolCall?.chunks?.[e.toolCall.chunks.length-1]?.slice(-32)??"",typeof e.toolCall?.args=="string"?e.toolCall.args.length:e.toolCall?.args?JSON.stringify(e.toolCall.args).length:0,e.reasoning?.chunks?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.slice(-32)??"",e.contentParts?.length??0,e.stopReason??"",t].join("\0")}function _S(){return new Map}function DS(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function NS(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function FS(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function $S(e){return e.role!=="assistant"||e.variant==="tool"||e.variant==="reasoning"?!1:e.variant==="approval"?!0:!!(e.content?.trim()||e.rawContent?.trim()||e.contentParts?.length)}function US(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function ir(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Ei(e,t){return ir(e)-e.scrollTop<=t}function VS(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:i=!1,pauseOnUpwardScroll:l=!1,pauseWhenAwayFromBottom:c=!0,resumeRequiresDownwardScroll:p=!1}=e,d=n-o;return i||Math.abs(d)<s?{action:"none",delta:d,nextLastScrollTop:n}:!t&&r&&(!p||d>0)?{action:"resume",delta:d,nextLastScrollTop:n}:t&&l&&d<0?{action:"pause",delta:d,nextLastScrollTop:n}:t&&c&&!r?{action:"pause",delta:d,nextLastScrollTop:n}:{action:"none",delta:d,nextLastScrollTop:n}}function jS(e){let{following:t,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:r=!1}=e;return t&&n<0?"pause":!t&&r&&n>0&&o?"resume":"none"}function qS(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function Tm(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),n=Math.max(0,t+e.viewportHeight-e.contentHeight+(e.slack??0));return{targetScrollTop:t,spacerHeight:n}}function zS(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}Bo();var Jl={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},p0=["pre","code","a","script","style"],Kp=e=>({type:e?.type??Jl.type,placeholder:e?.placeholder??Jl.placeholder,speed:e?.speed??Jl.speed,duration:e?.duration??Jl.duration,buffer:e?.buffer??Jl.buffer}),GS=[{name:"typewriter",containerClass:"persona-stream-typewriter",wrap:"char",useCaret:!0},{name:"pop-bubble",bubbleClass:"persona-stream-pop",wrap:"none"},{name:"letter-rise",containerClass:"persona-stream-letter-rise",wrap:"char"},{name:"word-fade",containerClass:"persona-stream-word-fade",wrap:"word"}],Zl=new Map;for(let e of GS)Zl.set(e.name,e);var YS=["wipe","glyph-cycle"],ec=e=>{Zl.set(e.name,e)},XS=e=>{GS.some(t=>t.name===e)||Zl.delete(e)},QS=()=>Array.from(Zl.keys()),tc=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:Zl.get(e)??null,Gp=(e,t,n,o,r)=>{if(!r)return e;if(n?.bufferContent)return n.bufferContent(e,o);if(!e)return e;if(t==="word"){let s=e.search(/\s(?=\S*$)/);return s<0?"":e.slice(0,s)}if(t==="line"){let s=e.lastIndexOf(`
|
|
30
30
|
`);return s<0?"":e.slice(0,s)}return e},u0=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-char",r.id=`stream-c-${n}-${o}`,r.style.setProperty("--char-index",String(o)),r.textContent=t,r},g0=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${n}-${o}`,r.style.setProperty("--word-index",String(o)),r.textContent=t,r},Pm=/\s/,f0=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let o=n;if(t.has(o.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},m0=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let i=o.createDocumentFragment(),l=0;for(;l<s.length;)if(Pm.test(s[l])){let c=l;for(;c<s.length&&Pm.test(s[c]);)c+=1;i.appendChild(o.createTextNode(s.slice(l,c))),l=c}else{let c=o.createElement("span");c.className="persona-stream-word-group";let p=l;for(;p<s.length&&!Pm.test(s[p]);)c.appendChild(u0(o,s[p],t,n.value)),n.value+=1,p+=1;i.appendChild(c),l=p}r.replaceChild(i,e)},h0=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let i=o.createDocumentFragment(),l=s.split(/(\s+)/);for(let c of l)c&&(/^\s+$/.test(c)?i.appendChild(o.createTextNode(c)):(i.appendChild(g0(o,c,t,n.value)),n.value+=1));r.replaceChild(i,e)},nc=(e,t,n,o)=>{if(!e||typeof document>"u")return e;let r=document.createElement("div");r.innerHTML=e;let s=new Set((o?.skipTags??p0).map(g=>g.toLowerCase())),i=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],c=i.nextNode();for(;c;)f0(c,s)||l.push(c),c=i.nextNode();let p={value:o?.startIndex??0},d=t==="char"?m0:h0;for(let g of l)d(g,n,p);return r.innerHTML},Yp=(e=document)=>{let t=e.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},oc=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let n=e.createElement("div");return n.className="persona-stream-skeleton-line",t.appendChild(n),t},KS=new WeakMap,y0=(e,t)=>{if(!e.styles)return;let n=KS.get(t);if(n||(n=new Set,KS.set(t,n)),n.has(e.name)){let s=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${s}"]`))return;n.delete(e.name)}n.add(e.name);let r=(t instanceof ShadowRoot?t.ownerDocument:t.ownerDocument??document).createElement("style");r.setAttribute("data-persona-animation",e.name),r.textContent=e.styles,t.appendChild(r)},km=new WeakMap,b0=(e,t)=>{if(!e.onAttach)return;let n=km.get(t);if(n||(n=new Map,km.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},JS=e=>{let t=km.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},rc=(e,t)=>{y0(e,t),b0(e,t)};dn();var{setLoader:B_,load:v0}=lt({fallbackImport:()=>import("@runtypelabs/persona/animations-extra")});var ZS=v0;Bo();function Lm(e,t=kn){let n=e.style.position,o=e.style.zIndex,r=e.style.isolation,s=getComputedStyle(e),i=s.position==="static"||s.position==="";return i&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{i&&(e.style.position=n),e.style.zIndex=o,e.style.isolation=r}}var sc=0,Is=null;function Hm(e=document){if(sc++,sc===1){let n=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;Is={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:r},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${r}px`,n.style.width="100%"}let t=!1;return()=>{if(!t&&(t=!0,sc=Math.max(0,sc-1),sc===0&&Is)){let n=e.body,o=e.defaultView??window;n.style.overflow=Is.originalOverflow,n.style.position=Is.originalPosition,n.style.top=Is.originalTop,n.style.width=Is.originalWidth,o.scrollTo(0,Is.scrollY),Is=null}}}Ma();var ic={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Lt=e=>(e?.launcher?.mountMode??"floating")==="docked",Rs=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",Jn=e=>{let t=e?.launcher?.dock,n=Br(e).dockWidth?t?.width:wn(No(e),"components.panel.width");return{side:t?.side??ic.side,width:n??ic.width,animate:t?.animate??ic.animate,reveal:t?.reveal??ic.reveal,maxHeight:t?.maxHeight??ic.maxHeight}};Je();Je();var tA=require("lucide");kt();Lr();var Im=e=>e==="followUp"?"follow-up":e,Rm=(e,t=0)=>{if(typeof e=="string"){let r=e.trim();return r?{id:r,label:r,prompt:r,emphasis:"default"}:null}let n=e.label.trim();if(!n)return null;let o=e.prompt?.trim()||n;return{id:e.id?.trim()||o||`suggestion-${t}`,label:n,prompt:o,description:e.description?.trim()||void 0,icon:e.icon,iconColor:e.iconColor?.trim()||void 0,behavior:e.behavior,emphasis:e.emphasis??"default"}},eA=new WeakSet,C0=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,w0=e=>{C0()||e.forEach((t,n)=>{typeof t.animate=="function"&&t.animate([{opacity:"0",transform:"translateY(4px)"},{opacity:"1",transform:"none"}],{duration:250,delay:n*60,easing:"ease-out",fill:"backwards"})})},Wm=e=>{let{item:t,index:n,surface:o,source:r,variant:s,streaming:i,config:l,plugins:c,chipsConfig:p,session:d,getTextarea:g,eventTarget:f,submitPrompt:h}=e,y=o==="followUp",v=t.behavior,C=()=>{if(d.isStreaming())return;let I={suggestion:{...t},surface:o,source:r,behavior:v},H=f.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:I,bubbles:!0,composed:!0,cancelable:!0}));if(y&&f.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:t.prompt},bubbles:!0,composed:!0})),!H)return;for(let V of c)if(V.onSuggestionSelect?.({suggestion:{...t},surface:o,source:r,variant:s,config:l})===!1)return;let _=g();if(v==="fill"){_.value=t.prompt,_.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),_.focus();return}if(h){h(t.prompt);return}_.value="",d.sendMessage(t.prompt)},A=()=>{let I=x("button",`persona-suggestion persona-suggestion--${s}`);if(I.type="button",I.disabled=i,I.dataset.suggestionId=t.id,I.dataset.emphasis=t.emphasis,I.dataset.behavior=v,s==="chip"&&(p?.fontWeight&&(I.style.fontWeight=p.fontWeight),p?.paddingX&&(I.style.paddingLeft=p.paddingX,I.style.paddingRight=p.paddingX),p?.paddingY&&(I.style.paddingTop=p.paddingY,I.style.paddingBottom=p.paddingY)),t.icon){let _=ge(t.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);_&&(_.classList.add("persona-suggestion__icon"),t.iconColor&&(_.style.color=t.iconColor),I.appendChild(_))}let H=x("span","persona-suggestion__copy");if(H.appendChild(Q("span",{className:"persona-suggestion__label",text:t.label})),t.description&&s!=="chip"&&H.appendChild(Q("span",{className:"persona-suggestion__description",text:t.description})),I.appendChild(H),s!=="chip"){let _=Nt(tA.ArrowRight,16,"currentColor",1.8);_&&(_.classList.add("persona-suggestion__arrow"),I.appendChild(_))}return I.addEventListener("click",C),I},L=null;for(let I of c)if(I.renderSuggestion&&(L=I.renderSuggestion({suggestion:{...t},index:n,surface:o,source:r,variant:s,streaming:i,config:l,defaultRenderer:A,select:C}),L))break;return L??=A(),L.dataset.suggestionId||=t.id,L.dataset.behavior||=v,L.dataset.emphasis||=t.emphasis,L instanceof HTMLButtonElement||L.setAttribute("aria-disabled",i?"true":"false"),L},ac=e=>{let t=[],n=[],o=null,r=null,s=()=>{e.removeAttribute("data-scroll-left"),e.removeAttribute("data-scroll-right")},i=()=>{if(r=null,e.hidden||e.dataset.variant!=="chip"||e.dataset.overflow!=="scroll"){s();return}let d=Math.max(0,e.scrollWidth-e.clientWidth);if(d<=1){s();return}let g=getComputedStyle(e).direction==="rtl",f=Math.min(d,Math.max(0,Math.abs(e.scrollLeft))),h=4,y=f<=h,v=f>=d-h,C=g?!v:!y,A=g?!y:!v;e.toggleAttribute("data-scroll-left",C),e.toggleAttribute("data-scroll-right",A)},l=()=>{if(r!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&i();return}r=requestAnimationFrame(i)};e.addEventListener("scroll",l,{passive:!0});let c=typeof ResizeObserver=="function"?new ResizeObserver(l):null;return c?.observe(e),{buttons:t,elements:n,destroy:()=>{e.removeEventListener("scroll",l),c?.disconnect(),r!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(r),r=null},render:(d,g,f,h,y,v)=>{e.replaceChildren(),t.length=0,n.length=0;let C=v?.source??"config",A=v?.surface??(C==="config"?"starter":"followUp"),L=A==="followUp",I=v?.variant??"chip",H=v?.behavior??"send",_=v?.overflow??"wrap",V=v?.config??{},oe=v?.plugins??[],W=typeof v?.maxItems=="number"?Math.max(0,Math.floor(v.maxItems)):void 0,j=L?"followUps":"starters";!eA.has(V)&&V.debug===!0&&I!=="chip"&&V.suggestions?.[j]?.overflow!==void 0&&(eA.add(V),console.info(`[persona] suggestions.${j}.overflow applies to the "chip" variant only; the "${I}" variant manages its own stacking.`));let X=U=>U.map(Rm).filter(ue=>ue!==null).map(ue=>({...ue,behavior:ue.behavior??H})),E=X(d??[]);oe.forEach(U=>{U.transformSuggestions&&(E=X(U.transformSuggestions({suggestions:E.map(ue=>({...ue})),surface:A,source:C,config:V})))});let T=W===void 0?E:E.slice(0,W);if(!T.length){e.hidden=!0,o=null,s();return}if(!L&&(h??g.getMessages()).some(ue=>ue.role==="user")){e.hidden=!0,o=null;return}e.hidden=!1,e.classList.add("persona-suggestions"),e.dataset.personaSuggestionSurface=Im(A),e.dataset.variant=I,e.dataset.overflow=_;let B=document.createDocumentFragment(),P=g.isStreaming();T.forEach((U,ue)=>{let fe=Wm({item:U,index:ue,surface:A,source:C,variant:I,streaming:P,config:V,plugins:oe,chipsConfig:y,session:g,getTextarea:()=>f,eventTarget:e,submitPrompt:v?.submitPrompt});B.appendChild(fe),n.push(fe),[...fe instanceof HTMLButtonElement?[fe]:[],...Array.from(fe.querySelectorAll("button"))].forEach(He=>{t.includes(He)||(He.disabled=P,t.push(He))})}),e.appendChild(B),i(),l();let J=JSON.stringify({normalized:T,surface:A,variant:I,source:C});J!==o&&(o=J,w0(n),e.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:T.map(U=>({...U})),surface:A,source:C,variant:I},bubbles:!0,composed:!0})),L&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:T.map(U=>U.prompt)},bubbles:!0,composed:!0})))}}};var io={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};Bo();Je();kt();wo();Je();kt();xa();var S0="persona-header-control",A0="persona-header-control--glyph",x0="persona-header-control--sparse",M0=20,E0={x:[1.4,1.05]},nA="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",T0="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Xp=(e,t,n={})=>{let{iconSize:o,iconText:r}=n,[s,i]=E0[t]??[1,1.5],l=!o;e.classList.toggle(A0,l),e.classList.toggle(x0,l&&s!==1);let c=parseFloat(o??"")||M0,p=ge(t,`${Math.round(c*s)}px`,"currentColor",i);p?(p.style.display="block",l||(p.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((i/1.5).toFixed(4))})`),e.replaceChildren(p)):r&&(e.textContent=r)},Ba=e=>{let{ariaLabel:t,tooltip:n=!0,tooltipHint:o,iconName:r,iconText:s,wrapperClassName:i=nA,size:l,iconSize:c,color:p,backgroundColor:d,borderWidth:g,borderColor:f,borderRadius:h,paddingX:y,paddingY:v,hidden:C,extraClassName:A,attrs:L}=e,I=x("div",i),H=!!(g||f),_=Q("button",{className:_n(S0,"persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!d&&"persona-bg-transparent hover:persona-bg-gray-100",!H&&"persona-border-none",!h&&"persona-rounded-full",A),attrs:{type:"button","aria-label":t,...L},style:{width:l,height:l,minWidth:l,minHeight:l,display:C?"none":void 0,color:p||Nn.actionIconColor,backgroundColor:d,border:H?`${g||"0px"} solid ${f||"transparent"}`:void 0,borderRadius:h,paddingLeft:y,paddingRight:y,paddingTop:v,paddingBottom:v}});return r?Xp(_,r,{iconSize:c,iconText:s}):s&&(_.textContent=s),I.appendChild(_),vn({anchor:_,trigger:I,text:()=>_.getAttribute("aria-label")??t,hint:o,enabled:n}),{button:_,wrapper:I}},_a=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=nA,buttonSize:r,iconSize:s}=t,i=e?.launcher??{},l=i.closeButtonTooltipText??"Close chat",c=i.closeButtonShowTooltip??!0,{button:p,wrapper:d}=Ba({ariaLabel:l,tooltip:c,iconName:i.closeButtonIconName??"x",iconText:i.closeButtonIconText??"\xD7",wrapperClassName:o,size:r??i.closeButtonSize,iconSize:s,color:i.closeButtonColor,backgroundColor:i.closeButtonBackgroundColor,borderWidth:i.closeButtonBorderWidth,borderColor:i.closeButtonBorderColor,borderRadius:i.closeButtonBorderRadius,paddingX:i.closeButtonPaddingX,paddingY:i.closeButtonPaddingY,hidden:!n});return{button:p,wrapper:d}},Da=(e,t={})=>{let{wrapperClassName:n=T0,buttonSize:o,iconSize:r}=t,i=(e?.launcher??{}).clearChat??{},l=i.tooltipText??"Clear chat",c=i.showTooltip??!0,{button:p,wrapper:d}=Ba({ariaLabel:l,tooltip:c,iconName:i.iconName??"refresh-cw",wrapperClassName:n,size:o??i.size,iconSize:r,color:i.iconColor,backgroundColor:i.backgroundColor,borderWidth:i.borderWidth,borderColor:i.borderColor,borderRadius:i.borderRadius,paddingX:i.paddingX,paddingY:i.paddingY});return{button:p,wrapper:d}};var Nn={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-control-state-fg, var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af)))",minHeight:"var(--persona-header-min-height, auto)"},Om={fontFamily:"var(--persona-components-header-title-fontFamily, inherit)",fontSize:"var(--persona-components-header-title-fontSize, 1rem)",fontWeight:"var(--persona-components-header-title-fontWeight, 600)",lineHeight:"var(--persona-components-header-title-lineHeight, 1.5rem)",letterSpacing:"var(--persona-components-header-title-letterSpacing, normal)"},P0={fontFamily:"var(--persona-components-header-subtitle-fontFamily, inherit)",fontSize:"var(--persona-components-header-subtitle-fontSize, 0.75rem)",fontWeight:"var(--persona-components-header-subtitle-fontWeight, inherit)",lineHeight:"var(--persona-components-header-subtitle-lineHeight, 1rem)",letterSpacing:"var(--persona-components-header-subtitle-letterSpacing, normal)"},jr=e=>{let{config:t,showClose:n=!0}=e,o=Q("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3",attrs:{"data-persona-theme-zone":"header"},style:{padding:"var(--persona-components-header-padding, 20px 24px)",minHeight:Nn.minHeight,backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),r=t?.launcher??{},s=r.headerIconSize??Bl,i=r.closeButtonPlacement??"inline",l=r.headerIconHidden??!1,c=r.headerIconName,p=Q("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:s,width:s,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!l)if(c){let _=parseFloat(s)||24,V=ge(c,_*.6,"currentColor",1);V?(V.style.width=`calc(${_}px * var(--persona-components-header-iconScale, 0.6))`,V.style.height=`calc(${_}px * var(--persona-components-header-iconScale, 0.6))`,p.replaceChildren(V)):p.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let _=x("img");_.src=t.launcher.iconUrl,_.alt="",_.className="persona-rounded-xl persona-object-cover",_.style.height=s,_.style.width=s,p.replaceChildren(_)}else p.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let d=x("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),g=Q("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:Nn.titleColor,...Om}}),f=Q("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Nn.subtitleColor,...P0}});d.append(g,f),l?o.append(d):o.append(p,d);let h=r.clearChat??{},y=h.enabled??!0,v=h.placement??"inline",C=null,A=null;if(y){let V=Da(t,{wrapperClassName:v==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});C=V.button,A=V.wrapper,v==="top-right"&&(A.style.right="48px"),v==="inline"&&o.appendChild(A)}let L=i==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":y&&v==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:I,wrapper:H}=_a(t,{showClose:n,wrapperClassName:L});return i!=="top-right"&&o.appendChild(H),{header:o,iconHolder:p,headerTitle:g,headerSubtitle:f,closeButton:I,closeButtonWrapper:H,clearChatButton:C,clearChatButtonWrapper:A}},Ti=(e,t,n)=>{let o=n?.launcher??{},r=o.closeButtonPlacement??"inline",s=o.clearChat?.placement??"inline";e.appendChild(t.header),r==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};Je();Je();kt();Bo();function Pi(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:s,onOpenChange:i}=e,l=x("div","persona-dropdown-menu persona-hidden");l.setAttribute("role","menu"),l.setAttribute("data-persona-theme-zone","dropdown"),s?(l.style.position="fixed",l.style.zIndex=String(wa)):(l.style.position="absolute",l.style.top="100%",l.style.marginTop="4px",r==="bottom-right"?l.style.right="0":l.style.left="0");for(let y of t){if(y.dividerBefore){let A=document.createElement("hr");l.appendChild(A)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",y.id),y.destructive&&v.setAttribute("data-destructive",""),y.icon){let A=ge(y.icon,16,"currentColor",1.5);A&&v.appendChild(A)}let C=document.createElement("span");C.textContent=y.label,v.appendChild(C),v.addEventListener("click",A=>{A.stopPropagation(),g(),n(y.id)}),l.appendChild(v)}let c=null;function p(){if(!s)return;let y=o.getBoundingClientRect();l.style.top=`${y.bottom+4}px`,r==="bottom-right"?(l.style.right=`${window.innerWidth-y.right}px`,l.style.left="auto"):(l.style.left=`${y.left}px`,l.style.right="auto")}function d(){let y=l.classList.contains("persona-hidden");p(),l.classList.remove("persona-hidden"),y&&i?.(!0),requestAnimationFrame(()=>{let v=C=>{!l.contains(C.target)&&!o.contains(C.target)&&g()};document.addEventListener("click",v,!0),c=()=>document.removeEventListener("click",v,!0)})}function g(){let y=!l.classList.contains("persona-hidden");l.classList.add("persona-hidden"),c?.(),c=null,y&&i?.(!1)}function f(){l.classList.contains("persona-hidden")?d():g()}function h(){g(),l.remove()}return s&&s.appendChild(l),{element:l,show:d,hide:g,toggle:f,destroy:h}}Je();kt();function Zn(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,chromeless:i,onClick:l,aria:c}=e,p=x("button",_n(!i&&"persona-icon-btn",s));p.type="button",p.setAttribute("aria-label",n),p.title=n;let d=ge(t,o??16,"currentColor",r??2);if(d&&p.appendChild(d),l&&p.addEventListener("click",l),c)for(let[g,f]of Object.entries(c))p.setAttribute(g,f);return p}function Bm(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:s,className:i,onClick:l,aria:c}=e,p="persona-label-btn";o!=="default"&&(p+=" persona-label-btn--"+o),p+=" persona-label-btn--"+r,i&&(p+=" "+i);let d=x("button",p);if(d.type="button",d.setAttribute("aria-label",n),t){let f=ge(t,s??14,"currentColor",2);f&&d.appendChild(f)}let g=x("span");if(g.textContent=n,d.appendChild(g),l&&d.addEventListener("click",l),c)for(let[f,h]of Object.entries(c))d.setAttribute(f,h);return d}function lc(e){let{items:t,selectedId:n,onSelect:o,className:r}=e,s=x("div","persona-toggle-group"+(r?" "+r:""));s.setAttribute("role","group");let i=n,l=[];function c(){for(let d of l)d.btn.setAttribute("aria-pressed",d.id===i?"true":"false")}for(let d of t){let g;d.icon?g=Zn({icon:d.icon,label:d.label,className:d.className,onClick:()=>{i=d.id,c(),o(d.id)}}):(g=x("button","persona-icon-btn"+(d.className?" "+d.className:"")),g.type="button",g.setAttribute("aria-label",d.label),g.title=d.label,g.textContent=d.label,g.addEventListener("click",()=>{i=d.id,c(),o(d.id)})),g.setAttribute("aria-pressed",d.id===i?"true":"false"),l.push({id:d.id,btn:g}),s.appendChild(g)}function p(d){i=d,c()}return{element:s,setSelected:p}}function oA(e){let{label:t,icon:n,iconSize:o,iconOnly:r,menuItems:s,onSelect:i,onPrimary:l,position:c="bottom-left",portal:p,chevronLabel:d="More options",chevronIconSize:g,className:f,primaryClassName:h,chevronClassName:y}=e,v=x("div","persona-split-btn"+(f?" "+f:"")),C={label:t,className:"persona-split-btn-primary"+(h?" "+h:""),onClick:l},A=r&&n?Zn({...C,icon:n,size:o??14}):Bm({...C,icon:n,iconSize:o??14}),L=Zn({icon:"chevron-down",label:d,size:g??14,className:"persona-split-btn-chevron"+(y?" "+y:""),aria:{"aria-haspopup":"true","aria-expanded":"false"}});v.append(A,L);let I=null,H=()=>{if(I)return I;let _=(typeof p=="function"?p():p)??void 0;return I=Pi({items:s,onSelect:i,anchor:v,position:c,portal:_,onOpenChange:V=>{L.setAttribute("aria-expanded",V?"true":"false")}}),_||v.appendChild(I.element),I};return v.isConnected?H():requestAnimationFrame(()=>{I||H()}),L.addEventListener("click",_=>{_.stopPropagation(),H().toggle()}),{element:v,primaryButton:A,chevronButton:L,openMenu:()=>H().show(),closeMenu:()=>I?.hide(),toggleMenu:()=>H().toggle(),destroy:()=>{I?.destroy(),v.remove()}}}function Qp(e){let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:i,className:l,hover:c}=e,p=x("div","persona-combo-btn"+(l?" "+l:""));p.style.position="relative",p.style.display="inline-flex",p.style.alignItems="center",p.style.cursor="pointer",p.setAttribute("role","button"),p.setAttribute("tabindex","0"),p.setAttribute("aria-haspopup","true"),p.setAttribute("aria-expanded","false"),p.setAttribute("aria-label",t);let d=x("span","persona-combo-btn-label");d.textContent=t,p.appendChild(d);let g=ge(n,14,"currentColor",2);g&&(g.style.marginLeft="4px",g.style.opacity="0.6",p.appendChild(g)),c&&(p.style.borderRadius=c.borderRadius??"10px",p.style.padding=c.padding??"6px 4px 6px 12px",p.style.border="1px solid transparent",p.style.transition="background-color 0.15s ease, border-color 0.15s ease",p.addEventListener("mouseenter",()=>{p.style.backgroundColor=c.background??"",p.style.borderColor=c.border??""}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="",p.style.borderColor="transparent"}));let f=Pi({items:o,onSelect:y=>{p.setAttribute("aria-expanded","false"),r(y)},anchor:p,position:s,portal:i});i||p.appendChild(f.element);let h=()=>p.getAttribute("data-persona-menu-locked")==="true";return p.addEventListener("click",y=>{if(y.stopPropagation(),h())return;let v=!f.element.classList.contains("persona-hidden");p.setAttribute("aria-expanded",v?"false":"true"),f.toggle()}),p.addEventListener("keydown",y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),p.click())}),{element:p,setLabel:y=>{d.textContent=y,p.setAttribute("aria-label",y)},open:()=>{p.setAttribute("aria-expanded","true"),f.show()},close:()=>{p.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let y=!f.element.classList.contains("persona-hidden");p.setAttribute("aria-expanded",y?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),p.remove()}}}mp();var _m=e=>{let t=jr({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=e.layoutHeaderConfig?.onTitleClick;if(n){let o=t.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",r=>{(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),n())}))}return t};function k0(e,t,n){if(t?.length)for(let o of t){let{button:r,wrapper:s}=Ba({ariaLabel:o.ariaLabel??o.label??o.id,iconName:o.icon,iconText:o.icon?void 0:o.label,tooltipHint:o.shortcut?fp(o.shortcut):void 0,wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center"});if(r.setAttribute("data-persona-header-action",o.id),o.shortcut){let i=Nl(o.shortcut);i&&r.setAttribute("aria-keyshortcuts",i)}if(o.menuItems?.length){let i=Pi({items:o.menuItems,onSelect:l=>n?.(l),anchor:s,position:"bottom-right"});s.appendChild(i.element),r.addEventListener("click",l=>{l.stopPropagation(),i.toggle()})}else r.addEventListener("click",()=>n?.(o.id));e.appendChild(s)}}var Dm=e=>{let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=e,i=t?.launcher??{},l=x("div","persona-flex persona-items-center persona-justify-between");l.setAttribute("data-persona-theme-zone","header"),l.style.minHeight=Nn.minHeight,l.style.padding="var(--persona-components-header-minimalPadding, var(--persona-components-header-padding, 16px 24px))",l.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",l.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",l.style.boxShadow="var(--persona-header-shadow, none)",l.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let c=r?.titleMenu,p,d;if(c){let H=Qp({label:i.title??"Chat Assistant",menuItems:c.menuItems,onSelect:_=>{let V=W=>{W===!1&&H.element.dispatchEvent(new CustomEvent("persona:title-menu-builtin",{bubbles:!0,composed:!0,detail:{actionId:_}}))},oe=c.onSelect(_);oe instanceof Promise?oe.then(V,()=>{}):V(oe)},hover:c.hover,className:""});p=H.element,p.style.color=Nn.titleColor,d=p.querySelector(".persona-combo-btn-label")??p}else{if(p=x("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),d=x("span","persona-text-base persona-font-semibold persona-truncate"),d.style.color=Nn.titleColor,Object.assign(d.style,Om),d.textContent=i.title??"Chat Assistant",p.appendChild(d),r?.onTitleClick){p.style.cursor="pointer",p.setAttribute("role","button"),p.setAttribute("tabindex","0");let _=r.onTitleClick;p.addEventListener("click",V=>{V.target.closest("button")||_()}),p.addEventListener("keydown",V=>{(V.key==="Enter"||V.key===" ")&&(V.preventDefault(),_())})}let H=r?.titleRowHover;H&&(p.style.borderRadius=H.borderRadius??"10px",p.style.padding=H.padding??"6px 4px 6px 12px",p.style.margin="-6px 0 -6px -12px",p.style.border="1px solid transparent",p.style.transition="background-color 0.15s ease, border-color 0.15s ease",p.style.width="fit-content",p.style.flex="none",p.addEventListener("mouseenter",()=>{p.style.backgroundColor=H.background??"",p.style.borderColor=H.border??""}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="",p.style.borderColor="transparent"}))}l.appendChild(p);let g="persona-relative persona-inline-flex persona-items-center persona-justify-center",{button:f,wrapper:h}=_a(t,{showClose:n,wrapperClassName:g});o&&f.addEventListener("click",o);let y=x("div","persona-flex persona-items-center persona-gap-1");c||k0(y,r?.trailingActions,r?.onAction??s);let v=i.clearChat??{},C=null,A=null;if(v.enabled??!0){let H=v.placement??"inline",_=Da(t,{wrapperClassName:H==="top-right"?"persona-absolute persona-top-4 persona-z-50":g});C=_.button,A=_.wrapper,H==="top-right"?A.style.right="48px":y.appendChild(A)}y.appendChild(h),l.appendChild(y);let L=x("div");L.style.display="none";let I=x("span");return I.style.display="none",{header:l,iconHolder:L,headerTitle:d,headerSubtitle:I,closeButton:f,closeButtonWrapper:h,clearChatButton:C,clearChatButtonWrapper:A}},Jp={default:_m,minimal:Dm},Nm=e=>Jp[e]??Jp.default,Na=(e,t,n)=>{if(t?.render){let i=t.render({config:e,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),l=x("div");l.style.display="none";let c=x("span"),p=x("span"),d=x("button");d.style.display="none";let g=x("div");return g.style.display="none",{header:i,iconHolder:l,headerTitle:c,headerSubtitle:p,closeButton:d,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}}let o=t?.layout??"default",s=Nm(o)({config:e,showClose:t?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:t,onHeaderAction:t?.onAction});return t&&(t.showIcon===!1&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};Je();Es();var ki=e=>{let{config:t}=e,n=Q("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),o=rp(),r=Q("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-persona-border persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""}}),{textarea:s,attachAutoResize:i}=ep(t);i();let l=tp(t),c=ka(t),p=np(t),d=op(t),g=Q("div",{className:"persona-widget-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});r.append(g),p&&(p.previewsContainer.style.gap="8px",g.append(p.previewsContainer),r.append(p.input)),r.append(s);let f=Q("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),h=Q("div",{className:"persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-start":""}}),y=Q("div",{className:"persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-end":""}});return p&&h.append(p.wrapper),c&&y.append(c.wrapper),y.append(l.wrapper),f.append(h,y),r.append(f),r.addEventListener("click",v=>{v.target!==l.button&&v.target!==l.wrapper&&v.target!==c?.button&&v.target!==c?.wrapper&&v.target!==p?.button&&v.target!==p?.wrapper&&s.focus()}),t?.statusIndicator?.mode==="transient"?n.append(o,d,r):n.append(o,r,d),{footer:n,suggestions:o,composerForm:r,header:g,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:c?.button??null,micButtonWrapper:c?.wrapper??null,statusText:d,attachmentButton:p?.button??null,attachmentButtonWrapper:p?.wrapper??null,attachmentInput:p?.input??null,attachmentPreviewsContainer:p?.previewsContainer??null,actionsRow:f,leftActions:h,rightActions:y,setSendButtonMode:l.setMode}};Je();var Zp=require("lucide");Lr();Es();Jd();var rA=()=>{let e=Q("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=x("span","persona-pill-peek__icon"),n=Nt(Zp.MessageSquare,16,"currentColor",1.5);n&&t.appendChild(n);let o=x("span","persona-pill-peek__text"),r=x("span","persona-pill-peek__caret"),s=Nt(Zp.ChevronUp,16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},eu=e=>{let{config:t}=e,n=Q("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=rp(),r=op(t);r.style.display="none";let{textarea:s,attachAutoResize:i}=ep(t,{defaultMaxLines:5});i();let l=tp(t),c=ka(t),p=np(t);p&&p.previewsContainer.classList.add("persona-pill-composer__previews");let d=Q("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""}}),g=Q("div",{className:"persona-widget-composer__left-actions persona-pill-composer__left",attrs:{"data-persona-composer-actions-start":""}});p&&g.append(p.wrapper);let f=Q("div",{className:"persona-widget-composer__right-actions persona-pill-composer__right",attrs:{"data-persona-composer-actions-end":""}});c&&f.append(c.wrapper),f.append(l.wrapper),d.addEventListener("click",v=>{v.target!==l.button&&v.target!==l.wrapper&&v.target!==c?.button&&v.target!==c?.wrapper&&v.target!==p?.button&&v.target!==p?.wrapper&&s.focus()}),p&&d.append(p.input),d.append(g,s,f);let h=Q("div",{className:"persona-pill-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});n.append(h),p&&h.append(p.previewsContainer),n.append(o,d,r);let y=d;return{footer:n,suggestions:o,composerForm:d,header:h,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:c?.button??null,micButtonWrapper:c?.wrapper??null,statusText:r,attachmentButton:p?.button??null,attachmentButtonWrapper:p?.wrapper??null,attachmentInput:p?.input??null,attachmentPreviewsContainer:p?.previewsContainer??null,actionsRow:y,leftActions:g,rightActions:f,setSendButtonMode:l.setMode}};Je();kt();Je();Vf();kt();Nr();var L0=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},H0=(e,t)=>{if(!e)return null;let n=L0(e);if(n===null)return null;let o=t?.[e],r=o!==void 0?o:n;return r||null},I0=(e,t)=>{let n=x("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},R0=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},$m=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},Um=320,cA=320,W0=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),O0=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),B0=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),_0=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),D0=e=>{if(!e||e.length===0)return null;let t=Q("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let n of e){let o=Q("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=x("span","persona-mention-chip-icon"),s=ge(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild(Q("span",{className:"persona-mention-chip-label",text:n.label})),t.appendChild(o)}return t},N0=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(Dl(o.ref,{readonly:!0,render:t}))}return n},sA="\uE000",iA="\uE001",F0=(e,t,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=f=>`${sA}${r}:${f}${iA}`,i=t.map((f,h)=>f.kind==="text"?f.text:s(h)).join(""),l=n(i);if(!t.every((f,h)=>f.kind==="text"||l.includes(s(h)))){e.replaceChildren(N0(t,o));return}e.innerHTML=l;let p=new RegExp(`${sA}${r}:(\\d+)${iA}`),d=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),g=[];for(let f=d.nextNode();f;f=d.nextNode())g.push(f);for(let f of g){let h=f;for(let y=p.exec(h.data);y;y=p.exec(h.data)){let v=t[Number(y[1])],C=h.splitText(y.index);C.data=C.data.slice(y[0].length),v?.kind==="mention"&&C.parentNode?.insertBefore(Dl(v.ref,{readonly:!0,render:o}),C),h=C}}},$0=(e,t,n)=>{if(e.length===0)return null;try{let o=x("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let r=0,s=!1,i=()=>{s||(s=!0,o.remove(),n?.())};return e.forEach((l,c)=>{let p=x("img");p.alt=l.alt?.trim()||`Attached image ${c+1}`,p.loading="lazy",p.decoding="async",p.referrerPolicy="no-referrer",p.style.display="block",p.style.width="100%",p.style.maxWidth=`${Um}px`,p.style.maxHeight=`${cA}px`,p.style.height="auto",p.style.objectFit="contain",p.style.borderRadius="10px",p.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",p.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let d=!1;r+=1,p.addEventListener("error",()=>{d||(d=!0,r=Math.max(0,r-1),p.remove(),r===0&&i())}),p.addEventListener("load",()=>{d=!0}),R0(l.image)?(p.src=l.image,o.appendChild(p)):(d=!0,r=Math.max(0,r-1),p.remove())}),r===0?(i(),null):o}catch{return n?.(),null}},U0=e=>{if(e.length===0)return null;try{let t=x("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!$m(o.audio))return;let r=x("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Um}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},V0=e=>{if(e.length===0)return null;try{let t=x("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!$m(o.video))return;let r=x("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Um}px`,r.style.maxHeight=`${cA}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},j0=e=>{if(e.length===0)return null;try{let t=x("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!$m(o.data))return;let r=x("a");r.href=o.data,r.download=o.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=o.filename,r.className="persona-message-file-attachment",r.style.display="inline-flex",r.style.alignItems="center",r.style.gap="6px",r.style.padding="6px 10px",r.style.borderRadius="8px",r.style.fontSize="0.875rem",r.style.textDecoration="underline",r.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",r.style.color="inherit",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Li=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let r=document.createElement("span");return r.className="persona-sr-only",r.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(o),e.appendChild(r),e},Vm=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:Li};if(t){let r=t(o);if(r!==null)return r}return Li()},q0=(e,t)=>{let n=x("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=t==="user"?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=x("img");r.src=o,r.alt=t==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(r)}else n.textContent=o,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},aA=(e,t,n="div")=>{let o=x(n,"persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return t.format?o.textContent=t.format(r):o.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},cc=(e,t="bubble")=>{let n=["persona-message-bubble"];switch(t){case"flat":e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-text","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-text-persona-text","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-border","persona-border-persona-message-border","persona-text-persona-text","persona-px-5","persona-py-3");break}return n},lA={bubble:{padding:"0.75rem 1.25rem",fontSize:"0.875rem",lineHeight:"1.75"},minimal:{padding:"0.5rem 0.75rem",fontSize:"0.875rem",lineHeight:"1.75"},flat:{padding:"0.5rem 0",fontSize:"inherit",lineHeight:"inherit"}},z0=(e,t,n="bubble",o)=>{if(!o)return;let r=t==="user"?"user":"assistant",s=lA[n??"bubble"]??lA.bubble;o.padding&&(e.style.padding=`var(--persona-message-${r}-padding, ${s.padding})`),o.fontSize&&(e.style.fontSize=`var(--persona-message-${r}-font-size, ${s.fontSize})`),o.lineHeight&&(e.style.lineHeight=`var(--persona-message-${r}-line-height, ${s.lineHeight})`),o.fontFamily&&(e.style.fontFamily=`var(--persona-message-${r}-font-family, inherit)`)},tu="custom:",K0=e=>`${tu}${e}`,dA=(e,t)=>t!=="user"&&t!=="assistant"?[]:(e?.custom??[]).filter(n=>(n.roles??["assistant"]).includes(t)),jm=(e,t,n,o)=>{let r=t.showCopy??!0,s=t.showUpvote??!1,i=t.showDownvote??!1,l=t.showReadAloud??!1,c=(t.showRegenerate??!1)&&o?.canRegenerate===!0,p=(t.showEdit??!1)&&o?.canEdit===!0,d=(t.showQuote??!1)&&o?.canQuote!==!1,g=dA(t,e.role);if(!r&&!s&&!i&&!l&&!c&&!p&&!d&&g.length===0){let I=x("div");return I.style.display="none",I.id=`actions-${e.id}`,I.setAttribute("data-actions-for",e.id),I}let f=t.visibility??"hover",h=t.align??"right",y=t.layout??"pill-inside",v={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[h],C={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[y],A=x("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${v} ${C} ${f==="hover"?"persona-message-actions-hover":""}`);A.id=`actions-${e.id}`,A.setAttribute("data-actions-for",e.id);let L=(I,H,_)=>{let V=Zn({icon:I,label:H,size:14,className:"persona-message-action-btn",chromeless:!0});return V.setAttribute("data-action",_),V};r&&A.appendChild(L("copy","Copy message","copy")),l&&A.appendChild(L("volume-2","Read aloud","read-aloud")),s&&A.appendChild(L("thumbs-up","Upvote","upvote")),i&&A.appendChild(L("thumbs-down","Downvote","downvote")),c&&A.appendChild(L("refresh-cw","Regenerate response","regenerate")),p&&A.appendChild(L("pencil","Edit message","edit")),d&&A.appendChild(L("quote","Quote message","quote"));for(let I of g)A.appendChild(L(I.iconName??"ellipsis",I.label,K0(I.id)));return A},Fa=(e,t,n,o,r,s)=>{let i=n??{},l=i.layout??"bubble",c=i.avatar,p=i.timestamp,d=c?.show??!1,g=p?.show??!1,f=c?.position??"left",h=p?.position??"below",y=cc(e.role,l),v=x("div",y.join(" "));v.id=`bubble-${e.id}`,v.setAttribute("data-message-id",e.id),v.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message");let C=Sm(s?.widgetConfig?.future).components.message,A=s?.widgetConfig?.theme?.components?.message;z0(v,e.role,l,e.role==="user"?{...C.user,...A?.user,...s?.widgetConfig?.darkTheme?.components?.message?.user}:{...C.assistant,...A?.assistant,...s?.widgetConfig?.darkTheme?.components?.message?.assistant}),l==="flat"?(v.style.backgroundColor="transparent",v.style.color=e.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):e.role==="user"?(v.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",v.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(v.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",v.style.color="var(--persona-message-assistant-text, var(--persona-text))");let L=W0(e),I=e.content?.trim()??"",_=L.length>0&&I===Ta,V=Kp(s?.widgetConfig?.features?.streamAnimation),oe=s?.widgetConfig?.features?.streamAnimation?.plugins,W=e.role==="assistant"&&V.type!=="none"?tc(V.type,oe):null,j=e.role==="assistant"&&W?.isAnimating?.(e)===!0,X=e.role==="assistant"&&W!==null&&(!!e.streaming||j);X&&W?.bubbleClass&&v.classList.add(W.bubbleClass);let E=document.createElement("div");E.classList.add("persona-message-content"),e.streaming&&E.classList.add("persona-content-streaming"),X&&W&&(W.containerClass&&E.classList.add(W.containerClass),E.style.setProperty("--persona-stream-step",`${V.speed}ms`),E.style.setProperty("--persona-stream-duration",`${V.duration}ms`));let T=X?Gp(e.content??"",V.buffer,W,e,!!e.streaming):e.content??"",B=()=>{let Oe=t({text:T,message:e,streaming:!!e.streaming,raw:e.rawContent});return X&&W?.wrap==="char"?nc(Oe,"char",e.id,{skipTags:W.skipTags}):X&&W?.wrap==="word"?nc(Oe,"word",e.id,{skipTags:W.skipTags}):Oe},P=null;if(_?(P=document.createElement("div"),P.innerHTML=B(),P.style.display="none",E.appendChild(P)):e.contentSegments?.length?F0(E,e.contentSegments,Oe=>t({text:Oe,message:e,streaming:!!e.streaming,raw:e.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):E.innerHTML=B(),X&&W?.useCaret&&!_&&I){let Oe=Yp(),$=E.querySelectorAll(".persona-stream-char, .persona-stream-word"),Be=$[$.length-1];if(Be?.parentNode)Be.parentNode.insertBefore(Oe,Be.nextSibling);else{let ye=E.lastElementChild;ye?ye.appendChild(Oe):E.appendChild(Oe)}}if(g&&h==="inline"&&e.createdAt){let Oe=aA(e,p,"span");Oe.classList.add("persona-timestamp-inline");let $=E.lastElementChild;$?$.appendChild(Oe):E.appendChild(Oe)}if(L.length>0){let Oe=$0(L,!_&&!!I,()=>{_&&P&&(P.style.display="")});Oe?v.appendChild(Oe):_&&P&&(P.style.display="")}let J=O0(e);if(J.length>0){let Oe=U0(J);Oe&&v.appendChild(Oe)}let U=B0(e);if(U.length>0){let Oe=V0(U);Oe&&v.appendChild(Oe)}let ue=_0(e);if(ue.length>0){let Oe=j0(ue);Oe&&v.appendChild(Oe)}let fe=e.contentSegments?.length?null:D0(e.contextMentions);if(fe&&v.appendChild(fe),v.appendChild(E),g&&h==="below"&&e.createdAt){let Oe=aA(e,p);Oe.classList.add("persona-mt-1"),v.appendChild(Oe)}let me=e.role==="assistant"?H0(e.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let Oe=!!(T&&T.trim()),$=V.placeholder==="skeleton",Be=$&&V.buffer==="line"&&Oe;if(Oe)Be&&v.appendChild(oc());else if($)v.appendChild(oc());else{let ye=Vm("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);ye&&v.appendChild(ye)}}me&&e.stopReason&&!e.streaming&&(I||(E.style.display="none"),v.appendChild(I0(e.stopReason,me)));let He=e.role==="assistant"&&!e.streaming&&!e.voiceCaption&&e.content&&e.content.trim()&&o?.enabled!==!1,Ee=s?.actionEligibility,Ie=e.role==="user"&&!e.streaming&&o?.enabled!==!1&&(o?.showEdit===!0&&Ee?.canEdit===!0||o?.showQuote===!0&&Ee?.canQuote===!0||dA(o,"user").length>0);if((He||Ie)&&o){let Oe=jm(e,Ie?{...o,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:o,r,Ee);v.appendChild(Oe)}if(!d||e.role==="system")return v;let yt=x("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),qe=q0(c,e.role);return f==="right"||f==="left"&&e.role==="user"?yt.append(v,qe):yt.append(qe,v),yt},pA=(e,t,n,o,r,s)=>{let i=n??{};return e.role==="user"&&i.renderUserMessage?i.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&i.renderAssistantMessage?i.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Fa(e,t,n,o,r,s)};var G0=40,Y0=(e,t)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}if(typeof t=="function"){let n=null;try{n=t()}catch(o){console.warn("[persona] welcome.icon renderer threw",o)}if(!n){e.hidden=!0;return}e.appendChild(n),e.hidden=!1;return}if(t.type==="lucide"){let n=ge(t.name,G0);if(!n){e.hidden=!0;return}e.appendChild(n)}else t.type==="image"?e.appendChild(Q("img",{className:"persona-welcome-icon-image",attrs:{src:t.url,alt:t.alt}})):e.appendChild(Q("span",{className:"persona-welcome-icon-text",text:t.text}));e.hidden=!1},uA=(e,t,n={})=>{let o=Q("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});o.hidden=!0;let r=x("p","persona-welcome-kicker");r.hidden=!0;let s=x("h2","persona-welcome-title"),i=x("p","persona-welcome-subtitle"),l=Q("div",{className:"persona-welcome-head-text"},r,s),c=Q("div",{className:"persona-welcome-title-row"},o,l);return{host:Q("div",{className:"persona-welcome persona-rounded-2xl",attrs:{"data-persona-welcome":"","data-persona-intro-card":"","data-persona-welcome-variant":"card"},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:n.flatShadow?"none":"var(--persona-intro-card-shadow, none)",border:"var(--persona-intro-card-border, none)"}},c,i,t),iconHolder:o,kicker:r,title:s,subtitle:i,starterSuggestions:t}},$a=(e,t,n)=>{t.hidden=!n,t.style.display=n?"":"none",e.classList.toggle("persona-gap-6",n),e.classList.toggle("persona-gap-3",!n)},ou=(e,t)=>{e.title.textContent=t.title,e.kicker.textContent=t.kicker??"",e.kicker.hidden=!t.kicker,e.subtitle.textContent=t.subtitle,e.subtitle.hidden=t.subtitle==="",Y0(e.iconHolder,t.icon),e.host.setAttribute("data-persona-welcome-variant",t.variant),e.host.setAttribute("data-persona-welcome-dismiss",t.dismiss),e.host.setAttribute("data-persona-welcome-layout",t.layout??"top"),e.host.setAttribute("data-persona-welcome-anchor",t.anchor??"bottom"),t.iconPlacement==="inline"?e.host.setAttribute("data-persona-welcome-icon-placement","inline"):e.host.removeAttribute("data-persona-welcome-icon-placement"),t.align?e.host.setAttribute("data-persona-welcome-align",t.align):e.host.removeAttribute("data-persona-welcome-align")},X0="data-persona-welcome-plugin",gA="data-persona-welcome-overlay",nu="persona-welcome-overlay-active",qm=new WeakMap,zm=(e,t,n)=>{n.setAttribute(X0,""),t.appendChild(n),t.setAttribute("data-persona-welcome-content","plugin"),t.setAttribute(gA,""),e.classList.contains(nu)||(qm.set(e,e.scrollTop),e.classList.add(nu),e.scrollTop=0)},Km=(e,t,n)=>{n&&n!==t&&n.remove(),t.removeAttribute("data-persona-welcome-content"),t.removeAttribute(gA),e.classList.contains(nu)&&(e.classList.remove(nu),e.scrollTop=qm.get(e)??e.scrollTop,qm.delete(e))},fA=()=>{let e=Q("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return e.hidden=!0,e},ru=(e,t,n)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}let o=n?.layout?.messages?.layout??"bubble",r=Q("div",{className:cc("assistant",o).join(" "),attrs:{"data-persona-theme-zone":"assistant-message"},text:t,style:o==="flat"?{backgroundColor:"transparent",color:"var(--persona-message-assistant-text, var(--persona-text))"}:{backgroundColor:"var(--persona-message-assistant-bg, var(--persona-container))",color:"var(--persona-message-assistant-text, var(--persona-text))"}});e.appendChild(Q("div",{className:"persona-flex"},r)),e.hidden=!1},mA=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,hA=(e,t)=>{if(mA()||typeof e.animate!="function"||!e.isConnected)return t(null),null;let n=e.getBoundingClientRect(),o=e.parentElement,r=0,s=0,i=0;if(o){let y=getComputedStyle(o);r=parseFloat(y.rowGap)||0;let v=e.previousElementSibling,C=e.nextElementSibling,L=o.getBoundingClientRect().top+(parseFloat(y.borderTopWidth)||0)+(parseFloat(y.paddingTop)||0)-o.scrollTop;s=Math.max(0,v?n.top-v.getBoundingClientRect().bottom-r:n.top-L),i=Math.max(0,C?C.getBoundingClientRect().top-n.bottom-r:0)}let l=e.style.overflow;e.style.overflow="hidden";let c=getComputedStyle(e),p=parseFloat(c.paddingTop)||0,d=parseFloat(c.paddingBottom)||0,g=e.animate([{opacity:"1",transform:"none",height:`${n.height}px`,minHeight:"0px",paddingTop:`${p}px`,paddingBottom:`${d}px`,marginTop:`${s}px`,marginBottom:`${i}px`},{opacity:"0",transform:"translateY(-4px)",height:"0px",minHeight:"0px",paddingTop:"0px",paddingBottom:"0px",marginTop:"0px",marginBottom:`${-r}px`}],{duration:180,easing:"ease-out",fill:"forwards"}),f=!1,h=()=>{f||(f=!0,e.style.overflow=l,t(g))};return g.finished.then(h).catch(h),g},yA=(e,t,n,o=260)=>{if(t<=1||mA()||typeof e.animate!="function"||!e.isConnected)return null;let r=n==="drop"?-t:t;return e.animate([{transform:`translateY(${r}px)`},{transform:"none"}],{duration:o,easing:"cubic-bezier(0.2, 0, 0, 1)",fill:"none"})};var Q0="Hello \u{1F44B}",J0="I can answer questions and help you get things done here.",bA=new WeakSet,Fn=(e,t)=>!!e&&e[t]!==void 0,Z0=(e,t)=>{!e||e.debug!==!0||!t.length||bA.has(e)||(bA.add(e),t.forEach(n=>console.warn(`[persona] ${n}`)))},Ua=(e,t=e?.launcher?.fullHeight===!0&&!e.launcher.sidebarMode&&e.launcher.mountMode!=="docked")=>{let n=e?.welcome,o=e?.copy,r=e?.future?.v5Defaults===!0,s=n?.layout??(r?"centered":"top"),i=Fn(n,"variant")?n.variant:o?.showWelcomeCard===!1?"none":"card",l=i==="hero"&&!r&&n?.layout===void 0?"on-first-message":Fn(n,"dismiss")?n.dismiss:r||i==="hero"?"on-first-message":"never",c=[];Fn(n,"title")&&Fn(o,"welcomeTitle")&&c.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),Fn(n,"subtitle")&&Fn(o,"welcomeSubtitle")&&c.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),Fn(n,"variant")&&Fn(o,"showWelcomeCard")&&c.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),i==="hero"&&Fn(n,"message")&&c.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),!r&&n?.layout===void 0&&i==="hero"&&Fn(n,"dismiss")&&n.dismiss!=="on-first-message"&&c.push('welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".');let p=n?.anchor??(s==="centered"&&t?"center":"bottom"),d=Ql(n?.anchorComposerTop)!==null;return Fn(n,"anchorComposerTop")&&!d&&c.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),p!=="center"&&(Fn(n,"anchorComposerTop")||Fn(n,"composerGap"))&&c.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),Z0(e,c),{title:Fn(n,"title")?n.title:o?.welcomeTitle??(r?"What can I help with?":Q0),kicker:n?.kicker??"",subtitle:Fn(n,"subtitle")?n.subtitle:o?.welcomeSubtitle??(r?"":J0),icon:n?.icon,align:n?.align==="start"||n?.align==="center"?n.align:s==="centered"?"center":void 0,iconPlacement:n?.icon&&typeof n.icon!="function"&&n.icon.placement==="inline"?"inline":"above",variant:i,dismiss:l,message:i==="hero"?void 0:n?.message,layout:s,anchor:p,anchorComposerTop:d?n.anchorComposerTop:"44%",composerGap:n?.composerGap?.trim()||qp}},vA=e=>(e??[]).some(t=>t.role==="user")?"active":"empty",Ws=(e,t)=>e.variant==="none"?!1:e.dismiss==="never"?!0:!(t??[]).some(n=>n.role==="user");Ma();var eL="var(--persona-components-panel-maxWidth)",CA="var(--persona-components-panel-height)",tL="var(--persona-components-panel-maxHeight)",Hi=e=>{let t=Br(e),n=t.launcherWidth?e?.launcher?.width:t.legacyLauncherWidth?e?.launcherWidth:void 0,o=e?.launcher?.heightOffset??0,r=o===0?`max(200px, ${CA})`:`max(200px, calc(${CA} - ${o}px))`;return{width:n??hC,maxWidth:n??eL,height:r,maxHeight:tL}},wA="16px",Ym="10px",Xm="14px",SA=e=>{let t=e?.launcher?.enabled??!0,n=Lt(e);if(Rs(e)){let p=e?.launcher?.composerBar??{},d=x("div","persona-widget-wrapper persona-fixed persona-transition");d.setAttribute("data-persona-composer-bar",""),d.dataset.state="collapsed",d.dataset.expandedSize=p.expandedSize??"anchored",d.style.zIndex=String(e?.launcher?.zIndex??kn);let g=x("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");g.style.width="100%",d.appendChild(g);let f=x("div","persona-widget-pill-root");return f.setAttribute("data-persona-composer-bar",""),f.dataset.state="collapsed",f.dataset.expandedSize=p.expandedSize??"anchored",f.style.zIndex=String(e?.launcher?.zIndex??kn),{wrapper:d,panel:g,pillRoot:f}}if(n){let p=x("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),d=x("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return p.appendChild(d),{wrapper:p,panel:d}}if(!t){let p=x("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),d=x("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),g=Br(e),h=g.launcherWidth||g.legacyLauncherWidth||e?.theme?.components?.panel?.width!==void 0?Hi(e).width:"100%";return p.style.width=h,d.style.width="100%",p.appendChild(d),{wrapper:p,panel:d}}let r=e?.launcher??{},s=r.position&&io[r.position]?io[r.position]:io["bottom-right"],i=x("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);i.style.zIndex=String(e?.launcher?.zIndex??kn);let l=x("div","persona-widget-panel persona-relative persona-min-h-[320px]"),c=Hi(e);return l.style.width=c.width,l.style.maxWidth=c.maxWidth,i.appendChild(l),{wrapper:i,panel:l}},Qm=e=>{let t=Q("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":Im(e)}});return t.hidden=!0,t},AA=(e,t)=>{let n=Qm("starter"),o=uA(e,n,{flatShadow:Lt(e)}),r=Ua(e);ou(o,r),$a(t,o.host,Ws(r,e?.initialMessages));let s=fA();return ru(s,r.message,e),{welcome:o,greetingHost:s}},nL=(e,t)=>{let n=x("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:r}=_a(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:wA,iconSize:Ym});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let s=e?.launcher?.clearChat?.enabled??!0,i=null,l=null;if(s){let oe=Da(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:wA,iconSize:Xm});i=oe.button,l=oe.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let c=Q("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),p=Q("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});p.style.setProperty("scrollbar-gutter","stable");let{welcome:d,greetingHost:g}=AA(e,p),{host:f,title:h,subtitle:y}=d,v=d.starterSuggestions,C=x("div","persona-widget-messages persona-flex persona-flex-col");C.style.gap="var(--persona-components-message-gap, 12px)";let A=Qm("followUp"),L=Hs(e,!0);L&&(C.style.maxWidth=L,C.style.marginLeft="auto",C.style.marginRight="auto",C.style.width="100%"),p.append(f,g,C,A);let I=Q("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}}),H=eu({config:e}),{root:_,textNode:V}=rA();return n.append(c,r,p,I),l&&n.appendChild(l),{container:n,body:p,messagesWrapper:C,starterSuggestions:v,transcriptSuggestions:A,composerOverlay:I,suggestions:H.suggestions,textarea:H.textarea,sendButton:H.sendButton,sendButtonWrapper:H.sendButtonWrapper,micButton:H.micButton,micButtonWrapper:H.micButtonWrapper,composerForm:H.composerForm,statusText:H.statusText,welcomeHost:f,welcomeIconHolder:d.iconHolder,greetingHost:g,introKicker:d.kicker,introTitle:h,introSubtitle:y,closeButton:o,closeButtonWrapper:r,clearChatButton:i,clearChatButtonWrapper:l,iconHolder:x("span"),headerTitle:x("span"),headerSubtitle:x("span"),header:c,footer:H.footer,attachmentButton:H.attachmentButton,attachmentButtonWrapper:H.attachmentButtonWrapper,attachmentInput:H.attachmentInput,attachmentPreviewsContainer:H.attachmentPreviewsContainer,actionsRow:H.actionsRow,leftActions:H.leftActions,rightActions:H.rightActions,setSendButtonMode:H.setSendButtonMode,peekBanner:_,peekTextNode:V}},xA=(e,t=!0)=>{if(Rs(e))return nL(e,t);let n=Q("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),o=e?.layout?.header,r=e?.layout?.showHeader!==!1,s=o?Na(e,o,{showClose:t}):jr({config:e,showClose:t}),i=Q("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});i.style.setProperty("scrollbar-gutter","stable");let{welcome:l,greetingHost:c}=AA(e,i),{host:p,title:d,subtitle:g}=l,f=l.starterSuggestions,h=x("div","persona-widget-messages persona-flex persona-flex-col");h.style.gap="var(--persona-components-message-gap, 12px)";let y=Qm("followUp"),v=Hs(e,!1);v&&(h.style.maxWidth=v,h.style.marginLeft="auto",h.style.marginRight="auto",h.style.width="100%"),i.append(p,c,h,y);let C=ki({config:e}),A=e?.layout?.showFooter!==!1;r?Ti(n,s,e):(s.header.style.display="none",Ti(n,s,e)),n.append(i);let L=Q("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}});return A||(C.footer.style.display="none"),n.append(C.footer),n.append(L),{container:n,body:i,messagesWrapper:h,starterSuggestions:f,transcriptSuggestions:y,composerOverlay:L,suggestions:C.suggestions,textarea:C.textarea,sendButton:C.sendButton,sendButtonWrapper:C.sendButtonWrapper,micButton:C.micButton,micButtonWrapper:C.micButtonWrapper,composerForm:C.composerForm,statusText:C.statusText,welcomeHost:p,welcomeIconHolder:l.iconHolder,greetingHost:c,introKicker:l.kicker,introTitle:d,introSubtitle:g,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:C.footer,attachmentButton:C.attachmentButton,attachmentButtonWrapper:C.attachmentButtonWrapper,attachmentInput:C.attachmentInput,attachmentPreviewsContainer:C.attachmentPreviewsContainer,actionsRow:C.actionsRow,leftActions:C.leftActions,rightActions:C.rightActions,setSendButtonMode:C.setSendButtonMode}};Es();Je();kt();Bo();var Jm=(e,t)=>{let n=x("button");n.type="button",n.innerHTML=`
|
|
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 mI(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===JH?new Uint8Array(e,44):new Uint8Array(e)}function Xx(e){let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window<"u"&&window.location?.protocol==="https:"?"wss:":"ws:"}//${t}`}function hI(e){return Xx(e).replace(/^ws/i,"http")}function yI(e){return typeof e!="number"||!Number.isFinite(e)?tI:Math.min(oI,Math.max(nI,Math.round(e)))}var vc=class{constructor(t){this.config=t;this.type="runtype";this.#e=null;this.#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<ZH)){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=`${hI(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=yI(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,eI)})]),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:lI,clientVersion:`persona/${Yn}`,voiceCapabilities:rI,clientCapabilities:r.join(",")});return o?.forEach((i,l)=>s.set(l,i)),`${Xx(t)}/ws/agents/${encodeURIComponent(n)}/voice?${s}`}async startListening(){if(this.#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:Bh,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:Bh});l.state==="suspended"&&await l.resume().catch(()=>{}),this.#t=l;let c=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new Ra(GH);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||dI: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()+iI,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(YH,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>XH;)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*QH));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 fI(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),aI)})]);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,cI),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=mI(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+sI)}#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 Oi=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 Xa(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new vc(e.runtype);case"browser":if(!Oi.isSupported())throw new Error("Browser speech recognition not supported");return new Oi(e.browser||{});case"custom":{let t=e.custom;if(!t)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof t=="function"?t():t;if(!n||typeof n.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Pu(e){if(e?.type==="custom"&&e.custom)return Xa({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return Xa({type:"runtype",runtype:e.runtype});if(Oi.isSupported())return Xa({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function _h(e){try{return Pu(e),!0}catch{return!1}}var Qx="webmcp:",bI=e=>e.startsWith(Qx)?e.slice(Qx.length):e,ku={warn(e,...t){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},Hu=class{constructor(t,n){this.config=t;this.#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 ku.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=CI(r.annotations);return{name:r.name,description:r.description,parametersSchema:wI(r.inputSchema),origin:"webmcp",...o?{pageOrigin:o}:{},...s?{annotations:s}:{},...s?.untrustedContentHint===!0?{untrustedContentHint:!0}:{}}})}async executeToolCall(t,n,o){if(await this.#c(),this.config.enabled!==!0)return $o("WebMCP is not enabled on this widget.");let r=this.#d();if(!r){let y=typeof document<"u"&&!!document.modelContext;return $o(y?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let s=bI(t),i;try{i=await r.getTools()}catch(y){let v=y instanceof Error?y.message:String(y);return $o(`Failed to read WebMCP registry: ${v}`)}this.#i.recordToolDisplayTitles(i);let l=i.find(y=>y.name===s);if(!l)return $o(`WebMCP tool not registered on this page: ${s}`);if(!this.#r(s))return $o(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return $o("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 $o("User declined the tool call.");if(o?.aborted)return $o("Aborted by cancel()");let d=new AbortController,g=!1,f=setTimeout(()=>{g=!0,d.abort()},this.#t),h=()=>d.abort();o&&(o.aborted?d.abort():o.addEventListener("abort",h,{once:!0}));try{let y=await r.executeTool(l,MI(n),{signal:d.signal});return SI(y)}catch(y){if(g)return $o(`WebMCP tool '${s}' timed out after ${this.#t}ms`);if(o?.aborted)return $o("Aborted by cancel()");let v=y instanceof Error?y.message:String(y);return $o(v)}finally{clearTimeout(f),o&&o.removeEventListener("abort",h)}}#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){ku.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,ku.warn("document.modelContext is present but does not expose getTools()/executeTool(): WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):t}async#A(t){let n=this.#e??AI;try{return await n(t)}catch(o){return ku.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,o),!1}}#r(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(o=>vI(t,o))}},vI=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Lu={type:"object",properties:{}},CI=e=>{if(!e||typeof e!="object")return;let t={...typeof e.readOnlyHint=="boolean"?{readOnlyHint:e.readOnlyHint}:{},...typeof e.untrustedContentHint=="boolean"?{untrustedContentHint:e.untrustedContentHint}:{}};return Object.keys(t).length>0?t:void 0},wI=e=>{if(e===void 0||e==="")return{...Lu};if(typeof e=="object")return e!==null&&!Array.isArray(e)?e:{...Lu};try{let t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:{...Lu}}catch{return{...Lu}}},SI=e=>{if(e==null)return{content:[{type:"text",text:""}]};let t;try{t=JSON.parse(e)}catch{return{content:[{type:"text",text:e}]}}return t!==null&&typeof t=="object"&&Array.isArray(t.content)?t:{content:[{type:"text",text:typeof t=="string"?t:EI(t)}]}},$o=e=>({isError:!0,content:[{type:"text",text:e}]}),AI=async e=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let t=xI(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
|
|
481
|
+
`)}function mI(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===JH?new Uint8Array(e,44):new Uint8Array(e)}function Xx(e){let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window<"u"&&window.location?.protocol==="https:"?"wss:":"ws:"}//${t}`}function hI(e){return Xx(e).replace(/^ws/i,"http")}function yI(e){return typeof e!="number"||!Number.isFinite(e)?tI:Math.min(oI,Math.max(nI,Math.round(e)))}var vc=class{constructor(t){this.config=t;this.type="runtype";this.#e=null;this.#n=null;this.#o=[];this.#t=null;this.#s=null;this.#r=null;this.#p=[];this.#f=0;this.#i=null;this.#g=!1;this.#l=!1;this.#c=0;this.#a=!1;this.#E=Number.NEGATIVE_INFINITY;this.#h=null;this.#S=!1;this.#v=!1;this.#A=0;this.#d=0;this.#m=!1;this.bridge=null;this.#C=!1;this.#x=new Set;this.#y=new Map;this.#b=new Set;this.#k=!1;this.#M=null;this.#I=null;this.#Y=Promise.resolve();this.#j=new Set;this.#B=!1;this.#T=new Set;this.#K=new Set;this.#_=[];this.#F=[];this.#ee=[];this.#te=[];this.#D=[]}#e;#n;#o;#t;#s;#r;#p;#f;#i;#g;#l;#c;#a;#E;#h;#S;#v;#A;#d;#u;#m;#C;#x;#y;#b;#H;#k;#M;#I;#Y;#j;#B;#T;#K;#_;#F;#ee;#te;#D;async connect(){}setSessionBridge(t){this.bridge=t}prewarm(){if(this.#g||this.#h)return;let t=this.config?.agentId,n=this.config?.clientToken,o=this.config?.host;if(!t||!n||!o)return;let r=Date.now();if(!(r-this.#E<ZH)){this.#E=r;try{this.config?.prewarmMode==="attach"?this.#Z(o,t,n):this.#X(o,t,n)}catch{}}}#X(t,n,o){if(typeof fetch!="function")return;let r=`${hI(t)}/v1/client/agents/${encodeURIComponent(n)}/voice/prewarm`;fetch(r,{method:"POST",headers:{Authorization:`Bearer ${o}`},keepalive:!0}).catch(()=>{})}#Z(t,n,o){let r=new URLSearchParams,s=this.config?.attachIdleMs,i=yI(s);s!==void 0&&r.set("attachIdleMs",String(i));let l=new WebSocket(this.#de(t,n,r),["runtype.bearer","runtype.attach",o]);l.binaryType="arraybuffer";let c=()=>{},p=new Promise(g=>{c=g}),d={ws:l,state:"connecting",ready:p,settle:c,openedAt:0,idleTimer:void 0};this.#h=d,l.onopen=()=>{this.#h===d&&(d.state=l.protocol==="runtype.attach"?"attached":"live",d.openedAt=Date.now(),this.#ne(d,i),d.state==="attached"&&l.send('{"type":"ping"}'),d.settle())},l.onmessage=g=>{if(this.#h!==d||typeof g.data!="string")return;let f;try{f=JSON.parse(g.data)}catch{return}f.type==="attached"&&typeof f.idleMs=="number"&&this.#ne(d,f.idleMs-(Date.now()-d.openedAt))},l.onerror=()=>{},l.onclose=()=>{this.#h===d&&this.#$()}}#ne(t,n){clearTimeout(t.idleTimer),t.idleTimer=setTimeout(()=>{this.#h===t&&this.#$()},Math.max(0,n))}#$(){let t=this.#h;if(!t)return;this.#h=null,clearTimeout(t.idleTimer);let{ws:n}=t;if(n.onopen=null,n.onmessage=null,n.onerror=null,n.onclose=null,t.settle(),n.readyState===WebSocket.CONNECTING||n.readyState===WebSocket.OPEN)try{n.close(1e3,"prewarm released")}catch{}}async#U(){let t=this.#h;if(!t)return null;if(t.state==="connecting"){let n;await Promise.race([t.ready,new Promise(o=>{n=setTimeout(o,eI)})]),clearTimeout(n)}return this.#h!==t?null:t.state==="connecting"||t.ws.readyState!==WebSocket.OPEN?(this.#$(),null):(this.#h=null,clearTimeout(t.idleTimer),{ws:t.ws,live:t.state==="live"})}#de(t,n,o){let r=["partial_transcript","context"];this.bridge&&this.config?.clientDelegation!==!1&&r.push("client_delegation","delegation_update","delegation_read_back"),o&&r.unshift("attach");let s=new URLSearchParams({voiceProtocol:lI,clientVersion:`persona/${Yn}`,voiceCapabilities:rI,clientCapabilities:r.join(",")});return o?.forEach((i,l)=>s.set(l,i)),`${Xx(t)}/ws/agents/${encodeURIComponent(n)}/voice?${s}`}async startListening(){if(this.#g)return;let t=this.config?.agentId,n=this.config?.clientToken,o=this.config?.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!o)throw new Error("Runtype voice requires a host (or widget apiUrl)");let r=++this.#c;this.#a=!1,this.#g=!0;try{let s=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:Bh,channelCount:1,echoCancellation:!0}});if(r!==this.#c){s.getTracks().forEach(g=>g.stop());return}this.#t=s;let i=window.AudioContext||window.webkitAudioContext,l=new i({sampleRate:Bh});l.state==="suspended"&&await l.resume().catch(()=>{}),this.#n=l;let c=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new Ra(GH);if(r!==this.#c){c.destroy(),s.getTracks().forEach(g=>g.stop()),l.close().catch(()=>{});return}this.#i=c,this.#G(),this.#be(l,s,r);let p=await this.#U();if(r!==this.#c){p?.ws.close(1e3,"client ended call");return}if(p){let{ws:g}=p;this.#e=g,this.#W(g,r),p.live||g.send('{"type":"start"}'),this.#oe(g),this.#w("listening");return}let d=new WebSocket(this.#de(o,t),["runtype.bearer",n]);d.binaryType="arraybuffer",this.#e=d,d.onopen=()=>{r===this.#c&&(this.#oe(d),this.#w("listening"))},this.#W(d,r)}catch(s){throw this.#Q(),this.#ie(s),this.#w("error"),s}}#W(t,n){t.onmessage=o=>this.#pe(o,n),t.onerror=()=>{n===this.#c&&(this.#ie(new Error("Voice connection failed")),this.#w("error"),this.#Q())},t.onclose=o=>{if(this.#a){this.#a=!1;return}if(n===this.#c){if(o.code!==1e3){let r=o.code?` (code ${o.code})`:"";this.#ie(new Error(`Voice connection closed${r}`)),this.#w("error")}else this.#w("idle");this.#Q()}}}getDisclosure(){let t=this.config?.disclosureText;return this.#g&&this.#S&&t!==!1?t||dI:null}async stopListening(){this.#Q(),this.#w("idle")}async disconnect(){this.#Q(),this.#w("disconnected"),this.#_=[],this.#F=[],this.#ee=[],this.#te=[],this.#D=[]}stopPlayback(){this.#ve();let t=this.#e;t&&t.readyState===WebSocket.OPEN&&(this.#S&&(this.#A=Date.now()+iI,t.send('{"type":"cancel"}')),this.#w("listening"))}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.#g}onLevel(t){this.#o.push(t)}async deactivateBargeIn(){this.#Q(),this.#w("idle")}#be(t,n,o){let r=t.createMediaStreamSource(n);this.#s=r;let s=t.createScriptProcessor(YH,1,1);this.#r=s,s.onaudioprocess=i=>{if(o!==this.#c)return;let l=this.#e,c=l?.readyState===WebSocket.OPEN;if(l&&!c&&l.readyState!==WebSocket.CONNECTING)return;let p=i.inputBuffer.getChannelData(0),d=new Int16Array(p.length),g=0;for(let f=0;f<p.length;f++){let h=Math.max(-1,Math.min(1,p[f]));g+=h*h,d[f]=h<0?h*32768:h*32767}if(l&&c)this.#oe(l),l.send(d.buffer);else for(this.#p.push(d.buffer),this.#f+=d.byteLength;this.#f>XH;)this.#f-=this.#p.shift().byteLength;if(this.#o.length>0){let f=Math.sqrt(g/p.length),h=Math.max(0,Math.min(1,f*QH));for(let y of this.#o)y(h)}},r.connect(s),s.connect(t.destination)}#oe(t){for(let n of this.#p)t.send(n);this.#p=[],this.#f=0}#pe(t,n){if(n!==this.#c)return;if(t.data instanceof ArrayBuffer){this.#L(t.data,n);return}let o;try{o=JSON.parse(t.data)}catch{return}switch(o.type){case"session_config":o.speechMode&&(this.#S=o.speechMode==="speech_to_speech",this.#i?.setContinuousMode?.(this.#S)),Array.isArray(o.capabilities)&&(this.#x=new Set(o.capabilities)),typeof o.callId=="string"&&(this.#H=o.callId),this.#C=this.#S&&this.#x.has("client_delegation")&&!!this.bridge,this.#S&&!this.#l&&this.#w("listening"),this.#x.has("context")&&!this.#k&&(this.#k=!0,this.#M=this.#re());break;case"transcript_update":{let r=o.role==="assistant"?"assistant":"user",s=o.utteranceId??o.turnId;if(!s||r==="assistant"&&this.#N())break;let i=String(s);if(r==="user")o.final===!0&&this.#se(n),this.#B=!1;else{if(this.#x.has("delegation_read_back")){let l=o.delegationId;typeof l=="string"&&this.#j.has(l)&&!this.#T.has(i)&&this.#K.add(i)}else this.#B&&!this.#T.has(i)&&(this.#K.add(i),this.#B=!1);if(this.#T.add(i),this.#K.has(i))break}this.#ae(r,o.text??"",o.final===!0,{turnId:i,...typeof o.startMs=="number"&&{startMs:o.startMs},...typeof o.endMs=="number"&&{endMs:o.endMs},...this.#C&&{caption:!0}});break}case"delegation_started":case"delegation_completed":{let r=String(o.delegationId??o.turnId);if(o.type==="delegation_started"){this.#se(n);let s=o.input;this.#C&&s&&this.#O(r,{delegationId:r,userText:String(s.text??""),userUtteranceIds:Array.isArray(s.userUtteranceIds)?s.userUtteranceIds.filter(i=>typeof i=="string"):[],messages:Array.isArray(s.messages)?s.messages:[]},n)}else o.speak!==!1&&this.#j.has(r)&&(this.#B=!0);this.#v=o.type==="delegation_started",!this.#l&&!this.#N()&&this.#w(this.#v?"processing":"listening");break}case"delegation_cancelled":this.#R(String(o.delegationId),o.reason!=="session_ending"&&o.reason!=="provider_cancelled");break;case"warning":console.warn(`[Persona voice] ${o.code}: ${o.message??""}`,this.#H??""),o.delegationId&&(o.code==="UNKNOWN_DELEGATION"||o.code==="LATE_RESULT_LIMIT")&&this.#R(String(o.delegationId));break;case"audio_clear":this.#ve(),this.#A=0,this.#w("listening");break;case"transcript_interim":this.#w("listening"),this.#ae("user",o.text??"",!1);break;case"transcript_final":{let r=o.role==="assistant"?"assistant":"user";this.#w(r==="user"?"processing":"speaking"),this.#ae(r,o.text??"",!0);break}case"audio_end":this.#i?this.#i.markStreamEnd():(this.#l=!1,this.#w("listening"));break;case"metrics":this.#we({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.#ie(new Error(o.error||"Voice error")),this.#w("error");break}}async#re(){let t=this.bridge?.getHistory()??[],n="";try{let o=this.config?.callContext;n=String((typeof o=="function"?await o():o)??"")}catch{}return fI(t,n)}#se(t){let n=this.#M;if(!n)return;this.#M=null;let o=!1,r=n.then(s=>{let i=this.#e;o||!s||t!==this.#c||i?.readyState!==WebSocket.OPEN||i.send(JSON.stringify({type:"context",text:s}))});this.#I={done:r,drop:()=>o=!0}}async#q(){let t=this.#I;if(!t)return;let n,o=await Promise.race([t.done.then(()=>!1),new Promise(r=>{n=setTimeout(()=>r(!0),aI)})]);clearTimeout(n),o&&t.drop()}#R(t,n=!1){this.#b.add(t),this.bridge?.dropDelegation?.(t,n),this.#y.get(t)?.abort()}#O(t,n,o){let r=this.bridge,s=(i,l,c)=>{let p=this.#e;return o!==this.#c||p?.readyState!==WebSocket.OPEN||this.#b.has(t)?!1:(p.send(JSON.stringify({type:i,delegationId:t,status:l,text:c})),!0)};this.#Y=this.#Y.then(async()=>{if(o!==this.#c||this.#b.has(t))return;let i=await r.runDelegatedTurn(n).catch(()=>({status:"failed",text:""}));await this.#q();let l=!!i.followUp,c=l&&this.#x.has("delegation_update");if(!s(c?"delegation_update":"delegation_result",l&&!c?"completed":i.status,i.text)||(i.status!=="failed"&&i.inChat!==!1&&this.#j.add(t),!i.followUp))return;let d=new AbortController;this.#y.set(t,d),i.followUp({signal:d.signal,approvalTimeoutMs:this.config?.approvalTimeoutMs&&Math.min(this.config.approvalTimeoutMs,cI),readBack:c,onUpdate:g=>s("delegation_update","pending_approval",g)}).then(g=>{this.#y.delete(t),c&&g&&!d.signal.aborted&&s("delegation_result",g.status,g.text)})})}#L(t,n){if(n!==this.#c||!this.#i||this.#N())return;let o=mI(t);o.length!==0&&(this.#l||(this.#l=!0,this.#w("speaking")),this.#G(),this.#i.enqueue(o),this.#S&&this.#xe(o.length))}#N(){return Date.now()<this.#A}#G(){if(this.#m||!this.#i)return;this.#m=!0;let t=this.#c;this.#i.onFinished(()=>{t===this.#c&&(this.#m=!1,this.#ue())})}#xe(t){let n=Date.now();this.#d=Math.max(n,this.#d)+t/48,clearTimeout(this.#u),this.#u=setTimeout(()=>this.#ue(),this.#d-n+sI)}#ue(){this.#l=!1,this.#d=0,this.#e&&this.#e.readyState===WebSocket.OPEN&&this.#w(this.#v?"processing":"listening")}#ve(){this.#i?.flush(),this.#m=!1,this.#G(),this.#l=!1,this.#d=0,clearTimeout(this.#u)}#Q(){this.#c+=1,this.#g=!1,this.#l=!1,this.#$(),this.#S=!1,this.#v=!1,this.#C=!1,this.#x=new Set;for(let t of this.#y.values())t.abort();if(this.#y.clear(),this.#b.clear(),this.#H=void 0,this.#k=!1,this.#M=null,this.#I=null,this.#Y=Promise.resolve(),this.#j.clear(),this.#B=!1,this.#T.clear(),this.#K.clear(),this.#m=!1,this.#A=0,this.#d=0,clearTimeout(this.#u),this.#p=[],this.#f=0,this.#r&&(this.#r.onaudioprocess=null,this.#r.disconnect(),this.#r=null),this.#s&&(this.#s.disconnect(),this.#s=null),this.#t&&(this.#t.getTracks().forEach(t=>t.stop()),this.#t=null),this.#n&&(this.#n.close().catch(()=>{}),this.#n=null),this.#i&&(this.#i.destroy(),this.#i=null),this.#e){this.#a=!0;try{this.#e.close(1e3,"client ended call")}catch{}this.#e=null}}onResult(t){this.#_.push(t)}onError(t){this.#F.push(t)}onStatusChange(t){this.#ee.push(t)}onTranscript(t){this.#te.push(t)}onMetrics(t){this.#D.push(t)}#w(t){this.#ee.forEach(n=>n(t))}#ie(t){this.#F.forEach(n=>n(t))}#ae(t,n,o,r){this.#te.forEach(s=>s(t,n,o,r))}#we(t){this.#D.forEach(n=>n(t))}};var Oi=class{constructor(t={}){this.config=t;this.type="browser";this.#e=null;this.#n=[];this.#o=[];this.#t=[];this.#s=!1;this.#r=typeof window<"u"?window:void 0}#e;#n;#o;#t;#s;#r;async connect(){this.#t.forEach(t=>t("connected"))}async startListening(){try{if(this.#s)throw new Error("Already listening");if(!this.#r)throw new Error("Window object not available");let t=this.#r.SpeechRecognition||this.#r.webkitSpeechRecognition;if(!t)throw new Error("Browser speech recognition not supported");this.#e=new t,this.#e.lang=this.config?.language||"en-US",this.#e.continuous=this.config?.continuous||!1,this.#e.interimResults=!0,this.#e.onresult=n=>{let o=Array.from(n.results).map(s=>s[0]).map(s=>s.transcript).join(""),r=n.results[n.results.length-1].isFinal;this.#n.forEach(s=>s({text:o,confidence:r?.8:.5,provider:"browser"})),r&&!this.config?.continuous&&this.stopListening()},this.#e.onerror=n=>{this.#o.forEach(o=>o(new Error(n.error))),this.#t.forEach(o=>o("error"))},this.#e.onstart=()=>{this.#s=!0,this.#t.forEach(n=>n("listening"))},this.#e.onend=()=>{this.#s=!1,this.#t.forEach(n=>n("idle"))},this.#e.start()}catch(t){throw this.#o.forEach(n=>n(t)),this.#t.forEach(n=>n("error")),t}}async stopListening(){this.#e&&(this.#e.stop(),this.#e=null),this.#s=!1,this.#t.forEach(t=>t("idle"))}onResult(t){this.#n.push(t)}onError(t){this.#o.push(t)}onStatusChange(t){this.#t.push(t)}async disconnect(){await this.stopListening(),this.#t.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Xa(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new vc(e.runtype);case"browser":if(!Oi.isSupported())throw new Error("Browser speech recognition not supported");return new Oi(e.browser||{});case"custom":{let t=e.custom;if(!t)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof t=="function"?t():t;if(!n||typeof n.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Pu(e){if(e?.type==="custom"&&e.custom)return Xa({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return Xa({type:"runtype",runtype:e.runtype});if(Oi.isSupported())return Xa({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function _h(e){try{return Pu(e),!0}catch{return!1}}var Qx="webmcp:",bI=e=>e.startsWith(Qx)?e.slice(Qx.length):e,ku={warn(e,...t){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},Hu=class{constructor(t,n){this.config=t;this.#r=n,this.#e=t.onConfirm??null,this.#n=3e4}#e;#n;#o=!1;#t=null;#s=!1;#r;setConfirmHandler(t){this.#e=t}isOperational(){return this.config.enabled!==!0||!this.#o?!1:this.#i()!==null}async snapshotForDispatch(){if(await this.#p(),this.config.enabled!==!0)return[];let t=this.#i();if(!t)return[];let n;try{n=await t.getTools()}catch(r){return ku.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}this.#r.recordToolDisplayTitles(n);let o=typeof location<"u"?location.origin:"";return n.filter(r=>this.#l(r.name)).map(r=>{let s=CI(r.annotations);return{name:r.name,description:r.description,parametersSchema:wI(r.inputSchema),origin:"webmcp",...o?{pageOrigin:o}:{},...s?{annotations:s}:{},...s?.untrustedContentHint===!0?{untrustedContentHint:!0}:{}}})}async executeToolCall(t,n,o){if(await this.#p(),this.config.enabled!==!0)return $o("WebMCP is not enabled on this widget.");let r=this.#i();if(!r){let y=typeof document<"u"&&!!document.modelContext;return $o(y?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let s=bI(t),i;try{i=await r.getTools()}catch(y){let v=y instanceof Error?y.message:String(y);return $o(`Failed to read WebMCP registry: ${v}`)}this.#r.recordToolDisplayTitles(i);let l=i.find(y=>y.name===s);if(!l)return $o(`WebMCP tool not registered on this page: ${s}`);if(!this.#l(s))return $o(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return $o("Aborted by cancel()");let c=this.#r.getToolDisplayTitle(s),p={toolName:s,args:n,description:l.description,...c?{title:c}:{},reason:"gate"};if(!await this.#g(p))return $o("User declined the tool call.");if(o?.aborted)return $o("Aborted by cancel()");let d=new AbortController,g=!1,f=setTimeout(()=>{g=!0,d.abort()},this.#n),h=()=>d.abort();o&&(o.aborted?d.abort():o.addEventListener("abort",h,{once:!0}));try{let y=await r.executeTool(l,MI(n),{signal:d.signal});return SI(y)}catch(y){if(g)return $o(`WebMCP tool '${s}' timed out after ${this.#n}ms`);if(o?.aborted)return $o("Aborted by cancel()");let v=y instanceof Error?y.message:String(y);return $o(v)}finally{clearTimeout(f),o&&o.removeEventListener("abort",h)}}#p(){return this.config.enabled!==!0?Promise.resolve():(this.#t||(this.#t=this.#f()),this.#t)}async#f(){try{if(this.#i()){this.#o=!0;return}(await this.#r.loadPolyfill()).initializeWebMCPPolyfill(),this.#o=!0}catch(t){ku.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",t),this.#o=!1}}#i(){if(typeof document>"u")return null;let t=document.modelContext;if(!t||typeof t!="object")return null;let n=t;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.#s||(this.#s=!0,ku.warn("document.modelContext is present but does not expose getTools()/executeTool(): WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):t}async#g(t){let n=this.#e??AI;try{return await n(t)}catch(o){return ku.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,o),!1}}#l(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(o=>vI(t,o))}},vI=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Lu={type:"object",properties:{}},CI=e=>{if(!e||typeof e!="object")return;let t={...typeof e.readOnlyHint=="boolean"?{readOnlyHint:e.readOnlyHint}:{},...typeof e.untrustedContentHint=="boolean"?{untrustedContentHint:e.untrustedContentHint}:{}};return Object.keys(t).length>0?t:void 0},wI=e=>{if(e===void 0||e==="")return{...Lu};if(typeof e=="object")return e!==null&&!Array.isArray(e)?e:{...Lu};try{let t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:{...Lu}}catch{return{...Lu}}},SI=e=>{if(e==null)return{content:[{type:"text",text:""}]};let t;try{t=JSON.parse(e)}catch{return{content:[{type:"text",text:e}]}}return t!==null&&typeof t=="object"&&Array.isArray(t.content)?t:{content:[{type:"text",text:typeof t=="string"?t:EI(t)}]}},$o=e=>({isError:!0,content:[{type:"text",text:e}]}),AI=async e=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let t=xI(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
|
|
482
482
|
|
|
483
483
|
Arguments:
|
|
484
484
|
${t}`:"")+(e.description?`
|